Explore the key concepts of Java variables with these easy but insightful questions. Great for beginners looking to strengthen their Java foundational knowledge.
Which of the following correctly declares a variable to store an integer value in Java?
Explanation: The correct way to declare an integer variable in Java is 'int num;'. The option 'integer num;' uses an incorrect keyword, 'num int;' has the order reversed, and 'int = num;' uses assignment incorrectly.
How do you correctly assign the value 10 to an already declared integer variable named x?
Explanation: 'x = 10;' assigns the value 10 to x, which is already declared. 'int x = 10;' redeclares x, '10 = x;' uses assignment in reverse, and 'x : 10;' is invalid syntax.
Which line correctly declares two Java variables named a and b of type int and assigns them both the value 5?
Explanation: 'int a = 5, b = 5;' properly declares both variables and assigns their values. 'int a == 5, b == 5;' uses the wrong assignment operator, 'a int, b int = 5;' uses an incorrect syntax, and 'integer a = 5, b = 5;' uses a non-Java keyword.
Which of these is a valid variable name in Java?
Explanation: 'userName' is valid in Java. '2users' cannot begin with a digit, 'user-name' contains an illegal character, and 'class' is a reserved keyword.
What is the correct data type in Java for storing a string of text?
Explanation: Java uses 'String' (capital S) for text. 'Text' and 'string' are not valid Java types, while 'Character' only holds a single character.
If an int variable is declared as a class member but not initialized, what is its default value in Java?
Explanation: Class member variables of type int default to 0. 'null' is for objects, 'undefined' is not a Java keyword, and '1' is not the default.
Are variable names in Java case sensitive?
Explanation: Java variable names are case sensitive. 'No' is incorrect, 'Only for classes' is misleading, and 'Sometimes' is inaccurate.
What happens if you try to use a local int variable in Java without initializing it first?
Explanation: Java requires local variables to be initialized before use, else a compilation error occurs. Class members default to 0, but not local variables. 'null' isn't valid for int, and the code won't just run.
How do you declare a constant (unchangeable) variable in Java?
Explanation: 'final' makes a variable unchangeable. 'const' is not a Java keyword. 'int constant MAX = 10;' and 'int MAX = constant 10;' use incorrect syntax and keywords.
Which data type is typically used in Java to store a decimal value like 3.14?
Explanation: 'double' stores decimal values such as 3.14. 'int' is for whole numbers, 'char' is for single characters, and 'boolean' stores true/false values.