Java Interview Questions - 6

Which of the following statements about arrays is syntactically wrong?
(a) Person[] p = new Person[5];
(b) Person p[5];
(c) Person[] p [];
(d) Person p[][] = new Person[2][];
Java Interview Questions


2. Given the following piece of code:
public class Test {
public static void main(String args[]) {
int i = 0, j = 5 ;
for( ; (i < 3) && (j++ < 10) ; i++ ) {
System.out.print(" " + i + " " + j );
}
System.out.print(" " + i + " " + j );
}
}
what will be the result?
(a) 0 6 1 7 2 8 3 8
(b) 0 6 1 7 2 8 3 9
(c) 0 5 1 5 2 5 3 5
(d) compilation fails


3. Which of the following declarations is correct? (2 answers):
(a) boolean b = TRUE;
(b) byte b = 255;
(c) String s = “null”;
(d) int i = new Integer(“56”);


4. Suppose a class has public visibility. In this class we define a protected method. Which of the following statements is correct?
(a) This method is only accessible from inside the class itself and from inside all subclasses.
(b) In a class, you can not declare methods with a lower visibility than the visibility of the class in which it is defined.
(c) From within protected methods you dnot have access tpublic methods.
(d) This method is accessible from within the class itself and from within all classes defined in the same package as the class itself.


5. Given the following piece of code:
public class Company{
public abstract double calculateSalaries();
}
which of the following statements is true?
(a) The keywords public and abstract can not be used together.
(b) The method calculateSalaries() in class Company must have a body
(c) You must add a return statement in method calculateSalaries().
(d) Class Company must be defined abstract.


6. Given the following piece of code:
public interface Guard{
void doYourJob();
}
abstract public class Dog implements Guard{}
which of the following statements is correct?
(a) This code will not compile, because method doYourJob() in interface Guard must be defined abstract.
(b) This code will not compile, because class Dog must implement method doYourJob() from interface Guard.
(c) This code will not compile, because in the declaration of class Dog we must use the key-word extends in stead of implements.
(d) This code will compile without any errors.


7. Given these classes:
public class Person{
public void talk(){ 
System.out.print("I am a Person "); 
}
}
public class Student extends Person {
public void talk(){ 
System.out.print("I am a Student "); 
}
}
what is the result of this piece of code:
public class Test{
public static void main(String args[]){
Person p = new Student();
p.talk();
}
}
(a) I am a Person
(b) I am a Student
(c) I am a Person I am a Student
(d) I am a Student I am a Person


8. Given the following piece of code:
public class Person{
private String firstName;
public Person(String fn){ 
firstName = fn; 
}
}
public class Student extends Person{
private String studentNumber;
public Student(String number) { 
studentNumber = number; 
}
}
Which of the following statements is true? (2 answers)
(a) This code will compile if we define in class Person a no-argument constructor.
(b) This code will compile if we define in class Student a no-argument constructor.
(c) This code will compile if we add in the constructor of Student the following line of code as first statement:super();
(d) This code will compile if we call the constructor of Person from within the constructor of Student.


9. Specify the correct characteristics of an enumeration type (2 answers)
(a) enum can define static fields and methods 
(b) enum can contain a public constructor
(c) enum can implement interfaces
(d) enum is a reference ta variable set of constants


10. Given the following piece of code:
class Person { 
public int number; 
}

public class Test{
public void doIt(int i , Person p){
i = 5;
p.number = 8;
}
public static void main(String args[]){
int x = 0;
Person p = new Person();
new Test().doIt(x, p);
System.out.println(x + " " + p.number);
}
}
What is the result?
(a) 0 8
(b) 5 0
(c) 0 0
(d) 5 8


11. Given the following piece of code:
class SalaryCalculationException extends Exception{}
class Person{
public void calculateSalary() throws SalaryCalculationException {
//...
throw new SalaryCalculationException();
//...
}
}
class Company{
public void paySalaries(){
new Person().calculateSalary();
}
}
Which of the following statements is correct? (2 answers)
(a) This code will compile without any problems.
(b) This code will compile if in method paySalaries() we return a boolean in stead of void.
(c) This code will compile if we add a try-catch block in paySalaries() 
(d) This code will compile if we add throws SalaryCalculationException in the signature of method paySalaries().


