Showing posts with label Core Java Interview Questions. Show all posts
Showing posts with label Core Java Interview Questions. Show all posts

Monday, February 26, 2018

Java main method interview questions and answers

1. Can I write java program without String args[] in main method ?

If you write java program without String args [] like below

public static void main (){
//Some code
}

The code will run. But JVM Can not recognize main method since it will always check main method string array parameter.

2. Difference between System.exit(0) and System.exit(1) ?

Sytem.exit(0) normally terminates the program. System.exit(1) also terminates the program, because It could find some error.

3. Is it possible to call main() from another class ?

Yes, Its possible by calling like Classname.main(). Note here, you should pass string array since main method will expect string array.

4. Can I overload main method ?

public class MainMethodOverloadExample
{
    public static void main(String[] args)
    {
        System.out.println("Execution will be started here");
    }
 
    void main(int args)
    {
        System.out.println("Overloaded main method I");
    }
 
    double main(int i, double d)
    {
        System.out.println("Overloaded main method II");
        //Some code here
    }
}

5. Is it possible change main method access modifier except public ?

No, main() method must be public. Your code will get compile.But Run time Error will happen when you try to run. Because JVM unable to access main method.

6. Can main() method take an argument other than string array?

No, argument of main() method must be string array

7. Can I change main() method to non static ?

No, main() method must be declared as static so that JVM can find and call main() method without instantiating it’s class. Compilation will be successful but program fails at run time.

8.Can we override main method in Java ?

No, you can not override main method in Java, Because main is static method and you can not override static method in Java.

9. Can we make main final in Java?

The Code will compile without any problems but it will throw a run-time exception saying "main method not public".

10. Can we make main method as synchronized in Java?

Yes, main can be synchronized in Java,  synchronized modifier is allowed in main signature.







Friday, June 17, 2016

Things to remember about Null Pointer Exception

Our day to day coding life, we are facing Null pointer exception in most cases. We can see some good points about this. 

1. The instanceof operator

Code: 
String str = null;
if(str instanceof String)
   System.out.println("String is an instance here");
else
   System.out.println("String is not an instance here");

Output:
String is not an instance here

You can use instanceof operator , even if the object reference equals to null. It will not throw null pointer exception.


2. Null with contains , containsKey and containsValue methods

Code: 
 
String value = map.get(key);
System.out.println(value.toString());  

We know map, which is working based on key and value concept. From the above code, suppose if value is null, then it will throw null pointer exception here.

To avoid Null pointer for above code : 
if(map.containsKey(key)) {
    String value = map.get(key);
    System.out.println(value.toString()); // Now No exception
}


3. Apache StringUtils class
 
if (StringUtils.isNotEmpty(str)) {
     System.out.println(str.toString());
}

We can use StringUtils.IsEmpty and StringUtils.equals also.


4. String comparison with equals 

This is very useful, in most of our programs.

String str = null;
 if(str.equals("Test")) { // Exception will throw here
    }

  To avoid above Code Error

String str = null;
    if("Test".equals(str)) { //No Exception now
    }


5. Ternary operator

String message = (str == null) ? "" : str.length();

From the above, if str is null, then assign empty for that, else calculate length.


6. valueOf() is better than toString()

    String str = null;
    System.out.println(String.valueOf(str));  // it will prints null        
    System.out.println(str.toString()); // it will throw NullPointer Exception


7. Working with Static method or Static members

Below code will not throw any error.

class Test {     
         public static void testMessage() {
              System.out.println("Test Message");
         }
    }

    public class TestStatic {
         public static void main(String[] args) {
              Test t = null;
              t.testMessage();
         }
    }

However, as per rule, static method should be called through class name only. Calling static method by object reference is not advisable.

Friday, June 10, 2016

extends Thread vs Implements Runnable

There are two ways to create a thread in Java.

1. By extending Thread class

2. By implementing Runnable Interface

Lets see the difference now.
  • If you are extending Thread class , you can not extends another class again, since Java does not support multiple inheritance.
  • If you are using implements Runnable interface , then there is a chance to extending another class.
  • Very important difference is, your thread will create unique object and make an associates with it while extends Thread.
  • But if you are using an implements Runnable Interface, It will share same object to multiple threads. 

Now we can understand this with one example, which will clarify more.

class ImplementsRunnable implements Runnable {
 
 private int count = 0;
 
