Showing posts with label Static Variables. Show all posts
Showing posts with label Static Variables. Show all posts

Tuesday, 15 September 2015

Java Tutorial : Java Variables

Master Core Java Concepts!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!

Subscribe Now on YouTube

Types of Variables in Java

A variable is a container that holds data during the execution of a Java program. In Java, variables are categorized into three main types based on where and how they are defined:

  1. Instance Variables: Declared inside a class but outside of any method, constructor, or block, without the static keyword. Each created object gets its own copy.
  2. Static Variables: Declared inside a class with the static keyword. Only one copy exists for the entire class, shared across all instances.
  3. Local Variables: Declared inside a method, constructor, or block. They are accessible only within that specific scope.

Code Example: Defining Java Variables

class Student {
  // Instance variable
  String name;

  // Static variable
  static String schoolCode = "SCH101";

  public void eat() {
    // Local variable
    int numberOfBiscuits = 10;
    System.out.println("Number of biscuits eaten: " + numberOfBiscuits);
  }
}

Accessing Different Variables in Java

public class StudentDemo {
  public static void main(String[] args) {
    // 1. Accessing instance variable via object reference
    Student student = new Student();
    student.name = "John";
    System.out.println("Name: " + student.name);

    // 2. Accessing static variable directly via class name
    System.out.println("School Code: " + Student.schoolCode);

    // 3. Calling method containing local variable
    student.eat();
  }
}

Key Takeaways

✔️ Instance Variables: Tied to class objects; created when an object is instantiated.

✔️ Static Variables: Loaded when the class is loaded; best accessed using ClassName.variableName.

✔️ Local Variables: Temporary variables destroyed as soon as method execution finishes.


Watch More Java Tutorials:

Tutorials