Java Interview Questions

Can you declare a class as ‘private’?

No, if we declare a class as private, then it is not available to java compiler and hence a compile time error occurs. But, inner class can be declared as private.

What are static methods?

Static methods are methods which do not act upon the instance variables of a class. Static methods are declared as ‘static’.

Reason: JVM executes the static methods and then only it creates the objects.

What are static blocks?

A static block is a block of statements declared as ‘static’,some thing like this:

static{

statements;

}

JVM executes a static block on a highest priority basis. This means JVM first goes to static block even before it looks for the main() method in the program.

Example:

Class test{

static{

system.out.println(“static block”);

}

public static void main(string args[])

{

system.out.println(“static method”);

}

}

Output: static block

static  method

Is it possible to compile and run a java program without writing main() method?

Yes, it is possible by using a static block in the java program.

Advertisements