Difficulty Level: Rookie
Predict the output of the following Java Programs.
Program 1:
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 the same package and in inherited classes of other packages. Since Test and Main are in the same package, no access-related problems in the above program. Also, the default constructors initialize integral variables as 0 in Java (Refer to this article for more details). That is why we get output as 0 0.
Program 2:
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 the 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.
Java
class Test {
public static void main(String[] args) {
for ( int i = 0 ; true ; i++) {
System.out.println("Hello");
break ;
}
}
}
|
Program 3:
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 without creating an object. If we make fun() static OR If we create an object of the Main class and then call the method on that object then the program compiles fine without any compiler error. Following is the corrected program.
1. By defining the method as “static”
Java
class Main {
public static void main(String args[]) {
System.out.println(fun());
}
static int fun() {
return 20 ;
}
}
|
2. By creating an object
Java
class Main {
public static void main(String args[]) {
Main obj = new Main();
System.out.println(obj.fun());
}
int fun() {
return 20 ;
}
}
|
Program 4:
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. Refer to this article for more 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.
Java
class Test {
private static int x;
public static void main(String args[]) {
System.out.println(fun());
}
static int fun() {
return ++x;
}
}
|
Please write comments if you find any of the answers/explanations incorrect, or want to share more information about the topics discussed above.