LightBlog

Java Fundamentals - Literals


A literal represents a constant value which can be assigned to the variables
int x = 10;  
int – Datatype, x – variable, 10 – Literal


1.Integral Literal:
We can specify an integral literal in the following ways.
  • Decimal literals: allowed digits are 0 to 9
  • Binary literals (digits 0–1): which uses the number 0 followed by b or B as a prefix—for example, 0b10
  • Octal literals (digits 0–7) : which uses the number 0 as a prefix—for example, 017
  • Hexadecimal literals (digits 0–9 and letters A–F), which uses the number 0 followed by x or X as a prefix—for example, 0xFF
System.out.println(56); // 56
System.out.println(0b11); // 3
System.out.println(017); // 15
System.out.println(0x1F); // 31

By default every integral lateral is of int datatype we can specify explicitly. An integral literal is of long type by suffixing with l or L.
·         10 - int value.
·         10L -  long value
There is no way to specify explicitly an integral literal is of type byte and short. If the integral literal is with in the range of byte then the JVM by default treats it as byte literal.


2.Floating – Point literals
By default floating-point literals are double type we can specify explicitly as float type by suffixing with ‘f’ or ‘F’.
float f = 10.5;  // C.E possible loss of precision
float f = 10.5f;

Floating point literals can be specified only in decimal form. i.e we can’t use octal and hexa decimal representation for floating point literals. But we can assign Octal & hexa interger values to float.
Double d = 0x123.456; // C.E Invalid hex literal number
Double d = 0x123;

added in Java 7. You can have underscores in numbers to make them easier to read:
int million1 = 1000000;
int million2 = 1_000_000;

double notAtStart = _1000.00; // DOES NOT COMPILE
double notAtEnd = 1000.00_; // DOES NOT COMPILE

double notByDecimal = 1000_.00; // DOES NOT COMPILE
double annoyingButLegal = 1_00_0.0_0; // this one compiles


3. Character literal
A char literal can be represented as a single character with in single quotes.
char ch = 'a';
char ch = 'ab'; C.E: unclosed character literal.

we can represent a char literal by it’s Unicode value. For the allowed Unicode values are 0 to 65535.
char ch = 97;
System.out.println(ch); O/P: a
char ch = 65535;
char ch = 65536; C.E : possible loss of precision found : int required :char

we can represent a char literal by using Unicode representation which is nothing but \uxxxx’(0-F)
char ch = '\u0061'
System.out.println(ch); --> O/P:a
char ch = '\ubeef';
char ch = '\uface';

we can also represent a char literal by using escape character.
char ch = '\b';
char ch = '\n';
char ch = '\l';

Share on Google Plus

About Unknown

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment