This post originated from an RSS feed registered with Java Buzz
by instanceof java.
Original Post: Top 10 Java Interview Questions on Static keyword
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
Clear understanding of static keyword is required to build projects.
We have static variables, static methods , static blocks.
Static means class level.
2.Why we use static keyword in java?
Static keyword is mainly used for memory management.
Static variables get memory when class loading itself.
Static variables can be used to point common property all objects.
3.What is static variable in java?
Variables declared with static keyword is known as static variables.
Static variables gets memory on class loading.
Static variables are class level.
If we change any static variable value using a particular object then its value changed for all objects means it is common to every object of that class.
static int a,b;
package com.instanceofjavastatic;
class StaticDemo{
static int a=40;
static int b=60;
}
We can not declare local variables as static it leads to compile time error "illegal start of expression".
Because being static variable it must get memory at the time of class loading, which is not possible to provide memory to local variable at the time of class loading.
package com.instanceofjava;
class StaticDemo{
static int a=10;
static int b=20;
public static void main(String [] args){
//local variables should not be static
static int a=10;// compile time error: illegal start of expression
Method which is having static in its method definition is known as static method.
static void show(){
}
JVM will not call these static methods automatically. Develioper needs to call these static methods from main method or static block or variable initialization.
Only Main method will b called by JVM automatically.
We can call these static methods by using class name itself no need to create object.
Static blocks will be executed at the time of class loading.
So if you want any logic that needs to be executed at the time of class loading that logic need to place inside the static block so that it will be executed at the time of class loading.
7.Why main method is static in java?
To execute main method without creating object then the main method should be static so that JVM will call main method by using class name itself.