In Java programming, which of the following is a valid declaration of a String variable?

Difficulty: Easy

Correct Answer: String s1 = null;

Explanation:


Introduction / Context:
Java treats java.lang.String as a reference type. A declaration must follow Java’s literal and casting rules. This question checks your understanding of valid String initializations and the difference between character literals, Unicode escapes, and reference nulls.



Given Data / Assumptions:

  • We are declaring String references in standard Java.
  • Single quotes denote a single char literal, not a String.
  • Unicode escapes like \uXXXX represent a single char code point when used inside character or string literals.


Concept / Approach:
A String variable may be assigned either a String object (e.g., a double-quoted literal) or the null reference. Casting a char to String is not legal without calling an API (such as Character.toString or String.valueOf). Single quotes are for char, not String.



Step-by-Step Solution:

Check option A: String s1 = null; → Valid; a reference can be null.Check option B: String s2 = 'null'; → 'null' is a char literal (and 4 chars are not allowed for char), invalid for String.Check option C: String s3 = (String) 'abc'; → Illegal cast; 'abc' would be invalid char literal and cannot be cast to String.Check option D: String s4 = (String) '\ufeed'; → A char literal with a Unicode escape cannot be cast to String directly.


Verification / Alternative check:
Compile the snippets individually; only option A compiles without extra helper methods.



Why Other Options Are Wrong:
They either misuse single quotes (char literal) or perform an invalid cast from char to String.



Common Pitfalls:
Confusing ' ' (char) with "" "" (String), and assuming casts can magically convert primitives to reference types.



Final Answer:
String s1 = null;

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion