Variables, Access modifiers, static Keyword | Java

Xander BillaXander Billa
10 min read

Variables

To play with data we need to store the data. To store the data we need some container and those containers are called variables. Variables are the container that is stored for hold some values of a specific data type. Variables are divided based on different parameters.

Based on type of value

Variables are divided into two types -

Primitive variable:

Use to represent primitive value. For example -

int x = 10

Reference variable:

Used to refer objects. For example -

Student st = new Student();

Based on position Declaration and behaviour

Variables are divided into three types -

Instance variable

  • Also double variable for attribute.

  • If the value of the variable is varied from object such type of variable are called instance variable.

  • For every object a separate copy of instance variable will be created.

  • It should be declared within a class directly but outside of method or block or constructor

  • Instance variable will be created at the time of object creation and destroyed at the time of object destruction. Hence, scope of instance variable is exactly same as the scope of object.

  • Stored in the heap of memory as a part of object.

  • We can't access instance variable directly from static area but we can access by using object reference.

  • We can access instance variable directly from instance area.

//Example 1
public class App {

    int x = 10;

    public static void main(String[] args){
        App a = new App();
        System.out.println(a.x);

        // Non static variable X can't be referenced from static context
        System.out.println(x); //Invalid
    }
}
  • For instance variable java will always provide default values and we are not required to perform initialization explicitly.
public class App {
    int i;
    double d;
    boolean b;
    String s;
    char c;
    int[] x;

    public static void main(String[] args){
        App a = new App();
        System.out.println(a.i); // 0
        System.out.println(a.d); // 0.0
        System.out.println(a.b); // false
        System.out.println(a.s); // null
        System.out.println(a.c); // whitespace
        System.out.println(a.x); // null
    }
}

Static variable

  • If the value of variable is fixed for all objects then it is not recommended to declare variable as instance variable.

  • We need to declare such type of variable at class level by using static modifier.

  • In the case of instance variable for every object a separate copy will be created. But in the case of static variable a single copy will be created at class level and shared by every object of class.

  • It should be declared within the class directly but outside of any method/block/constructor.

  • Static variable will be created at the time of class loading and destroyed at the time of class unloading hence scope of static variables is exactly same as scope of .class file.

  • when we run Java file following things happen in internally -

    S1. Start JVM.
    S2. Create and start main thread.
    S3. Locate Test.class file.
    S4. Load Test.class file. (At this time static variable created)
    S5. Execute main method.
    S6. Unoad Test.class file. (At this time static variable is destroyed)
    S7. Terminate main thread.
    S8. Shutdown JVM.

  • Static variable studied in method area.

  • We can access static variable using object reference or class name but recommended to use class name.

  • Within the same class it is not recommended to use the class name and we can assign directly.

class App {
    static int x = 10;

    public static void main(String[] args) {
        System.out.println(App.x); // Accessing using class name
        System.out.println(x);      // Accessing directly in same class
    }
}

class Test {
    public static void main(String[] args) {
        App app = new App();
        System.out.println(App.x); // Accessing using class name
        System.out.println(app.x); // Also works, but not recommended for static variables
    }
}
  • For static variable JVM will provide the default values and we are not required to perform initialisation explicitly.
public class App {
    static int i;
    static double d;
    static boolean b;
    static String s;
    static char c;
    static int[] x;

    public static void main(String[] args){
        System.out.println(i); // 0
        System.out.println(d); // 0.0
        System.out.println(b); // false
        System.out.println(s); // null
        System.out.println(c); // whitespace
        System.out.println(x); // null
    }
}
  • Static variables in Java are often referred to as class-level variables or class fields. This is because they are associated with the class itself rather than with instances of the class. These variables are shared among all instances of the class and can be accessed using the class name.
public class Test {
    static int x = 10;
    int y = 20;
    public static void main(String[] args) {
        Test t1 = new Test();
        Test t2 = new Test();
        t1.x = 888;
        t2.y = 999;
        System.out.println(t2.x + "..." + t2.y); // 888...999
        System.out.println(t1.x + "..." + t1.y); // 888...20
    }
}

Local variable

  • Sometimes to be temporary requirement of the programmer we can declare variable.

  • We can declare variable inside method or block or constructors such type of variable is called temporary stack or automatic variable also called local variable.

  • Local variables stored in stack of memory.

  • Local variable will be created by executing the block in which we declared it.

  • For local variable JVM won't provide default variants so we need to provide values explicitly if we're using that variable.

  • Once block execution complete automatically local variable will be destroyed hence the scope of local variable is the block in which we declare.

public class Test {
    public static void main(String[] args) {
        int i = 0;
        for (int j = 0; j < 5; j++) {
            i = j + i;
            System.out.println(j + "..." + i);
            /* Output
             * 0...0
             * 1...1
             * 2...3
             * 3...6
             * 4...10
             */
        }
    }
}
  • We can call and time to local variable in that particular block.

  • For every execution of the block/method/constructor a new local variable will be created.

  • i part of main method so we can access from anywhere within the method, j is part of for loop block so we cant access that outside of block.

Note:

- It's not recommended to perform initialisation for local variables inside logical blog because there is no guarantee for execution of these blocks always at runtime.

- It is highly recommended to perform initialization for local variable at the time of declaration at least with default values.

If you're not declaring any modifier then by default the default modifier is applicable but this rule is only for instance and static variable but not for local variable.

- The only applicable modifier for local variable is final by mistake if we are trying to apply any other modifier then we will get compile time error.

