Website For Developers

Static keyword in Java



Static Variable and Method


Characteristics of static in Java


Example of static variable in Java

public class FootballTeam {

   String name;
   int age;
   static String gender = "male";

   FootballTeam (String n, int a) {
     name = n;
     age = a;
   }
   void show() {
     System.out.println( "Player name: "+name );
     System.out.println( "Player age: "+age );
     System.out.println( "Player gender: "+gender+ "\n------------------" );
   }

   public static void main(String args[]) {
     FootballTeam object1 = new FootballTeam ("Suraze", 22);
     FootballTeam object2 = new FootballTeam ("Messi", 28);
     FootballTeam object3 = new FootballTeam ("Neymar", 24);
    
     object1.show();
     object2.show();
     object3.show();
   }
}

Output

Player name: Suraze
Player age: 22
Player gender: male
------------------
Player name: Messi
Player age: 28
Player gender: male
------------------
Player name: Neymar
Player age: 24
Player gender: male
------------------


Explanation


Example of static method in Java

public class StaticMethodDemo {

   String name;
   int age;
   static String gender = "male";
   static String team_name;

   StaticMethodDemo(String n, int a) {
     name = n;
     age = a;
   }
   //Static Method
   static void team() {
     team_name = "abc";
   }
   void show() {
     System.out.println( "Team name: "+team_name );
     System.out.println("Player name: "+name );
     System.out.println( "Player age: "+age );
     System.out.println( "Player gender: "+gender+ "\n------------------" );
   }

   public static void main(String args[]) {
     StaticMethodDemo.team();
     StaticMethodDemo object1 = new StaticMethodDemo("Suraze", 22);
     StaticMethodDemo object2 = new StaticMethodDemo("Messi", 28);
     StaticMethodDemo object3 = new StaticMethodDemo("Neymar", 24);

     object1.show();
     object2.show();
     object3.show();
   }
}

Output

Team name: abc
Player name: Suraze
Player age: 22
Player gender: male
------------------
Team name: abc
Player name: Messi
Player age: 28
Player gender: male
------------------
Team name: abc
Player name: Neymar
Player age: 24
Player gender: male
------------------


Explanation