Output of Java Program | Set 1

Difficulty Level: Rookie

Predict the output of following Java Programs.

Program 1

// filename Main.java
class Test {
    protected int x, y;
}
  
class Main {
    public static void main(String args[]) {
        Test t = new Test();
        System.out.println(t.x + " " + t.y);
    }
}

Output

0 0


In Java, a protected member is accessible in all classes of same package and in inherited classes of other packages. Since Test and Main are in same package, no access related problem in the above program. Also, the default constructors initialize integral variables as 0 in Java (See this GFact for more details). That is why we get output as 0 0.



Program 2

// filename Test.java
class Test {
    public static void main(String[] args) {
        for(int i = 0; 1; i++) {
            System.out.println("Hello");
            break;
        }
    }
}

Output: Compiler Error
There is an error in condition check expression of for loop. Java differs from C++(or C) here. C++ considers all non-zero values as true and 0 as false. Unlike C++, an integer value expression cannot be placed where a boolean is expected in Java. Following is the corrected program.

// filename Test.java
class Test {
    public static void main(String[] args) {
        for(int i = 0; true; i++) {
            System.out.println("Hello");
            break;
        }
    }
}
// Output: Hello



Program 3

// filename Main.java
class Main {
    public static void main(String args[]) {   
        System.out.println(fun());
    
    int fun() {
        return 20;
    
}

Output: Compiler Error
Like C++, in Java, non-static methods cannot be called in a static method. If we make fun() static, then the program compiles fine without any compiler error. Following is the corrected program.

// filename Main.java
class Main {
    public static void main(String args[]) {
        System.out.println(fun());
    
    static int fun() {
        return 20;
    }
}
// Output: 20



Program 4

// filename Test.java
class Test {
   public static void main(String args[]) {
       System.out.println(fun());
   }
   static int fun() {
       static int x= 0;
       return ++x;
   }
}

Output: Compiler Error
Unlike C++, static local variables are not allowed in Java. See this GFact for details. We can have class static members to count number of function calls and other purposes that C++ local static variables serve. Following is the corrected program.

class Test {
   private static int x;
   public static void main(String args[]) {
       System.out.println(fun());
   }
   static int fun() {
       return ++x;
   }
}
// Output: 1

Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above.



My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :



2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.