For example -

public class Test {
    public static void main(String[] args) {
        public int x = 0;       // Illegal Modifier only final is permitted
        private int x = 0;      // Illegal Modifier only final is permitted
        protected int x = 0;    // Illegal Modifier only final is permitted
        static int x = 0;       // Illegal Modifier only final is permitted
        transient int x = 0;    // Illegal Modifier only final is permitted
        volatile int x = 0;     // Illegal Modifier only final is permitted
        final int x = 0;        // Valid
        System.out.println(x);
    }
}

Variables - Conclusion

  • For instance in static variable JVM will provide default values if it wont initialise the value explicitly.

  • For local JVM won't provide default values compulsory we should perform initialisation explicitly before using that variable.

  • Instance in static variable can be accessed by multiple threads simultaneously and hence these are not threads safe.

  • In local variable for each thread a separate copy will be created and hence local variable or thread safe.

  • The various combinations of variable in Java should be either resistance static or local and every variable in Java should be either primitive or reference.

public class Test {
    int x = 0;                  //Instance Variable (Primitive Type)
    static String y = "Hello";  //Static Variable (Primitive Type)
    public static void main(String[] args) {
        int[] a = new int[3];   //Reference Variable
    }
}

Access Modifiers

Access modifiers in Java are keywords that specify the visibility or accessibility of a class, method, or variable. There are four main access modifiers in Java:

Public (public):

  • The member (class, method, or variable) declared as public is accessible from any other class.

  • There is no restriction on access.

javaCopy codepublic class MyClass {
    public int myVariable;
    public void myMethod() {
        // Code here
    }
}

Private (private):

  • The member declared as private is accessible only within the same class.

  • It is the most restrictive access level.

public class MyClass {
    private int myVariable;
    private void myMethod() {
        // Code here
    }
}

Protected (protected):

  • The member declared as protected is accessible within the same package and by subclasses (even if they are in different packages).

  • It is more restrictive than public but less restrictive than private.

public class MyClass {
    protected int myVariable;
    protected void myMethod() {
        // Code here
    }
}

Default (Package-Private, no modifier):

  • If no access modifier is specified, the default access level is package-private.

  • The member is accessible only within the same package.

class MyClass {
    int myVariable;
    void myMethod() {
        // Code here
    }
}

It's important to choose the appropriate access modifier based on the design and requirements of your code. Using the most restrictive access level that still allows your code to function properly is a good practice for encapsulation and security.

static Keyword

In Java, the static keyword is used to define members (fields, methods, and nested classes) that belong to the class rather than to instances of the class. Here are the main uses of the static keyword:

  1. Static Variables (Class Variables):

    • When a variable is declared with the static keyword, it becomes a class variable or a static variable.

    • It is shared among all instances of the class.

    • It is accessed using the class name, not through instances of the class.

    public class Example {
        static int staticVariable = 10;
    }
  1. Static Methods:

    • When a method is declared with the static keyword, it becomes a static method.

    • Static methods belong to the class, and they can be called using the class name without creating an instance of the class.

    • They cannot directly access instance variables and instance methods (non-static members) of the class.

    public class Example {
        static void staticMethod() {
            // Code here
        }
    }
  1. Static Blocks:

    • A static block is a block of code enclosed in curly braces {} and marked with the static keyword.

    • It is executed when the class is loaded into memory, and it is used for static initialization.

    • Static blocks are often used to initialize static variables.

    public class Example {
        static {
            // Code for static initialization
        }
    }
  1. Static Nested Classes:

    • A nested class that is declared as static is called a static nested class.

    • It can access only static members of the outer class and does not have an implicit reference to an instance of the outer class.

    public class OuterClass {
        static class StaticNestedClass {
            // Code here
        }
    }
  1. Static Import:

    • The static keyword can also be used with the import statement to import static members of a class directly into another class.

    • This allows you to use static members without qualifying them with the class name.

        import static mypackage.MyClass.myStaticMethod;

        public class AnotherClass {
            public static void main(String[] args) {
                myStaticMethod(); // No need to use MyClass.myStaticMethod()
            }
        }
  1. Static Constants:

    • It is a common practice to declare constants as static final variables in Java.

    • These constants are shared among all instances of the class and can be accessed using the class name.

        public class Constants {
            public static final double PI = 3.14159;
        }
  1. Static Factory Methods:

    • Static methods are often used as factory methods to create instances of a class.

    • These methods provide a way to create objects without directly using the constructor.

        public class MyClass {
            private int value;

            private MyClass(int value) {
                this.value = value;
            }

            public static MyClass createInstance(int value) {
                return new MyClass(value);
            }
        }
  1. Static Polymorphism:

    • Static polymorphism, also known as method overloading, allows a class to have multiple methods with the same name but different parameters.

    • This is determined at compile time based on the method signature.

        public class MathOperations {
            public static int add(int a, int b) {
                return a + b;
            }

            public static double add(double a, double b) {
                return a + b;
            }
        }

The static keyword plays a crucial role in Java for managing shared resources, reducing memory footprint, and providing utility methods that don't require an instance of the class. However, it's essential to use it judiciously, as misuse can lead to potential issues related to global state and testability.

0
Subscribe to my newsletter

Read articles from Xander Billa directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Xander Billa
Xander Billa

Myself Vikas Singh from Varanasi, Uttar Pradesh. Learning and exploring technical domains at Acharya Institute, Bangalore (IN) from the last two years. The main goal is to learn as much domains, tool