access static method from static variable

  • Last Update :
  • Techknowledgy :

We cannot directly access the instance variables within a static method because a static method can only access static variables or static methods.,An instance variable, as the name suggests is tied to an instance of a class. Therefore, accessing it directly from a static method, which is not tied to any specific instance doesn't make sense. Therefore, to access an instance variable, we must have an instance of the class from which we access the instance variable.,Can we declare a static variable within a method in java?,Can we initialize static variables in a default constructor in Java?

Example:

public class Test {
   public int instanceVariable = 10;
   public static void main(String args[]) {
      Test test = new Test();
      System.out.println(test.instanceVariable);
   }
}

Output:

10

Suggestion : 2

Last Updated : 16 Jun, 2021,GATE CS 2021 Syllabus

Static variable: 5

Static variable: 5

 

prog.java: 16: error: non - static variable a cannot be referenced from a static context
System.out.println("Non - Static variable:" + a); ^
1 error

Value of a = 0
Value of b = 1
Value of a = 0
Value of b = 2

Suggestion : 3

Syntax:

<class-name>.<variable-name>

Step 1) Copy the following code into a editor

public class Demo {
   public static void main(String args[]) {
      Student s1 = new Student();
      s1.showData();
      Student s2 = new Student();
      s2.showData();
      //Student.b++;
      //s1.showData();
   }
}

class Student {
   int a; //initialized to zero
   static int b; //initialized to zero only when class is loaded not for each object created.

   Student() {
      //Constructor incrementing static variable b
      b++;
   }

   public void showData() {
      System.out.println("Value of a = " + a);
      System.out.println("Value of b = " + b);
   }
   //public static void increment(){
   //a++;
   //}

}

Step 4) It is possible to access a static variable from outside the class using the syntax ClassName.Variable_Name. Uncomment line # 7 & 8 . Save , Compile & Run . Observe the output.

Value of a = 0
Value of b = 1
Value of a = 0
Value of b = 2
Value of a = 0
Value of b = 3
6._
class Test {
   static {
      //Code goes here
   }
}

Example: How to access static block

public class Demo {
   static int a;
   static int b;
   static {
      a = 10;
      b = 20;
   }
   public static void main(String args[]) {

      System.out.println("Value of a = " + a);
      System.out.println("Value of b = " + b);

   }
}

Suggestion : 4

The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class.,If you apply static keyword with any method, it is known as static method.,The static variable gets memory only once in the class area at the time of class loading.,A static method can be invoked without the need for creating an instance of a class.

111 Karan ITS
222 Aryan ITS
1
1
1
1
2
3
Output: 111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Output: 125
Output: Compile Time Error

Suggestion : 5

Can a Non Static Method Access a Static Variable/M..., Learn Java, Programming, Spring, Hibernate throw tutorials, examples, and interview questions ,Can you overload or override static method in Java? (answer),How to convert lambda expression to method reference in Java 8?


public class StaticTest {

   public static int iStatic = 10;

   public void nonStatic() {
      System.out.println("can access static variable inside non-static method : " +
         iStatic);
      main(new String[2]);
   }

   public static void main(String[] args) {
      System.out.println("Inside main method");
   }

}

Suggestion : 6

Static Methods can access class variables(static variables) without using object(instance) of the class, however non-static methods and non-static variables can only be accessed using objects. Static methods can be accessed directly in static and non-static methods. Syntax: Static keyword followed by return type, followed by method name.,Unlike non-static variables, such variables can be accessed directly in static and non-static methods.,Here we have a static method disp() and two static variables var1 and var2. Both the variables are accessed directly in the static method.,Static keyword can be used with class, variable, method and block. Static members belong to the class instead of a specific instance, this means if you make a member static, you can access it without object. Let’s take an example to understand this:

Static members are common for all the instances(objects) of the class but non-static members are separate for each instance of class.

class SimpleStaticExample {
   // This is a static method
   static void myMethod() {
      System.out.println("myMethod");
   }

   public static void main(String[] args) {
      /* You can see that we are calling this
       * method without creating any object. 
       */
      myMethod();
   }
}

Output:

myMethod

As you can see that both the static variables were intialized before we accessed them in the main method.

class JavaExample {
   static int num;
   static String mystr;
   static {
      num = 97;
      mystr = "Static keyword in Java";
   }
   public static void main(String args[]) {
      System.out.println("Value of num: " + num);
      System.out.println("Value of mystr: " + mystr);
   }
}

Output:

Static Block 1
Static Block 2
Value of num: 98
Value of mystr: Block2

Here we have a static method disp() and two static variables var1 and var2. Both the variables are accessed directly in the static method.

class JavaExample3 {
   static int var1;
   static String var2;
   //This is a Static Method
   static void disp() {
      System.out.println("Var1 is: " + var1);
      System.out.println("Var2 is: " + var2);
   }
   public static void main(String args[]) {
      disp();
   }
}

