Thursday, 25 December 2014

Important Core Java Quetions

  • Can we overload main method?     Java tutorial

You can overload the main() method, but only public static void main(String[] args) will be used   when your class is launched by the JVM. For example:

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

    public static void main(String arg1) {
        System.out.println("main(String arg1)");
    }

    public static void main(String arg1, String arg2) {
        System.out.println("main(String arg1, String arg2)");
    }
}

That will always print main(String[] args) when you run java Test ... from the command line, even if you specify one or two command-line arguments.
You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.

Note that you can use a var args signature, as that's equivalent from a JVM standpoint:
public static void main(String... args)


  

  • Constructor returns a value but, what?

First of all ,what actually happens with the constructor is that the runtime uses constructor method to determine how much space is needed to store an object instance in memory. After this space is allocated, the constructor is automatically called as an internal part of the instantiation and initialization process ( if you don't provide values for attributes it will use default values for each type). When the constructor exits, the runtime returns the newly-created instance.
You don't need to write a constructor, because compiler will use one of the built ones, but complex classes will not initialize object correctly, so it's necessary that wee write few of them :).
By a definition in Java constructor don't have return statement. It's by default a instance that is constructed at the moment. Basically you can write something like
public Hello(int a){
aa=a;
return this;
}
In your case, when you are getting errors, it's because Java is strongly typed language, so each function has it's returning type, and constructor always returns an instance of the class. So when you try to return anything that's not a Hello type you will get an error.

  • Can we create a program without main method?

Many Java programmer gives you answer that they can run Java program without main method by writing code in static initializer block, which is half true. Yes, code written in static initializer block is executed before calling main method, but you won't be able to run a class by using Java command, or Eclipse or anything else, until it got  public static void main(String args[]) method on it. If you try to run such programs, you will get following error :


Error: Main method not found in class JavaAppWithoutMain, please define the main
 method
 as:   public static void main(String[] args)





Though you can run a Java program with empty Main method, in which case only code executed will be from static initializer block. Following is a simple Java program with some code written on static initializer block, including a print statement, a variable initialization and starting a thread. As soon as you remove the main method, it will compile fine but will throw above error, when you try to run this program from command line.



public class JavaAppWithoutMain {

    static {
        System.out.println("HelloWorld, Java progarm without main method");
        int x = 20; // Can initialize static variables
        System.out.println("Variable x : " + x);

        Thread t = new Thread() {
            @Override
            public void run() {
                System.out.println("Started thread from static initializer block");
    System.out.println("Thread Finished");
            }
        };
        t.start();
    }

    public static void main(String args[]) {
          // Empty main method
    }

}

Here is how the output look like, when you run this program from command prompt with empty main method.



That's all about whether you can run a Java program without main method in Java or not. In short, Yes, you can run a Java program without main method in a managed environment e.g. Applet,Servlet, and MIDlet, which runs under control of browser, server and mobile device, but can't run a core Java program without public static void main(string args[]) method. JVM will not allow you to execute those methods.





  • What are the 6 ways to use this keyword?

Here is given the 6 usage of java this keyword.
  1. this keyword can be used to refer current class instance variable.
  2. this() can be used to invoke current class constructor.
  3. this keyword can be used to invoke current class method (implicitly)
  4. this can be passed as an argument in the method call.
  5. this can be passed as argument in the constructor call.
  6. this keyword can also be used to return the current class instance.

  • Why multiple inheritance is not supported in java?

In order to enforce simplicity should be the main reason for omitting multiple inheritance. For instance, we can consider diamond problem of multiple inheritance.
We have two classes B and C inheriting from A. Assume that B and C are overriding an inherited method and they provide their own implementation. Now D inherits from both B and C doing multiple inheritance. D should inherit that overridden method, which overridden method will be used? Will it be from B or C? Here we have an ambiguity.


  • Why use aggregation?
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.
1.   class Employee{  
2.   int id;  
3.   String name;  
4.   Address address;//Address is a class  
5.   ...  
6.   }  
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.
Why use Aggregation?
  • For Code Reusability.
When use Aggregation?
  • Code reuse is also best achieved by aggregation when there is no is-a relationship.
  • Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.



  • Can we override the static method?

The answer is ‘Yes’. We can have two ore more static methods with same name, but differences in input parameters. For example, consider the following Java program.
// filename Test.java
public class Test {
    public static void foo() {
        System.out.println("Test.foo() called ");
    }
    public static void foo(int a) {
        System.out.println("Test.foo(int) called ");
    }
    public static void main(String args[])
    {
        Test.foo();
        Test.foo(10);
    }
}
Output:
Test.foo() called
Test.foo(int) called






  • What is covariant return type?

The covariant return type specifies that the return type may vary in the same direction as the subclass.
Before Java5, it was not possible to override any method by changing the return type. But now, since Java5, it is possible to override method by changing the return type if subclass overrides any method whose return type is Non-Primitive but it 


1.   class A{  
2.   A get(){return this;}  
3.   }  
4.     
5.   class B1 extends A{  
6.   B1 get(){return this;}  
7.   void message(){System.out.println("welcome to covariant return type");}  
8.     
9.   public static void main(String args[]){  
10.                new B1().get().message();  
11.                }  
12.                }  

Output: welcome to covariant return type
As you can see in the above example, the return type of the get() method of A class is A but the return type of the get() method of B class is B. Both methods have different return type but it is method overriding. This is known as covariant return type.

  • What are the three usage of super keyword?

  1. super is used to refer immediate parent class instance variable.
  2. super() is used to invoke immediate parent class constructor.
  3. super is used to invoke immediate parent class method.

  • Why use instance initializer block?

Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created.
The initialization of the instance variable can be directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.

No comments:

Post a Comment