Alphalearningschool
        

<<< Prev

Next >>>

Up
Java Data Types

Need of data types

Data Types are used to store data temporarily in computer through a program.

 In real world we have different types of data like integer, floating-point, character, boolean, and string, etc. To store all these types of data in program to perform business required calculation and validations we must data types concept.

 Definition of data type

Data types is something which gives information about

  • Size of the memory location and range of data that can be accommodated inside that location.
  • Possible legal operations those can be performed on that location.

                      For Example: on boolean data we cannot perform addition operation.

  • What type of result comes out from an expression when these types are used in side that expression.

Different java data types

In java mainly we have two types of data types

  • Primitive data types (8 sub types) -   used to store single value at a time.
  • Non -primitive data types (4) - used to collect multiple of values using primitive types.

Data types Hierarchy

1. Primitives Data types:

  • The primitive data types are the predefined data types given by the programming language and they are meant for storing a single value.
  • Based on the type and range of data, primitive types are divided into 8 types.

Integer category: 

  • This category can be used for storing numbers which can be either positive value  or negative value without decimal points.
  • In this category we have 4 primitive data types whose memory sizes are different. 
  • All the 4 types under this category are used for storing same data. But there ranges are different. The java language is providing 4 types under Integer category. So that the memory is utilized efficiently. 
  1. byte  
  2. short
  3. int
  4. long 
  1. i) byte data type in java: 
  • Size 1 byte. i.e 8 bits
  • Minimum value is -128 (-2^7)
  • Maximum value is 127 (2^7 -1)
  • Default value is 0.
Example:

Class Byte Demo {

   public static void main(String[] args) {

    byte x=10;

    byte y=20;

 

 byte z= (byte) (x+y);

 System.out.prtinln (z);

}

}

   Output: 30

  

  1. ii)  Short data type in java:
  • Size 2 bytes.
  • Minimum value is -32,768 (-2^15)
  • Maximum value is 32,767 (2^15-1)
  • Default value is 0
Example:

      Class ShortDemo {

public static void main(String[] args) {

  short x=20;

  short y=20;

         short z= (short) (x+y);

         System.out.println(z);

}

          }

Output: 40

 

  int data type in java:

  • Size 4 bytes.
  • Minimum value is - 2,147,483,648.(-2^31)
  • Maximum value is 2,147,483,647 (2^31 -1)
  • Default value is 0
Example:

Class IntDemo {

 public static void main(String[] args) {  

int x=15;

 int y=20;

     int z=x+y;

    System.out.println(z);

  }

}

Output:   35

 

long data type in java:

  • Size 8 bytes.
  • Minimum value is -9,223,372,036,854,775,808.(-2^63)
  • Maximum value is 9,223,372,036,854,775,807 (2^63 -1)
  • Default value is 0
Example:

Class LongDemo {

public static void main(String[] args)

{

 long x=109876677777l;

 long y=20666677766l;

  long z=x+y;

 System.out.println(z);

}

}

Output:   130543355543

 

Floating point category: 

  • This category can be used for storing numbers which can be either +VE or –VE with decimal point. In the floating point category we have two types whose size is different. The two data types are float and double.
  • Default value of float is 0
  • Default value of double is 0.0 
  1. float
  2. double

 Float data type in java:

  • Size 4 bytes.
  • Minimum value is 1.4e-45
  • Maximum value is 3.4e38
  • Default value is 0.0f
Example:

Class FloatDemo {

public static void main(String[] args) { float x=231231.0031f;

float y= 53423423434.43231f;

float z= x+y;

System.out.println(z);

}

}

Output: 5.3423653E10

 

double data type in java:

  • Size 8 bytes.
  • Minimum value is 4.9e-324
  • Maximum value is 1.8e308
  • Default value is 0.0d
Example:

Class DoubleDemo {

public static void main(String[] args) {

double x=231231.0031f;

double y= 53423423434.43231f;

 double z= x+y;

 System.out.println(z);

 }

}

Output: 5.34236546654354

 

Character category: 

  • This category can be used for storing a single character. A character can be represented by alphabets, a digit and special symbols. 
  • This category contains only one data type an it is char.
  • Default value of char is "one space"
  1. char


char data type in java:

  • Size 2 bytes.
  • Minimum value is 0
  • Maximum value is 65,535
  • Default value is ' '
