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
T he Correct Answer and Explanation is :
✅ Correct Java Code:
public class Initials {
public static void main(String[] args) {
// Declare variables to store three 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:
In Java, characters are represented using the char data type, which stores a single 16-bit Unicode character. Each char value must be enclosed in single quotes (e.g., 'A', 'z', '3'). In this program, we want to store three initials—each being a single character—so we declare three char variables: firstInitial, middleInitial, and lastInitial.
char firstInitial = 'J';
char middleInitial = 'M';
char lastInitial = 'F';
These variables store the initials “J”, “M”, and “F” respectively.
To display the initials in the desired format (J.M.F), we use System.out.println() to print the characters along with periods . as separators.
System.out.println(firstInitial + "." + middleInitial + "." + lastInitial);
In Java, the + operator can be used for string concatenation when one or more operands are strings. Even though char is not a string type, when used in a + operation with a string (like "."), the characters are automatically converted into strings and concatenated.
So, firstInitial + "." becomes "J.", then "J." + "M" becomes "J.M", and so on. The final result printed is J.M.F.
This is a common approach in Java for formatting output involving characters and strings. It demonstrates basic principles of variable declaration, data types, and output formatting, which are essential for beginner-level programming in Java.
