Data Types in Java with Examples

In Java, we need a variable to store data during the execution of program. Internally, a variable represents a memory location where data is stored. When we use a variable in Java program, we have to declare first it along with its data type. For example:

int x;

Here,

  • “x” is a variable that can store integer (int) type data.
  • int represents the nature of data that can be stored into x.

Thus, int is called a data type in Java.

What is Data Type in Java?


A data type in Java is a term that specifies memory size and type of values that can be stored into the variable (memory location). In other words, data types define different values that a variable can take in a Java program. They tell the Java compiler what kind of data (integer, float, character, boolean, etc.) a variable will hold and how much memory it requires.

Examples of Data Types in Java

Let’s take some examples to understand how data types work:

Example 1: Integer Data type

int x;
x = 100; // Here, = means the value 100 is stored into variable x.

In this example,

  • int is the data type.
  • x is the variable.
  • 100 is the integer value stored into x.

Example 2: String Data Type

String name = "Deep";

Here,

  • String is a data type that allow only string values (i.e. text values).
  • name is a variable that can take only string values such as “Deep”, “John”, and “Alice”.

Example 3: Integer Data Type with Initialization

int num = 10;

Here,

  • int is a data type.
  • num is variable which can only take integer values like 10, 20, 30, 40, and so on.

The semicolon (;) is used to end a particular statement in Java like a pull stop in the English language. It tells the Java compiler that the statement has completed and the next instruction can begin.

Types of Java Data Types


The Java programming language provides several data types to handle different kinds of data. All data types in Java are divided into two main categorized:

  1. Primitive data types (also called intrinsic or built-in types)
  2. Non-primitive data types (also called derived or reference types)

Types of data types in Java: primitive and non-primitive.

Important Note:

Numeric data types are also called arithmetic data types in Java. They are used to perform mathematical operations.

Primitive Data types in Java


Primitive data types in Java are those data types whose variables can store only one value at a time. We cannot store multiple values of the same type in a single primitive variable. These data types are predefined by Java language. They are named by a keyword.

Example: Primitive Data Type Declaration

int x; // Valid declaration.
x = 10; // Valid because "x" store only one value at a time.
x = 20; // Valid because the previous value 10 is replaced by 20.
x = 10, 20 ,30 40; // Invalid because you cannot assign multiple values at once.

Here,

  • int is a primitive data type.
  • x is a variable of type int that can store only one integer value at a time.

Primitive data types are not user-defined data-types. Programmers cannot create new primitive data types. They are faster and more memory-efficient than non-primitive data types. Primitive data types are stored in stack memory.

Types of Primitive Data Types in Java


Java defines eight primitive data types: boolean, char, byte, short, int, long, float, and double. These primitive types are further categorized into four main groups:

  • Conditional category data type: boolean
  • Character category data type: char
  • Integer category data types: byte, short, int, and long.
  • Float category data types: float and double

All the above data types are predefined keywords in Java. They are written in small letters.

Choosing the Right Data Type


Now it is important to understand the memory size limitations of each data type before using it. Choosing the right data type improves memory efficiency and performance of the program.

For example, when we define the age of a person, the age of any person will not cross 120. In this case, using a short data type is enough instead of using long which will take a big memory. Therefore, understanding the size, range, and default values of each data type is important.

Size of Data Types in Java


Each primitive data type has some memory size defined in Java. Whenever you declare a variable with a data type, the JVM automatically defines the memory size in the RAM based on its data type. For example, if we declare int a;  JVM allocates 4 bytes as the size of the memory for the variable a.

Default Values in Java


Every primitive data type has a default value defined in Java. When the programmer does not declare any value to the variables, the JVM will assign default values during the object creation. For example:

  • The default value of int is 0 (zero).
  • The default value of the byte is 0.

Example : Default Value of int 

package javaProgram;
public class Test {
// Declare a variable of type int.	
   int x;
   public static void main(String[] args) 
   {
   // Create an object of class.
      Test t = new Test();
      System.out.println("Default value of x: " +t.x);
   }
}

Output:

Default value of x: 0

Since the variable x is an instance variable and not initialized at the time of declaration, JVM automatically assigns it the default value 0 for the int data type.

Range of Data Types in Java


The range of a data type represents the minimum and maximum values it can hold. If you assign the value of a variable which is not fit in the range of data type, JVM throws a compile-time error or overflow/underflow behavior occurs.


For example, the range of int data type is between the minimum value -2,147,483,648(2^31) and the maximum value +2,147,483,648(2^31-1).

int num = 2147483648; // Error: integer number too large

Positive and Negative Values

All numeric data types in Java (except char) represent both positive and negative numbers. In the Java programming language, zero is considered a positive number.

Integer Data Types in Java