Suggestion : 7

Static methods cannot access or change the values of instance variables, but they can access or change the values of static variables.,Static methods only have access to other static variables and static methods. Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods. However, non-static methods have access to all variables (instance or static) and methods (static or non-static) in the class.,Non-static methods and constructors can use any instance or static variables in the class., Non-static methods and constructors can use any instance or static variables in the class.

class ClassName {
   // static variable
   public static type variableName;

   // static method
   public static returnType methodName(parameters) {
      // implementation not shown
   }
}
// To call a static method or variable, use the Class Name
System.out.println(ClassName.staticVariable);
ClassName.staticMethod();
public class Temperature {
   private double temperature;
   public static double maxTemp = 0;

   public Temperature(double t) {
      temperature = t;
      if (t > maxTemp)
         maxTemp = t;
   }

   public static void main(String[] args) {
      Temperature t1 = new Temperature(75);
      Temperature t2 = new Temperature(100);
      Temperature t3 = new Temperature(65);
      System.out.println("Max Temp: " + Temperature.maxTemp);
   }
}

Suggestion : 8

To access a static variable, we provide the name of the class that defines the variable, followed by a dot (.), followed by the name of the variable, as shown in the following generalized code:,Earlier we learned that each static method and static variable is accessed through the class that defines it. For example, to access the static variable maxCalories, which is defined by the VirtualPet class, we use the following code:,Static variables are often used to maintain settings whose values should not change once a program has started. To prevent a variable’s value from changing, we define that variable as a constant, as discussed in the next section.,In the preceding code, the use of the class name VirtualPet is not merely a matter of syntax; VirtualPet actually refers to an object that defines the variable maxCalories. The object referenced by VirtualPet is an automatically created instance of the built-in Class class.

class SomeClass {
   static
   var identifier = value;
}
5._
package zoo {
   internal class VirtualPet {
      private static
      var maxNameLength = 20;
      private static
      var maxCalories = 2000;

      private
      var petName;
      // Give each pet 50% of the maximum possible calories to start with.
      private
      var currentCalories = VirtualPet.maxCalories / 2;

      public
      function VirtualPet(name) {
         setName(name);
      }

      public
      function eat(numberOfCalories) {
         var newCurrentCalories = currentCalories + numberOfCalories;
         if (newCurrentCalories > VirtualPet.maxCalories) {
            currentCalories = VirtualPet.maxCalories;
         } else {
            currentCalories = newCurrentCalories;
         }
      }

      public
      function getHunger() {
         return currentCalories / VirtualPet.maxCalories;
      }

      public
      function setName(newName) {
         // If the proposed new name has more than maxNameLength characters...
         if (newName.length > VirtualPet.maxNameLength) {
            // ...truncate it
            newName = newName.substr(0, VirtualPet.maxNameLength);
         } else if (newName == "") {
            // ...otherwise, if the proposed new name is an empty string,
            // then terminate this method without changing petName
            return;
         }

         // Assign the new, validated name to petName
         petName = newName;
      }

      public
      function getName() {
         return petName;
      }
   }
}
package zoo {
   internal class VirtualPet {
      private static
      var maxNameLength = 20;
      private static
      var maxCalories = 2000;

      private
      var petName;
      // Give each pet 50% of the maximum possible calories to start with.
      private
      var currentCalories = VirtualPet.maxCalories / 2;

      public
      function VirtualPet(name) {
         setName(name);
      }

      public
      function eat(numberOfCalories) {
         var newCurrentCalories = currentCalories + numberOfCalories;
         if (newCurrentCalories > VirtualPet.maxCalories) {
            currentCalories = VirtualPet.maxCalories;
         } else {
            currentCalories = newCurrentCalories;
         }
      }

      public
      function getHunger() {
         return currentCalories / VirtualPet.maxCalories;
      }

      public
      function setName(newName) {
         // If the proposed new name has more than maxNameLength characters...
         if (newName.length > VirtualPet.maxNameLength) {
            // ...truncate it
            newName = newName.substr(0, VirtualPet.maxNameLength);
         } else if (newName == "") {
            // ...otherwise, if the proposed new name is an empty string,
            // then terminate this method without changing petName
            return;
         }

         // Assign the new, validated name to petName
         petName = newName;
      }

      public
      function getName() {
         return petName;
      }
   }
}
static
const IDENTIFIER = value
class SomeClass {
   static
   function methodName(identifier1 = value1,
      identifier2 = value2,
      ...
      identifiern = valuen) {}
}
package {
   import flash.system.*;

   public class MailReader {
      static
      var theme;
      if (Capabilities.os == "MacOS") {
         theme = "MAC";
      } else if (Capabilities.os == "Linux") {
         theme = "LINUX";
      } else {
         theme = "WINDOWS";
      }
   }
}
VirtualPet.maxCalories