Example:

Class Char Demo {

public static void main(String[] args) {

 char a='a';

 System.out.println(a);

 }

}
Output: a

 

Boolean category: 

  • This category can be used for storing either true or false. Under the Boolean category only one data type an it is Boolean. The size is dependent on JVM to JVM.

boolean data type in java:

  • boolean data type represents one bit of information.
  • There are only two possible values: true and false.
  • This data type is used for simple flags that track true/false conditions.
  • Default value is false. '
Example:

Class CharDemo {

Public static void main(String[] args) {

boolean x= false;

System.out.println (x);

}
 }

Operators in java

What is an operator and what is the use of it?

A symbol or a word that performs a specific operation on one or two or three operands and then returns a result is called operator.  An operator is used for performing validations and calculation on the given input value.

  • Validation means checking given input value is our expected value or not.
  • Calculation means performing one operation and generating result.
Performing calculation

For Example:

          int x =30+40;

Performing Validation

                               

    if(x == 70){  

         System.out.println("Hi");

           }

         else{

          System.out.println("Hello");

          }                   


Using operators we will perform three operations:

  1. Validation
  2. Calculations
  3. Result storing 
  • The operators those perform validations will return boolean type result true/false. So these operators are also called boolean operators.

For Example:

      <, > , == ,!=, etc….are validations operators generates boolean type result. 

  • The operators those perform calculations will return number type result.

For Example:

     +, - , * , / , % , & , | ,…. are calculations operators which generate number type result. 

  • The operator store result in destination variable will return the   copying value as

Result. So it does not have any specific result type. This operator is called as assignment operator

   For Example:

   “=” is assignment operators means for storing result value in a variable.

 What is an operand and what is the use of it?

 A literal or a variable or a method call that is used with an operator to perform validations and calculations are called operand.

 For Example:

            int c =10+20// Here the variable c and the values 10 and 20 are operands

 What is an expression and what is the use of it?

The combination of operators and operands is called an expression. It is used for grouping operators and operands to perform validations and calculations. Expression evaluates to a single value   

For Example:

                int x =10+20;   //This statement is called expression and “=” & “+”  are operators            

                                            // variable c and the values 10 and 20 are operands

Types of operators

Based on number of operators accepts by an operator, operators are divided into three types

            1) Unary operators

            2) Binary operators

            3) Ternary operators

  • An operator that can take only one operand is called unary operator.

We can place unary operator either before or after given operand.

 For Example:  +a, -a, !true, ++a, --a, a++, a--, new Employee();

  • An operator that takes two operands is called binary operator.

We can place binary operator only in between two operands.

For Example:    a+ b, a – b, a< b, a == b, a & b, etc…

  • An operator that takes three operands is called ternary operator.

A ternary operator will contains two operators.

(? :) is ternary operator, it has two operator (? and : )

Ternary operator should be placed between three operands

 

Ternary operator execution flow

If result is true,  exp 1 ,exp 2 is executed

If result is true,  exp 1 ,exp 3is executed

 

For example:

exp1      ?       exp2:          exp3                                                                          

 Ternary operator is an alternative way of creating if-else condition

For example:

exp1      ?       exp2:          exp3                                                                          

Ternary operator is an alternative way ofcreating if-else condition

 int a =10;

  int  b;

    if(a == 10){

       b =10;

   }else{

       b=20;

}

System.out.prtinln(b); 

For example:

 int a = 10;

 int  b;

 b= (a == 10)? 5:6;

System.out.prtinln (b);

 

public class Test {

     public static void main(String[] args ) {

            //unary operators

           System.out.prtinln ("Unary operator");

           int   i1   = +5;     System.out.prtinln (i1);

           int    i2 = -6;     System.out.prtinln (i2);

           boolean b1 = !true; System.out.prtinln n(b1);  

            System.out.prtinln ();

             //binary operator

     System.out.prtinln ("binary operator");

     int     i3 =7 + 8; System.out.prtinln (i3);

     int     i4 = 7 & 8; System.out.prtinln (i4);

     boolean b3 = 7 < 8; System.out.prtinln (b3);

     boolean b4 = 7 == 8; System.out.prtinln (b4);   

       System.out.prtinln ();  

      // ternary operator

      System.out.prtinln ("Ternary operator");

      System.out.prtinln (true? "Hi": "Hello");

      System.out.prtinln (false? "Hi": "Hello");

      String s1= true? "Hi" :"Hello";

      String s2 =false ? "Hi" : "Hello";

      System.out.prtinln (s1);

      System.out.prtinln (s2);;

      String s3 = true? "Hi":"Hello";

      System.out.prtinln (s3);

      String s4;

      if(true) {

            s4="Hi";

      }else {

            s4="Hello";

      }

      System.out.prtinln (s4);

      }

}

