Вы находитесь на странице: 1из 6

static

static variables are classes variables not instance


variables .They are instantianted only once for a
class.They are initialised at class load time.
Static method can be referenced with the name of the name
of the particular object of that clas

1) static keyword can be applied with variable, method or nested class. static keyword can not be applied on
top level class. Making a top level class static in Java will result in compile time error.
2) static variables are associated with class instead of object.

3) static variables in java keeps same value for every single object.
4) you can not use non-static variable inside a static method , it will result in compilation error as shown below.
See Why static variable can not be called from static method for more details.
public class TradingSystem {
String description = "electronic trading system";
public static void main(String[] args) {
description = "commodity trading system";
}
}
Cannot make a static reference to the non-static field description
at TradingSystem.main(TradingSystem.java:8)

How to access non static variable inside static method or block


You can still access any non static variable inside any static method or block by creating an instance of class in Java
and using that instance to reference instance variable. This is the only legitimate way to access non static variable
on static context. here is a code example of accessing non static variable inside static context:
public class StaticTest {
private int count=0;
public static void main(String args[]) throws IOException {
StaticTest test = new StaticTest(); //accessing static variable by creating an instance of class
test.count++;
}
}

6) Static fields are initialized at the time of class loading in Java, opposite to instance variable which is initialised
when you create instance of a particular class.
7) Static keyword can also be used to create static block in Java which holds piece of code to executed when class
is loaded in Java. This is also known as static initialize block as shown in below example.

static {
String category = "electronic trading system";
System.out.println("example of static block in java");
}

8) Static method can not be overridden in Java as they belong to class and not to object. so if you have same
static method in subclass and super class , method will be invoked based on declared type of object instead of
runtime for example. Can we override static method in Java is also a popular Java question asked in interviews.

public class TradingSystem {


public static void main(String[] args) {
TradingSystem system = new DirectMarketAccess();
DirectMarketAccess dma = new DirectMarketAccess();
// static method of TradingSystem class will be called,
// even though object is of sub-class DirectMarketAccess
system.printCategory();
//static method of DirectMarketAccess class will be called
dma.printCategory();
}
public static void printCategory(){
System.out.println("inside super class static method");
}
}
class DirectMarketAccess extends TradingSystem{
public static void printCategory(){
System.out.println("inside sub class static method");
}
}
Output:
inside super class static method
inside sub class static method

This shows that static method can not be overridden in Java declaring same static
method on Child class is known as method hiding in Java.
9. If you try to override a static method with a non-static method in sub class you will get compilation error.

10. you can overload static method in Java but you can not override static method in Java.

**
* Java program to show that we can overload static method in Java.
*/
public class StaticOverloadingTest {
public static void main(String args[]) {
greet("John"); //will call static method with one String argument
greet("John", "Good Morning"); //overloaded static method will be call
}
/*
* static method which will be overloaded
*/
public static void greet(String name){
System.out.println("Hello " + name);
}
/*
* Another static method which overload above Hello method
* This shows that we can overload static method in Java
*/
public static void greet(String name, String greeting){
System.out.println(greeting + " " + name);
}

}
Output
Hello John
Good Morning John

static is a keyword in java and we cant create a class or package name as static. Java
static keyword can be used in four cases.
1.

Java static variables: We can use static keyword with a class level
variable. A static variable is a class variable and doesnt 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
1
//static variable example
private static int count;
2
public static String str;
3
public static final String DB_USER = "myuser";
4

2.

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 classesand utility classes contains a lot of static
methods. The main() method that is the entry point of a java program itself
is a
1
2
3
4
5
6
7
8
9
10
11
12

3.

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;
}

From Java 8 onwards, we can have static methods in interfaces too, for
more details please read Java interface static methods.

4.

Java static Block: Java static block is the group of statements that gets
executed when the class is loaded into memory by Java ClassLoader. It is
used to initialize static variables of the class. Mostly its used to create static
resources when class is loaded. We cant access non-static variables in static
block. We can have multiple static blocks in a class, although it doesnt
make much sense. Static block code is executed only once when class is
loaded into memory.
1
static{
2
//can be used to initialize resources when class is loaded
3
System.out.println("StaticExample static block");
//can access only static variables and methods
4
str="Test";
5
setCount(2);
6
}
7

5.

Java Static Class: We can use static keyword with nested classes. static
keyword cant be used with top-level classes. Static nested class is same as
any other top-level class and is nested for only packaging convenience.

Main method Interview Questions in Java


Can we overload main method in Java ? Which main method JVM will call ?
Can we override main method in Java ?
Can we make main final in Java?
Can we make main synchronized in Java ?
How to call a non static method from main in Java ?

Can we overload main in Java ?


Yes you can overload main method in Java, nothing wrong with this but Java will only call your specific main method,
i.e. main method with following signature :
public static void main(String[] args) or public static void main(String args...) which is
main method asvariable argument method and only supported post Java 5 world.

Can we override main in Java ?


No you can not overrdie main method in Java, Why? because main is static method and in Java static method is
bonded during compile time and you can not override static method in Java. If you decalre method with same name
and signature its called method hiding.

Can we make main final in Java?


Ofcourse you can make main method final in Java. JVM has no issue with that. Unlike any final method you can not
override main in Java.

Can we make main synchronized in Java?


Yes, main can be synchronized in Java, synchronized modifier is allowed in main signature and you can make your
main method synchronized in Java.

How to call a non static method from main in Java ?


This question applies not only to main but all static methods in Java. Since non static methods can not be called from
static context directly, you need to first create an Object as local variable and then you can call non static method
using that object, as shown in following example :

import java.util.Date;

/**
* Java program to show how to call non static method from static method in Java
*
* @author http://java67.blogspot.com
*/
public class StaticTest {

public static void main(String args[]) {

// calling non static method from main in Java


//printCurrentTime(); //compile time error - can not call non static method
from main

StaticTest test = new StaticTest();


test.printCurrentTime();

public void printCurrentTime(){


System.out.println(new Date());
}
}

Output:
Tue Nov 06 19:07:54 IST 2012

So these were some of the frequently asked questions about main method in Java. This are not only help to answer
interview question but also to build your concept on main method in Java.

Вам также может понравиться