brunch

You can make anything
by writing

C.S.Lewis

by 이승현 May 09. 2016

Java 면접 질문 #02

Java interview questions

Java hungry

Top 25 Most Frequently Asked Interview Core Java Interview Questions And Answers


http://javahungry.blogspot.com/2013/06/top-25-most-frequently-asked-core-java.html




Question #01

Which two method you need to implement for key Object in HashMap?

(HashMap의 key 객체 구현을 위해 필요한 두 가지 메소드는?)

                              

   

Answer

In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java  for detailed explanation on how equals and hashcode method is used to put and get object from HashMap. 

(Java에서 HashMap의 Key 객체를 위해 'equals'와 'hashcode' 메소드를 반드시 구현해야 한다. HashMap으로부터 객체를 put / get 하기 위해 어떻게 equals와 hashcode를 이용하는지 해당 링크에 자세히 읽어보길)


* HashMap : Map 인터페이스를 구현한 녀석이기 때문에 Map의 속성(Key와 Value로 이루어진 자료구조)을 모두 가지고 있고, 저장 방식 또한 동일합니다. 그리고 해싱(hashing)이란 검색 방법을 사용하기 때문에 많은 양의 데이터를 검색하는 데 있어서 뛰어난 성능을 보여줍니다.


Question #02

What is immutable object? Can you write immutable object?

(immutable 객체란?)

                              

   

Answer

Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java.

(Immutable(불변) 클래스는 한번 생성되면 수정할 수 없는 객체 클래스입니다. Immutable 객체에서의 수정은 새로운 객체 생성을 의미합니다. 예를 들어 Java에서 String 은 Immutable입니다.)


Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. 

(Java에서 서브 클래스의 오버 라이딩된 메소드에서의 불변성을 손상시키는 것을 방지하기 위해 대부분의 Immutable 들에 final을 붙인다.)


You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

(기능적으로는 private 접근 제한자를 붙여 non final 멤버로 만들 수 있다. 하지만 이 경우 생성자를 통해 값을 변경할 수 있다.)


Question #03

What is the difference between creating String as new() and literal?

(String을 new()와 literal을 통해 생성할 때 차이?)

                              

   

Answer

When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

(String을 new() 연산자를 통해 생성할 때, 이 것은 heap 메모리 영역에 생성되고 Heap의 PermGen 영역에 존재하는 string pool 자체에서 만든 string 사용하여 생성하는 동안 문자열 풀에 추가되지 않습니다.)


String s = new String("Test");


does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal 

(위 코드는 String pool에 추가하지 않는다. String pool에 명시적으로 추가하기 위해서는 String.intern() 메소드를 호출해야 한다. String 객체를 String literal처럼 사용하기 위한 유일한 방법이다.)


String s = "Test" // Java automatically put that into String pool.

Question #04

What is difference between StringBuffer and StringBuilder in Java?

(StringBuffer와 StringBuilder  차이?)

                              

   

Answer

StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs StringBuffer for more differences.

(StringBuilder는 Java 5에서 소개되었고 둘의 차이점은 Stringbuffer는 동기화되고 StringBuilder는 동기화하지 않는다.)


Question #05

Write code to find the First non repeated character in the String?

(String의 첫 번째 비 반복 문자를 찾기 위해 코드를 작성?)

                              

   

Answer

Another good Java interview question, This question is mainly asked by Amazon and equivalent companies. See first non repeated character in the string : Amazon interview question

(뜬금없이 코딩 문제가...)


Question #06

What is the difference between ArrayList and Vector?

(ArrayList와 Vector 차이?)

                              

   

Answer

This question is mostly used as a start up question in Technical interviews  on the topic of Collection framework. Answer is explained in detail here Difference between ArrayList and Vector.


ArrayList : 비동기화

* Vector : 동기화


Question #07

How do you handle error condition while writing stored procedure or accessing stored procedure from java?

(저장된 procedure을 작성하거나 접근할 때 에러 상황을 다뤄본 적 있는가?)

                              

   

Answer

