brunch

You can make anything
by writing

C.S.Lewis

by 이승현 May 03. 2016

Java 면접 질문 #01

Java interview questions

Java2novice


Java 면접 문제들이 있는 외국 사이트입니다.

Java 개발자이지만 헷갈리는 문제들이 많네요.

몇 가지만 추려봤습니다.


http://www.java2novice.com/java-interview-questions/



Question #01

Can Java thread object invoke start method twice?

(자바 스레드 객체는 start 메소드를 두 번 호출할 수 있나요?)

                              

   

Answer

No, it throws IllegalThreadStateException

(아니요, IllegalThreadStateException가 발생합니다.)

                

http://www.java2novice.com/java_interview_questions/thread-start-twice/


Question #02

Can we override static method?

(static 메소드를 오버라이드 할 수 있나요?)
                                  

          

Answer

We cannot override static methods. Static methods are belogs to class, not belongsto object. Inheritance will not be applicable for class members.

(static 메소드를 오버라이드 할 수 없습니다. static 메소드들은 객체가 아닌 클래스에 속해 있습니다. 상속은 클래스 멤버에 적용되지 않습니다. )


http://www.java2novice.com/java_interview_questions/override_static_method/


Question #03

Can you list serialization methods?
(serialization 메소드들을 나열할 수 있나요?)

 

      

Answer

Serialization interface does not have any methods. It is a marker interface.It just tells that your class can be serializable.

(Serialization 인터페이스는 메소드를 가지고 있지 않습니다. 이것은 마커 인터페이스이고 단지 클래스가 직렬화 될 수 있다는 것만 알려줍니다.)


http://www.java2novice.com/java_interview_questions/list_serialization_methods/


Question #04

What is the difference between super() and this()?

(super()와 this()의 차이점은?)


            

Answer

super() is used to call super class constructor, whereas this() used to call constructors in the same class, means to call parameterized constructors.

(this()는 같은 클래스의 생성자를 호출하거나, 매개 변수가 있는 생성자를 호출하는 것을 의미하는 반면, super()는 super 클래스의 생성자를 호출하는 데 사용됩니다.)


http://www.java2novice.com/java_interview_questions/this_super_difference/


Question #05

How to prevent a method from being overridden?

(메소드 overridden 방지 법은?)



Answer

By specifying final keyword to the method you can avoid overriding in a subcalss.

Similarlly one can use final at class level to prevent creating subclasses.

(메소드에 final 키워드를 지정하여 서브 클래스에서 재정의를 방지할 수 있습니다.

마찬가지로 클래스에 final을 지정하여 서브 클래스 생성(상속)을 막을 수 있습니다.)


http://www.java2novice.com/java_interview_questions/stop_overriding/


Question #06

Can we create abstract classes without any abstract methods?

(추상 메소드 없이 추상 클래스를 만들 수 있나요?)
            


Answer

Yes, we can create abstract classes without any abstract methods.

(추상 메소드 없이 추상 클래스를 만들 수 있습니다.)


http://www.java2novice.com/java_interview_questions/without_abstract_methods/


Question #07

What is transient variable?
(transient 변수?)


            

Answer

Transient variables cannot be serialized. During serialization process, transient variable states will not be serialized.

(Transient 변수는 직 할 수 없습니다. 직렬화 과정에서 transient 변수 상태는 직렬화 되지 않습니다.)


http://www.java2novice.com/java_interview_questions/transient-variable/


Question #08

Incase, there is a return at the end of try block, will execute finally block?
(try block이 끝날 때 return이 없다면 finally block이 실행될까요?)


         

Answer

Yes, the finally block will be executed even after writing return statementat the end fo try block.

(예, finally block은 try block의 끝에서 상태를 return 하더라도 실행합니다. System.exit()이 아닌 이상 항상 실행합니다.)


http://www.java2novice.com/java_interview_questions/try-finally-return/


Question #09

What is abstract class or abstract method?

(추상 클래스? 추상 메소드?)


            

Answer

We cannot create instance for an abstract class. We can able to create instance for its subclass only. By specifying abstract keyword just before class, we can make a class as abstract class.

(추상 클래스의 인스턴스는 서브 클래스에서만 만들 수 있다. abstract 키워드를 클래스 앞에 붙이면 된다.)