12. Which of the following statements regarding static methods are correct? (2 answers)
(a) static methods are difficult tmaintain, because you can not change their implementa-tion.
(b) static methods can be called using an object reference tan object of the class in which this method is defined.
(c) static methods are always public, because they are defined at class-level.
(d) static methods dnot have direct access tnon-static methods which are defined inside the same class.


13. Given the following piece of code:
class Person{ 
public void talk(){} 
}
public class Test{
public static void main(String args[]){
Person p = null;
try{
p.talk();
} catch(NullPointerException e){
System.out.print("There is a NullPointerException. ");
} catch(Exception e){
System.out.print("There is an Exception. ");
}
System.out.print("Everything went fine. ");
}
}
what will be the result?
(a) If you run this program, the outcome is: There is a NullPointerException. Everything went fine.
(b) If you run this program, the outcome is: There is a NullPointerException.
(c) If you run this program, the outcome is: There is a NullPointerException. There is an Exception.
(d) This code will not compile, because in Java there are npointers.


14. Which of the following statement about Generics are correct? (2 answers)
(a) Generics are typed subclasses of the classes from the Collections framework
(b) Generics are used tparameterize the collections in order tallow for static type check-
ing at compile tIme of the objects in the collection.
(c) Generics can be used tperform type checking of the objects in a collection at runtime.
(d) Generics can be used titerate over a complete collection in an easy way, using the ‘enhanced for’ loop.


15. Which collection class associates values witch keys, and orders the keys according ttheir natural order?
(a) java.util.HashSet
(b) java.util.LinkedList
(c) java.util.TreeMap
(d) java.util.SortedSet


16. Which of the following statements about GUI components is wrong?
(a) Swing exists since version 1.2 of the jdk.
(b) AWT stands for Abstract Window Toolkit
(c) You can not place AWT components on Swing containers.
(d) The AWT classes are deprecated.


17. Which of the following statements about events are correct? (2 answers)
(a) Event objects are placed on a Queue, where they are fetched by subscribers (objects of classes which implement the interface Subscriber).
(b) The listener of an event must implement the method public void listen(EventObject obj).
(c) Each event object must be an object of a subclass of EventObject.
(d) Each event listener can investigate about the source of an event by calling the method getSource() on the event object.


18. How can you serialize an object?
(a) You have tmake the class of the object implement the interface Serializable.
(b) You must call the method serializeObject()(which is inherited from class Object) on the object.
(c) You should call the static method serialize(Object obj) from class Serializer, with as argument the object tbe serialized.
(d) You don’t have tdanything, because all objects are serializable by default.


19. Which statements about Iare correct (2 answers)?
(a)OutputStream is the abstract superclass of all classes that represent an outputstream of bytes.
(b) Subclasses of the class Reader are used tread character streams.
(c) Twrite characters tan outputstream, you have tmake use of the class CharacterOutputStream.
(d) Twrite an object ta file, you use the class ObjectFileWriter.


20. Given the following piece of code:
public class MyThread extends Thread{
public String text;
public void run(){
System.out.print(text);
}
}
public class Test{
public static void main(String args[]){
MyThread t1 = new MyThread(); t1.text = "one ";
MyThread t2 = new MyThread(); t2.text = "tw";
t1.start();
t2.start();
System.out.print("three ");
}
}
Which of the following statements is true?
(a) If you execute this program, the result is always one twthree
(b) If you execute this program, the result is always three one two
(c) The result of this program is undetermined.
(d) Compilation will faill.


Answers:

1. b
2. a
3. c, d
4. d
5. d
6. d
7. b
8. a, d
9. a, c
10. a
11. c, d
12. b, d
13. a
14. b, d
15. c
16. d
17. c, d
18. a
19. a, b
20. c

How to concatenate 2 List in Java

We have seen situation that we need to merge or concatenate 2 Lists of same type into single List. To do this instead of iterating all elements and adding to new List we can use addAll() function to concatenate 2 List items. There are two types of addAll() function in Java.
How to concatenate 2 List in Java
  • First we can merge all elements at the end of List.
  • Second we can insert all of the elements from specified position of List.
Lets see both types by simple example


import java.util.ArrayList;
import java.util.List;

public class ListTest {