Integer data types in Java represent integer numeric values or numbers with no fractional parts or decimal points. For example, 225, -56524, 0, 1045, etc. come under this category. Integer data types are again subdivided into four types:

  • byte
  • short
  • int
  • long

Types of integer data types in Java: byte, short, int, long

Important Note:

All Java values are signed types (positive or negative). Java does not support unsigned types. Many other computer languages, including C/C++ support both unsigned and signed integers.

Byte Data Type

  1. A byte is the smallest integer data type that occupies the least amount of memory. It is mainly used to save memory in large arrays where memory saving is essential.
  2. Byte data type is an 8 bits signed two’s complement integer.
  3. The memory size of byte type is a 8-bit (i.e. 1 byte). One byte is equal to 8 bits.
  4. A byte variable represents from -128 to +127.
    • On the positive side: 0 to +127
    • On the negative side: -1 to -128
    • Thus, it can represent the total 256 (2^8) numbers.
  5. The default value of byte data type is 0.
  6. Variables of type byte are especially used to flow a stream of data from network or file.

Syntax Example

We can declare a variable of type byte by using byte keyword as:

byte b, c; // Variables b and c of type byte.

Example: Basic Byte Program

package datatypePrograms; 
public class ByteExample { 
public static void main(String[] args) 
{ 
   byte num = 100; // byte is 8 bit value. 
   System.out.println(num); 
 } 
}

Output:

100

In the preceding example, we have declared a variable named num of type byte and assigned it the value 100 which is stored into num. Since the value 100 lies within the valid range of byte (−128 to +127), the program compiles and runs successfully.

Important Note:

If you try to assign a value 150 outside the range of byte, you will get a compile-time error.

byte num = 150; // Error: Type mismatch

Error Message:

Type mismatch: cannot convert from int to byte

This happens because:

  • Integer literals like 150 are treated as int by default in Java.
  • The value 150 exceeds the maximum range of byte (+127).
  • Therefore, Java’s compiler does not allow implicit narrowing conversion from int to byte.

Short Data Type

  1. The short data type has greater memory size than byte but less than int.
  2. This data type is used when you need to store medium-range integer values and want to save memory.
  3. A short data type is a 16-bit signed two’s complement integer.
  4. The default memory size allocated to a short variable is allocated 16 bits, i.e. 2 bytes.
  5. The range of short data type is
    • On positive side: 0 to 32767
    • On the negative side: -1 to -32768.
    • Therefore, it represents any value between -32768 to 32767. So, it can represent a total of 65536(2^16) numbers.
  6. The default value of short data type is 0.

Example: Short Data Type

package datatypePrograms; 
class ShortExample { 
public static void main(String[] args)
{ 
   short num = 200; // Here, we have stored a value 200 into a variable num of short data type. 
   System.out.println(num); 
  } 
}

Output:

200

In this example, we declared a variable num of type short and assigned it the value 200. The program runs successfully because the value 200 lies within the valid range of the short data type (−32,768 to +32,767).

We cannot use the byte data type in the above example because a byte variable cannot hold the value 200. Its range is only −128 to +127. Hence, the short data type is the correct choice here due to its wider range.


Int Data Type

  1. The int data type is the most commonly used integer type in Java programming.
  2. It is suitable for storing whole numbers without decimal points.
  3. The int data type is a 32-bit signed two’s complement integer.
  4. It has a wide range of values, from −2,147,483,648 (−2³¹) to +2,147,483,647 (2³¹ − 1).
  5. The memory size allocated to an int variable is 32 bits, i.e., 4 bytes.
  6. The default value of int data type is 0.

Example: Using int Data type

Let’s create a Java program where we will store two values into variables a and b with data type int. Then, we will add both values and display them.

package datatypeProgram; 
class IntegerExample { 
public static void main(String[] args)
{ 
   int a = 200; // Variable a declared as int type. 
   int b = 300; // Variable b declared as int type. 
   System.out.println(a+b); // Prints the sum of a and b.
  } 
}

Output:

500

In the above example,

  • We have declared two integer variables a and b using the int data type and assigned them values 200 and 300.
  • The System.out.println(a + b); statement displays the sum of the two integers, which is 500.

The program compiles and runs perfectly because both values are within the valid range of the int data type (−2,147,483,648 to +2,147,483,647).


Long Data Type

  1. The long data type is used to store large integer values when the range of the int type is not large enough to store the desired value.
  2. A long data type is a 64-bit signed two’s complement integer.
  3. The default memory size allocated to long variable is 64 bits, i.e. 8 bytes.
  4. The default value of long data type is 0L.
  5. The range of long data type is from -9,223,372,036,854,775,808 (-2^63) to 9,223,372,036,854,775,807 (-2^63-1).
  6. Long data type is useful when you need to work with large whole numbers, such as distance, population, or time calculations. For example:
