PhysicsTeacher.in

High School Physics + more

Java Program – how to use static variable and static method?

This Java Program will show how to use static variables and static methods in Java.

Java Program showing use of static variables and static methods

class StaticTest
{

static int j;
int k;

void setVal(int p)
{
k=p;
j=p;//ok ..non-static method can access a static variable

}
static void setStatVal(int p)
{

j=p;
//k=p;

/*the above statement wont compile, because static can access static only
error: non-static variable k cannot be referenced from a static context */
}

void writeVal()
{
System.out.println(“value of j=”+j);
System.out.println(“value of k=”+k);
}

}

class TestMain

{
public static void main(String args[])
{
StaticTest test=new StaticTest();

test.setVal(10);
test.writeVal();

test.setStatVal(20);
test.writeVal();
}

}

Output of the java program

value of j=10
value of k=10
value of j=20
value of k=10

See also  Java Program to find the greatest and smallest numbers
Scroll to top
error: physicsTeacher.in