CS Engineering Gyan

Variables & Data Types in Java

Every program needs a way to store and work with information, whether it is a person's age, a product price, or a simple true-or-false decision. In Java, this is done using variables, and the kind of data each variable can hold is determined by its data type.

Unlike some languages where a variable can freely change the type of value it stores, Java requires you to declare the data type of a variable before using it. This approach is known as static typing, and it helps catch many errors early, before the program is even executed.

In this tutorial, you will learn what variables are, how to declare and initialize them, the different categories of data types available in Java, and how values can be converted from one type to another.


What is a Variable in Java?

A variable is a named location in memory that is used to store a value during program execution. Once a variable is declared with a specific data type, it can only hold values that match that type throughout its lifetime, unless it is explicitly reassigned or converted.

Example

public class VariableExample {

    public static void main(String[] args) {

        int score = 85;

        System.out.println(score);

    }

}

Output

85

In this example, score is the name of the variable, int is its data type, and 85 is the value stored inside it. This combination of a type, a name, and a value forms the basic building block of almost every Java program.


Declaring and Initializing Variables

Declaring a variable means telling the compiler its name and data type, while initializing it means assigning it an actual value. In Java, these two steps can be done together or separately, depending on your program's needs.

Syntax

dataType variableName;

dataType variableName = value;

Example

public class DeclarationExample {

    public static void main(String[] args) {

        int age;

        age = 22;

        String city = "Mumbai";

        System.out.println(age);

        System.out.println(city);

    }

}

Output

22

Mumbai

Notice that age was declared first and given a value afterward, while city was declared and initialized in a single line. Both approaches are valid in Java, and the choice usually depends on how the program is structured.


Rules for Naming Variables

Java has specific rules that every variable name must follow. Ignoring these rules will cause the program to fail during compilation.

Beyond these strict rules, it is also good practice to use meaningful, descriptive names that make your code easier to read, such as totalMarks instead of a vague name like x.


Categories of Data Types in Java

Java data types are broadly divided into two main categories. Each category behaves differently in terms of memory storage and usage.

Category Description
Primitive Data Types Store simple, single values directly in memory.
Reference Data Types Store references (addresses) that point to objects in memory.

Primitive types are the foundation of Java and are built directly into the language, while reference types include classes, arrays, and interfaces that are created using those primitive building blocks.


Primitive Data Types in Java

Java provides eight primitive data types, each designed to store a specific kind of value efficiently. These types are not objects and do not have methods attached to them directly.

Data Type Size Description
byte 1 byte Stores small whole numbers, useful for saving memory in large arrays.
short 2 bytes Stores whole numbers larger than byte but smaller than int.
int 4 bytes Stores standard whole numbers and is the most commonly used numeric type.
long 8 bytes Stores very large whole numbers beyond the range of int.
float 4 bytes Stores decimal numbers with moderate precision.
double 8 bytes Stores decimal numbers with higher precision than float.
char 2 bytes Stores a single character, such as a letter or symbol.
boolean 1 bit (conceptually) Stores only true or false values.

Example

public class PrimitiveExample {

    public static void main(String[] args) {

        byte smallNumber = 25;

        int normalNumber = 15000;

        double price = 499.75;

        char grade = 'A';

        boolean isAvailable = true;

        System.out.println(smallNumber);

        System.out.println(normalNumber);

        System.out.println(price);

        System.out.println(grade);

        System.out.println(isAvailable);

    }

}

Output

25

15000

499.75

A

true

Choosing the correct primitive type based on the range and nature of your data helps make programs more memory-efficient, especially in large-scale applications.


Reference Data Types in Java

Unlike primitive types, reference data types do not store the actual value directly. Instead, they store a reference pointing to the location in memory where the object is stored. Common examples of reference types include classes, arrays, and strings.

Reference Type Description
String Represents a sequence of characters, such as names or sentences.
Array Stores multiple values of the same type in a single variable.
Class Acts as a blueprint used to create custom objects.
Interface Defines a contract that classes can implement.

Example

public class ReferenceExample {

    public static void main(String[] args) {

        String message = "Learning Java Variables";

        int[] numbers = {10, 20, 30};

        System.out.println(message);

        System.out.println(numbers[1]);

    }

}

Output

Learning Java Variables

20

Reference types are especially important as programs grow larger, since they allow you to model real-world entities such as students, products, or vehicles using custom-built classes.


Difference Between Primitive and Reference Types

Primitive Types Reference Types
Store actual values directly. Store references pointing to objects in memory.
Have a fixed size defined by the language. Size depends on the object being referenced.
Cannot be set to null. Can be set to null to represent no value.
Faster to access due to direct storage. Slightly slower due to indirect memory access.

Type Casting in Java

Sometimes a program needs to convert a value from one data type to another. This process is known as type casting, and Java supports two forms of it depending on whether data might be lost during conversion.

Widening Casting (Automatic)

Widening casting happens automatically when converting a smaller data type into a larger one, since no data is lost in the process.

public class WideningExample {

    public static void main(String[] args) {

        int wholeNumber = 50;

        double decimalNumber = wholeNumber;

        System.out.println(decimalNumber);

    }

}

Output

50.0

Narrowing Casting (Manual)

Narrowing casting must be done manually because converting a larger data type into a smaller one can result in a loss of information.

public class NarrowingExample {

    public static void main(String[] args) {

        double price = 299.95;

        int roundedPrice = (int) price;

        System.out.println(roundedPrice);

    }

}

Output

299

Notice that the decimal portion of the value is discarded during narrowing casting rather than rounded, which is an important detail to remember when working with numeric conversions.


Variable Scope in Java

The scope of a variable determines where in the program it can be accessed. Java defines a few different types of scope based on where a variable is declared.

Scope Type Description
Local Variable Declared inside a method and accessible only within that method.
Instance Variable Declared inside a class but outside any method, tied to individual objects.
Static Variable Declared using the static keyword and shared across all objects of a class.

Understanding scope becomes especially important once you start working with multiple methods and classes, since it determines which parts of your program can read or modify a particular variable.


Best Practices for Using Variables


Common Mistakes Beginners Make

Mistake Correct Practice
Using a variable before initializing it. Always assign a value before using a local variable in a statement.
Choosing int for very large numbers. Use long when values may exceed the range supported by int.
Confusing float and double precision. Remember that double offers higher precision and is used more often by default.
Forgetting that narrowing casting requires an explicit cast. Always use a cast operator when converting a larger type into a smaller one.

Frequently Asked Interview Questions

  1. What is the difference between a variable declaration and initialization?
  2. What are the eight primitive data types in Java?
  3. What is the difference between primitive and reference data types?
  4. What is the difference between widening and narrowing type casting?
  5. Why can primitive variables not be assigned a null value?
  6. What is the difference between local, instance, and static variables?
  7. Why does Java require explicit casting for narrowing conversions?
  8. What happens to decimal values during narrowing casting to an integer type?

Summary

Variables and data types form the foundation of every Java program, allowing you to store, organize, and manipulate information effectively. Java's use of static typing, where every variable must have a defined data type, helps catch errors early and makes programs more predictable.

By understanding the difference between primitive and reference data types, learning proper naming rules, and knowing how type casting works, you gain the tools needed to handle data confidently in your programs. With this foundation in place, you are now ready to explore how operators allow you to perform calculations and comparisons using these variables.


← Previous: Java Program Structure Next: Operators in Java →

Home Visit Our YouTube Channel