Characters
The char
data type is designed to store a single character, and the character should be enclosed in single quotes.
Example:
JAVA
x
char grade = 'A';
System.out.println(grade); // Outputs: A
You can also use ASCII values to represent characters. ASCII values are numerical codes for characters.
Example:
In this example, 65, 66, and 67 are the ASCII values for ‘A’, ‘B’, and ‘C’, respectively.
JAVA
char firstLetter = 65, secondLetter = 66, thirdLetter = 67;
System.out.println(firstLetter); // Outputs: A
System.out.println(secondLetter); // Outputs: B
System.out.println(thirdLetter); // Outputs: C
Strings
The String
data type is used to store a series of characters, and it must be enclosed in double quotes.
Example:
Strings are not considered primitive data types; they are objects with methods that provide various functionalities.
JAVA
String greeting = "Hello World";
System.out.println(greeting); // Outputs: Hello World
Summary
- Characters (
char
): Used for storing a single character and enclosed in single quotes. - Strings (
String
): Used for storing sequences of characters and enclosed in double quotes. - ASCII Values: Can be used to represent characters by their numerical codes.