Java Variables

Variables in Java are containers for storing data values. Each variable has a specific type that determines the kind of data it can store. In this tutorial, we’ll explore the basics of variables in Java.

Declaring and Initializing Variables

In Java, you need to declare a variable with its type and optionally initialize it:

int number = 10; // Declares an integer variable and assigns a value
    String name = "Alice"; // Declares a string variable
    boolean isJavaFun = true; // Declares a boolean variable

Types of Variables

Java supports several data types, including:

  • Primitive types: int, double, char, boolean, etc.
  • Reference types: Classes, arrays, or interfaces (e.g., String).

Variable Naming Rules

Here are some important rules for naming variables:

  • Variable names must start with a letter, _, or $.
  • They cannot start with a number.
  • Names are case-sensitive (e.g., myVar and myvar are different).

Example Program

Here’s a simple example using different types of variables:

public class VariablesExample {
        public static void main(String[] args) {
            int age = 25;
            double salary = 45000.50;
            String name = "Alice";
            boolean isEmployed = true;

            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Salary: $" + salary);
            System.out.println("Employed: " + isEmployed);
        }
    }

Output:

Name: Alice
    Age: 25
    Salary: $45000.5
    Employed: true

Next Steps

Experiment with different variable types and operations. Variables are a fundamental concept in Java and programming in general. Happy coding! Now you can learn about if else statements!