Google

Dec 19, 2011

Tricky Java interview questions and answers

Q. Can interfaces contain inner classes?
A. Yes, but not recommended as it can compromise on clarity of your code.

The interface with an inner class for demo purpose only

package innerstatic;

public interface InterfaceWithInnerClass {
    
    
    public static final Util UTIL = new Util( );
    

    public String getName(); // next node in this list

    public final static InterfaceWithInnerClass FIELD =
      //anonymous inner class as the interface field declaration  
      new InterfaceWithInnerClass() {
          public String getName() {
            return "Peter";
        }
    };

    
 //static inner class
    public static class Util {
        public String getDetail(){
            return FIELD.getName() + " age 25";
        }
    }
}


The class that implemnts the above interface.


package innerstatic;

public class Test implements InterfaceWithInnerClass {

    @Override
    public String getName() {
        return FIELD.getName() + " : " + UTIL.getDetail();
    }
    
    public static void main(String[] args) {
        System.out.println(new Test().getName());
    }
}


The output is:

Peter : Peter age 25


Q. What happens if you pass a primitive int value to a method that accepts

a) long primitive
b) float primitive
c) Float object
d) Number object

A.

a) A widening conversion takes place from int to long. So, no compile or run time error.
b) A widening conversion takes place from int to float. So, no compile or run time error.
c) compile-time error. primitive type int can be auto-boxed to type Integer, but type Integer and Float are derived from type Number, and don't have the parent child relationship. So, they cannot be implicityly or exlplicitly cast to each other.
d) primitive type int can be auto-boxed to type Integer, and then implicitly cast to type Number as Number and Integer have the parent child relationship. So, no compile or run time error.



Q. What is the purpose of the intern( ) method in the String class?
A. It is used for moving the String objects created with the "new" operator to the internal string pool.



Q. Why is the String class in Java is final immutable object?
A.

Security: the system can pass on sensitive info like password, credit card number, etc as read-only information without worrying that it will be altered.

Immutable objects are thread-safe. Two or more threads can  work on an immutable object at the same time without any possibility of conflict. Immutable String objects are great to be used as keys in a map without worrying about the key getting modified.

To keep things simple. Since final, you can't subclass it to have two different String objects that have the same value. It is also easier to implement some of the string methods like substring because of its immutability.


Q. Is the finally block is always guaranteed to be execute?
A. No. The finally block is not executed under circumstances like

  • System.exit( ) in try or catch block.
  • If the thread executing the try or catch block is killed or interrupted. 
  • If an exception is thrown from the finally block and not handled, then remaining code in the finally block is ignored.

Q. What is the purpose of 'const' reserved keyword in Java?
A. It is reserved, but not currently used in Java. 

Labels:

16 Comments:

Blogger Ruby Claire said...

Q. Explain different way of using thread? ..oo i remember once my friend ask a java question to me to answer here,,, the question was,,
What is the purpose of garbage collection in Java? can you answer it pls.


Career questionnaire

4:38 PM, December 26, 2011  
Anonymous Java JDBC Interview questions said...

Thanks for detail answer for the questions

2:13 AM, January 12, 2012  
Anonymous Anand Kumar said...

I wouldn't want to work for someone who comes up with interview questions designed to trick the interviewee. I mean looking for a job is painful enough, but then to have an interviewer who wants to make every interview like a game of Jeopardy, what's the point. Sure, as an employer, I want someone whose mentally agile, but if I have to resort to asking trick questions to figure that out, then it's my fault for not putting together a good set of questions.

3:03 AM, February 29, 2012  
Blogger Unknown said...

Rubie,

The purpose of garbage collection is to manage memory. The object references that are not reachable considered garbage and automatically removed from memory. The GC runs in a low priority thread.

10:13 AM, February 29, 2012  
Blogger Unknown said...

Anand,

You have a point there. The job interviews are not technical contests to see who gets most questions right. It is all about evaluating if one can get the job done, whether he/she likes the job on offer and how well fit in with the team. Interviewers will cover a wider range of questions like technical questions, coding questions, behavioral questions, open-ended questions, and tricky questions.

The Java technical and coding questions on fundamentals like OO concepts, language basics, specification basics, etc are generally must know type questions and can result in immediate passing or failing an interview.


The tricky and open-ended interview questions are generally used to test your soft skills and attitude to make a collective decision.

One of the tricky questions that I had come across was -- How would you go about determining how many petrol or service stations are there in Sydney?


What the interviewer is trying to look for here is

1. How you think and go about analyzing and solving problems?

2. How well you handle pressure? Do you get stressed out easily?

3. Do you easily give up or passionate about trying it out?

4. Do you ask the right questions?

and many other things. The open-ended and tricky questions are good for determining one's experience and seniority.

10:31 AM, February 29, 2012  
Blogger safik said...

could you please explain/example for how is security of the code gets affected by using inner class in the interface?

3:41 AM, April 24, 2012  
Blogger Unknown said...

Safic, it is a mistake and thanks for pointing that out. I have removed it. I was thinking more along the lines of

the gotcha like any outer class private members accessed by an inner class are silently changed to default (package) access! at runtime.

10:35 AM, April 24, 2012  
Anonymous Anonymous said...

Good questions.
I found more good JAVA interview questions at www.prepareforexam.com/Interview.jsp or in interview section in www.prepareforexam.com

8:20 PM, August 08, 2012  
Blogger meow said...

solve this : if a method/function has a try-catch-finally system like:
int ABC(){
try{
......
...
return 1;
}
catch(exception e){
return 2;
}
finally{
return 3;
}
}
static void main(args[]){
int i=ABC();
}

is this possibel?? if yes, wat will be the value of i in the end???
please clarify

9:48 PM, August 25, 2012  
Blogger Unknown said...

it will give 3 when the compiler reaches at return 2 it will find that there is a finally statement present it will skip return 2 and jumps to finally block which will
return 3

7:03 AM, September 09, 2012  
Anonymous Vicky said...

Hi Ruby, Garbage collection is used to reclaim used memory in Java heap space. This is one of the reason of using Java programming language. If you are interested in more information about GC see How Garbage collection works in Java

2:15 PM, September 10, 2012  
Anonymous Anonymous said...

This will always give an answer as 3 because finally is always called irrespective whether an exception is called or not. Here before returning (before executing "return 1" or "return 2" finally will be executed. In finally JVM will encounter "return 3" and it will return that value.

11:31 PM, October 30, 2012  
Anonymous Madhu Chimata said...

Hi Mates,

In Exception Handling mechanism,

the finally block always dominates Return Statement, that is written in either try block or catch block.

Means when the control comes to return statement, It immediately jumps to finally block and executes it.
Thanks..

11:17 PM, December 04, 2012  
Anonymous Anonymous said...

public class Parent
{
public void show()
{
System.out.println("Hello Parent Show");
}
}

public class Child extends Parent
{
public void show()
{
System.out.println("Hello Child Show");
}

public String toString()
{
System.out.println("Hello toString");
}
}

OUTPUT :
Hello Child Show
Hello toString


How the parent class is extending the Object Class Methods

6:56 AM, December 05, 2012  
Blogger Unknown said...

That is implicit. Every Java class implicitly extends the Object class.

8:34 PM, March 06, 2014  
Blogger Unknown said...

thead can implement in two ways one is implementing runnable interface and extending thread class

3:43 AM, March 25, 2014  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home