Which is a valid declarations of a String?

  1. String s1 = null;

  2. String s2 = 'null';

  3. String s3 = (String) 'abc';

  4. String s4 = (String) '\ufeed';


Correct Option: A
Explanation:

To solve this question, the user needs to understand the syntax and rules for declaring a String in Java.

Let's go through each option and explain why it is right or wrong:

A. String s1 = null; This option is a valid declaration of a String. In Java, a String variable can be assigned a null value, which means it does not reference any object. This option is correct.

B. String s2 = 'null'; This option is incorrect. In Java, single quotes (' ') are used to represent characters, not Strings. To declare a String, double quotes (" ") should be used. Therefore, this option is wrong.

C. String s3 = (String) 'abc'; This option is incorrect. In Java, to declare a String, the value must be enclosed in double quotes (" "). The syntax (String) is used for type casting, which is not necessary when declaring a String. Therefore, this option is wrong.

D. String s4 = (String) '\ufeed'; This option is incorrect. The value '\ufeed' is an escape sequence representing a Unicode character. However, to declare a String, the value must be enclosed in double quotes (" "). Therefore, this option is wrong.

The Answer is: A. String s1 = null;

Find more quizzes: