Java Data Types
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java Data Types

Jeevadharshan

Java Data Types 

In Java, every variable must be declared with a specific data type. The data type tells Java what kind of data the variable can store and how much memory it needs. 

Example: Declaring Variables with Different Data Types 

int score = 85;                 // Stores whole numbers 
double temperature = 36.6;      // Stores decimal values 
char grade = 'A';             // Stores a single character 
boolean isPassed = true;        // Stores true or false 
String message = "Welcome";     // Stores text 

Each variable above holds a different type of value, and Java strictly enforces these types. 

Categories of Data Types 

Java data types are divided into two main groups: 

1. Primitive Data Types 

These are basic data types that store simple values directly. 

2. Non-Primitive Data Types 

These store references to objects and include String, Arrays, and Classes. 

Primitive Data Types in Java 

Java provides eight primitive data types, each designed for a specific purpose:

Table

Data Type byte Description Stores small whole numbers short Stores slightly larger whole numbers int long float double boolean char Stores standard whole numbers Stores very large whole numbers Stores decimal values (less precision) Stores decimal values (high precision) Stores true or false Stores a single character

Example: Using Multiple Primitive Data Types 

byte age = 21; 
short distance = 1500; 
int population = 120000; 
long worldPopulation = 8000000000L; 
float price = 99.99f; 
double piValue = 3.141592653; 
boolean isAvailable = false; 
char currencySymbol = '$'; 

System.out.println("Age: " + age); 
System.out.println("Distance: " + distance); 
System.out.println("Population: " + population); 
System.out.println("World Population: " + worldPopulation); 
System.out.println("Price: " + price); 
System.out.println("PI Value: " + piValue); 
System.out.println("Available: " + isAvailable); 
System.out.println("Currency Symbol: " + currencySymbol); 

Non-Primitive Data Types 

Non-primitive data types are more complex and can store multiple values or objects.

Common examples include: 
  • String 
  • Arrays 
  • Classes 
Example: Non-Primitive Data Type (String) 

String cityName = "Chennai"; 
System.out.println("City: " + cityName); 

Data Type Safety in Java 

Java is a strongly typed language, meaning once a variable is declared with a data type, it cannot be changed later. 

Example: Type Mismatch Errors 

int number = 10; 
// number = "Ten";   //  Not allowed 

String text = "Java"; 
// text = 100;       // Not allowed 

These errors occur because Java does not allow mixing incompatible data types.

Why Java Enforces Data Types

  • Prevents unexpected errors 
  • Makes programs safer and more reliable 
  • Helps the compiler detect mistakes early
If you need to convert one data type into another, Java provides type casting and conversion methods, which you’ll learn later. 

Java Numeric Data Types 

Overview of Numbers in Java 

In Java, numeric primitive data types are divided into two categories: 

1. Integer Types 

Used to store whole numbers (without decimal points). 
These include:
  • byte 
  • short 
  • int
  • long

2 .Floating-Point Types 

Used to store numbers that contain decimal values. 
These include: 
  • float 
  • double
Although Java provides multiple numeric types, the most commonly used ones are:
  • int → for whole numbers 
  • double → for decimal numbers

Integer Data Types 

Integer types differ mainly in memory size and range of values. 

1. Byte 

byte is the smallest integer type. It stores values from -128 to 127 and is useful when memory efficiency matters. 

Example 

byte roomTemperature = 25; 
System.out.println("Room Temperature: " + roomTemperature); 

2. Short 

short stores larger values than byte, but smaller than int. 

Example 

short yearlySales = 12000; 
System.out.println("Yearly Sales: " + yearlySales); 

3. Int 

int is the most commonly used integer type in Java. 
It is suitable for most whole number calculations. 

Example 

int totalStudents = 450; 
System.out.println("Total Students: " + totalStudents); 

4. Long 

long is used when int is not large enough. 
Values must end with L. 

Example 

long nationalPopulation = 1400000000L; 
System.out.println("National Population: " + nationalPopulation); 

Floating-Point Data Types 

