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).

J.M.F

The Correct Answer and Explanation is:

✅ Correct Java Code:

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

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

🧠 Explanation (300+ words):

In Java, when we want to store individual characters, we use the char data type. The char data type in Java is used to store a single 16-bit Unicode character. Each character must be enclosed in single quotes, like 'A', 'M', or 'F'.

In the code above, we declare three char variables:

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

Each of these stores one initial. Then, we use System.out.println() to display them in the specified format.

To format the initials like J.M.F, we concatenate the characters and string literals (the periods) using the + operator. In Java, the + operator is used both for numeric addition and for string concatenation. When used with strings or characters, it joins them together into one string.

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

Let’s break this line down:

  1. firstInitial + "." results in something like 'J' + ".", which becomes "J."
  2. Then, "J." + middleInitial becomes "J.M"
  3. Next, "J.M" + "." becomes "J.M."
  4. Finally, "J.M." + lastInitial becomes "J.M.F"

The System.out.println() method then prints this final string to the console.

This program is simple but demonstrates key Java principles:

  • Variable declaration
  • Use of the char data type
  • String concatenation
  • Output with System.out.println()

This is a common beginner-level exercise to reinforce character handling and string manipulation in Java, especially useful in learning how to structure formatted outputs.

Scroll to Top