KnowledgeBoat Logo
|

Computer Applications

Which of the following is a valid Java declaration?

Values & Data Types Java

3 Likes

Answer

int num = 'B';

Reason — Let's analyze each of the options:

1. float x = 12.5;Incorrect

  • A floating-point literal (like 12.5) is by default double in Java.
  • To store it in a float variable, explicitly specify f or F:
    float x = 12.5f; // Corrected version

2. char ch = "A";Incorrect

  • A char must be enclosed in single quotes (''), not double quotes ("").
  • Correct version:
    char ch = 'A';

3. boolean b = 0;Incorrect

  • Java does not allow assigning integers (0 or 1) to boolean.
  • Only true or false is allowed.
  • Correct version:
    boolean b = false;

4. int num = 'B';Correct

  • A char in Java can be assigned to an int because characters are internally stored as Unicode values (ASCII-compatible).
  • 'B' corresponds to Unicode 66, so num will store 66.

Answered By

2 Likes


Related Questions