long num = -2334456L;

Here,

  • long is the data type.
  • num is the variable name.
  • The suffix L (or lowercase l) tells the JVM that this value should be treated as a long literal instead of an int.
  • Without the suffix, the compiler treats all integer literals as int by default.

Example: Calculating Distance Traveled by Light

Let’s create a program where we will calculate the distance traveled by light in 1000 days using long data type.

package datatypePrograms; 
public class LongExample { 
public static void main(String[] args) 
{ 
   int lightSpeed; // Speed of light in miles per second.
   long days; // Number of days
   long seconds; // Total seconds
   long distance; // Distance travelled

// Speed of light in miles per sec. 
   lightSpeed = 186282; 
   days = 1000; // Number of days. 

// Convert days into seconds.
   seconds = days*24*60*60;
// Calculate the distance. 
   distance = lightSpeed * seconds; 
   System.out.println("In 1000 days, distance traveled by light: " +distance + " miles"); 
   } 
}

Output:

In 1000 days, distance traveled by light: 16094764800000 miles

In this example,

  • The speed of light (186282 miles/sec) is multiplied by the number of seconds in 1000 days.
  • The resulting value is very large, far exceeding the range of the int data type. Therefore, we have used long data type to handle this big number without overflow or data loss.
  • If we had used int for the variable distance, it would cause integer overflow, producing an incorrect result.

Table: Size and Range of Integer Data types

TypeSizeMinimum valueMaximum value
byteOne byte-128127
shortTwo bytes-32, 76832, 767
intFour bytes-2, 147, 483, 6482, 147, 483, 647
longEight bytes-9, 223, 372, 036, 854, 775, 8089, 223, 372, 036, 854, 775, 807
Important Note:

Whenever possible, use smaller data types to reduce memory usage, especially when you are dealing with large arrays or collections.

However, using smaller data types like byte or short does not necessarily improve execution speed because Java automatically promotes these types to int during arithmetic operations.

On modern JVMs and CPUs, int operations are often faster or equally fast as smaller types. Therefore, prefer int for most integer operations, and use smaller types only when memory optimization is important.

Java Floating-Point Data Types


Floating-point data types in Java are used to represent numbers that have decimal points or fractional parts. For example, 3.14, -2.567, 0.00034, etc. are called floating-point numbers. These are useful in scientific calculations, graphics, and engineering applications where precision and decimal representation are required.

Java provides two floating-point types based on the IEEE 754 standard:

  • float → single precision (32-bit)
  • double → double precision (64-bit)

Types of floating point data types in Java: float and double


Float Data Type

  1. A float data type is used to represent the decimal number, which can hold approximately 6 to 7 significant decimal digits.
  2. It is mainly used to save memory in large arrays of floating-point numbers.
  3. The float data type is a single-precision 32-bit IEE 754 floating-point.
  4. The default memory size allocated for this data type is 32 bits, i.e. 4 bytes.
  5. The default value float data type is 0.0f.
  6. A float literal must end with the suffix f or F to indicate it is a float constant.

For example:

float num = 10.6f;

Here, if we do not write “f” suffix, JVM will consider as double by default and would have allotted 8 bytes. In this case, it will give an error ” Type mismatch: cannot convert from double to float”. But if you add f or F, JVM will consider it as float value and allot only 4 bytes.


Double Data Type

  1. A double data type is also used to represent decimal numbers up to 15 decimal digits accurately.
  2. It is a double-precision 64-bit IEEE 754 floating-point number.
  3. The memory size allocated to this data type is 64 bits, i.e. 8 bytes.
  4. The default value is 0.0d. You may also use 0.0 — d suffix is optional.
  5. This date type is suitable for high-precision mathematical operations such as sin(), cos(), sqrt(), etc.

For example:

double num = 1345.6;
double distance = 1.50e9; // Here, e represents x 10 to the power.

Hence, 1.50e9 means 1.50*10^9. It is called scientific notation of representing number.

Example: Calculate Area of a Circle

Let’s make a Java program where we will use double variables to calculate the area of circle.

package datatypePrograms; 
public class Area { 
public static void main(String[] args) 
{ 
   double pi, r; 
   r = 5.5; // Radius of circle. 
   pi = 3.1416; // Approximate value of π

// Calculate the area of circle. 
   double area = pi * r * r; 
   System.out.println("Area of circle: " +area); 
  } 
}

Output:

Area of circle: 95.0334
Important Note:
  • A single-precision (float) number takes less space in the memory than double precision. But when the value is large, single-precision is less accurate.
  • A double-precision (double) number consumes more memory but provides higher accuracy and a wider range.
  • Therefore, double is preferred for most floating-point calculations in Java unless you need to optimize memory usage.

Table: Size and Range of Floating-point Data types

