Data Types and Operators in Java

Data types are responsible for holding the data during the execution of the program and operators performing operations. As we know Java is a statically typed language because each data type is predefined.

Data Types in java are similar to C++ except few.

Mainly Java has two types of Data Types

Primitive Data Types

This is predefined data types available in Java. There are total of 8 primitive data types.

TypeDescriptionDefaultSizeExamples
booleantrue or falsefalse1 bittrue, false
bytetwo’s complement integer08 bits(none)
charunicode character\u000016 bits‘a’,’\n’,’\u0041′
shorttwo’s complement integer016 bits(none)
inttwo’s complement integer032 bits-1,0,1
longtwo’s complement integer064 bits-1L,0L,1L
floatIEEE 754 floating point0.032 bits-1.23e100f,2.45e100f
doubleIEEE 754 floating point0.064 bits-3.45e300d,4.56e245d

Now, we are going to discuss each of data types in details.

boolean:

boolean represents only one bit of information. you must initialize the boolean variable before access. You can not convert boolean variables into any data type variables.

import java.io.*; 

public class GeeksToCode { 
	public static void main(String args[]) 
	{ 

	 boolean bool= false;
		System.out.println(bool); 
	} 
} 

Check Output here

byte

byte data type has a size of 8 bits. The byte data type is useful for saving memory in large arrays. It’s value ranges from -128 to 127

import java.io.*; 

public class GeeksToCode { 
	public static void main(String args[]) 
	{ 

	 byte bt = 127;
		System.out.println(bt);
		
	bt++;
	System.out.println(bt);
	
	bt++;
	System.out.println(bt);
	} 
} 

Predict the output and check your answer

short

The short data type has a size of 16 bit. Similar to byte, use a short to save memory in large arrays, in situations where the memory savings actually matters. It’s value is from -32,768 to 32,767 (inclusive)

import java.io.*; 
//geekstocode.com
public class GeeksToCode { 
	public static void main(String args[]) 
	{ 

	 short bt = 32766;
		System.out.println(bt);
		
	bt++;
	System.out.println(bt);
	
	bt++;
	System.out.println(bt);
	} 
} 

predict the output and check your answer here

int:

The short data type has a size of 32 bit. It’s value is from -231 to 231-1 (inclusive)

import java.io.*; 
//geekstocode.com
public class GeeksToCode { 
	public static void main(String args[]) 
	{ 

	 int bt = 845784;
		System.out.println(bt);
		
	bt++;
	System.out.println(bt);
	
	bt--;
	System.out.println(bt);
	} 
} 

Please predict the answer and check here

long:

The short data type has a size of 64 bit. It’s value is from -263 to 263-1.

float:

The float data type is a single-precision 32-bit IEEE 754 floating point. Use a float (instead of double) if you need to save memory in large arrays of floating point numbers.

  • Size: 32 bits
  • Suffix : F/f Example: 9.8f

double:

The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this data type is generally the default choice.

Note: Both float and double data types were designed especially for scientific calculations, where approximation errors are acceptable. If accuracy is the most prior concern then, it is recommended not to use these data types and use BigDecimal class instead.


char:

The char data type is a single 16-bit Unicode character. A char is a single character.

  • Value: ‘\u0000’ (or 0) to ‘\uffff’ 65535

Operators in Java

Java gives numerous types of operators which can be utilized by their need. They are classified according to their use. Generally utilized operators are examined beneath :

Arithmetic Operators

They are utilized to perform straightforward arithmetic operations on different data types.

  • * : Multiplication
  • / : Division
  • % : Modulo
  • + : Addition
  • – : Subtraction

// Java program to illustrate
// arithmetic operators
public class operators 
{
    public static void main(String[] args) 
    {
        int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
        String x = "Thank", y = "You";

        // + and - operator
        System.out.println("a + b = "+(a + b));
        System.out.println("a - b = "+(a - b));

        // + operator if used with strings
        // concatenates the given strings.
        System.out.println("x + y = "+x + y);

        // * and / operator
        System.out.println("a * b = "+(a * b));
        System.out.println("a / b = "+(a / b));

        // modulo operator gives remainder
        // on dividing first operand with second
        System.out.println("a % b = "+(a % b));

        // if denominator is 0 in division
        // then Arithmetic exception is thrown.
        // uncommenting below line would throw
        // an exception
        // System.out.println(a/c);
    }
}

Check The Output Here

Unary Operators

Unary operators needs just a single operand. They are utilized to addition, decrement or negate a value

  • ( – )Unary minus, It negates the values
  • ( + )Unary plus, It is used for giving positive values. It is only used when you need to convert negative values to positive ones.

  • (++)Increment operator, This is used for incrementing the value by 1. There are two types of increment operator.
  • Post-Increment: Value is first used for computing the result and then incremented.
  • Pre-Increment: Value is incremented first and then the result is computed.
  • (–) Decrement operator, used for decrementing the value by 1. There are two varieties of decrement operator.
  • Post-decrement : Value is first used for computing the result and then decremented.
  • Pre-Decrement : Value is decremented first and then result is computed.

