What is the output of the following Java code?Code:class HackerEarth{ public static void main(String[] args) { int val = 1; while((val<=5 ? val++: --val)<5) { System.out.print("MAC"); } if(val>5); System.out.print("PC"); }}
Question
What is the output of the following Java code?Code:class HackerEarth{ public static void main(String[] args) { int val = 1; while((val<=5 ? val++: --val)<5) { System.out.print("MAC"); } if(val>5); System.out.print("PC"); }}
Solution
The output of the given Java code is "MACMACMACMACPC".
Here's the step-by-step explanation:
-
The variable
valis initialized with the value 1. -
The
whileloop condition checks ifvalis less than or equal to 5. If it is, it incrementsvalby 1 and then checks if the incrementedvalis less than 5. Ifvalis greater than 5, it decrementsvalby 1 and then checks if the decrementedvalis less than 5. -
The
System.out.print("MAC")statement is executed as long as thewhileloop condition is true. This means "MAC" is printed each time the loop iterates. -
The loop iterates 4 times (for
val= 1, 2, 3, 4), printing "MAC" each time. Whenvalbecomes 5, theval++operation in thewhileloop condition makesval6, which is not less than 5, so the loop ends. -
After the loop, the
ifstatement checks ifvalis greater than 5. Sincevalis 6 at this point, the condition is true, soSystem.out.print("PC")is executed, printing "PC".
So, the final output is "MACMACMACMACPC".
Similar Questions
What is the output of the following Java code:Code:class hacker{ public static void main(String[] arg) { int[] a = { 128, 132, 98, 116, 100 }; int x = func(a); System.out.println(x); } public static int func(int[] no) { int b = no[0]; for (int i: no) { if (i > b) b = i; } return b; }}
What is the output of the below program?public class Main{ public static void main(String[] args) { int a = 25; if(a > 5) System.out.print("Hi "); if(a < 20) System.out.print("Hello "); else System.out.print("Know Program "); }}
What is the output of the program below? public static void main(String[] args) { int x = 0; while (x < 10) { if (x & 2 == 0) { System.out.print(x + “ “); } x++; } } Note: Simply type the output. No explanation whatsoever.
e correct answerWhat is the output of the following Java program?class Main { public static void main(String args[]) { final int i; i = 20; i = 30; System.out.println(i); }}
What is the output of the following Java code?Code:class HackerEarth{ public void print() { System.out.println("Inside HackerEarth"); }}class Hacker extends HackerEarth{ public void print() { System.out.println("Inside Hacker"); }}public class HackerEarthMain{ public static void main(String[] args) { HackerEarth obj1 = new HackerEarth(); Hacker obj2 = new Hacker(); ((HackerEarth) obj2).print(); obj1 = obj2; obj1.print(); }}
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.