Data types, variables, and constants – Java MCQs

21.) Which of the following is NOT a valid variable name in Java?

A) myVariable
B) _value
C) 123variable
D) variable123

Answer: Option C

Explanation: Variable names in Java cannot start with a number. Hence, “123variable” is not a valid variable name. Valid variable names must begin with a letter, underscore (_), or a dollar sign ($).

22.) In Java, which of the following is used to initialize an instance variable of an object during object creation?

A) Constructor
B) finalize()
C) new
D) this

Answer: Option A

23.) In Java, what is the data type of the result when dividing two integers?

A) int
B) long
C) double
D) float

Answer: Option A

Explanation: When two integers are divided in Java, the result is an integer value. Any fractional part is truncated, and only the whole number part is retained.

24.) How is a constant variable typically declared in Java?

A) const int VALUE = 10;
B) constant int VALUE = 10;
C) int VALUE = 10;
D) final int VALUE = 10;

Answer: Option D

Explanation: In Java, a constant variable is declared using the “final” keyword before the data type. For example, “final int VALUE = 10;” declares an integer constant named “VALUE” with a value of 10.

25.) What will happen if you try to change the value of a constant variable in Java?

A) It will raise a compilation error.
B) It will automatically update the new value throughout the program.
C) It will prompt the user to enter a new value during runtime.
D) It will replace the old value with the new value without any error.

Answer: Option A

Explanation: In Java, a constant variable is declared with the “final” keyword, and once it is assigned a value, that value cannot be changed. If you attempt to modify the value of a constant variable, the compiler will raise a compilation error.

26.) Which of the following data types can be used to declare a constant in Java?

A) int
B) double
C) String
D) All of the above

Answer: Option D

Explanation: Constants can be declared with various data types in Java. The “int,” “double,” and “String” data types are commonly used to declare constants, depending on the nature of the constant value.

27.) In Java, the word true is?

A) A Boolean literal
B) A Java keyword
C) Similar to value 1
D) Similar to value 0

Answer: Option A