(!)Logical not operator, used for inverting a boolean value.


// Java program to illustrate
// unary operators
public class operators 
{
    public static void main(String[] args) 
    {
        int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
        boolean condition = true;

        // pre-increment operator
        // a = a+1 and then c = a;
        c = ++a;
        System.out.println("Value of c (++a) = " + c);

        // post increment operator
        // c=b then b=b+1
        c = b++;
        System.out.println("Value of c (b++) = " + c);

        // pre-decrement operator
        // d=d-1 then c=d
        c = --d;
        System.out.println("Value of c (--d) = " + c);

        // post-decrement operator
        // c=e then e=e-1
        c = e--;
        System.out.println("Value of c (e--) = " + c);

        // Logical not operator
        System.out.println("Value of !condition =" + !condition);

    }
}

Check The Output Here

Assignment Operator :

As name suggest, assignment operator is used to assign the right hand side values on the left side.

value given on right hand side of operator is assigned to the variable on the left and therefore right hand side value must be declared before using it or should be a constant.

Syntax of assignment operator is,

variable = value;

The assignment operator can also be combined with other operators to build a shorter version of the statement called as Compound Statement

Compound Statement.

For example, instead of a = a+5 , we can write a += 5.

  • +=, This is for adding left operand with right operand and then assigning it to the variable on the left.
  • -=, This is for subtracting left operand with right operand and then assigning it to the variable on the left.
  • *=, This is for multiplying left operand with right operand and then assigning it to the variable on the left.
  • /=, This is for dividing left operand with right operand and then assigning it to the variable on the left.
  • %=, This is for assigning modulo of left operand with right operand and then assigning it to the variable on the left.

// Java program to illustrate
// assignment operators
public class operators 
{
    public static void main(String[] args) 
    {
        int a = 20, b = 10, c, d, e = 10, f = 4, g = 9;

        // simple assignment operator
        c = b;
        System.out.println("Value of c = " + c);

        // This following statement would throw an exception
        // as value of right operand must be initialised
        // before assignment, and the program would not
        // compile.
        // c = d;

        // instead of below statements,shorthand
        // assignment operators can be used to
        // provide same functionality.
        a = a + 1;
        b = b - 1;
        e = e * 2;
        f = f / 2;
        System.out.println("a,b,e,f = " + a + "," 
                           + b + "," + e + "," + f);
        a = a - 1;
        b = b + 1;
        e = e / 2;
        f = f * 2;

        // shorthand assignment operator
        a += 1;
        b -= 1;
        e *= 2;
        f /= 2;
        System.out.println("a,b,e,f (using shorthand operators)= " + 
                            a + "," + b + "," + e + "," + f);
    }
}

Predict the output and check result here

Relational Operators :

These operators are used to check for relations like equality, greater than, less than. They return boolean results after the comparison and are extensively used in looping statements as well as conditional if-else statements. The general format is,

variable relation_operator value 

Some of the relational operators are-

  • ==, Equal to: returns true of the left-hand side is equal to the right-hand side.
  • !=, Not Equal to: returns true of the left-hand side is not equal to the right-hand side.
  • <, less than: returns true of the left-hand side is less than the right-hand side.
  • <=, less than or equal to returns true of the left-hand side is less than or equal to the right-hand side.
  • >, Greater than: returns true of the left-hand side is greater than the right-hand side.
  • >=, Greater than or equal to returns true of the left-hand side is greater than or equal to the right-hand side

Logical Operators :

These operators are used to perform “logical AND” and “logical OR” operation, i.e. the function similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e. it has a short-circuiting effect. Used extensively to test for several conditions for making a decision.
Conditional operators are-

  • && , Logical AND : returns true when both conditions are true.
  • || , Logical OR : returns true if at least one condition is true.

Ternary operator :

The ternary operator is a shorthand version of the if-else statement. It has three operands and hence the name ternary. The general format is-

condition ? if true : if false

The above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else execute the statements after the ‘:’.

Bitwise Operators :

These operators are used to perform manipulation of individual bits of a number. They can be used with any of the integer types. They are used when performing updates and query operations of the Binary indexed tree.

  • &, Bitwise AND operator: returns bit by bit AND of input values.
  • |, Bitwise OR operator: returns bit by bit OR of input values.
  • ^, Bitwise XOR operator: returns bit by bit XOR of input values.
  • ~, Bitwise Complement Operator: This is a unary operator that returns the one’s complement representation of the input value, i.e. with all bits inverted.

Shift Operators :

These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two. General format-

 number shift_op number_of_places_to_shift;
  • << , Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as of multiplying the number with some power of two.
  • >> , Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit depends on the sign of initial number. Similar effect as of dividing the number with some power of two.
  • >>> , Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit is set to 0.

Leave a Comment

Your email address will not be published. Required fields are marked *