Variables and Data Types in Java


Introduction

Variables and data types are fundamental concepts in Java programming. Variables store data, and data types specify the type of data a variable can hold. This tutorial explains these concepts with examples.

What is a Variable?

A variable is a container for storing data. Each variable has a name, a type, and a value. In Java, you must declare a variable before using it.

Syntax for Declaring Variables

      = ;
        

For example:

    int age = 25;
        

Data Types in Java

Java has two main categories of data types:

  • Primitive Data Types: Basic data types like int, double, char, boolean, etc.
  • Reference Data Types: Objects and arrays.

Primitive Data Types

Data Type Size Example
byte 1 byte byte b = 10;
short 2 bytes short s = 200;
int 4 bytes int i = 5000;
long 8 bytes long l = 100000L;
float 4 bytes float f = 5.75f;
double 8 bytes double d = 19.99;
char 2 bytes char c = 'A';
boolean 1 bit boolean b = true;

Reference Data Types

Reference data types store the memory address of an object. Examples include:

    String name = "John";
    int[] numbers = {1, 2, 3};
        

Example: Using Variables and Data Types

Step 1: Write the Program

Save the following code in a file named VariablesDemo.java:

    public class VariablesDemo {
        public static void main(String[] args) {
            // Primitive Data Types
            int age = 25;
            double salary = 55000.50;
            char grade = 'A';
            boolean isEmployed = true;
    
            // Reference Data Types
            String name = "John Doe";
            int[] scores = {85, 90, 95};
    
            // Output Values
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Salary: " + salary);
            System.out.println("Grade: " + grade);
            System.out.println("Employed: " + isEmployed);
            System.out.print("Scores: ");
            for (int score : scores) {
                System.out.print(score + " ");
            }
        }
    }
        

Step 2: Compile the Program

Open the terminal, navigate to the file location, and type:

    javac VariablesDemo.java
        

Step 3: Run the Program

Type the following command to run the program:

    java VariablesDemo
        

You should see the output:

    Name: John Doe
    Age: 25
    Salary: 55000.5
    Grade: A
    Employed: true
    Scores: 85 90 95 
        

Conclusion

Variables and data types are essential for managing data in Java programs. By understanding and using them correctly, you can create efficient and effective programs.





Advertisement