* Objcet(객체) : 선언 (MyClass myClass;)

* Instance(인스턴스) : 메모리에 할당 (MyClass myClass = new MyClass();)


public abstract class MyAbstractClass {

}


Abstract class may or may not contains abstract methods. Abstract method is just method signature, it does not containes any implementation. Its subclass must provide implementation for abstract methods.

(추상 클래스는 추상 메소드를 포함할 수 도, 안 할 수도 있습니다. 추상 메소드는 단지 메소드를 선언만 했지,  어떤 구현도 포함하지 않습니다. 서브 클래스에서 추상 메소드의 구현을 반드시 해줘야 합니다.)


public abstract int getLength();


http://www.java2novice.com/java_interview_questions/abstract-class-method/


Question #10

What is default value of a boolean?
(boolean의 기본 값은?)



Answer

Default value of a boolean is false.

(false)


http://www.java2novice.com/java_interview_questions/boolean-default-value/


Question #11

When to use LinkedList or ArrayList?

(언제 LinkedList나 ArrayList를 사용하나요?)


                                            

Answer

Accessing elements are faster with ArrayList, because it is index based.But accessing is difficult with LinkedList. It is slow access. This is to access any element, you need to navigate through the elements one byone.

(특정  element 접근은 하나하나씩 elements를 거쳐야 하는 LinkedList 보다는 index 기반의 ArrayList가 더 빠릅니다.)


But insertion and deletion is much faster with LinkedList, because if you know the node, just change the pointers before or after nodes.Insertion and deletion is slow with ArrayList, this is because, during these operations ArrayList need to adjust the indexes according to deletion or insetion if you are performing on middle indexes.

(그러나 삽입, 삭제는 LinkedList가 더 빠릅니다. 왜냐면 LinkedList는 해당 노드의 앞, 뒤 노드 포인터만 바꿔 주면 되기 때문입니다. ArrayList는 삽입, 삭제 시 index 값들을 조정해야 되기 때문에 느립니다.)


* 검색 : ArrayList가 빠름.

* 삽입, 삭제 : LinkedList가 빠름.


http://www.java2novice.com/java_interview_questions/arraylist-linkedlist-use/


Question #12

Does each thread in java uses separate stack?

(Java에서는 각각의 스레드가 별도의 스택을 이용합니까?)
            


Answer

In Java every thread maintains its own separate stack. It is called Runtime Stack but they share the same memory.

(Java에서는 모든 스레드는 자신의 별도의 런타임 스택이라 불리는 스택을 유지한다. 하지만 동일한 메모리를 공유한다.)


http://www.java2novice.com/java_interview_questions/thread-stack/


Question #13

What is the difference between Enumeration and Iterator?

(Enumeration와 Iterator 차이점은?)
            


Answer

The functionality of Enumeration and the Iterator are same. You can get remove() from Iterator to remove an element, while while Enumeration does not have remove() method. Using Enumeration you can only traverse and fetch the objects, where as using Iterator we can also add and remove the objects. So Iterator can be useful if you want to manipulate the list and Enumeration is for read-only access.

(기능적으로는 둘은 같다.)


* Enumeration :  단지 traverse와 fetch만을 할 수 있다. 단순히 읽기만 한다면 더 유용하다.

* Iterator : add, remove 할 수 있다. list를 다룬다면 더 유용하다.


http://www.java2novice.com/java_interview_questions/enumeration-iterator-difference/


Question #14

Does system.exit() in try block executes code in finally block?

(try block에서 system.exit()이 실행되면 finally block을 실행할까?)



Answer

It will not execute finally block. The program will be terminated after System.exit() statement.

(finally block이 실행되지 않는다. System.exit() 이후 프로그램은 종료된다.)


http://www.java2novice.com/java_interview_questions/system-exit-try-finally/


Question #15

What is final, finally and finalize?
(final, finally, finalize?)



Answer

final: final is a keyword. The variable decleared as final should be initialized only once and cannot be changed. Java classes declared as final cannot be extended. Methods declared as final cannot be overridden.

(final은 키워드이다. 변수 앞에 붙으면 한 번만 초기화되고 수정이 불가능하다. 클래스 앞에 붙으면 상속이 안되고 메소드 앞에 붙으면 오버라이드가 안된다.)


