Java Multiple Choice Questions
What is Java?
Java is a programming language and a platform. It is a high-level, robust, object-oriented, and secure programming language.
Java was developed by Sun Microsystems (now a subsidiary of Oracle) in 1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered company, James Gosling and his team changed the name from Oak to Java.
1) Observe the following code snippet and choose the correct option.
byte b = 10; // line 1 b = b * 10; // line 2
- Lines 1 and 2 are both executed without any error.
- Because of line 2, the code will not compile.
- Because of line 1, the code will not compile.
- None of the above
Show Answer Workspace
Answer: b) Because of line 2, the code will not compile. Explanation: The * operator has converted the expression b * 10 into an integer. We know that integer size is always greater than the byte size in Java. Therefore, assigning an integer to a byte may lead to lossy conversion and such conversion is always done explicitly (by doing type-casting). Hence, we get the compilation error because of line 2.
2) Predict the outcome
Filename: Basic.java
public class Basic { public static void main(String argvs[]) { int var; System.out.println(var + 1); } }
- 1
- 2
- Compilation Error
- Runtime Error
Show Answer Workspace
Answer: c) Compilation Error Explanation: Class member variables can be accessed without assigning a value. However, the same is not true for the local variable. In our code, var is a local variable. Therefore, var must be initialized with some value before accessing it. Hence, the compilation error.
3) Predict the outcome
Filename: Basic1.java
public class Basic1 { public static void main(String argvs[]) { int var1 = 5; int var2 = 6; System.out.println(var1 + var2 + " = " + var1 + var2); } }
- 56 = 56
- 11 = 11
- 56 = 11
- 11 = 56
Show Answer Workspace
Answer: d) 11 = 56 Explanation: The + operator acts differently in the different scenarios. We have used the + operator thrice in our code. The first + operator does the addition work. But the second and third + plus operator does the concatenation work. This is because, before the second + operator, the compiler has already encountered a string (=). Therefore, the second and third + operator does the concatenation work.