In this tutorial, we will learn about the Static Data in Java, or its types, and how to use them with the help of examples.
Static data is the data declare using ‘static’ keyword. The static data creates a single copy for the class which will be share by all the objects of that class is know as Static Data in Java.
Syntax
Syntax of Static datastatic datatype var;
Example of Static data
Input Value
Example of Static data in Javapublic class staticm { int n; static int rec; public void input (int z) { n=z; rec++; } public void show() { System.out.println("Data:" +n); } public void showrec() { System.out.println("Data:" +rec); } public static void main (String args[]) { staticm a=new staticm(); staticm b= new staticm(); a.input(15); b.input(16); a.show(); a.showrec(); b.show(); b.showrec(); } }
Let’s run the code
Output Value
Static Method in Java
This method is the method declare using static keyword. Static method define within class occupy single copy of memory which object name (but object calling also allowed) static method only holds static data.
Syntax
Syntax of Static Method in Javapublic static return function(par,par,…) { }
Example of Static Method in Java
Input Value
Example of Static Method in Javapublic class staticm { int n; static int rec; public void input (int z) { n=z; rec++; } public void show() { System.out.println("Data:" +n); } public void showrec() { System.out.println("Data:" +rec); } public static void main (String args[]) { staticm a=new staticm(); staticm b= new staticm(); a.input(11); a.show(); b.input(12); b.show(); b.showrec(); } }
Let’s run the code
Output Value
Nesting Of Methods
Nesting of methods means one user defined function can call the other user defined function without creating object of the class.
Syntax of Nesting of methods
Syntax of Nesting of methodsclass Main { method1(){ } method2() { method1(); } method3() { method2(); } }
Example of Nesting of methods
Input Value
Example of Nesting of methodspublic class staticm { public void show() { System.out.println("Basic Engineer"); } public void disp() { show(); System.out.println("Hello Student"); } public static void main (String args[]) { staticm p= new staticm(); p.show(); p.disp(); } }
Let’s run the code
Output Value
If you have any queries regarding this article or if I have missed something on this topic, please feel free to add in the comment down below for the audience. See you guys in another article.
To know more about JAVA Wikipedia please click here .
Stay Connected Stay Safe, Thank you
0 Comments