static variables java
Static keyword is used a lot in java.
Static means, you
can access those static variables
without creating an object,
just by using a class name.
This means that only one instance of
that static member is created which
is shared across all instances of the class.
Basically we use static keyword when
all members share same instance.
4.25
4
We can declare a method as static by adding keyword “static” before method name.
Let’s see example on static method in java.
public class StaticMethodExample
{
static void print()
{
System.out.println("in static method.");
}
public static void main(String[] args)
{
StaticMethodExample.print();
}
}
Thank you!
4
0
0
0
class JavaExample{
private static String str = "BeginnersBook";
//Static class
static class MyNestedClass{
//non-static method
public void disp() {
/* If you make the str variable of outer class
* non-static then you will get compilation error
* because: a nested static class cannot access non-
* static members of the outer class.
*/
System.out.println(str);
}
}
public static void main(String args[])
{
/* To create instance of nested class we didn't need the outer
* class instance but for a regular nested class you would need
* to create an instance of outer class first
*/
JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();
obj.disp();
}
}
Thank you!
0
0
3.75
8
The methods or variables defined as static are shared among all the objects
of the class. The static is the part of the class and not of the object.
The static variables are stored in the class area, and we do not need
to create the object to access such variables.
Therefore, static is used in the case, where we need to define
variables or methods which are common to all the objects of the class.
For example, In the class simulating the collection of the students in
a college, the nameof the college is the common attribute to all the students.
Therefore, the college name will be defined asstatic
Thank you!
8
0
3.73
9
static keyword is a non-access modifier. static keyword can be used with
class level variable, block, method and inner class or nested class.
Thank you!
9
0
Are there any code examples left?
New code examples in category Java
-
Java 2022-03-27 21:35:04 Sort string array in case insensitive order and case sensitive order java
-
Java 2022-03-27 21:25:10 java -jar -l resources\es.porperties -i ejemplo.txt -o inject.bin
-
Java 2022-03-27 21:20:21 Debug & Fix a 2-Dimensional Array Java Console Application
-
Java 2022-03-27 20:40:19 TreeSet headSet(E toElement) method in java
-
Java 2022-03-27 19:30:06 close keyboard android
-
Java 2022-03-27 19:20:40 java measure execution time
-
Java 2022-03-27 19:10:06 how to add cardview support in android studio
-
Java 2022-03-27 18:55:08 android studio lower case letters on a button