 public void run() {
 count++;
 System.out.println("ImplementsRunnable checking Test : " + count);
 }
 }
 
 class ExtendsThread extends Thread {
 
 private int count = 0;
 
 public void run() {
 count++;
 System.out.println("ExtendsThread checking Test : " + count);
 }
 }
 
 public class ThreadVsRunnable {
 
 public static void main(String args[]) throws Exception {


 ImplementsRunnable rc = new ImplementsRunnable();
 Thread t1 = new Thread(rc);
 t1.start();

 Thread.sleep(1000); 
 Thread t2 = new Thread(rc);
 t2.start();

 Thread.sleep(1000); 
 Thread t3 = new Thread(rc);
 t3.start();
 

 ExtendsThread tc1 = new ExtendsThread();
 tc1.start();
 Thread.sleep(1000);
 
 ExtendsThread tc2 = new ExtendsThread();
 tc2.start();
 Thread.sleep(1000); 

 ExtendsThread tc3 = new ExtendsThread();
 tc3.start();
 }
 }

Output :

ImplementsRunnable checking Test : 1
ImplementsRunnable checking Test : 2
ImplementsRunnable checking Test : 3
ExtendsThread checking Test : 1
ExtendsThread checking Test : 1
ExtendsThread checking Test : 1

If you will analyze the output, it says well like Runnable interface sharing one instance and increment values. But it is opposite in Thread class, since it creates separate instance every time.

Monday, June 6, 2016

Difference between sleep and wait in java ?

Sleep and wait () method

sleep () is a method , which is used to hold the process for a particular time or How much time you wanted to hold. 

wait () method goes to waiting stage and it wont come back to normal until notify() or notifyAll() method should be called. 

Important points about sleep() method

1. Sleep is a static method on Thread class. 

2. It will makes your current thread into Not Runnable state for the specified amount of time.      
    Thread keeps the lock, during this time. 

3. It will be waked by interrupt or time expires.

4. It throws interrupted exception if another thread interrupts a sleeping thread.


Important points about wait() method

1. wait is an object class method.

2. It will makes your current thread into Not Runnable state. 

3. Remember, wait is called on an object not on thread. 

4. wait() should be used inside synchronized block or synchronized method. 

5. It will release the lock and gives the chance to others. 

6. It will be awake by calling on notify() or notifyAll() methods.

Friday, March 11, 2016

Which one developer should use for writing file , FileOutputStream or FileWriter ?

Well, Good question. But all developer will get struggle to choose to write file. Developer should choose based on his/her requirements.

1. FileOutputStream -  Write the file in the streams of raw bytes like IMAGE.
2. FileWriter - Writting streams of characters (Text type of data)

Tuesday, March 8, 2016

Create Singleton with Thread-Safe

Many blog could teach you how to write singleton but somebody may interest to face singelton with thread safe. We can see the below example for create the singleton instance with thread safe.

The below code will also explain What is volatile keyword and its responsibilty.

private static volatile Test instance;

public static Test getInstance () {

if (instance == null) {

synchronized (Test.class) {

instance = new Test();

}

}

return instance;

}

}


From the above, We know static will execute at first as per java rules. Here we able to see volatile keyword, which will create that instance in Main memory. The reason behind for adding volatile here is, we need multi threading task should be happened with the help of that instance. A lot of parallel threads will load simultaneously and if they want to access the instance, which should be in Main memory. The below picture will represent clearly.

Volatile
Volatile with Thread Safe Explanation
Hope you understand volatile purpose here. Suppose if volatile is not used. some thread could access instance as NULL. 

Wednesday, May 7, 2014

Why toString() method in bean class?

Why toString() method in bean class?

We can use it to print object values directly, if overriding toString() method. If you will try to print object without overriding toString() method, it will print some hexadecimal values.

Generally we will use toString() in bean class, to check the bean property values.

For example,

public class TestBean implements Serializable {

private string name;
private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name= name;
}

public int getAge() {
return age;
}

public void setAge(String age) {
this.age= age;
}

@Override
public String toString() {

return "TestBean [name=" +  name  + ", age=" + age + "]";
}
}


Now you should set values to this bean property. Now somewhere you can create object for this bean class like below.

TestBean test = new TestBean();

try to print the test object ,
System.out.println(test);

It will display the value like below.

=TestBean[name=test, age=19 ]

So you can use this to debug or log etc.,



Monday, February 24, 2014

Interface Interview Questions

1.What is Interface? 

You can only declare the method here, You can not implement here.

2.Why do we want to use Interface?

Java does not support multiple inheritance. Instead of that, we can use interface. Next thing is, it will               allow the third party to implement its methods.

3.Simple interface example

interface JavaHit {
void test(); //you can only do method declare here.
}

