Variables and Data Types in Java

Subject: Data Structures and Algorithms · Language: Java · Level: beginner · 4 min read

Learn variables, primitive data types, non-primitive data types, declaration, initialization, and type choice.

A variable is a named place in memory where a program stores a value. When you write a program, you often need to remember information such as age, marks, salary, name, count, index, or result. Variables make this possible.

In Java, every variable must have a data type. The data type tells Java what kind of value the variable can store and how much memory is generally needed for that value. This is why Java is called a strongly typed language: you cannot use a variable without clearly telling Java what type of data it will hold.

For example, if you want to store a student's age, you can use `int`. If you want to store a student's name, you can use `String`. If you want to store whether the student passed or failed, you can use `boolean`.

Declaring a Variable

Declaring a variable means creating the variable by writing its data type and name. At this point, you are telling Java that this name will be used to store a value of a particular type.

```java

int age;

```

Here, `int` is the data type and `age` is the variable name. This line tells Java that `age` will store an integer value. A variable name should be meaningful so that anyone reading the code can understand its purpose.

Initialization

Initialization means assigning the first value to a variable. You can declare a variable first and assign the value later, or you can declare and initialize it in the same line.

```java

int age = 20;

```

Here, the variable is declared and initialized in the same line. Java now knows that `age` is an integer variable and its current value is `20`. You can also update the value later if the variable is not declared as `final`.

```java

age = 21;

```

After this line, the old value `20` is replaced by the new value `21`.

Primitive Data Types

Primitive data types are the basic built-in data types of Java. They store simple values directly, such as numbers, characters, and true/false values.

For DSA and coding interviews, you will mostly use `int`, `long`, `char`, `boolean`, and sometimes `double`. For example, array indexes are usually `int`, large sums often need `long`, character problems use `char`, and condition checks use `boolean`.

Why Data Type Choice Matters

Choosing the correct data type prevents wrong answers and runtime issues. Suppose an array contains very large numbers and you are calculating their sum. If the sum becomes bigger than the range of `int`, the answer may overflow and become incorrect. In that case, `long` is a better choice.

Data type also improves code clarity. When another programmer sees `boolean isPrime`, they immediately understand that the variable stores a true/false result. When they see `char ch`, they understand that it stores one character.

Type Casting

Type casting means converting a value from one data type to another. Java performs some safe conversions automatically, such as storing an `int` value inside a `long` variable.

```java

int marks = 85;

long totalMarks = marks;

```

Manual casting is needed when information may be lost. For example, converting a `double` value into `int` removes the decimal part, so Java asks the programmer to write the cast clearly.

```java

double price = 99.75;

int roundedPrice = (int) price;

```

After this conversion, `roundedPrice` becomes `99`. This is important in DSA because careless casting can silently change the answer.

Constants Using final

A constant is a value that should not change after it is assigned. In Java, constants are created using the `final` keyword.

```java

final double PI = 3.14159;

```

After a variable is declared as `final`, Java does not allow reassignment. Constants are useful for fixed values such as maximum marks, tax rate, mathematical values, and configuration values.

Non-Primitive Data Types

Non-primitive data types do not store simple values in the same way as primitives. They store references to objects. A reference means the variable points to the place where the actual object is stored.

Examples of non-primitive data types include `String`, arrays, classes, interfaces, and collection classes such as `ArrayList`, `HashMap`, `HashSet`, and `Queue`.

```java

String name = "Rahul";

int[] marks = {80, 90, 85};

```

Here, `name` refers to a `String` object, and `marks` refers to an integer array. These are called non-primitive because they are object-based or reference-based types.

Primitive vs Non-Primitive

A primitive variable stores a simple value such as `10`, `true`, or `'A'`. A non-primitive variable stores a reference to an object such as a string, array, or collection. Another important difference is that primitive types start with lowercase names like `int`, `long`, and `boolean`, while many non-primitive types start with uppercase names like `String`, `Scanner`, and `ArrayList`.

Choosing the Correct Data Type

Use `int` for normal counting, indexing, loop variables, and most integer-based problems. Use `long` when values can become very large, such as sums in large arrays, factorial-related calculations, or multiplication of big numbers. Use `double` for decimal calculations such as average, percentage, or measurement. Use `char` when working with single characters in strings. Use `boolean` when the result is true or false, such as `isSorted`, `isPrime`, `found`, or `visited`.

Use `String` when storing text, names, words, or sentences. Use arrays when you need to store multiple values of the same type together.

Example Program

```java

public class Main {

public static void main(String[] args) {

int age = 20;

char grade = 'A';

boolean passed = true;

System.out.println("Age = " + age);

System.out.println("Grade = " + grade);

System.out.println("Passed = " + passed);

}

}

``` In this program, `age` stores an integer value, `grade` stores one character, and `passed` stores a true/false value. The `System.out.println` statements print each value on a new line.

Variables in DSA

Variables are used everywhere in DSA. A loop counter like `i`, an answer variable like `sum`, a flag like `found`, and a maximum value like `max` are all variables. When solving problems, first think about what information must be stored. Then choose a meaningful variable name and the correct data type. This habit makes your code easier to write, debug, and explain in interviews.

Practice Question

Create variables for a student's name, roll number, marks, grade, and pass status. Choose the correct data type for each value and print all details in a clean format.

More Java Lessons

Browse all PrepCampus study materials