 public static void main(String[] args) {
  
  List<String> list1 = new ArrayList<String>();
  list1.add("one");
  list1.add("two");
  list1.add("three");
  
  List<String> list2 = new ArrayList<String>();
  list2.add("four");
  list2.add("five");
  list2.add("six");
  
  // First type merging at the end of list
  list1.addAll(list2);
 
  System.out.println("First Type : "+list1);
  
  list1.clear();
  list1.add("one");
  list1.add("two");
  list1.add("three");
  
  // Second type merging at index(1)
  list1.addAll(1, list2);
  
  System.out.println("\nSecond Type : "+list1);
 }
}

OUTPUT:


First Type : [one, two, three, four, five, six]

Second Type : [one, four, five, six, two, three]

How to Iterate Map key and value

We can Iterate Map's key and values in lot of ways like getting keySet or by getting entrySet or by using Iterator interface. Lets see all these ways with simple example.
How to Iterate Map key and value


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapTest {

 public static void main(String[] args) {

  Map<String, String> map = new HashMap<String, String>();
  map.put("2", "two");
  map.put("3", "three");
  map.put("1", "one");
  map.put("4", "four");
  map.put("5", "five");
  

  System.out.println("Using entrySeT() ---- ");
  
                   for (Map.Entry<String, String> myMap : map.entrySet()) {
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }

  
  System.out.println("\nUsing keySet() ---- ");
  
  for (Object myKey : map.keySet()) {
   System.out.println(myKey.toString() + " : " + map.get(myKey));
  }

  
  System.out.println("\nUsing Iterator interface ---- ");
  
  Iterator<?> itr = map.entrySet().iterator();
  while (itr.hasNext()) {
   Map.Entry myMap = (Map.Entry) itr.next();
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }
 }
}

OUTPUT:


Using entrySeT() ---- 
2 : two
3 : three
1 : one
4 : four
5 : five

Using keySet() ---- 
2 : two
3 : three
1 : one
4 : four
5 : five

Using Iterator interface ---- 
2 : two
3 : three
1 : one
4 : four
5 : five

Difference between Hashtable, HashMap, TreeMap and LinkedHashMap

 
Map is one of the most important data structures and when we talk about Map all these 4 implementation classes (Hashtable, HashMap, TreeMap and LinkedHashMap) are most used. Hashtable, HashMap and LinkedHashMap are directly implements Map interface, but TreeMap implements Map interface through implementing SortedMap. Below are the few differences between these classes
Difference between Hashtable, HashMap, TreeMap and LinkedHashMap
  • HashMap implemented as same as Hashtable except it is unsynchronized and permits null. As common both HashMap and Hashtable won't have any ordering on keys or values.
  • TreeMap implemented based on red-black tree structure and it follows natural ordering on key. 
  • LinkedHashMap is a subclass of HashMap and inherits all properties of HashMap class and additionally its ordering will based on insertion order.
NOTE:
  • If we use any Map implementation classes and if the key is user-defined class Object then we need to override hashcode() and equals() methods. 
  • Next when we use TreeMap, by default they are sorted by keys. If we use user-defined class Object for key, then to compare with each other we need to implement Comparable interface.

Next lets see simple examples for each classes. 

Hashtable:


import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

public class MapTest {

 public static void main(String[] args) {

  Map<String, String> map = new Hashtable<String, String>();
  map.put("1", "one");
  map.put("2", "two");
  map.put("3", "three");
  map.put("4", "four");
  map.put("5", "five");

  Iterator<?> itr = map.entrySet().iterator();
  while (itr.hasNext()) {
   Map.Entry myMap = (Map.Entry) itr.next();
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }
 }
}

OUTPUT:


5 : five
4 : four
3 : three
2 : two
1 : one


HashMap:


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class MapTest {

 public static void main(String[] args) {

  Map<String, String> map = new HashMap<String, String>();
  map.put("1", "one");
  map.put("2", "two");
  map.put("3", "three");
  map.put("4", "four");
  map.put("5", "five");

  Iterator<?> itr = map.entrySet().iterator();
  while (itr.hasNext()) {
   Map.Entry myMap = (Map.Entry) itr.next();
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }
 }
}

OUPTUT:


3 : three
2 : two
1 : one
5 : five
4 : four


TreeMap:


