STATIC - JAVA: Learn JAVA Quickly (2017)

JAVA: Learn JAVA Quickly (2017)

CHAPTER 7. STATIC

All attributes and methods that we covered belong to some object, except one. Do you remember seasonOfYear() method? What was difference? Of course method has static modifier, but what does it means? Is there any object whose is used for call of this method? No. So, static fields and methods belong to class, not an object.

If there is a need for a variable to be common to all object of some java class, then it is supposed to be static variables(class variables).All instances share the same copy of the variable. Static variables are initialized only once.

Like static variables, static methods belong to class, not and object. Static method is called by class name. It is time so see some examples of static. Create StaticClass which will include this fields:

intval = 3;

staticintval2 = 4;

staticvoid changeValue() {

val2 = 6;

System.out.println(val2);

}

staticvoid print() {

System.out.println("Static method calling!");

}

So, in our main method we will call static methods:

StaticClass.print();

StaticClass.changeValue();

expected: Static method calling! Will be printed to console

6

Let`s now change val2to valinside changeValue() method. What will happen? It is complaining: Cannot make a static reference to the non-static field val. It is because static method can only access static fields. There is also another way for calling static methods, result will be same:

print();

changeValue();

Now when we covered everything that is needed, our famous main method can be explained in total.

public – method is visible in whole project.

static – method belong to class. Reason why main is static is because it can be ambiguity, compile doesn`t know which constructor to call.

void – method doesn`t return any value.

Ok, let`s see now one very interesting example:

static{

System.out.println("static");

}

publicstaticvoid main(String[] args) {

System.out.println("main");

}

expected: static will be printed to console

main

How this happens? Aren`t we said that methods are executing in main method? This is called static block. Static block will be executed when a class is first loaded into the JVM, even before main method.

Output of this program will be random number from 0 to 1:

System.out.println("Random number: " + Math.random());

But, how is this working? Just like System.out.println();

java.lang.System

java.land.Math

Both classes have their static methods that can be called. They don`t need object so it is simplified. So, methods that we already commonly used, out(), is static method from class System, on which class name is called. It is same with random() method from Math class. Try to use other methods like this:

inta = 4;

intb = 2;

doublec = 2.4;

System.out.println("Minimum is: " + Math.min(a, b));

System.out.println("Maximum is: " + Math.max(a, b));

System.out.println("Pow of c is: " + Math.round(c));