Java Programming Questions | Java sample coding problems

This is a post dedicated to Java programming challenges that can be useful to refresh and validate your knowledge of Java.

Question 1

Write the output of the following code?

int x = 1, y = 1, z = 0;
if (x == y | x < ++y) {
z = x + y;
} else {
z = 1;
}
System.out.println(z);

Question 2

Write the output of the following code?

int x = 1, y = 1, z = 0;
if (x == y | x < ++y) {
z = x + y;
} else {
z = 1;
}
System.out.println(z);

Not Sure why the out of questions 1 and 2 are different read about Java short circuit and full evaluation.

Question 3

Write the output of the following code?

int period = 1, amt = 10;
float rate = 0.5f;
switch (period) {
case 4:
	amt += amt * rate;
case 3:
	amt += amt * rate;
case 2:
	amt += amt * rate;
case 1:
	amt += amt * rate;

	System.out.println("final amt : " + amt);
}

Also, try to run the above code after modifying case 4 as below

case 4:
    amt += amt * rate;
    break;

Question 4

Write the output of the following code?

public static void main(String... strings) {
	int localVal = 5;
	calculate(localVal);
	System.out.println(localVal);
}

public static void calculate(int calcVal) {
    calcVal = calcVal * 100;
}

Question 5

Write the output of the following code?

String str = ""; 
str  = 1 + 1 + "u";
System.out.println(str);
str  = "u" + 1 + 1;
System.out.println(str);
str  = "u" + (1 + 1);
System.out.println(str);

Happy Learning !!

Leave a Comment