JavaCore java

Variables in java

Why Do We Build Software?

  • To solve real-world problems.
  • Software works with data → storing, processing, and displaying.
  • Data can be stored temporarily in memory using variables.

What is a Variable?

  • A variable is like a box where we store data.

  • Each box has a name (identifier) and a type.

  • Example:

    int age = 25;    // 'age' is a variable of type int

Naming Conventions

  • Should start with a letter or _ or $.

  • Cannot start with a number.

  • Use camelCase for variable names.

    • Example: studentName, accountBalance.
  • Avoid special symbols (@, %, -) in names.

  • Variable names should be meaningful.

Strongly Typed Language

  • Java is strongly typed → every variable must have a data type.

  • Examples:

    • int → numbers
    • double → decimal values
    • String → text
    • boolean → true/false

Example Code 1

public class Hello {
    public static void main(String[] args) {
        System.out.println(3 + 5);  // Direct addition
        System.out.println(8 + 7);  // Direct addition
    }
}

Print vs Println

  • print → prints in same line.
  • println → prints and moves to next line.

Example Code 2 – Using Variables

public class Hello {
    public static void main(String[] args) {
        int num = 3;  
        System.out.println(num);   // Prints 3
    }
}

Example Code 3 – Storing Results

public class Hello {
    public static void main(String[] args) {
        int num1 = 3;
        int num2 = 5;
        int result = num1 + num2;
        System.out.println(result);   // Output: 8
    }
}

⚡ Key Point:

  • Think of variables as containers with a name and a type.
  • Java enforces data type safety → you cannot mix types incorrectly.