what is static and non static in java code example
Example 1: static in java
//Java Program to get the cube of a given number using the static method
using static before a method or variable we can access it by not creating a
instance of it.in the program we directly used student.cube(5)
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
Example 2: static in java
The static keyword in Java is used for memory management mainly. We can apply static keyword with
variables, methods, blocks and nested classes. The static keyword belongs to the class
than an instance of the class.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class
Example 3: static vs non static java
// Static vs Object Called
// Static Methods don't require you to call a constructor
// Initialize statically
public class MyClass {
private static int myInt;
static {
myInt = 1;
}
public static int getInt() {
return myInt;
}
}
// Then call it
System.out.println(MyClass.getInt());
// VS Constructor
public class MyClass {
private int myInt;
public MyClass() {
myInt = 1;
}
public int getInt() {
return this.myInt;
}
}
// Then call it
MyClass myObj = new MyClass();
System.out.println(myObj.getInt());