In java, there are various uses of static keyword few of them you can see with example.
static variable :
It is used in java for a single copy in class.
Example :
package com.pkjavacode.com; /** * * @author pradeep */ public class StaticExample { static String company = "Infosys Limited"; String name; String id; long salary; public StaticExample(String name, String id, long salary) { this.name = name; this.id = id; this.salary = salary; } public static void main(String arg[]) { StaticExample se = new StaticExample("Pradeep Yadav", "IL981243", 40000); System.out.println("Employee Name :" + se.name + "\nEmployee Id :" + se.id + "\nEmployee Salary :" + se.salary + "\nCompany Name :" + company); } }
Output :
Employee Name :Pradeep Yadav
Employee Id :IL981243
Employee Salary :40000
Company Name :Infosys Limited
—————————————————————–
static block :
When you need to print something before main method called used static block of code.
Example :
package com.pkjavacode.com; /** * * @author pradeep */ public class StaticExample { static String company = "Infosys Limited"; String name; String id; long salary; public StaticExample(String name, String id, long salary) { this.name = name; this.id = id; this.salary = salary; } public static void main(String arg[]) { StaticExample se = new StaticExample("Pradeep Yadav", "IL981243", 40000); System.out.println("Employee Name :" + se.name + "\nEmployee Id :" + se.id + "\nEmployee Salary :" + se.salary + "\nCompany Name :" + company); } static { System.out.println("Excellent work by this employee"); //You can also add some logic here!! } }
Output :
Excellent work by this employee
Employee Name :Pradeep Yadav
Employee Id :IL981243
Employee Salary :40000
Company Name :Infosys Limited
——————————————————————
Nested static class :
Through nested static class you can define a class within a class and can access their member.
Example :
package com.pkjavacode.com; /** * * @author pradeep */ public class StaticExample { public static void main(String arg[]) { StaticDemo sd = new StaticDemo(); sd.display(); } static class StaticDemo { //Can add some method and variable here!! void display() { System.out.println("Nested static class method"); } } }
Output :
Nested static class method
—————————————————————————————————-
static method :
When you need to access a method without creating class object used static keyword in method signature.
Example :
package com.pkjavacode.com; /** * * @author pradeep */ public class StaticExample { public static void show() { System.out.println("static method print"); } public static void main(String arg[]) { StaticExample.show(); } }
Output :
static method print