Introduction to Java | Programming Basics

Java Variables

Variables in Java are used to store data that can change during the execution of a program. A variable in Java is a container that holds a value and has a specific data type associated with it. The data type determines the kind of value the variable can store.

Types of Variables in Java

There are several types of variables in Java:

Declaring and Initializing Variables

A variable is declared with a type, followed by its name. Optionally, a value can be assigned to the variable during declaration or afterward. Here's how you declare and initialize a variable in Java:

Code Example


public class VariableExample {
public static void main(String[] args) {
// Declaring variables
    int age = 25;             // Integer variable
    double salary = 45000.50; // Double variable
    char grade = 'A';         // Character variable
    boolean isStudent = true; // Boolean variable
        
    // Outputting variable values
    System.out.println("Age: " + age);
    System.out.println("Salary: " + salary);
    System.out.println("Grade: " + grade);
    System.out.println("Is Student: " + isStudent);
                    }
                }
                    

Output

Age: 25
Salary: 45000.5
Grade: A
Is Student: true

Variable Naming Rules

In Java, there are certain rules for naming variables:

Example of Variable Naming

Code Example


public class VariableNamingExample {
public static void main(String[] args) {
    int myAge = 30;            // Correct variable name
    double salaryAmount = 60000.75; // Correct variable name
    // int 2ndAge = 28;         // Invalid, variable cannot start with a number
    // String class = "Math";   // Invalid, 'class' is a reserved keyword
            }
     }
                    

Data Type Conversion (Type Casting)

Sometimes, you may need to convert one data type into another. This is called type casting in Java. There are two types of type casting:

Example of Type Casting

Code Example


public class TypeCastingExample {
public static void main(String[] args) {
// Implicit casting (widening)
    int num = 100;
    double d = num; // int to double (automatic)
        
    // Explicit casting (narrowing)
    double pi = 3.14;
    int intPi = (int) pi; // double to int (manual)
    System.out.println("Double: " + d);
    System.out.println("Integer: " + intPi);
            }
        }
                    

Output

Double: 100.0
Integer: 3

Practice Exercises

  1. Write a program to swap the values of two variables without using a third variable.
  2. Create a program to calculate the area of a circle, where the radius is a variable.
  3. Write a program to convert a temperature from Celsius to Fahrenheit using variables.

💡 Pro Tip

Always give your variables meaningful names so that your code is easier to understand and maintain.