import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class MapTest {

 public static void main(String[] args) {

  Map<String, String> map = new TreeMap<String, String>();
  map.put("2", "two");
  map.put("3", "three");
  map.put("1", "one");
  map.put("4", "four");
  map.put("5", "five");

  Iterator<?> itr = map.entrySet().iterator();
  while (itr.hasNext()) {
   Map.Entry myMap = (Map.Entry) itr.next();
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }
 }
}

OUTPUT:


1 : one
2 : two
3 : three
4 : four
5 : five


LinkedHashMap:


import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class MapTest {

 public static void main(String[] args) {

  Map<String, String> map = new LinkedHashMap<String, String>();
  map.put("2", "two");
  map.put("3", "three");
  map.put("1", "one");
  map.put("4", "four");
  map.put("5", "five");

  Iterator<?> itr = map.entrySet().iterator();
  while (itr.hasNext()) {
   Map.Entry myMap = (Map.Entry) itr.next();
   System.out.println(myMap.getKey() + " : " + myMap.getValue());
  }
 }
}

OUTPUT:


2 : two
3 : three
1 : one
4 : four
5 : five

Implementing Queue in Java

 
Queue is a First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the queue will be the first to be removed. Suppose if a queue contains 4 elements and 5th element added at back and if we need to remove that element then we need to remove all front 4 elements first. As like Stack implementation in java we can implement Queue Data Structure and also we have operations in Queue like enqueue(), dequeue(), front(), isempty() etc.,
Implementing Queue in Java

enqueue() - Insert element in front of the Queue.

dequeue() - Return front element and remove same element from the Queue.

front() - Same as dequeue() returns front element but same element won't be removed from the Queue.

clean() - cleans the Queue.



Lets see simple example to implement Queue using ArrayList and using Generics for holding any datatype.



import java.util.ArrayList;
import java.util.List;

public class MyQueue <E>{

 private List<E> list = null;
 
 public MyQueue() {
  list = new ArrayList<E>();
 }

 public void enqueue(E val){
  list.add(val);
 }
 
 public E dequeue(){
  E val = null;
  if(list.size() > 0){
   val = list.get(0);
   list.remove(0);
  }  
  return val;
 }
 
 public boolean isEmpty(){
  if(list.size() == 0)return true;
  else return false;
 }
 
 public int size(){
  return list.size();
 }
 
 public E front(){
  E val = null;
  if(list.size() > 0){
   val = list.get(0);
  }  
  return val;
 }
 
 public void clean(){
  list = new ArrayList<E>();
 }
 
 @Override
 public String toString() {
  return list.toString();
 }
}


Our Queue class is ready and we can test with below code.


public class TestMyQueue {

 public static void main(String[] args) {
  
  MyQueue<String> queue = new MyQueue<String>();
  
  int qSize = queue.size();
  System.out.println("QUEUE SIZE : "+qSize);
  
  //ENQUEUE
  queue.enqueue("one");
  queue.enqueue("two");
  queue.enqueue("three");
  queue.enqueue("four");
  queue.enqueue("five");
  System.out.println("5 ELEMENTS ADDED IN QUEUE");
  qSize = queue.size();
  System.out.println("QUEUE SIZE : "+qSize);
  
  //QUEUE
  System.out.println("QUEUE      : "+queue);
  
  //FRONT
  System.out.println("FRONT       : "+queue.front());
  
  //DEQUEUE
  System.out.println("DEQUEUE        : "+queue.dequeue());
    
  qSize = queue.size();
  System.out.println("QUEUE SIZE : "+qSize);
  
  //FRONT
  System.out.println("FRONT       : "+queue.front());
  
  //ISEMPTY
  System.out.println("EMPTY      : "+queue.isEmpty());
  
  //CLEAN
  queue.clean();
  System.out.println("QUEUE CLEANED");
  
  //ISEMPTY
  System.out.println("EMPTY      : "+queue.isEmpty());
  
 }
}


OUTPUT:


QUEUE SIZE     : 0
5 ELEMENTS ADDED IN QUEUE
QUEUE SIZE     : 5
QUEUE             : [one, two, three, four, five]
FRONT             : one
DEQUEUE         : one
QUEUE SIZE      : 4
FRONT             : two
EMPTY             : false
QUEUE CLEANED
EMPTY             : true