TypeSizeMinimum valueMaximum value
floatFour bytes3.4e-0383.4e+038
doubleEight bytes1.7e-3081.7e+308

Character (char) Data Type

  1. A char data type is mainly used to store a single character like ‘P’, ‘a’, ‘b’, ‘z’, ‘x’, etc.
  2. It is a single 16-bit Unicode character. Java uses Unicode to support international characters.
  3. Memory size taken by a single char is 2 bytes.
  4. The range of char data type is
    • 0 to 65,535 (\u0000 to \uFFFF), representing all Unicode characters.
  5. A default value of char is ‘u0000’ which represents the null character, which may appear as a blank space when printed. Here, ‘u’ represents that character is a Unicode. For example:
char ch = 'D';

Example: Character Data Type

package datatypePrograms; 
public class CharExample { 
public static void main(String[] args) 
{ 
  char ch1, ch2; 
  ch1 = 88; // ASCII value 88 → 'X'
  ch2 = 'R'; // Character literal
  char ch3; 
  ch3 = 'A';
  
  ch3++; // Increment character → 'B'
  System.out.println(ch1); 
  System.out.println(ch2); 
  System.out.println(ch3); 
  } 
}

Output:

X 
R 
B

In the above example,

  • We have assigned a value 88 (which is an ASCII value) in a variable ch1, and specifies a letter X.
  • ch3 is assigned value A and then it is incremented.
  • So, ch3 will now store B, the next character in the ASCII sequence.
  • The data type char can store both numeric values (ASCII/Unicode) and character literals.

Boolean Data Type

  1. The boolean data type stores one of two possible values: true or false.
  2. Internally, JVM uses one bit of storage to represent a boolean value.
  3. It is generally used to test a particular conditional statements, loops, and logical operations during the execution of the program.
  4. Technically, Java does not define an exact memory size for boolean. It takes zero byte of memory.
  5. Default value is false.

For example:

boolean b = false;

In the above all examples, we assigned a value of the variable, assigned value will be printed as output.

Example: Default Values of Java Primitive Data Types

Suppose if you do not assign the value of the variable, JVM will assign the default value and the default value will be print. Let’s take an example program based on boolean data type.

package datatypePrograms; 
public class DefaultExample 
{ 
// Declaration of instance Variables. 
   int a; 
   char b; 
   float c; 
   boolean d; 

// Static method or main method. 
   public static void main(String[] args) 
   { 
  // Create the object of the class. 
     DefaultExample obj = new DefaultExample(); 
  // Call the variable and print it. 
     System.out.println(obj.a);
     System.out.println(obj.b); 
     System.out.println(obj.c); 
     System.out.println(obj.d); 
    } 
}

Output:

0 
u0000 (represents blank space) 
0.0 
false

Does Boolean Data Type Take Zero Bytes of Memory?


It is incorrect to say boolean always takes zero bytes of memory. In Java, the boolean data type logically represents true or false, which is 1 bit of information.

The JVM does not define a fixed size of memory for a single boolean variable. Its actual memory size can vary:

  • In arrays: Each boolean may take 1 byte (i.e. 8 bits) for alignment purposes.
  • As individual variables: The JVM can optimize memory, so the storage may be less visible at the byte level.

A boolean logically stores 1 bit, but the actual memory usage depends on the JVM and not guaranteed to be zero bytes.

Different Ways to Initialize Variables in Java

// 1. Single variable initialization.
int a = 10; 
System.out.println(a);
// Output: 10

// 2. Multiple variables declaration without initialization.
int a, b, c;
System.out.println(a);
System.out.println(b);
System.out.println(c);
// Accessing these variables without initialization in local scope causes a compilation error

// 3. Mixed initialization.
int a = 20, b, c;
System.out.println(a);
System.out.println(b);
System.out.println(c);
// b and c are uninitialized; accessing them in local scope will cause a compilation error

// 4. Multiple initialization.
int a = 10, b = 20, c;
System.out.println(a);
System.out.println(b);
System.out.println(c);
// c is uninitialized; using it will cause an error.

// 5. Full initialization.
System.out.println(a + ", " + b + ", " + c);
// Output: 10, 20, 30
Note:
  • For instance variables (class-level variables), Java automatically assigns default values: 0 for int, 0.0 for float/double, false for boolean, \u0000 for char.
  • For local variables, you must explicitly initialize them before use. Otherwise, the compiler will throw an error.

Key Points about Java Data Types:

  • Primitive data types is used to store a single value in Java programming. It is also known as fundamental data types.
  • Non-primitive data types known as advanced data types store multiple values or a group of values.
  • The basic and most common data types are integer, floating-point number, character, string, and boolean.
  • Data types are used in Java because it is a strongly typed language. Java compiler checks type compatibility. Illegal operations cannot be compiled.