In Java programming, declare a variable that can store three initials (each represented by a single character).

In Java programming, declare a variable that can store three initials (each represented by a single character). Then, display the initials in the format: J.M.F (each initial followed by a period).

The Correct Answer and Explanation is:

✅ Correct Java Code:

public class Initials {
    public static void main(String[] args) {
        // Declare three character variables to store initials
        char firstInitial = 'J';
        char middleInitial = 'M';
        char lastInitial = 'F';

        // Display the initials in the format: J.M.F
        System.out.println(firstInitial + "." + middleInitial + "." + lastInitial + ".");
    }
}

📘 Explanation (300+ words):

In Java, variables are containers that store data of specific types. To store single characters, such as initials, the char data type is used. The char type in Java holds a single 16-bit Unicode character and is enclosed in single quotes, like 'J'.

In the code above:

char firstInitial = 'J';
char middleInitial = 'M';
char lastInitial = 'F';

We declare three variables of type char: firstInitial, middleInitial, and lastInitial, and assign them the values 'J', 'M', and 'F', respectively. These values represent a person’s initials (for example, “John Michael Ford”).

To display the initials in the format J.M.F., we use the System.out.println() method. This method prints data to the console:

System.out.println(firstInitial + "." + middleInitial + "." + lastInitial + ".");

Here, each initial is concatenated with a string (the "." period character) using the + operator. When Java evaluates this line, it automatically converts the char values to strings and concatenates them in order:

  1. 'J' + "." becomes "J."
  2. Then, "J." + 'M' becomes "J.M"
  3. Then, "J.M" + "." becomes "J.M.", and so on.

So the final output is:

J.M.F.

🔑 Key Concepts:

  • char is used for single characters.
  • Characters are written in single quotes: 'A'.
  • The + operator is used to concatenate strings and characters.
  • The output format strictly follows the pattern: Initial + period.

This approach is useful in many real-world applications where initials need to be displayed—for example, on official documents or in user interfaces.

Scroll to Top