Literals in Java
What is literal in Java?
A literal is the source code representation of a value of a primitive type, the String type, or the null type – JLS 3.10
Let’s understand with an example.
1 |
int age = 30; |
In above example int is data type of the variable, age is the name of that variable of type int and 30 is an int literal which represents a value 30 of primitive type int.
Got what literals are?
If not yet please comment below no worries.
In Java by default whole number is int and floating number is double.
How to prove that? Let’s try another example.
1 2 3 4 5 6 7 8 9 |
package com.codetechclub; public class LiteralsDemo { public static void main(String[] args) { byte salary = 30000; // Compile time error 1 float tax = 1000.50; // Compile time error 2 } } |
Compiler is smart enough to identify the type of literal. Here are the screenshots of compile time errors i got in Eclipse IDE is
CE 1 where compiler clearly states can’t convert from int to byte means 30000 is an int literal.
CE 2 where compiler states can’t convert from double to float means 1000.50 is a double literal.
If try compiling in command prompt then this is what CE you get with pointing to where precisely error occurred.
Since Java 7 underscores are allowed as separators between digits that denote the integer.
Integer Literal:
We can express integer literal in decimal ( base 10 ), octal( base 8 ), hexadecimal( base 16) and binary ( base 2 ) form.
Integer literal create an int value which is a 32 bit integer value in Java.
-
- Decimal Number: 10, 13, 45 these are all decimal values means they are describing a base 10 number.
- Octal Number: Octal values are denoted by leading a zero. Decimal numbers can’t have a leading zero hence 09 will give compile time error since 09 is outside of the range of octal which is 0-7.
123456789101112131415package com.codetechclub;public class OctalDemo {public static void main(String[] args) {int num1 = 07;// int num2 = 09;// Gives CE The literal 09 of type int is out of range.int num3 = 010;System.out.println("num1: " + num1 + " num3: " + num3);}}
1num1: 7 num3: 8
-
- Hexadecimal Number: Hexadecimal values are denoted by a leading zero with x or X ( 0x or 0X ). The range of Hexadecimal numbers is 0-15 where 10 to 15 are substituted by A or a to F or f therefore when prints 0xA it prints 10 and 0xD prints 13 so forth.
When you print 0x10 or 0X10 which prints 16, 0x11 prints 17 so on.
123456789101112131415package com.codetechclub;public class HexadecimalDemo {public static void main(String[] args) {int num1 = 0x7;int num2 = 0XA;int num3 = 0xD;int num4 = 0x10;System.out.println("num1: " + num1 + " num2: " + num2);System.out.println("num3: " + num3+ " num4: " + num4);}}
12num1: 7 num2: 10num3: 13 num4: 16
- Binary Number: Since JDK 7 we can also specify integer literal using binary expression. For that we have to prefix the value with 0b or 0B. Suppose we want to represent decimal value 10 in binary expression then we have to write it like 0b1011 or 0B 1011.
123456789101112package com.codetechclub;public class BinaryDemo {public static void main(String[] args) {int num1 = 0b101;int num2 = 0B1111;System.out.println("num1: " + num1 + " num2: " + num2);}}
1num1: 5 num2: 15
- Hexadecimal Number: Hexadecimal values are denoted by a leading zero with x or X ( 0x or 0X ). The range of Hexadecimal numbers is 0-15 where 10 to 15 are substituted by A or a to F or f therefore when prints 0xA it prints 10 and 0xD prints 13 so forth.
Since Java is strongly typed still it is possible to assign an integer literal to Java’s other integer types such as byte or short etc. without any error or issue.
When an integer literal value is assigned to a byte or short variable no error is generated if the literal value is within the range of the target type.
As we know the byte range of value is -128 to 127 hence in the following example we can see the integer literal i.e. by default int 127 and -128 is withing the range of byte so it implicitly cast int to byte and then assigns those values to byte variables respectively.
In case of literal 128 which doesn’t fit in the range of byte therefore it gives compile time error saying ” Type mismatch: cannot convert from int to byte”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.codetechclub; public class LiteralDemo { public static void main(String[] args) { byte num1 = 127; // byte num2 = 128; // Gives CE Type mismatch: cannot convert from int to byte. byte num3 = -128; System.out.println("num1: " + num1 + " num3: " + num3); } } |
1 2 |
num1: 127 num3: -128 |
How to specify long literal?
As you know that whole number integer literal by default is int in Java so to specify the whole number integer literal is of long type then you need to explicitly tell the compiler that literal value is of a long type by appending l or L to the literal.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.codetechclub; public class LiteralDemo { public static void main(String[] args) { long num1 = 120L;// Appended upper case L long num2 = 2500l;// Appended lower case l // int num3 = 128L; // byte num4 = 12L; // Above num3 and num4 gives CE // saying cannot convert from long to int // and cannot convert from long to byte respectively. System.out.println("num1: " + num1 + " num2: " + num2); } } |
1 |
num1: 120 num2: 2500 |
According to JLS 5.2. Assignment Contexts for a narrowing primitive conversion the constant expression must be of type byte, short, char, or int but in our example constant expression assigning to num3 and num4 are of long therefore gives compile time error although value 128 and 12 fits in their respective variable data type range.
Floating-Point Literals
- Floating point numbers are decimal values with a fractional component. They can be expressed in either standard or scientific notation. In standard notation a whole number component is followed by a decimal point followed by a fractional component. Example 2.0, 3.415
Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number, which can be positive or negative. Examples include 6.022E23, 314159E–05, and 2e+100. - Since JDK 7 underscores ( _ ) are allowed as separator between digits that denotes whole number part, fraction part and exponent.
- By default floating point literal is of double type in Java which optionally can be suffixed with letter D or d which is redundant. Example: 10.30d or 10.30D
- To specify float literal we must append f or F to the constant floating point literal. Example: 10.30f or 10.30F
- Double literal type consumes 64 bits of storage where as float type consumes 32 bits.
- Floating point literal can be expressed in decimal ( base 10 ) and hexadecimal ( base 16 ) but hexadecimals are used very rarely.
Boolean Literals
- Boolean literal can have only two values true or false.
- Boolean literal values true or false can not be converted into any numerical representations.
- In Java neither true literal is not equal to 1 nor false literal equal to 0.
- Boolean literals can only be assigned to the variables of type boolean or used in expressions with Boolean operators.
12345678910111213141516171819package com.codetechclub;public class BooleanLiteral {public static void main(String[] args) {boolean flag1 = true;boolean flag2 = false;// int flag3 = false;// boolean literal can be assigned to boolean variable only.// System.out.println(flag1 + flag2);// + is numeric operator not allowed for booleansSystem.out.println(flag1 && flag2);System.out.println(flag1 || flag2);}}
12falsetrue
Character Literal
- A character literal is expressed as character or an escape sequence enclosed in single quotes.
- Character literals can only represent UTF-16 code units, values from \u0000 to \uffff
- A character literal is always of type char.
- Character literals are 16 bit values which can be converted into integers and perform addition, subtraction operations on them.
1234567891011121314package com.codetechclub;public class CharacterLiteral {public static void main(String[] args) {char char1 = 'A';// ASCII of 'A' = 65char char2 = 'B';// ASCII of 'B' = 66char char3 = 67;// ASCII of 'C' = 67System.out.println(char1 + char2);// 65 + 66 = 131System.out.println("char3: " + char3);}}
12131char3: C
Escape Sequences:
1 2 3 4 5 6 7 8 9 |
package com.codetechclub; public class EscapeSequence { public static void main(String[] args) { System.out.println("\"Java\tis\na programming language\""); } } |
1 2 3 |
"Java is a programming language" |
String Literal
- A string literal consists of zero or more characters enclosed in double quotes.
- A string literal is a reference to an instance of class String.
- A string literal always refers to the same instance of class String because string literals or we can say strings that are the values of constant expressions are interned so as to share unique instances, using the method String.intern.
- Example of String literal is “Hello World”.
- In Java Strings are not implemented as array of characters like in C/C++ but these are actually object types.
- In Java Strings must begin and end on same line because there is no line continuation escape sequence.
Null Literal
- It has only one value i.e. null reference represented by null literal null, formed from ASCII characters.
- Null literal is always of the null type.