Core Java Questions And Answers Part-3

Can we declare main() method as private or protected or with no access modifier?

No, main() method must be public. You can’t define main() method as private or protected or with no access modifier. This is because to make the main() method accessible to JVM. If you define main() method other than public, compilation will be successful but you will get run time error as no main method found.

public class MainMethod
{
    private static void main(String[] args)
    {
        //Run time error
    }
}

Can We Declare main() Method As Non-Static?

No, main() method must be declared as static so that JVM can call main() method without instantiating it’s class. If you remove ‘static’ from main() method signature, compilation will be successful but program fails at run time.

public class MainMethod
{
    public void main(String[] args)
    {
        System.out.println(1);         //Run time error
    }
}


Why main() method must be static?
Suppose, If main() is allowed to be non-static, then while calling the main method JVM has to instantiate it’s class. While instantiating it has to call constructor of that class. There will be an ambiguity if constructor of that class takes an argument. For example, In the below program what argument JVM has to pass while instantiating class “MainMethod”?.

public class MainMethod
{
    public MainMethod(int i)
    {
        //Constructor taking one argument
    }

    public void main(String[] args)
    {
        //main method as non-static
    }
}
That’s why main() method must be static.


Can we change return type of main() method?
No, the return type of main() method must be void only. Any other type is not acceptable.

public class MainMethod
{
    public static int main(String[] args)
    {
        return 1;    //run time error : No main method found
    }
}


Can main() method take an argument other than string array?
No, argument of main() method must be string array. But, from the introduction of var args you can pass var args of string type as an argument to main() method. Again, var args are nothing but the arrays.

public class MainMethod
{
    public static void main(String... args)
    {
        //Var args as an argument
    }
}


Can we run java class without main() method?
No, you can’t run java class without main method. But, there are some scenarios like if super class has main() method, then sub class can be run without defining main() method in it. For example, if you run class B in the below program, you will get 1 as output.

class A
{
    public static void main(String[] args)
    {
        System.out.println(1);
    }
}

public class B extends A
{

}

Can we make main final in Java?
Of course, you can make the main method final in Java. JVM has no issue with that. Unlike any final method, you cannot override main in Java.


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


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

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


Key-points on main method :
The main() method is a static method
You can overload main() method in Java.
You cannot override main() method in Java
You can make the main method final in Java
You can make the main method synchronized in Java.
You cannot call a non-static method from main in Java.


Explain the main method signature?
public static void main(String args[]) - Explanation.

public - public means everyone can access it.That means it's in global scope. As, main method is called by JVM [Java Virtual Machine], which is actually out of the project scope, the access specifier of this method is public.
static - Java environment should be able to call this method without creating an instance of the class , so this    method must be declared as static.
void - the return type of this method is void means there's no return value.
main( ) - the name of the method, main because it's the main method.


I don’t want my class to be inherited by any other class. What should i do?
You should declared your class as final. But you can't define your class as final, if it is an abstract class. A class declared as final can't be extended by any other class.
I want to print "Hello" even before main() is executed. How will you acheive that?

Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once.


What is JVM,JRE and JDK?

Java Development Kit (JDK)
Java Development Kit is the core component of Java Environment and provides all the tools, executables and binaries required to compile, debug and execute a Java Program. JDK is a platform specific software and thats why we have separate installers for Windows, Mac and Unix systems. We can say that JDK is superset of JRE since it contains JRE with Java compiler, debugger and core classes.



Java Runtime Environment (JRE)
JRE is the implementation of JVM, it provides platform to execute java programs. JRE consists of JVM and java binaries and other classes to execute any program successfully. JRE doesn’t contain any development tools like java compiler, debugger etc. If you want to execute any java program, you should have JRE installed but we don’t need JDK for running any java program.

Java Virtual Machine(JVM)
JVM is the heart of java programming language. When we run a program, JVM is responsible to converting Byte code to the machine specific code. JVM is also platform dependent and provides core java functions like memory management, garbage collection, security etc.



What is the difference between JVM,JRE and JDK?

JDK is for development purpose whereas JRE is for running the java programs.
JDK and JRE both contains JVM so that we can run our java program.
JVM is the heart of java programming language and provides platform independence.


What us Just-in-time Compiler (JIT)
JIT is part of JVM that optimizes byte code to machine specific language compilation by compiling similar byte codes at same time, hence reducing overall time taken for compilation of byte code to machine specific language.


How is java platform independent?
Java Portability
In order to understand portability in Java you need to understand what happens to java code from start to finish.
1- Java Source Code (Written by Developer) (Machine Neutral)
2- Compiled Code / Byte Code (Compiled by javac) . (Machine Neutral)
3- Byte Code executed (Executed by JVM) (Machine Specific)

In step 2, javac (Java Compiler) converts Java code to byte code. This can be moved to any machine(Windows / Linux) and executed by JVM. JVM reads the bytecode and generates machine specific code. In order to generate machine specific code JVM needs to be machine specific. So every type of Machine(Windows / Linux / Mac) has a specific JVM. So in this way the coder doesn’t need to bother with generating byte code. JVM takes care of portability. So the final answer is Java is Portable but JVM is Machine Specific.



What is difference between break, continue and return statements? 
The break statement results in the termination of the loop, it will come out of the loop and stops further iterations.
The continue statement stops the current execution of the iteration and proceeds to the next iteration.
The return statement takes you out of the method. It stops executing the method and returns from the method execution.


What is default value of a boolean?
Default value of a boolean is false.


What are the environment variables do we neet to set to run Java? 
We need to set two environment variables those are PATH and CLASSPATH.


What is the difference between declaring a variable and defining a variable?
When variable declaration we just mention the type of the variable and it's name, it does not have any reference to live object. But defining means combination of declaration and initialization. The examples are as given below:

Declaration:
List list;

Defining:
List list = new ArrayList();


What is the difference between the prefix and postfix forms of the increment(++) operator? 
prefix operator: The prefix form first performs the increment operation and then returns the value of the increment operation.
For example:
int count=1;
System.out.println(++count);
displays 2.

postfix operator:The postfix form first returns the current value of the expression and then performs the increment operation on that value.
For example:
int count=1;
System.out.println(count++);
displays 1.

No comments:

Post a Comment