Static

Java static member variable example

Want to learn quickly?
Try one of the many quizzes. More than Java 400 questions with detailed answers.

Add Comment

  • Static Members cannot access in the non-static methods
    Static Members can access in the static methods only

    but u have written above as
    #
    *
    #
    * Static members are class level variables and shared by all the objects
    #
    * of the class.

    • Static memebers can be accessed from non-static methods,
      But the reverse is not true.
      i.e., static methods cannot access non-static members.
      Compliler will give error like :”Non-static member is referenced from a static context”

  • Only static methods may access static members.
    hence, change oublic int numberOfObjects() to public static int numberOfObjects()

    • You can also access static member from non static methods but it’s reverse not possible. so there is no need to change the code.

  • given below is a program ive been trying to create,it has two static variables, and all the mathods are static and they dont have any return type.i’m enable to get the output of the prog.i need help please!

    import java.util.Scanner;

    class Mathop

    {

    static int a,b;

    public static void getdata(int a,int b)

    {

    Mathop.a=a;

    Mathop.b=b;

    }

    }

    public class Maths

    {

    public static void ADD(int a,int b)

    {

    System.out.println(“sum = ” + (a+b));

    }

    public static void SUB(int a,int b)

    {

    System.out.println(“diff = ” + (a-b));

    }

    public static void MUL(int a,int b)

    {

    System.out.println(“mul = ” + (a*b));

    }

    public static void DIV(int a,int b)

    {

    System.out.println(“div = ” + (a/b));

    }

    public static void main(String[] args)

    {

    m.getdata(2,4);

    ADD(a,b);

    SUB(a,b);

    MUL(a,b);

    DIV(a,b);

    }

    }

Sponsors

Facebook Fans