Java Variables and Literals

Master the basics of storing and using data in Java. Learn how variables work and what literals mean in simple terms.

What is a Variable?

A variable is a container that stores data in your program. Think of it like a labeled box where you can put information, use it later, and even change what's inside. Every variable has three things: a name, a type (what kind of data it holds), and a value (the actual data).

  • Name: What you call your variable (like myAge, studentName)
  • Type: What kind of data it stores (numbers, text, true/false)
  • Value: The actual data stored inside the variable

Real-World Analogy: Think of a variable like a mailbox. The mailbox has a label (name), can only hold certain types of mail (type), and contains your actual mail (value). You can check what's inside, take it out, or put new mail in.

Declaring and Using Variables

To use a variable, you must first declare it by specifying its type and name. You can also assign a value right away.

Example: Basic Variable Declaration


public class VariableExample {
    public static void main(String[] args) {
        // Declaring and initializing variables
        int age = 20;                      // Integer (whole number)
        double height = 5.8;               // Decimal number
        String name = "Alice";             // Text
        boolean isStudent = true;          // True or False
        
        // Printing the variables
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Height: " + height);
        System.out.println("Is Student: " + isStudent);
        
        // Changing variable values
        age = 21;
        System.out.println("Updated Age: " + age);
    }
}
Output:
Name: Alice
Age: 20
Height: 5.8
Is Student: true
Updated Age: 21

Explanation:

  • int age = 20; - Creates a variable named "age" of type int (integer) and assigns it the value 20
  • double height = 5.8; - Creates a decimal number variable named "height"
  • String name = "Alice"; - Stores text inside the variable "name"
  • boolean isStudent = true; - Stores a true/false value
  • age = 21; - You can change what's stored in a variable by assigning a new value

What is a Literal?

A literal is a fixed value written directly in your code. It's the actual data you write, not a container. For example, when you write "20" directly in code, that 20 is a literal. Literals are the real values, while variables are containers that hold those values.

Key Difference: A variable is like a water bottle (the container), while a literal is like the water inside (the actual value). When you write int age = 20;, "age" is the variable, and "20" is the literal.

  • Integer Literal: 10, 100, -5 (whole numbers)
  • Decimal Literal: 3.14, 5.8, 0.5 (numbers with decimals)
  • String Literal: "Hello", "Java", "CrackEase" (text in quotes)
  • Boolean Literal: true, false (only two values)
  • Character Literal: 'A', 'x', '9' (single character in quotes)

Literals in Action

Here's how literals work directly in code:

Example: Different Types of Literals


public class LiteralExample {
    public static void main(String[] args) {
        // Integer Literals (no decimal point)
        int score = 95;              // 95 is a literal
        int count = -10;             // -10 is a literal
        
        // Double Literals (with decimal point)
        double price = 19.99;        // 19.99 is a literal
        double pi = 3.14159;         // 3.14159 is a literal
        
        // String Literals (text inside quotes)
        String message = "Welcome to Java!";  // "Welcome to Java!" is a literal
        
        // Boolean Literals (only true or false)
        boolean isPassed = true;     // true is a literal
        boolean isFailure = false;   // false is a literal
        
        // Character Literals (single character in single quotes)
        char grade = 'A';            // 'A' is a literal
        
        // Direct literals in print statements
        System.out.println(100);           // 100 is used directly as a literal
        System.out.println("Score: " + score);
        System.out.println("Price: $" + price);
    }
}
Output:
100
Score: 95
Price: $19.99

Explanation:

  • Every number, text, or value you write directly in code is a literal
  • The variable stores the literal value, but you can reuse it later
  • Literals give variables their initial values
  • You can use literals anywhere you need a fixed value

Common Variable Types

1. int - Whole Numbers

Used to store whole numbers without decimals, like ages, counts, scores, or quantities.

Examples: int age = 25; int students = 150; int score = -5;

2. double - Decimal Numbers

Used to store numbers with decimals, like prices, heights, weights, or measurements.

Examples: double price = 99.99; double height = 5.9; double temperature = 37.5;

3. String - Text

Used to store text like names, addresses, messages, or any sequence of characters.

Examples: String name = "John"; String city = "Mumbai"; String message = "Hello World";

4. boolean - True or False

Used to store true/false values, perfect for decisions and conditions in your program.

Examples: boolean isPassed = true; boolean hasLicense = false; boolean isWorking = true;

5. char - Single Character

Used to store a single character like a letter, digit, or symbol.

Examples: char grade = 'A'; char initial = 'J'; char symbol = '@';

Rules for Naming Variables

Java has rules about what you can name your variables. Follow these to write clean code:

  • Start with a letter: Use a letter (a-z, A-Z), underscore (_), or dollar sign ($)
  • No spaces: Variable names cannot have spaces
  • Case-sensitive: age, Age, and AGE are three different variables
  • No special characters: Don't use symbols like @, #, %, &
  • Use meaningful names: Write studentName instead of sn for clarity
  • camelCase is standard: Start lowercase, capitalize first letter of next words (myFirstName)

Good Examples: firstName, totalScore, isPassed, userAge
Bad Examples: 1name (starts with number), first name (has space), user@ (has symbol)