finally: finally is a block. The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

(finally는 block이다. finally block은 try block 이후 항상 실행된다. 심지어 예상치 못한 exception에서도 실행된다.)


finalize: finalize is a method. Before an object is garbage collected, the runtime system calls its finalize() method. You can write system resources release code in finalize() method before getting garbage collected.

(finalize는 메소드이다. 객체가 gc 되기 이전에 런타임 시스템은 finalize() 메소드를 호출한다. gc 하기 전에 시스템 자원은 finalize 메소드에서 해제 코드를 작성할 수 있습니다.)


http://www.java2novice.com/java_interview_questions/final-finally-finalize/


Question #16

What is difference between wait and sleep methods in java?
(Java에서 wait 메소드와 sleep 메소드의 차이점은?)


Answer

sleep(): It is a static method on Thread class. It makes the current thread into the "Not Runnable" state for specified amount of time.

(Thread 클래스의 static method이다. 특정 시간만큼 스레드 상태를 "Not Runnable" 상태로 만든다.)


wait(): It is a method on Object class. It makes the current thread into the "Not Runnable" state. Wait is called on a object, not a thread.

(Object 클래스의 메소드이다. 현재 스레드 상태를 "Not Runnable" 상태로 만든다. Wait는 스레드가 아닌 객체에서 불립니다.)


http://www.java2novice.com/java_interview_questions/wait-sleep-difference/


Question #17

How to get current time in milli seconds?

(현재시간을 얻는 방법은?)



Answer

System.currentTimeMillis() returns the current time in milliseconds.It is a static method, returns long type.

(System.currentTimeMillis()는 현재시간을 리턴한다. static 메소드이며 long 타입 값을 리턴한다.)


http://www.java2novice.com/java_interview_questions/current-time-in-milli-seconds/


Question #18

When to use String and StringBuffer?

(String과 StringBuffer)


                                            

Answer

We know that String is immutable object. We can not change the value of a String object once it is initiated. If we try to change the value of the existing String object then it creates new object rather than changing the value of the existing object. So incase, we are going to do more modificatios on String, then use StringBuffer. StringBuffer updates the existing objects value, rather creating new object.

(String은 immutable 객체이다. String 객체를 한번 초기화하면 값을 바꿀 수 없다. 만약 값을 바꾸면 기존의 객체의 값을 바꾸지 않고 새로운 String 객체를 생산 한다. 만약 값을 계속 수정해야 한다면 StringBuffer를 이용하자. StringBuffer는 새로운 객체를 생성하지 않고도 값을 바꿀 수 있다.)


http://www.java2novice.com/java_interview_questions/string-stringbuffer/



Question #19

What is wrapper class in java?

(Java에서 wrapper 클래스란?)


            

Answer

Everything in java is an object, except primitives. Primitives are int, short, long, boolean, etc. Since they are not objects, they cannot return as objects, and collection of objects. To support this, java provides wrapper classes to move primitives to objects. Some of the wrapper classes are Integer, Long, Boolean, etc.

(Java에선 primitives(int, short, long, boolean, char, float, double, byte)를 제외하고 다 객체이다.  primitives는 객체가 아니기 때문에 객체나 객체들의 collection으로 반환할 수 없다. java는 이를 위해 wrapper class(Integer, Long, Boolean, etc. )를 제공한다.)


http://www.java2novice.com/java_interview_questions/wrapper-class/


Question #20

Is Iterator a Class?

(Iterator는 클래스?)


            

Answer

Iterator is an interface. It is not a class. It is used to iterate through each and every element in a list. Iterator is implemented Iterator design pattern.

(Iterator는 클래스가 아닌 인터페이스이다. 각각의 list에 있는 모든 요소를 통해 Iterator 하는 데 사용됩니다. Iterator는 Iterator 디자인 패턴을 통해 구현된다.)


http://www.java2novice.com/java_interview_questions/iterator-interface/


Question #21

What is the super class for Exception and Error?

(Exception과 Error의 super 클래스?)


            

Answer

The super class or base class for Exception and Error is Throwable.

(Throwable)


http://www.java2novice.com/java_interview_questions/exception-super-class/


Question #22

Can interface be final?

(interface는 final이 될 수 있는가?)



