Java Static Keyword With Programming Examples

Java static keyword

Java static keyword:- Usually, when we create a class, we point out the appearance and behavior of objects of that class. Unless an object of that class is created with new, it does not actually do not get anything. Only after executing new will the data storage space be formally generated and the corresponding methods can be used. But in two special cases, the above method is not applicable. One situation is that you only want to use a storage area to store a specific data-none No matter how many objects are to be created, or even no objects at all.

 Another situation is that we need a special method, it has no responsibility with this class What object is associated. In other words, even if the object is not created, a method that can be called is required. To meet these two requirements, you can use The Java static keyword. Once something is set to static, the data or method will not be associated with any object instance of that class Up. So even though you have never created an object of that class, you can still call a Java static method or access some Java static data. And here Previously, for non-static data and methods, we must create an object and use that object to access the data or methods.



This is due to non Static data and methods must know the specific objects they operate on. Of course, before the official use, because the Java static method does not need to create any Objects, so they cannot simply call other members without referring to a named object, thus directly accessing non-static members Or methods (because non-static members and methods must be associated with a specific object).

Some object-oriented languages ​​use the terms “class data” and “class method”. They mean that the data and methods The class of the body does not exist for any particular object of that class. Sometimes, you will find this name in some other Java books. In order to set a data member or method to static, just precede the definition with this keyword. For example, the following code can generate static Data members and initialize them:

class StaticTest {

Static int i = 47;

 }

Now, although we have made two StaticTest objects, they still only occupy one storage space of StaticTest.i. These two pairs The elephants all share the same i. Consider the following code:

StaticTest st1 = new StaticTest();

StaticTest st2 = new StaticTest();

At this time, both st1.i and st2.i have the same value of 47, because they refer to the same memory area.

There are two ways to reference a Java static variable. As shown above, it can be named by an object, such as st2.i. Can also be used directly It is referenced by the class name, and this does not work in non-static members (it is best to use this method to refer to Java static variables, because it emphasizes that variable The “static” nature of this).

StaticTest.i++;

Among them, the ++ operator will increase the value of the variable. At this time, the value of both st1.i and st2.i is 48.

Similar logic applies to Java static methods. You can refer to a static method through an object like any other method, or you can use a special syntax The format “class name. method ()” to be quoted. The definition of a Java static method is similar:

 class StaticFun {

static void incr() {

StaticTest.i++;

}

 }


It can be seen that the method incr() of StaticFun increases the value of static data i. Through the object, incr() can be called in a typical method:

StaticFun sf = new StaticFun();

 sf.incr();

Or, since incr() is a Java static method, it can be called directly through its

class: StaticFun.incr();

Although it is “static”, as long as it is applied to a data member, it will clearly change the way the data is created (one member per class, and each object has a non-static member). If applied to a method, it is not so dramatic. For methods, Java static is an important use It is to help us call that method without having to create an object. As you will see later, this is very important-especially Don’t be when defining the main() method, the entry point of the program. Like any other method, the Java static method can also create its own type of named object. So the Java static method is often used as a “leader “Sheep” uses it to generate a series of “instances” of its own type.

The relationship between class and instance variables can be traced directly to that between class and instance methods to compare. Class methods are available for all instances of the class itself and can be made available to other classes will. In addition, with class methods, unlike instance methods, no instance of the class is necessary, so whose class methods can be called. The Java class library contains e.g. a class named Math. The Math class defines a set of mathematical operations that you can use in any program or on any of the number types, as is the case in the following:

float root = Math.sqrt (453.0);

System.out.print (“The larger of x and y is” + Math.max (x, y));

To define class methods, use the Java static keyword in front of the method definition, as when creating it of class variables. The class method max could have the following signature, for example:

static int max (int arg1, int arg2) {…}

Java provides wrapper classes or envelope classes for all basic types in a similar way, e.g. the classes integer, Float, and Boolean. Using the class methods defined in these classes, you can classify objects in basic types and convert reverse. The class method parseInt () e.g. in the Integer class works with strings. A string is given as an argument sent the method. This string is used to determine a return value that is returned as an int becomes:

int count = Integer.parseInt (“42”) // Returns 42


In the above statement, the parseInt () method returns the string “42” as an integer with the value 42. This value is saved in the variable count. If the keyword static is not in front of the name of a method, this becomes an instance method. Instance methods always refer to a concrete object instead of the class itself.  you have one Created an instance method called feedJabberwock () that fed a single Jabberwock object. Most of the methods applicable to or affecting a particular object should be considered as Instance methods are defined. Methods that offer some general utility and are not directly related to affecting an instance of a class are preferred to be declared as class methods.

First attempt at java static keyword example:

At first glance, this program looks very simple and clear. A for loop can do that Argument array, the sum, and the mean value is determined and output as the last step. But what happens if you try to compile this program? You get the following error:

SumAverage.java:6: Incompatible type for + =. Can’t convert java.lang.String to int sum + = args [i];

This error message appears because the argument array is a string array. Although integers are sent to the program in passed on the command line, these integers are converted to strings and then stored in the array. In order to sum these integers, they must be converted back from strings to integers. In the Class Integer, there is the class method parseInt (), which serves exactly this purpose. If you change line 6 so that using this method here, the program works:

sum + = Integer.parseInt (args [i]);

If you compile the program now, it will run without errors and give the expected results. Java SumAverage For example, 1 2 3 gives the following output:

Sum is: 6

Average is: 2



Programming example: how to use java static keyword:

Java Static


Related Article:

Java variables

Java Array

 

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: