Blog

Data Types in java with example

  • (4.0)
  • | 1225 Ratings

Data Types in Java

Data Types

Java’s robustness and safety is due to its strong datatypes. Everything in Java has a type and that type is defined. Data types define size and value a variable can hold. There are majorly 2 types of data types in Java.

  • Primitive -There are 8 primitive types available in Java: byte, short, int, long, char, float, double, and boolean.
  • Non-primitive – Non-primitive data types are classes, interfaces and arrays.

data-types-in-java

Primitive Data Types

Primitive types are the basis of Java. They all have mathematical behaviour and explicit range as described in below table:

Data Types Range Default Size Default Values Example
boolean True/ False 1bit FALSE boolean b1 = True
char ‘u0000’ to ‘uffff’ 2byte ‘u0000’ char ch1=’P’
byte -128 (-2^7) to 127 (2^7 -1) 1byte 0 byte b2 = 14
short -32,768 (-2^15) to 32,767(2^15 -1) 2byte 0 short s1=100
int – 2,147,483,648 (-2^31) to 2,147,483,647(2^31 -1) 2byte 0 int j= 10000000
long -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1) 8byte 0L long l1= 1000000L
float Single-precision 32-bit IEEE 754 floating point 4byte 0.0f float f1 = 24.7f
double Double-precision 64-bit IEEE 754 floating point 8byte 0.0d double d1 = 142.5

We will be learning about Non-primitive types further in this tutorial.

Variables

Variables are the basic unit of storage in Java. Variable is defined by using an identifier, a type and an initializer(optional). All variables have their own scope and lifetime. Here are few of the examples for declaring variables:

int x,y; // declares 2 ints, x and y.
int i = 3, e, j = 5; // declares three more ints and initializing i and j.
double p = 3.14 // declares a double variable of p.
char a = 'c'; // the character variable y has the value 'c'.

Variables can be initialized dynamically. Here is the example to retrieve the sum of 2 initialized variables (a & b) and assign it to 3rd uninitialized variable(c).

class sumDemo {
 public static void main(String args[]) {
 int a = 3, b = 4;
 // c is dynamically initialized here
 int c = a + b;
 System.out.println("a+b = " + c);
 }
}

Check Out Core Java Tutorials

Scope and Lifetime of Variables

There are 3 types of variables in Java according to their scope and lifetime. Let us look at them one by one with examples.

  • Local Variable – Variables declared inside a method body is called local variables and they are only accessible within that method.
public class varDemo {
   public static void main(String[] args) {
        {
            int x =5;
            System.out.println(x);
        }
         System.out.println(x);
    }
}

When we will try to compile this code, we will get below error.

varDemo.java:16: error: cannot find symbol
         System.out.println(x);
                            ^
  symbol:   variable x
  location: class varDemo
1 error

Braces {} defines the scope of the variable x. If it is written in any method then, it is only accessible within that method. If a method is having same variable name of class variable then this keyword is used to access method level variable.

  • Static Variable – A variable declared as static is called a static variable. It is not a local variable. Static variable is also known as class variable. It can be accessed through class object and will be same for all instances of class. Let’s look at an example for same:
public class varDemo {
   public static String s="Static Variable";
   public static void main(String args[]){
      varDemo obj = new varDemo();
      varDemo obj1 = new varDemo();
      varDemo obj2 = new varDemo();
      System.out.println(obj.s);
      System.out.println(obj1.s);
      System.out.println(obj2.s);
      obj2.s = "XYZ";
      System.out.println(obj.s);
      System.out.println(obj1.s);
      System.out.println(obj2.s);
   }
}

Output

Static Variable
Static Variable
Static Variable
XYZ
XYZ
XYZ 

Here we can see that if one instance of class will change the value of the static variable, then all instances will be having same value.

Check Out Core Java interview questions

  • Instance Variable – Variable declared in class but outside of a method is called an instance variable. Its value is an instance specific which makes it an instance variable. Unlike static variables, instance variable will have own copies. Now let just remove the static keyword from above example and let us see what changes will be seen in output.
public class varDemo {
   String s="Instance Variable";
   public static void main(String args[]){
      varDemo obj = new varDemo();
      varDemo obj1 = new varDemo();
      varDemo obj2 = new varDemo();
      System.out.println(obj.s);
      System.out.println(obj1.s);
      System.out.println(obj2.s);
      obj2.s = "XYZ";
      System.out.println(obj.s);
      System.out.println(obj1.s);
      System.out.println(obj2.s);
   }
}

Output:

Instance Variable
Instance Variable
Instance Variable
Instance Variable
Instance Variable
XYZ 

Here we can see that each object has their own copy of instance variable and show the value in it accordingly.

Arrays

Arrays in Java is a collection of same type of elements. Arrays elements are accessed through arrays index in Java. Arrays index starts with 0.

Array   a Index
31 a[0]
57 a[1]
20 a[2]
14 a[3]
27 a[4]
88 a[5]
69 a[6]

Array Length = 7

Arrays declaration can be done in below 2 ways.

datatype arrayvar[];
datatype[] arrayvar;
int a[];
int[] a;

Once array is declared, we need to instantiate it with size. Size specifies number of elements an array can store. Datatype represents what each arrays element should have in it. Here we have declared an array of integer of size 5. It means array a can store 5 array elements.

arrayvar = new datatype[size]
a= new int[5];

Once array is declared, we need to initialize it with values by using index of an array. Below code will store 15 to the first element of an array and 25 to second element of an array. As mentioned earlier, array index starts from 0.

arrayvar[0]= 15;
arrayvar[1] = 25;
a[0] = 15;
a[1]=25;

There are 2 types of arrays supported in Java.

Single Dimensional Array

public static void main(String []args){
        int a[]=new int[5];//declaration and instantiation  
        a[0]=15;  
        a[1]=22;  
        a[2]=87;  
        a[3]=90;  
        a[4]=9;  
        for(int i=0;i<a.length;i++) pre="">
</a.length;i++)>

Output:

15
22It is a simple array having same values. Let us see one example for it.
public class ArrayDemo{
87
90
9

Length is the property of an array which returns no. of elements stored in it. So, we will be using this property whenever we want to traverse the array.

Multi-Dimensional Array

Multi-Dimensional Array is called arrays of arrays. Internally for multi-dimensional array, matrix is implemented. For Example –

int a[][] = new int[3][4];

This allocates 3 by 4 array to variable a. This array looks like below matrix. Here left index is row index and right index is column index.

Let us see below multi-dimensional array example to understand it better.

public class ArrayDemo{
     public static void main(String []args){
         int[][] a = { {10,20,30,40}, {50, 60, 70} };
        for (int i = 0; i < a.length; ++i) {
                for(int j = 0; j < a[i].length; ++j) {
                    System.out.println("a["+i+"]["+j+"] : " +a[i][j]);
      }
        }
     }
}

Output:

a[0][0] : 10
a[0][1] : 20
a[0][2] : 30
a[0][3] : 40
a[1][0] : 50
a[1][1] : 60
a[1][2] : 70
Explore Core Java Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.

Ravindra Savaram
About The Author

Ravindra Savaram is a Content Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.


DMCA.com Protection Status

Close
Close