/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2016 * Time: 8:09 PM */ Core Java test2 Java Tech Tutorials

Literals, Operators and type Casting

Core Java

Literals in Java

A constant value in a program is denoted by a literal. Literals represent numerical (integer or floating-point), character, boolean or string values.

Integer literals :-

A whole number, such as 123 and -456, is treated as an int by default. In Java, the range of 32-bit int literals is -2,147,483,628 (-2^31) to 2,147,483,627 (2^31-1). For example,

		int number = -123;
		int sum = 1234567890;     // This value is within the range of int
		int bigSum = 8234567890;  // ERROR: this value is outside the range of int
		int number = 1234;   // Decimal
		int number = 01234;  // Octal 1234, Decimal 2322
		int number = 0x1abc; // hexadecimal 1ABC, decimal 15274
		// from (JDK 1.7)
		int number1 = 0b01010000101000101101000010100010;
		int number2 = 0b0101_0000_1010_0010_1101_0000_1010_0010; //break the digits with underscore (JDK 1.7)
		int number3 = 2_123_456;  // break the digits with underscore (JDK 1.7)
		long bigNumber = 1234567890123L;  // Suffix 'L' needed
		long sum = 123;                   // int 123 auto-casts to long 123L
		byte smallNumber = 12345;     // ERROR: this value is outside the range of byte.
		byte smallNumber = 123;       // This is within the range of byte
		short midSizeNumber = -12345;

(JDK 1.7) From JDK 7, you can use prefix '0b' or '0B' to specify a value in binary. You are also permitted to use underscore (_) to break the digits into groups to improve the readability. But you must start and end the literal with a digit. As above Example shown

Floating-point literals :-

A number with a decimal point, such as 55.66 and -33.44, is treated as a double, by default. You can also express them in scientific notation, e.g., 1.2e34, -5.5E-6, where e or E denotes the exponent in power of 10.
You could precede the fractional part or exponent with a plus (+) or minus (-) sign. Exponent values are restricted to integer. There should be no space or other characters in the number. You can optionally use suffix 'd' or 'D' to denote double literals.
You MUST use a suffix of 'f' or 'F' for float literals, e.g., -1.2345F. For example,

		float average = 55.66;      // Error! RHS is a double. Need suffix 'f' for float.
		float average = 55.66f;

Character Literals :-

A printable char literal is written by enclosing the character with a pair of single quotes, e.g., 'z', '$', and '9'. In Java, characters are represented using 16-bit Unicode, and can be treated as a 16-bit unsigned integers in arithmetic operations. In other words, char and 16-bit unsigned integer are interchangeable. You can also assign an integer in the range of [0, 65535] to a char variable.
For example,

		char letter = 'a';                 // Same as 97
		char anotherLetter = 98;           // Same as the letter 'b'
		System.out.println(letter);        // 'a' printed
		System.out.println(anotherLetter); // 'b' printed instead of the number
		anotherLetter += 2;                // 100 or 'd'
		System.out.println(anotherLetter); // 'd' printed

String Literals :-

A String literal is composed of zero of more characters surrounded by a pair of double quotes, e.g., "Hello, world!", "The sum is ".
For example

	String directionMsg = "JavaEssential.com";
	String greetingMsg = "Hello";
	String statusMsg = "";             // empty string

	System.out.println("Use \\\" to place%n a \" within\ta\tstring");

String literals may contains escape sequences. Inside a String, you need to use \" for double-quote to distinguish it from the ending double-quote, e.g. "\"quoted\"". Single quote inside a String does not require escape sequence. As shwon in above Example,

boolean Literals :-

