|2. Variables & Data Types
Chapter 2Java Tutorial~1 min read

Variables & Data Types

Variables आणि Data Types

Java strongly typed language आहे — प्रत्येक variable ला type declare करणे mandatory आहे. Java मध्ये 8 primitive data types आहेत. Type चुकला तर compile time error येतो — Python सारखे runtime error नाही.

Primitive Data Types

Java चे 8 primitive types

java
public class DataTypes {
    public static void main(String[] args) {
        // Integer types
        byte  b  = 127;           // 1 byte, -128 to 127
        short s  = 32000;         // 2 bytes
        int   i  = 2_000_000;     // 4 bytes — most common
        long  l  = 9_000_000_000L; // 8 bytes — L suffix लागतो

        // Floating point
        float  f = 3.14f;         // 4 bytes — f suffix
        double d = 3.14159265;    // 8 bytes — more precise

        // Other
        char  c   = 'A';          // 2 bytes — single quotes
        boolean flag = true;      // true / false

        System.out.println("int: " + i);
        System.out.println("double: " + d);
        System.out.println("char: " + c);
        System.out.println("boolean: " + flag);
    }
}

Variable Declaration

Local, Instance, Static variables

java
public class VariableTypes {

    // Instance variable — object level
    String name = "Rahul";
    int age = 20;

    // Static/Class variable — class level, सगळ्यांसाठी common
    static String schoolName = "ABC School";

    public void show() {
        // Local variable — फक्त method आत
        int marks = 85;
        System.out.println(name + " — " + marks);
        // marks बाहेर access करता येत नाही
    }

    public static void main(String[] args) {
        VariableTypes obj = new VariableTypes();
        obj.show();
        System.out.println(schoolName);  // static — obj नाही लागत
    }
}

Type Casting

Widening vs Narrowing casting

java
// Widening (implicit) — smaller → larger — auto होतो
int a = 100;
long b = a;      // int → long, auto
double d = a;    // int → double, auto

// Narrowing (explicit) — larger → smaller — manually करावे
double pi = 3.99;
int x = (int) pi;   // cast — decimal part cut होतो
System.out.println(x);  // 3

// var — Java 10+ (type inference)
var city = "Pune";   // String type auto
var count = 42;      // int type auto

Key Points — लक्षात ठेवा

  • int (4B), long (8B, L suffix), double (8B), float (4B, f suffix)
  • char — single quotes, String — double quotes (String is not primitive!)
  • boolean — true / false (lowercase)
  • Widening casting automatic, Narrowing needs explicit (int) cast
  • final — constant, बदलता येत नाही — UPPER_CASE convention
0/11 chapters पूर्ण