What are Literals in java - Integer, Floating-Point, Character and String literal, Escape sequence in java

Literals in java >

  • primitive types are special data types in java.
  • primitive types are created without using new keyword.
  • primitive types are not objects.
  • A literal is the source code representation of a fixed value; literals are represented directly in your code without requiring computation
Example -
byte b = -128 ;
short s = -32768;
int i = -2147483648;

Integer Literals >

Integer literal is of type long if it ends with the L or l, otherwise it is int type.
int literals can be used to create values of the byte, short, int, and long types.

Integer literals can be expressed by these number systems:
  • Decimal (Base 10) -  digits between 0 through 9
  • Hexadecimal (Base 16) - digits between 0 to 9  & letters between  A to F
  • Binary (Base 2) in java 7 - digits 0 and 1.
Example -
            int decimalInt = 26; //decimal
          int hexaDecimalInt = 0x1c; //hexadecimal
          int binaryInt = 0b11100; //binary


Program - How to convert >
  • decimal to hexaDecimal (using Java API)
  • decimal to binary (using Java API)
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class Conversions {
   public static void main(String[] args) {
         
          int i =28; //decimal
          //decimal to hexaDecimal conversion
          String hexaDecimalInt  = Integer.toHexString(i);
          System.out.println("hexaDecimal > " + hexaDecimalInt); //1c
          //decimal to binary conversion
          String binaryInt  = Integer.toBinaryString(i);
          System.out.println("binary   > " + binaryInt ); //11100
   }
}
/*OUTPUT
hexaDecimal  > 1c
binary   > 11100
*/

Floating-Point Literals
A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.
A floating-point literal is double by default (optionally, we may use D or d)
If floating-point literal is float if and only if it ends with F or f.
The floating-point types can be expressed using scientific notation (E or e)

double d = 131.4;  //floating-point literal 131.4 is double by default
float f  = 131.4f; //floating-point literal 131.4f is float
// using d in scientific notation (Note: d is equal to d1)
double d1 = 1.314e2;  //1.314e2 = 1.314 * 100


Character and String Literals >

char and String type literals contain any Unicode (UTF-16) characters.
If editor and file system allow it, you can use such characters directly in your code.

We must always use >
  • 'single quotes' for char literals and
  • "double quotes" for String literals.

Escape sequence in java >
Escape sequence
Description
\n
new line
\t
tab
\b
backspace


\'
single quote
\"
double quote


\\
backslash
\s
space


\r
carriage return
\f
formfeed

No comments:

Post a Comment