Java Programming

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 is not actually, Did not get anything. Only after executing new the data storage space will 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, 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. 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 a static Data member 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 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.

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 “leadership” 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. On the 2nd day 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 affecting an instance of a class are preferred to be declared as class methods.


First attempt at SumAverage.java

class SumAverage {

public static void main (String arguments []) {

 int sum = 0;




 for (int i = 0; i <arguments.length; i ++) {

 sum + = arguments [i];

}

System.out.println ("Sum is:" + sum);

 System.out.println ("Average is:" + (float) sum / arguments.length);

}

}

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

SumAverage.java:9: 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:

class Student

{

                String S_name;

                int S_rollNo;

               

               

                static String school_name;

               

                // static counter to set unique roll no

                static int counter = 0;

               

               

                public Student(String name)

                {

                                this.S_name = name;

                               

                                this.S_rollNo = setRollNo();

                }

               

                static int setRollNo()

                {

                                counter++;

                                return counter;

                }

               

                static void setSchoolName(String name){

                                school_name= name ;

                }

               

               

                void getStudentInfo(){

                                System.out.println("Student Name : " + this.S_name);

                                System.out.println("Student RollNo : " + this.S_rollNo);

                               

                               

                                System.out.println("School Name : " + school_name);

                }

}




//Driver class

public class StaticDemo

{

                public static void main(String[] args)

                {

               

                                Student.setSchoolName("oxford grammar school");

               

                                Student s1 = new Student("Fawad khan");

                                Student s2 = new Student("Shaista");

                               

                                s1.getStudentInfo();

                                s2.getStudentInfo();

                               

                }

}

Java Static

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

 

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button