Floating-point numbers are used when decimals are required. 

1. Float 

float stores decimal numbers with 6–7 digits precision. Values must end with f. 

Example 

float productWeight = 2.75f; 
System.out.println("Product Weight: " + productWeight); 

2. Double 

double provides higher precision (about 15–16 digits). It is generally preferred for most decimal calculations. 

Example 

double bankBalance = 10500.56789; 
System.out.println("Bank Balance: " + bankBalance);

Float vs Double – Which Should You Use?  

Table
Type float Double Precision 6–7 digits 15–16 digits Recommended Use When memory usage must be reduced Most real-world calculations

In most cases, double is safer and more accurate. 

Scientific Notation in Java 

Java allows numbers to be written in scientific format using e or E, which represents powers of 10. 

Example 

double distanceToSun = 1.496e8;   // 1.496 × 10^8 
float smallValue = 3.5E2f;        // 3.5 × 10^2 

System.out.println("Distance to Sun: " + distanceToSun); 
System.out.println("Small Value: " + smallValue); 

Key Takeaways

  • Use integer types for whole numbers. 
  • Use floating-point types for decimal values. 
  • int and double are the most commonly used. 
  • Add L for long and f for float. 
  • Scientific notation simplifies very large or small numbers.

Java Boolean Data Type 

In programming, many situations require a variable that can store only two possible values. 
Forexample:
  • YES / NO 
  • ENABLED / DISABLED 
  • SUCCESS / FAILURE 
  • TRUE / FALSE
To represent such conditions, Java provides the boolean data type. 

A boolean variable can store only:
  • true 
  • false
Example: Declaring Boolean Variables 

boolean isLoggedIn = true; 
boolean hasPermission = false; 

System.out.println("User Logged In: " + isLoggedIn); 
System.out.println("Permission Granted: " + hasPermission); 

Output: 

User Logged In: true 
Permission Granted: false

Boolean in Real-World Scenarios 

Booleans are commonly used to track status or conditions in a program. 

Example: Checking Voting Eligibility 

int age = 20; 
boolean isEligibleToVote = age >= 18; 

System.out.println("Eligible to Vote: " + isEligibleToVote); 

Here, the expression age >= 18 evaluates to either true or false. 

Boolean in Conditional Statements 

Boolean values are mostly used in decision-making structures like if statements. 

Example: 

boolean isServerRunning = true; 
if (isServerRunning) { 
     System.out.println("Server is active."); 
} else { 
    System.out.println("Server is offline."); 
}

Key Points to Remember 

  • boolean stores only true or false. 
  • It is mainly used for logical conditions. 
  • Boolean values are essential for decision-making and control flow. 
  • Comparison operators (>, <, ==, >=) often produce boolean results. 

Java Characters and Strings 

Character Data Type (char) 

In Java, the char data type is used to store a single character. Characters must always be enclosed within single quotation marks (' '). 

Example: Using char Variables 

char section = 'A'; 
char grade = 'C'; 

System.out.println("Section: " + section); 
System.out.println("Grade: " + grade); 

Output: 

Section: A 
Grade: C 

Using Numeric (ASCII) Values with char 

Each character in Java is internally represented by a numeric value (based on the ASCII/Unicode standard). You can assign a number to a char, and Java will display the corresponding character. 

Example: ASCII-Based Characters 

char ch1 = 72;  // H 
char ch2 = 73;  // I 
char ch3 = 33;  // ! 

System.out.println(ch1); 
System.out.println(ch2); 
System.out.println(ch3); 

Output: 


Tip: ASCII values are useful when working with character encoding or low-level text processing. 

String Data Type (String) 

The String data type is used to store multiple characters together, forming text. String values must be enclosed within double quotation marks (" "). 

Example: Creating and Printing a String 

String message = "Welcome to Java programming"; 
System.out.println(message); 

Output: 

Welcome to Java programming 

Difference Between char and String

Table

Feature Stores char Single character String Single character Quotes used Data type Single ' ' Primitive Double " " Non-primitive (Object)

