Literals

In Java, literals refer to fixed values that are represented in their human-readable form For example, the number 100 is a literal. Literals are also commonly called constants. Below is the basic Java literals example.


public class literalExample {
	public static void main(String[] args) {
		int i = 10; // 10 is integer literal
		long l1 = 20; // 20 is by default integer literal
		long l2 = 10L; // 10 is a long literal because L is suffixed
		float f1 = 20.00; // by default 20.00 is a double literal
		float f2 = 20.00f; // now 20.00 is a float literal because of suffix f
		double d1 = 21.00; // 21.00 is a double literal
		char c1 = 65; // 65 is a character literal, ASCII value will be printed
						// according to integer literal
		System.out.println("c1" + c1);
	}
}

Hexadecimal and Octal Constants

The number system based on 8 is called octal, and it uses the digits 0 through 7. In octal the number 10 is the same as 8 in decimal. The base 16 number system is called hexadecimal and uses the digits 0 through 9 plus the letters A through F, which stand for 10, 11, 12, 13, 14, and 15. For example, the hexadecimal number 10 is 16 in decimal. Because of the frequency with which these two number systems are used, Java allows you to specify
integer constants in hexadecimal or octal instead of decimal. A hexadecimal constant must begin with 0x (a zero followed by an x). An octal constant begins with a zero. Here are some examples:

public class OctalAndHexadecimal {
	public static void main(String[] args) {
		int number1 = 011; // 9 in decimal
		int number2 = 0xFF; // 255 in decimal
		System.out.println(number1); // printing decimal value for number1
		System.out.println(number2); // printing decimal value for number2
		System.out.println("In binary number System"
				+ Integer.toBinaryString(number1)); // printing the in the
  								    // binary number system
	}
}

Character Escape Sequences

Enclosing character constants in single quotes works for most printing characters, but a few characters, such as the carriage return, pose a special problem when a text editor is used. In addition, certain other characters, such as the single and double quotes, have special meaning in Java, so you cannot use them directly. Escape sequences are used in place of the characters that they represent

char tabChar = '\t'; // a Tab character
char singleQuote = '\''; // single quote character

There are many character escape sequences which are given below :

Escape Sequence Description
\’  Single quote
\"  Double quote
\\  Backslash
\r  Carriage return
\n  New line
\f  Form feed
\t  Horizontal tab
\b  Backspace
\ddd  Octal constant (where ddd is an octal constant)
\uxxxx  Hexadecimal constant (where xxxx is a hexadecimal constant)

String Literals

String s = "hello\nworld"; // hello world is a string literal whereas \n
			   // invoke a newline character.
String s1 = "hello\tworld"; // word will be printed after hello
			    // following a tab