Java coding challenge - Day 1 | Output Prediction MCQ

 What Is the Output of This Java Code?

daily java coding challenge

Question :

public class Main {

    public static void main(String[] args) {

        int x = 5;

        System.out.println(x++ + ++x);

    }

}


Options :

A) 10
B) 11
C) 12
D) 13


Correct answer :

C) 12

Explanation :


Step 1 - class declaration

public class Main

  •  public →   Access modifier . this class can be accessed form anywhere.
  •    class → Used to create a class in java
  •     main Name of the class

So this line creates a class called main.


Step 2 - main method :

public static void main(String[ ] args)


This is the entry point of every java program.

  • public → Accessible form anywhere.
  • static  → JVM can call this method without creating an object.
  • void →  This methods does not return any value.
  • main →  Method name where the program starts. 
  • String[ ] args →  Stores command line arguments. 

So the program starts executing form this method.


Step 3 - create variable :

int x = 5;


  • int  → Integer data type.
  •   → Variable name .
  • = 5  → Assign value 5 to variable x.

Now the value stored in memory is :

X = 5


Step 4 - print statement :

System.out.println(x++ + ++x);


Now break this line in to parts :

System  is a built-in Java class.

out is an object of PrintStream used for printing output.

println() prints the value and moves to the next line.


Step 5 - Evaluate expression :

Expression:

x++  +  ++x

Initial value:

x = 5

 

Step 6 - Post Increment (X++) :

X++

Rule of post increment :

1. First use the value

2. Then increase it

So :

Use value = 5

x becomes = 6


Step 7 - Pre Increment (++x) :

++X

Rule of pre increment :

1. First increase the  value

2. Then use it

Current value :

X = 6

After increment :

++x = 7


Step 8 - Final calculation :

Expression :

5 + 7

Result :

12


Final Output :

12


Key points :

X++  → Use value first then increment

++X  → Increment first then use value


Practice daily Java coding challenges to improve your programming and logical thinking skills.

Happy coding ❤️











No comments:

Post a Comment