Important Note: After compilation, that method declaration will changed like
public abstract void test();
Because of, that interface should allow thaird party to implement that. So its giving access like public.

4.Can you write one interface example?

interface JavaHit {
void connect(); //it will change to public access after compilation.
oid disconnect();
}

class SqlDb implements JavaHit {
public void connect() {
System.out.println("SQL Database Connected");
}
public void disconnect() {
System.out.println("SQL Database Disconnected");
}
}
class OracleDb implements JavaHit {
public void connect() {
System.out.println("Oracle Database Connected");
}
public void disconnect() {
System.out.println("Oracle Database Disconnected");
}
}

5.Can I create methods inside interface with private or protected access?

No. public only allowed. Refer: Question 3

6.How do I create an object to interface?

You can not create object to interface class.

7.An interface can extend another interface?

Yes. Possible.

8.An interface can implement another interface?

No.

9.Can I write a class inside an interface?

Yes.

Friday, February 21, 2014

Interview Question about Static in java

1.What is static method?

Static method is a method , it should be declared with keyword static.

2.How will you call static method?

static method should be called by className.static method name.

e.g   A.test();
Here A is a class ad test is a static method.

3.Can I call static method with the help of object?

No. Before creating object static method should be called. I mean, static mehtod is not part of the object.

4.Can I use instance variable inside the static method?

No. JVM will create the object and instance variables after executing static method.So you can not use instance variable inside the static method.

5.What is static block?

static block is a block of statements declared as static.

e.g
static {
System.out.println("You are insdie static block");
}

6.Can I override static method in java?

No.

7.Can I overload static method?

Yes.

public class Test {
    public static void test() {
        System.out.println("Test for static overload I");
    }
    public static void test(int a) {
        System.out.println("Test for static overload II");
    }
    public static void main(String args[])
    {
        Test.test();
        Test.test(2);
    }
}

Output:

Test for static overload I
Test for static overload II

8.I have static block, static method and static variable. what is the order of execution?

static variable, static block, static method.

Saturday, February 15, 2014

Exception Handling Interview Questions

1.What are the 3 types of error?

1. Compile Time Error
2. Runtime Error
3. Error

2.What is Throwable?

Throwable is a class, for all errors and Exceptions.

3.What is the super class for all exceptions?

Exception class.

4.How will you create own exception in java?

You have to extends Exception class to create your own exception.

5.What are checked exception or Compile time Error?

The java compiler will check the exception at compile time is called checked exception.

6.What is unchecked exception or Runtime exception?

JVM will check the exception at runtime called unchecked exception.

7.What is Error?

Error is an error and it can not be handled by programmer. For example Memory error.

8.What is try catch in java?

try is the block , you can write your code logic here. Suppose if any exception will come in try block, you have to catch it.
For that you will write catch block to catch the exception.

For example,
try {
// DB connection coding
   }
catch(SQLException e){
e.printStackTrace();
}

9.What is throws and throw ?

If the programmer dont want to handle the exception, at the same time, programmer want to throw exception out of a method, throws will be helpful.

If the programmer want to throw the exception explicitly , then should handle it in catch block. 

So please remember throws and throw both are very different.

10.What is finally block?

whether the exception will occur or not, finally block will be executed. 

For example,

try {
// DB connection coding
   }
catch(SQLException e){
e.printStackTrace();
}
finally {
        // DB connection close code
}

So here, the exception will occur or not, finally bloack will be executed. DB connection will also close for security purpose.

11.Can I write the try block without catch block?

Yes. you can write try block without catch block.

12.Can I write the multiple catch block?

Yes.

13.What is nested try?

If you will write a try block within aother try, is called nested try.

14.Can I write the code between try and catch?

No.

Friday, February 14, 2014

String Interview Questions

1.Shall we consider String is a class or DataType or both?

You can consider string as a both class and datatype.

2.What is String constant pool?

It is a separate block of memory for strig objects and it will be assigned by JVM.
If you will use assignment operator, that wil be stored in constant pool only.

e.g String test="javahit";

3.Can you tell me the example for  ==  and equals()?

== does not compare the contet of the objects.
equals() - compare the contents.

e.g   Strig test = "java";
String check = "java";
if(test == check) {
System.out.println("Same");
else
System.out.pritln("Not same");
}

String t1 = new String("Test");
String t2 = new String("Test");

if(t1.equals(t2)) {
System.out.println("Same");
else
System.out.pritln("Not same");
}

4.Can you tell me some important methods in String class?

String concat(String t);
int length();
char charAt(int i);
int index(String s);
boolean equals(String s);
String substring(int i1, int i2);