Data Types in java

Java is both a statically typed and a highly typed language, since each data type is declared in the scripting language, and all parameters and variables defined in a program must be expressed using one of the data types. This blog discusses the various data types available in Java.

Java Data Types

Java’s robustness and safety are 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

If you want to enrich your career and become a professional in Core Java, then visit Mindmajix - a global online training platform: "Core Java Online Course" This course will help you to achieve excellence in this domain.

Primitive Data Types

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

Data TypesRangeDefault SizeDefault ValuesExample
booleanTrue/ False1bitFALSEboolean b1 = True
char‘u0000’ to ‘uffff’2byte‘u0000’char ch1=’P’
byte-128 (-2^7) to 127 (2^7 -1)1byte0byte b2 = 14
short-32,768 (-2^15) to 32,767(2^15 -1)2byte0short s1=100
int– 2,147,483,648 (-2^31) to 2,147,483,647(2^31 -1)2byte0int j= 10000000
long-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)8byte0Llong l1= 1000000L
floatSingle-precision 32-bit IEEE 754 floating point4byte0.0ffloat f1 = 24.7f
doubleDouble-precision 64-bit IEEE 754 floating point8byte0.0ddouble 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);
 }
}

Core Java Tutorial for Beginners

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.

 MindMajix YouTube Channel

  • 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.

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   aIndex
31a[0]
57a[1]
20a[2]
14a[3]
27a[4]
88a[5]
69a[6]

Array Length = 7

Arrays declaration can be done in below 2 ways.

atatype 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 array element should have in it. Here we have declared an array of integers 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 the 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 that 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 the multi-dimensional array, the matrix is implemented. For Example –

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

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

Let us see below the 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!

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Core Java TrainingNov 23 to Dec 08View Details
Core Java TrainingNov 26 to Dec 11View Details
Core Java TrainingNov 30 to Dec 15View Details
Core Java TrainingDec 03 to Dec 18View Details
Last updated: 03 Apr 2023
About Author

Ravindra Savaram is a Technical 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.

read less
  1. Share:
Java Articles