This is one of the tough Java interview question and its open for all, my friend didn't know the answer so he didn't mind telling me. my take is that stored procedure should return error code if some operation fails but if stored procedure itself fail than catching SQLException is only choice.

(가장 더럽고 대답하기 힘든 질문이다. 만약 몇 가지 동작 오류가 발생하면 procedure은 반드시 에러 코드를 리턴해야 한다 그러나 저장된 procedure 자체가 실패할 경우에는 SQLException을 catch 하는 것이 유일한 방법이다. 뭔 말이지???)


Question #08

What is difference between Executor.submit() and Executer.execute() method?

(Executor.submit() and Executer.execute() 차이?)

                              

   

Answer

There is a difference when looking at exception handling. If your tasks throws an exception and if it was submitted with execute this exception will go to the uncaught exception handler (when you don't have provided one explicitly, the default one will just print the stack trace to System.err). If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task's return status. For a task that was submitted with submit and that terminates with an exception, the Future.get will re-throw this exception, wrapped in an ExecutionException.

(excepton을 다룰 때 다른 점이 있다.)

* execute : caught 되지 않는 exception 핸들러로 이동합니다.

(명시적으로 제공하지 않는 경우, 기본적으로 System.err를 통해 stack trace를 출력한다.)

* submit : exception는 task의 리턴 상태의 한 부분이다.

Future.get는 wrapped 된 ExecutionException를 다시 throw 합니다.


Question #09

What is the difference between factory and abstract factory pattern?

(factory와 abstract factory pattern 패턴 차이?)

                              

   

Answer

Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for creation of different hierarchies of objects based on the type of factory. E.g. Abstract Factory extended by AutomobileFactory, UserFactory, RoleFactory etc. Each individual factory would be responsible for creation of objects in that genre.

(Abstract Factory는 한 단계 이상의 추상화를 더 제공한다. 다른 factory들 각각 Abstract Factory에서 확장 및 Factory의 유형에 따라 개체의 다른 계층 구조의 생성에 대한 책임을 고려해야 한다. 예를 들어 Abstract Factory는 AutomobileFactory, UserFactory, RoleFactory  등으로 확장되어지고, 각각의 factory는 다르게 생성된다.)


Question #10

What is Singleton? is it better to make whole method synchronized or only critical section synchronized?

(Singleton?)

                              

   

Answer

Singleton in Java is a class with just one instance in whole Java application, for example java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy. see my article How to create thread-safe Singleton in Java for more details on writing Singleton using enum and double checked locking which is purpose of this Java interview question.

(싱글톤은 하나의 클래스가 하나의 인스턴스만 자기는 패턴이다. 예를 들어 java.lang.Runtime도 싱글톤이다. 자바 4에서는 까다로웠지만 자바 5에서 Enum이 소개되면서 상당히 쉬워졌다. 싱글톤 손 코딩 많이 시키네요. 한번 보세요.)


Question #11

Can you write critical section code for singleton?

(Singleton?)

                              

   

Answer

This core Java question is follow up of previous question and expecting candidate to write Java singleton using double checked locking. Remember to use volatile variable to make Singleton thread-safe.

(더블 체크와 volatile 키워드를 사용하여 작성.)


Question #12

Can you write code for iterating over hashmap in Java 4 and Java 5?

(Java 4~5에서 HashMap의 반복에 대한 코드를 작성할 수 있습니까?)

                              

   

Answer

Tricky one but he managed to write using while and for loop.

(4는 까다롭고 5는 while과 for loop를 이용해 작성할 수 있다. 8이 나왔는데 옛날 문제네요.)


Question #13

When do you override hashcode and equals()?

(Java 4~5에서 HashMap의 반복에 대한 코드를 작성할 수 있습니까?)

                              

   

Answer

Whenever necessary especially if you want to do equality check or want to use your object as key in HashMap.

(4는 까다롭고 5는 while과 for loop를 이용해 작성할 수 있다. 8이 나왔는데 옛날 문제네요.)


Question #14

Is it better to synchronize critical section of getInstance() method or whole getInstance() method?

(getInstance()의 임계 영역만 동기화getInstance()의 전체 동기화?)

                              

   

Answer

Answer is critical section because if we lock whole method than every time some one call this method will have to wait even though we are not creating any object.

(임계 영역만 하는 게 더 좋다. 만약 모든 메소드를 동기화한다면 호출할 때마다 무조건 wait 해야 한다.)


Question #15

What is the difference when String is gets created using literal or new() operator?

(String을 new()와 literal을 통해 생성할 때 차이?)

                              

   

Answer

When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

(String을 new() 연산자를 통해 생성할 때, 이 것은 heap 메모리 영역에 생성되고 Heap의 PermGen 영역에 존재하는 string pool 자체에서 만든 string 사용하여 생성하는 동안 문자열 풀에 추가되지 않습니다.)


Question #16

Does not overriding hashcode() method has any performance implication?

(hashcode()를 오버 라이딩하지 않는 점이 성능적으로 의미가 있는가?)

                              

   

Answer

This is a good question and open to all , as per my knowledge a poor hashcode function will result in frequent collision in HashMap which eventually increase time for adding an object into Hash Map.

(안 좋은 hashcode 기능은 HashMap에서 충돌을 빈번하게 일으켜 HashMap에 객체를 더할 때마다 시간이 늘어나게 된다.)


Question #17

What’s wrong using HashMap in multithreaded environment? When get() method go to infinite loop?

(멀티스레드 환경에서 HashMap을 사용하면 단점이? 언제 무한루프에 빠지는가?)

                              

   

Answer
Another good question. His answer was during concurrent access.

(동시접속 시 무한루프에 빠진다.)


Question #18

What will happen if we put a key object in a HashMap which is already there?

(중복된 key 객체를 HashMap에 넣으면?)

                              

   

Answer

This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys. 

(HashMap은 중복 Key를 허용하지 않는다. 따라서 old mapping으로 교체될 것이다.)


Question #19

If a method throws NullPointerException in super class, can we override it with a method which throws RuntimeException?

(super 클래스의 메소드에서 NullPointerExcepion이 발생한 경우, RuntimeException과 함께 오버 라이딩할 수 있는가?)

                              

   

Answer

One more tricky Java questions from overloading and overriding concept. Answer is you can very well throw super class of RuntimeException in overridden method but you can not do same if its checked Exception. 

(super 클래스의 오버 라이딩된 메소드의 RuntimeException을 throw 할 수 있다. 그러나 checked Exception의 경우엔 불가하다.)


Question #20

What is the issue with following implementation of compareTo() method in Java?

(compareTo() 메소드를 구현?)

                              

   

Answer

public int compareTo(Object o){

   Employee emp = (Employee) emp;

   return this.id - o.id;

}

Question #21

How do you ensure that N thread can access N resources without deadlock?

(데드락 없이 N개의 스레드가 N개의 자원에 접근할 수 있는가?)

                              

   

Answer

If you are not well versed in writing multi-threading code then this is real tricky question for you. This Java question can be tricky even for experienced and senior programmer, who are not really exposed to deadlock and race conditions. Key point here is order, if you acquire resources in a particular order and release resources in reverse order you can prevent deadlock. 

(멀티 쓰레딩 코드를 작성할 줄 모른다면 어려운 문제이다. 이 문제는 자바 전문가에게도 어렵다. 데드락은 정말 예상치 못하거나 정말 드물게 일어나기 때문이다. 핵심은 데드락을 방지하기 위해 자원을 할당하고 해제하느냐 이다.)


Question #22

Can you access non static variable in static context?

(static context에서 not static 변수에 접근할 수 있는가?)

                              

   

Answer

Another tricky Java question from Java fundamentals. No you can not access static variable in non static context in Java. Read why you can not access non-static variable from static method to learn more about this tricky Java questions.


* static context --- non static variable (접근 가능)

* static context --- static variable (접근 가능)

* non static context --- non static variable (접근 가능)

* non static context --- static variable (접근 불가)

매거진의 이전글 안드로이드 개발자 이직 공부 #01

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari