static is a keyword in java and we can’t create a class or package name as static. Java static keyword can be used in four cases.
Java static variables: We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe. Usually static variables are used with final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it with ClassName.variableName
//static variable example
private static int count;
public static String str;
public static final String DB_USER = "myuser";
Java static methods: Same as static variables, static methods belong to class and not to class instances. A static method can access only static variables of class and invoke only static methods of the class. Usually static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance; for example Collections class. Java Wrapper classes and utility classes contains a lot of static methods. The main() method that is the entry point of a java program itself is a static method.
//static method example
public static void setCount(int count) {
if(count > 0)
StaticExample.count = count;
}
//static variable example
private static int count;
public static String str;
public static final String DB_USER = "myuser";
Java static methods: Same as static variables, static methods belong to class and not to class instances. A static method can access only static variables of class and invoke only static methods of the class. Usually static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance; for example Collections class. Java Wrapper classes and utility classes contains a lot of static methods. The main() method that is the entry point of a java program itself is a static method.
//static method example
public static void setCount(int count) {
if(count > 0)
StaticExample.count = count;
}
//static util method
public static int addInts(int i, int...js){
int sum=i;
for(int x : js) sum+=x;
return sum;
}
public static int addInts(int i, int...js){
int sum=i;
for(int x : js) sum+=x;
return sum;
}
No comments:
Post a Comment