There are only two boolean literals, i.e., true and false.
For example,

		boolean done = true;
		boolean gameOver = false;

		public class LiteralTest {
		   public static void main(String[] args) {
		      String name = "Rajesh kumar "; // String is double-quoted
		      char gender = 'm';           // char is single-quoted
		      boolean isMarried = true;    // true or false
		      byte numChildren = 8;        // Range of byte is [-127, 128]
		      short yearOfBirth = 1945;    // Range of short is [-32767, 32768]. Beyond byte
		      int salary = 88000;          // Beyond the ranges of byte and short
		      long netAsset = 8234567890L; // Need suffix 'L' for long. Beyond int
		      double weight = 88.88;       // With fractional part
		      float gpa = 3.88f;           // Need suffix 'f' for float
		      // println() can be used to print value of any type
		      System.out.println("Name is " + name);
		      System.out.println("Gender is " + gender);
		      System.out.println("Is married is " + isMarried);
		      System.out.println("Number of children is " + numChildren);
		      System.out.println("Year of birth is " + yearOfBirth);
		      System.out.println("Salary is " + salary);
		      System.out.println("Net Asset is " + netAsset);
		      System.out.println("Weight is " + weight);
		      System.out.println("GPA is " + gpa);
		Output :- 
		Name is Rajesh kumar
		Gender is m
		Is married is true
		Number of children is 8
		Year of birth is 1945
		Salary is 88000
		Net Asset is 1234567890
		Weight is 88.88
		Height is 188.8

Operators in Java :-

Arithmetic Operators :-


Increment and Decrement Operator :-

Java supports these unary arithmetic operators: increment '++' and decrement '--' for all numeric primitive types (byte, short, char, int, long, float and double, except boolean)
This one is most confused of operators , see the table below to get some idea


The increment (++) and decrement (--) operate on its operand and store the result back to its operand.
For example, x++ retrives x, increment and stores the result back to x.

	x = 5;
	System.out.println(x++);  // Print x (5), then increment x (=6). Output is 5. (x++ returns the oldX.)
	x = 5;
	System.out.println(++x);  // Increment x (=6), then print x (6). Output is 6. (++x returns x+1.)

String Concatenation Operator (+) :-

Its overloaded operator in java, it atleast one operand is String then it acts as String Concatenation operator and if both argumrnts are number type then + operators acts as arithmetic operator.

class StringConcatTest 
		public static void main(String[] args) 
			String a = "javaEssential";
			int b = 10, c = 20, d = 30;
			System.out.println(a+b+c+d);	//string!
			System.out.println(a+c+d);	//String!
			System.out.println(b+c+d);	//number!
			System.out.println(a+d);	//String!
			System.out.println(c+d);	//Number!

You will get atleast one Question from String Concatenation Topic in OCJP { 100% }

Relational Operators :-

(< , <= , > , >= , ==, != )

// Return true if x is between 0 and 100 (inclusive)
(x >= 0) && (x <= 100)
// wrong to use 0 <= x <= 100
// Return true if x is outside 0 and 100 (inclusive)
(x < 0) || (x > 100)   //or
!((x >= 0) && (x <= 100))
// Return true if year is a leap year
// A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.
((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)

Equality Operators :-

Bitwise Operators :-

&(AND) , | (OR) , ^ (XOR) are known as bitwise operators.
We can apply bitwise operators to Integral type too

Bitwise Operators Example

class BitwiseTest 
	public static void main(String[] args) 
		System.out.println(true & true);
		System.out.println(true & false);
		System.out.println(true | true);
		System.out.println(true | false);
		System.out.println(true ^ true);
		System.out.println(true ^ false);
		System.out.println(false ^ false);
		System.out.println(4 & 5);//since (100) AND (101) is 100
		System.out.println(4 | 5); //since (100) OR (101) is 100
		System.out.println(4 ^ 5); //since (100) XOR (101) is 100

Bitwise Complement Operator (~)

We cannot apply this operator only for integral types

class BitwiseExample 
	public static void main(String[] args) 
		System.out.println(~ 4);//-5	

How ~4 is -5 ?
4 is represented as 000………0100 (in 32 bits).
MSB here is 0 that means this is a positive number if we apply bitwise complement to the above number it becomes 111….1011. Notice now the MSB is 1, it means now the number is negative and negative numbers are always represented in 2′s complement form.
111….1011 is in 2′s complement so number is 1′s complement + 1
i.e. 000….0100+1 which is equal to 5 and since MSB is 1 the result i -5.

Type Casting :-

In Java, you will get a compilation error if you try to assign a double value of to an int variable. This is because the fractional part would be lost. The compiler issues an error "possible loss in precision". For example,

	double f = 3.5;
	int i;
	i = f;            // Compliation Error: possible loss of precision (assigning a double value to an int variable)
	int sum = 55.66f; // Compliation Error: possible loss of precision (assigning a float value to an int variable)
Type-casting forces an explicit conversion of the type of a value. Type-casting is an operation which takes one operand. It operates on its operand, and returns an equivalent value in the specified type. Take note that it is an operation that yield a resultant value, similar to an addition operation although addition involves two operands. Java supports two types of castings – primitive data type casting and reference type casting. Reference type casting is nothing but assigning one Java object to another object. It comes with very strict rules we will explain it later in Object Casting. Now let us go for data type casting.

There are two kinds of primitive Data type-casting in Java:

Explicit Type-Casting :-

(narrowing conversion)
A data type of higher size (occupying more memory) cannot be assigned to a data type of lower size. This is not done implicitly by the JVM and requires explicit casting. a casting operation to be performed by the programmer. The higher size is narrowed to lower size. To assign the a double value to an int variable, you need to invoke the so-called type-casting operator - in the form of prefix (int) - to operate on the double operand and return a truncated value in int type. In other words, you concisely perform the truncation. You can then assign the truncated int value to the int variable. For example,

double f = 3.5;
int i;
i = (int) f;  // Cast double value of 3.5 to int 3. Assign the resultant value 3 to i
                  // Casting from double to int truncates.

Implicit Type-Casting in Assignment :-

(widening conversion)
A data type of lower size (occupying less memory) is assigned to a data type of higher size. This is done implicitly by the JVM. The lower size is widened to higher size. This is also named as automatic type conversion.


	int i = 3;
	double f;
	f = i;         // OK, no explicit type casting required
	                // f = 3.0
	f = (double) i;  // Explicit type casting operator used here
	double aDouble = 55;   // Compiler auto-casts to 55.0
	double nought = 0;     // Compiler auto-casts to 0.0, int 0 and double 0.0 is different.
	double average = (double)sum / count;  // Assume sum and count are int

The following diagram shows the order of implicit type-casting performed by compiler. The rule is to promote the smaller type to a bigger type to prevent loss of precision, known as widening conversion. Narrowing conversion requires explicit type-cast to inform the compiler that you are aware of the possible loss of precision. Take note that char is treated as an 16-bit unsigned integer in the range of [0, 65535]. boolean value cannot be type-casted (i.e., converted to non-boolean).


Example of Implicit Type casting

	public class SumTest {
   	public static void main(String[] args) {
      int sum = 0;
      double average;
      int number = 1;
      while (number <= 100) {
         sum += number;      // Final sum is int 5050
      average = sum / 100;   // Won't work perfect (average = 50.0 instead of 50.5)
      System.out.println("Average is " + average);  // Average is 50.0
      average = (double)sum / 100;   
      System.out.println("Average2 is " + average); // Cast sum from int to double before division
      										//Average is 50.5
      average = sum / (double)100;
      System.out.println("Average3 is " + average); //Average is 50.5

For method overloading and Overriding please referer OOP concept

Click here to access OOp's Concept

feel free to ask any of your doubts