Output:

Unary operator
5
-6
false

binary operator
15
0
true
false

Ternary operator
Hi
Hello
Hi
Hello
Hi
Hi

Java supports 39 operators

 All these 39 operators are categorized into 12 separate groups based on their functionality

Arithmetic operators are used for simple arithmetic operations. The various operators are represented by the symbols:

Description                    Operator

Addition                                 +                      1 + 1 = 2

Subtraction                              -                       2 - 1 = 1

Multiplication                          *                      2 * 3 = 6 (same as 2 X 3 = 6) 

Division                                   /                       6 / 2 = 3

Modulus                                  %                     7 % 2 = 1

The modulus operator gives the remainder when a division operation is performed.

import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {

Scanner scanner = new Scanner (System. in);

System.out.println ("Enter a number: ");

double numberl = scanner.nextDouble();

System.out.println ("Enter another number:");

double number2 = scanner.nextDouble();

System.out.println ("The result is:" + (numberl - number2) );

                }

}

 Output:

Enter a number: 
3
Enter another number:
2
The result is:1.0

The -+- operator can be used in a different context in print statements-to concatenate different types. For example, the following statement concatenates the string "The result is:" with the result of the subtraction number1 -number2: 

"The result is:" + (number1 - number2) 

You can also pass primitive types as arguments to the print and print.ln methods. Therefore, the following arguments are all valid: 

int x = 10, Y = 20; String s = "30";

System.out.println(x); // prints out 10

System.out.println(x + y + x); // prints out 40

System.out.println(s + x + x); // prints out 301010

In the last statement, the + operator performs a concatenation because the first argument s is of type String.

Working with System.out.println

 Using System.out.println statement we can print all types of literals

  • Directly
  • Using variable
  • Using expression
  • Using non-void methods

Increment and decrement operator 

Example:

public class Incredecrement {

	public static void main(String[] args) {

		// Rule #1:

		// 10++;//CE:unexpected type

		// ++10; //CE:unexpected type

		// Rule #2

		int x = 10;
		long l = 10;

		x++;
		l++;

		++x;
		++l;

		float f = 10.0F;
		double d = 10.0;

		f++;
		d++;

		++f;
		++d;

		char ch = 'c';

		ch++;

		System.out.println(ch); // ch=(char)(ch+1);

		byte b = 1;

		b++;

		++b; // b=)(byte)(b+1);

		b = 127;

		b++;

		System.out.println(b); // b=(byte)(b+1);

		// Rule #3: boolean bo=true;

		// bo++; //CE:bad operand boolean

		String s1 = "a";

		// s1++; //CE:bad operand String

		// Rule #4:

		class A {
		}
		;

		A a1 = new A();

		// a1++;

		int[] ia = new int[5];

		// ia++;

	}

	}

	Output:

	Relational operator

	Example:

	public class Relational {

		public static void main(String[] args) {

			int a = 10;
			int b = 20;
			int c = 20;

			System.out.println(a < b);

			System.out.println(a <= c);

			System.out.println(a > b);

			System.out.println(b >= c);

			System.out.println(b <= c);

			System.out.println(b < c);

			System.out.println(a >= c);

			System.out.println('a' < 'b');

			// System.out.println("a"< "b");

			// System.out.println(true<false);

		}

	}

	Output:

	true true false true true false false true

	Relational operator

	Example:

	public class Relational {

		public static void main(String []args) {                       

                                    int a=10;int b =20; int c =20;                       

                        System.out.println (a<b);

                        System.out.println(a<=c);

                        System.out.println(a>b);  

                        System.out.println(b>=c);

                        System.out.println(b<=c);

                        System.out.println(b<c);

                        System.out.println(a>=c);

                        System.out.println('a'<'b');

                    // System.out.println("a"< "b");

                  //  System.out.println(true<false);

            }

}

Output:

true true false true true false false true