Back to Java Course

Java Course

In Java, variables come in three distinct types: local variables, instance variables, and static variables.

Local Variables:

  • Defined within a specific method or code block

  • Only accessible within that method/block

  • Cease to exist when the method/block completes

Instance Variables:

  • Belong to a specific object or instance of a class

  • Can be accessed throughout the entire class

  • Persist as long as the object exists

Static Variables:

  • Belong to the class itself, not any specific object

  • Can be accessed without creating an instance of the class

  • Shared across all objects of that class

  • Often used for constants or class-level data

Static vs Non Static

screenshot of the app

Now Lets see about Control Flow, there are two types of Control Flow.

  1. Static Control Flow

    • Identification of static members from top to bottom.

    • Execution of static variable assignments and static blocks from top to bottom.

    • Execution of main method.

  2. Instance Control Flow

    • Identification of instance members from top to bottom.

    • Execution of instance variable assignments and instance blocks from top to bottom.

    • Execution of constructor.

Let's see sample code

public class ControlFlow { public static void main(String args[]) { A1 a1 = new A1(); a1.displayA1(); } } class A1 { A1() { System.out.println("In constructor A1"); } static { System.out.println("In static block of A1"); } { System.out.println("In initialization block of A1"); } void displayA1() { System.out.println("In displayA1 method"); } }

Output

screenshot of the app