Answer

No. We can not instantiate interfaces, so in order to make interfaces useful we must create subclasses. The final keyword makes a class unableto be extended.

(될 수 없다. final 키워드는 클래스의 상속을 막으므로 서브 클래스를 통해 구현되어야 할 interface는 final 키워드를 쓸 수 없다.)


http://www.java2novice.com/java_interview_questions/can-interface-final/


Question #23

What is the difference between exception and error?

(exception과 error의 차이점은?)



Answer

An error is an irrecoverable condition occurring at runtime like out of memory error. These kind of jvm errors cannot be handled at runtime.

Exceptions are because of condition failures, which can be handled easily at runtime.

(error는 out of memory처럼 런타임 도중 발생하는 예측 불가능한 상황에서 일어난다. 이런 jvm 에러들은 런타임 시 처리할 수 없다.

Exception들은 런타임 시 쉽게 처리할 수 있는 실패 상황들이다.)


http://www.java2novice.com/java_interview_questions/error-exception-difference/


Question #24

Can we initialise uninitialized final variable?

(초기화되지 않은 final 변수를 초기화할 수 있나요?)


            

Answer

Yes. We can initialise blank final variable in constructor, only in construtor. The condition here is the final variable should be non-static.

(예. 오직 생성자안에서만 빈 final 변수를 초기화할 수 있습니다. 단 final 변수가 not-static일 경우에만.)


http://www.java2novice.com/java_interview_questions/final-variable-initialization/


Question #25

Can we declare abstract method as final?
(추상 메소드에 final을 선언할 수 있나요?)



Answer

No, we can not declare abstract method as final. We have to proved implementation to abstract methods in subclasses.

(아니요. 서브클래스에서 추상 메소드를 구현해야 하기 때문에 오버라이딩을 막는 final을 선언할 수 없다.)


http://www.java2novice.com/java_interview_questions/final-abstract-method/


Question #26

Can we have finally block without catch block?

(catch block 없이 finally block을 쓸 수 있나요?)


            

Answer

Yes, we can have finally block without catch block.

(예. catch block 없이도 finally block을 쓸 수 있습니다.)


http://www.java2novice.com/java_interview_questions/finally-without-catch/


Question #27

What is pass by value and pass by reference?

(pass by value? pass by reference?)


           

Answer

Pass by value: Passing a copy of the value, not the original reference.

(오리지널 레퍼런스가 아닌 복사한 값만 넘긴다.)


Pass by reference: Passsing the address of the object, so that you can access the original object.

(객체의 주소를 넘겨 오리지널 객체에 접근할 수 있다.)



http://www.java2novice.com/java_interview_questions/pass-by-value-reference/


Question #28

Can we declare main method as private?

(메인 메소드를 private로 선언할 수 있나요?)


            

Answer

Yes, we can declare main method as private. It compiles without any errors, but in runtime, it says main method is not public.

(예. 메인 메소드를 private로 선언할 수 있다. 컴파일 시 아무 문제없지만 런타임 시 문제가 발생한다.)


http://www.java2novice.com/java_interview_questions/private-main-method/


Question #29

Can you serialize static fields of a class?

(클래스의 static 영역을 직렬화 할 수 있나요?)


            

Answer

Since static fields are not part of object state, they are part of class, serialization ignores the static fields.

(static 영역은 객체가 아닌 클래스 소속이기 때문에 serializationd은 static 영역은 무시한다.)


http://www.java2novice.com/java_interview_questions/static-field-serialization/


Question #30

Which one is faster? ArrayList or Vector? Why?

(ArrayList와 Vector 중 뭐가 더 빠른가? 왜?)


            

Answer

ArrayList is faster than Vector. The reason is synchronization. Vector is synchronized. As we know synchronization reduces the performance.

(ArrayList가 Vector보다 더 빠르다. 왜냐면 동기화 때문이다. Vector는 자동으로 동기화된다. 동기화는 성능을 저하시킨다.)


http://www.java2novice.com/java_interview_questions/arraylist-vector-faster/


Question #31

Can we have private constructor in java?

(생성자를 private로 선언할 수 있나?)



Answer

Private constructor is used if you do not want other classes to instantiate the object.

Private constructors are used in singleton design pattern, factory method design pattern.

