3.core Java Literals
3.core Java Literals
Literals in Java:
• In programming, a literal represents a value directly in the source code.
• Java provides five types of literals.
Types of Literals:
• Integer Literals
• Floating point Literals
• Character Literals
• Boolean Literals
• String Literals
Integer Literals:
• Represent whole numbers.
• Can be in binary (base 2), octal (base 8), decimal (base 10) and hexadecimal (base 16)
format.
Number System:
1. Binary (allowed from JDK 7)
2. Octal
3. Decimal
4. Hexadecimal
Decimal:
Allowed digits: 0-9, not start with 0
Octal:
Allowed digits: 0-7, starts with 0
Hexadecimal:
Allowed digits: 0-9, a-f or A-F
Prefix with: 0x or 0X
Here a/A = 10, b/B = 11, …
Binary:
Allowed digits: 0, 1
Prefix with: 0b or 0B
Example:
class Test
{
public static void main(String[] args)
{
int x = 123; //decimal
int y = 012; //octal
[email protected] Cell: 78 42 66 47 66
Leela Soft Core Java (J2SE) Madhusudhan
System.out.println("Decimal : "+x);
System.out.println("Octal : "+y);
System.out.println("HexaDecimal : "+z);
System.out.println("HexaDecimal : "+a);
System.out.println("Binary : "+b);
}
}
Example:
class Test {
public static void main(String[] args) {
double x = 12.3;
double y = 12.3e3; // 12.3*10**3
double z = 12.3e+3; // 12.3*10**3
double a = 12.3e-3; // 12.3/10**3
Character Literal:
• Represent single characters enclosed in single quotes.
• Can be a character literal or an escape sequence
class Test {
public static void main(String[] args) {
char x = 'N'; // Single Character
Example:
[email protected] Cell: 78 42 66 47 66
Leela Soft Core Java (J2SE) Madhusudhan
class Test {
public static void main(String[] args) {
char x1 = 'N'; // Single Character
char x2 = '/'; // Single Character
char x3 = '"'; // Single Character
char x4 = '\\'; // Single Character
char x5 = '\''; // Single Character
Boolean Literals:
• True or False value representation.
Example:
class Test {
public static void main(String[] args) {
boolean x1 = true;
boolean x2 = false;
String Literals:
• Enclosed with in the double quotes.
Example:
class Test {
public static void main(String[] args) {
String x1 = "Java";
String x2 = "Python";
Example:
class Test {
public static void main(String[] args) {
[email protected] Cell: 78 42 66 47 66
Leela Soft Core Java (J2SE) Madhusudhan
String x1 = "Java'";
String x2 = "Python\"\"";
String x3 = "Python\\";
[email protected] Cell: 78 42 66 47 66