This section contains carefully selected MCQs and Previous Year Questions with explanations to help students understand concepts and prepare effectively for examinations, interviews, and competitive tests.
Q: 1What will be the output of the following Java code?
public static void main(String args[])
{
byte p=32;
int i;
byte q;
i=p<<3;
q=(byte)(p<<3);
System.out.print(i+” “+q);
}
Option A
In Java, when you apply a Bitwise Left Shift (<<) to a byte, the value is first promoted to int before the shift. The result of p<<3 is computed in int arithmetic, but if you cast it back to byte, any bits outside the byte range are truncated, which can cause overflow and produce a different value.
Here, p = 32, So p << 3 means multiply by 23 = 8. So, 32*8=256. Since Java automatically promotes the result of bitwise operations to int, the value of i becomes 256.
Next, when assigning the same result to byte q using q=(byte)(p<<3), the value 256 is cast back to a byte. However, a byte can store only 8 bits, so the higher bits are truncated, leaving 0000 0000, which equals 0. Therefore, the final output printed is 256 0.
Q: 2What is the output of the following code?
public class Demo {
public static void main(String[] args) {
int x = 5;
System.out.println(++x*2);
}
}
Option A
In this code, the variable x is initially assigned the value 5. The expression ++x * 2 uses the pre-increment operator, which means x is increased before it is used in the calculation. So, ++x changes the value of x from 5 to 6, and then the multiplication 6 * 2 is performed. Therefore, the output printed by System.out.println(++x * 2); is 12.
Q: 3What will be the output of the code after the given code executes?
int a = 5;
int b = a++;
System.out.println(“a = ”+a+”b = ”+b);
Option A
In this code, the variable a is first assigned the value 5. When the statement int b = a++; executes, the operator used is the post-increment operator (a++).
In post-increment, the current value of the variable is used first, and then the increment happens afterward. This means that the value of a is first assigned to b, and only after this assignment does a increase by 1. As a result, after the statement executes, a becomes 6 while b remains 5.
You have reached the end of this topic. Continue learning with the next topic below.
Thank you so much for taking the time to read my Computer Science MCQs section carefully. Your support and interest mean a lot, and I truly appreciate you being part of this journey. Stay connected for more insights and updates! If you'd like to explore more tutorials and insights, check out my YouTube channel.
Don’t forget to subscribe and stay connected for future updates.