(만약 다른 클래스들이 객체를 인스턴스화 시키기 원하지 않으면 private 생성자를 이용할 수 있다. 주로 싱글톤 패턴이나 팩토리 패턴에서 쓰인다.)


http://www.java2novice.com/java_interview_questions/private-constructor/



Question #32

What is the difference between the prefix and postfix forms of the increment(++) operator?

(증가(++) 동작의 prefix와 postfix 차이점은?)


            

Answer

The prefix form first performs the increment operation and then returns the value of the increment operation. The postfix form first returns the current value of the expression and then performs the increment operation on that value.

(prefix 형태는 처음에 증가 동작을 수행하고 이 동작의 값을 리턴 한다. postfix 형태는 현재 값을 리턴하고 증가 동작을 수행한다.)


For example:

int count=1;
System.out.println(++count);

displays 2.

int count=1;
System.out.println(count++);

displays 1.


http://www.java2novice.com/java_interview_questions/increment-position/


Question #33

What is the difference between Hashtable and HashMap?            

(Hashtable과 HashMap의 차이점은?)



Answer

The basic differences are Hashtable is synchronized and HashMap is not synchronized. Hashtable does not allow null values, and HashMap allows null values.

* Hashtable : 동기화, null 값 안됨.

* HashMap :  비동기화, null 허용.


http://www.java2novice.com/java_interview_questions/hashtable-hashmap/


Question #34

What are the differences between C++ and Java.

(C++과 Java의 차이는?)


                                           

Answer

Java doesnot support pointers. Pointers are tricky to use and trouble some.

(Java는 pointer를 지원하지 않는다.)


Java does not support multiple inheritances because it causes more problems than it solves. Instead Java supports multiple interface inheritance, which allows an object to inherit many method signatures from different interfaces with the condition that the inheriting object must implement those inherited methods. The multiple interface inheritance also allows an object to behave polymorphically on those methods.

(Java는 다중 상속을 지원하지 않는다. 대신 상속 객체가 그 상속된 메소드를 구현해야 한다는 조건으로 서로 다른 인터페이스에서 여러 메소드들을 상속할 수 있도록 다중 인터페이스 상속을 지원합니다)


Java does not include structures or unions.

(Java는 structure나 union을 포함하지 않는다.)


Java does not support destructors but adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which has the finalize() method. This means you do not know when the objects are going to be finalized.

(Java는 소멸자를 제공하지 않지만 finalize() 메소드를 제공한다. finalize 메소드는 객체가 점유된 메모리를 회수하기 전에 gc에 의해 호출됩니다.   객체가 언제 finalize 될지 모른다는 것을 의미한다.)


C++ requires explicit memory management, while Java includes automatic garbage collection.

(Java가 자동으로 gc 하는 동안 C ++은 명시 적으로 메모리 관리가 필요합니다.)


http://www.java2novice.com/java_interview_questions/difference_c_java/


Question #35

Why do we need generics in java?

(Java에서 generics 이 왜 필요한가?)


                                          

Answer

Code that uses generics has many benefits over non-generic code:

(generics을 이용하는 코드가 아닌 일반 코드에 비해 많은 장점이 있습니다)


1) Stronger type checks at compile time: A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

(컴파일 시 강한 타입 검사 : Java 컴파일러는 generic 코드와 문제 에러에 강한 타입 검사를 적용하여 잘못된 코드로부터 안전하게 한다. 컴파일 에러 수정이 런타임 에러 수정보다 찾기 편하고 쉽다.)


2) Elimination of casts: If you use generics, then explicit type casting is not required.

(캐스트 제거 : generics 사용하는 경우, 명시 적 형 변환이 필요하지 않습니다.)


3) Enabling programmers to implement generic algorithms: By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

(프로그래머들이 generic 알고리즘을 구현하기 위해 이용 : generics을 이용하면, 프로그래머는 커스터마이즈 된 다른 타입의 collection들을 가지고 generic 알고리즘을 안전하고 좀 더 쉽게 이해하여 구현할 수 있습니다.


http://www.java2novice.com/java_interview_questions/why-generics/



매거진의 이전글 안드로이드 개발자 이직 준비 #04

작품 선택

키워드 선택 0 / 3 0

댓글여부

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