Board Formulas
β˜• JavaπŸ“… Day 2

Variables in Java

Declare, initialize and use variables in Java. Primitive types, default values and variable scope.

🎯

Learning objectives

  • β†’Declare and initialize primitive variables
  • β†’Know the 8 primitive types and their sizes
  • β†’Understand local, instance and static variables

πŸ’‘ Key points

  • Java is statically typed β€” every variable has a declared type known at compile time.
  • Eight primitive types: byte, short, int, long, float, double, char, boolean.
  • Local variables MUST be initialized before use. Instance/static variables get default values.
  • Use final to declare a constant β€” value cannot change after initialization.

πŸ’» Code examples(3)

#1Declaring variables
java
int age = 21;
double price = 99.99;
char grade = 'A';
boolean isActive = true;
String name = "Rohan";      // String is a class, not a primitive
final double PI = 3.14159;  // constant
Every declaration is [modifier] type name = value;. String literals use double quotes; char uses single quotes.
#2Default values (instance variables)
java
public class Player {
    int score;         // defaults to 0
    double health;     // defaults to 0.0
    boolean alive;     // defaults to false
    String name;       // defaults to null
}
Instance and static variables are auto-initialized to type defaults. Local variables are NOT β€” using them uninitialized is a compile error.
#3Scope demo
java
public class ScopeDemo {
    static int shared = 10;         // class scope
    int perObject = 5;              // instance scope

    void method() {
        int localVar = 3;           // method scope
        System.out.println(localVar);
    }
}

🎯 Practice

Q1. What is the difference between int and Integer in Java?+

int is a primitive (holds a raw value). Integer is a wrapper class (an object). Integer can be null and used in collections; int cannot.

Q2. Will this compile: int x; System.out.println(x); ?+

No. x is a local variable and must be explicitly initialized before use, otherwise the compiler rejects it.

Q3. Declare a final constant TAX_RATE with value 0.18.+

final double TAX_RATE = 0.18;

πŸ“ Notes

Primitive types cheat sheet

| Type | Size | Range / Example | |---|---|---| | byte | 8-bit | βˆ’128 to 127 | | short | 16-bit | βˆ’32,768 to 32,767 | | int | 32-bit | ~Β±2.1 billion (default for whole numbers) | | long | 64-bit | very large integers, suffix L | | float | 32-bit | decimal, suffix f | | double | 64-bit | decimal (default for decimals) | | char | 16-bit | single Unicode character 'A' | | boolean | JVM-dependent | true / false |

Naming rules

  • Start with a letter, _ or $; then letters/digits.
  • Case-sensitive: age and Age are different.
  • Cannot be a reserved keyword (class, int, if, …).
  • Convention: camelCase for variables, SCREAMING_SNAKE_CASE for constants.