Data types and Literals in Java

Data types

Data types category: 

Data types summary:


A constant value which can be assigned to variable is called "Literal".

Integral Literals

All possible value of Integral data type(byte, short, int and long) are called Integral Literals.

Default Value:

By default every Integral literal is int type. When you assign a value in long data byte and that value is more than 2147483647(Maximum value for int) then compiler will give you error.

long a = 3000000000;

Error: The literal 3000000000 of type int is out of range 
Even though we have used long data type and value is also within range of long but still compiler gives error because every integral literal is int type.
We can resolve this error by specifying long type explicitly. We can specify long type by suffixing l or L.

long a = 3000000000L;

Number System:

Integral Literal can be represented as Decimal, Octal and Hexadecimal number systems.
Let's see how to specify literal values in different number systems - 
  1. Decimal literals:
  2.     - Allowed digits are 0 to 9
                int a = 10;
  3. Octal literals:
  4.     - Allowed digits are 0 to 7
        - Literals value must be prefixed with 0.
                int a = 010;
          Output: 8

  5. Hexadecimal:

  6.     - Allowed digits are 0 to 9, a to f and A to F.
        - Literal must be fixed with 0x or 0X
             int a = 0X10
         Output: 16

Floating Point Literals

Default Value

Every floating point literal is by default double type. We can't assign floating point literal directly to float variable. Below statement will give you compilation error.

float a = 10.2;

Error: Type mismatch: cannot convert from double to float

You can resolve this error by suffixing F or f.

float a = 10.2F;

Number System

You can't specify floating point literals in Octal or Hexadecimal. You can specify only in decimal form.

Note: You can assign integral literals in floating point data types and that integral literal can be specified in decimal, octal and hexadecimal form.

Scientific Form

It is also possible to specify floating point literal in scientific form as well.
double a = 1.2e3;

Output: 1200.0

Boolean Literals

There are 2 possible value for boolean literal - true/false.
In some languages, integer can be used to represent boolean condition. One example is C language, where non-zero value is always true. But in Java, you can either use true or false to represent boolean.

Character Literals

A Character Literal can be represented as single character within single quotes.
char ch = 'A';

You can assign integer literal into char data type. Integer literal within char data type represent unicode of character and can be specified as Decimal, Octal and Hexadecimal. 
char ch = 65;

Output: A


Post a Comment

Popular posts from this blog

equals() method of Object class in Java

Create your own LinkedList in Java