Why String Is Special in Java

Although String looks like a simple data type, it is actually a non-primitive type in Java. This means:
  • It represents an object 
  • It comes with many built-in methods (like length, uppercase, lowercase, etc.) 
  • It is heavily used in almost every Java program
Don’t worry if the term object feels unfamiliar right now — it will be explained clearly when you learn OOP concepts later. 

What Are Non-Primitive Data Types? 

In Java, non-primitive data types are also known as reference types. Instead of storing the actual value directly, they store a reference (address) to an object in memory. These data types are more flexible and powerful compared to primitive data types.

Key Differences: Primitive vs Non-Primitive

Table

Feature      
Definition 
Example 
Primitive Data Types 
Built-in data types  
int, char, boolean  
Non-Primitive Data Types 
Created using classes 
String, Arrays, Classes 
Stores  
Methods 
Null value  
Naming style   
Actual value  
Cannot call methods 
Cannot be null 
Lowercase (int)      
Common Non-Primitive Data Types 
Reference to an object 
Can call methods 
Can be null 
Capitalized (String) 

Common Non-Primitive Data Types

Some frequently used non-primitive data types in Java include:
  • String 
  • Arrays 
  • Classes 
  • Interfaces (advanced topic)
You will explore these in detail in upcoming chapters. 
 
Example 1: String (Non-Primitive Type) 
 
The String class allows you to use built-in methods to work with text. 
 
String city = "Chennai"; 
System.out.println(city.toUpperCase()); 

Output:  

CHENNAI 
 
 Here, toUpperCase() is a method that works only because String is a non-primitive type. 
 
Example 2: Array (Non-Primitive Type) 
 
An array stores multiple values of the same type. 
 
int[] marks = {85, 90, 78}; 
 
System.out.println(marks[0]); 
System.out.println(marks[1]); 
System.out.println(marks[2]); 
 
Output: 
 
85 
90 
78 
 
Example 3: Non-Primitive Can Be Null 
 
Unlike primitive types, non-primitive types can hold null, meaning they refer to no object. 

String message = null; 
System.out.println(message); 

Output: 

null 

Why Use Non-Primitive Data Types?

Non-primitive data types allow you to:
  • Store complex data 
  • Group multiple values 
  • Reuse code using classes 
  • Perform operations using methods
They are essential for real-world Java applications. 

What Is the var Keyword? 

The var keyword was introduced in Java 10 to make variable declarations simpler. Instead of explicitly writing the data type, Java can infer the type automatically from the value you assign. This reduces repetition and makes code easier to read, especially when dealing with long or complex types. 

Basic Example of var 

Normally, you might write: 

int count = 10; 

Using var, you can write: 

var count = 10; 
System.out.println(count); 

The compiler understands that 10 is an integer, so count becomes an int.  

var with Different Data Types 

The type of a var variable depends entirely on the value assigned at declaration time. 
 
var score = 95;            // int 
var price = 149.75;        // double 
var grade = 'A';           // char 
var isPassed = false;      // boolean 
var message = "Welcome";   // String 
 
Once declared, the variable behaves exactly like a normal variable of that type.

Important Rules of var 

1 . Assignment Is Mandatory 

You must assign a value immediately when using var.
  • Invalid: 
              var total;
  • Valid:
              var total = 100;

2  .Type Cannot Change Later  

After the compiler determines the type, it cannot be changed. 
 
var number = 25;   // number is int 
number = 40;       // valid 
// number = 12.5;  // Error: cannot assign double to int 

When Should You Use var? 

Good Use Case: Complex Types 
 
For long or repetitive type names, var makes code cleaner. 
 
// Without var 
java.util.ArrayList<Integer> marks = new java.util.ArrayList<>(); 
// With var 
var marks = new java.util.ArrayList<Integer>(); 

This improves readability without losing clarity. 

Avoid for Simple Types 

For simple variables, explicitly writing the type is often clearer: 

int age = 21;   // clearer than: var age = 21;
Tags
Our website uses cookies to enhance your experience. Learn More
Accept !