Friday, 10 November 2017

TCS Tech Lounge Exception Handling and Collections

import java.util.*;
import java.io.*;
class Test
{
            public static void main(String[]args)
            {
                        TreeSet map = new TreeSet();
                        map.add("one");
                        map.add("two");
                        map.add("three");
                        map.add("four");
                        map.add("one");
                        //System.out.println(map);
                        Iterator it=map.iterator();
                        while(it.hasNext()){
                                    System.out.println(it.next()+"");
                        }
            }                                                             
}
What is the result?
Ans: four one three two.


import java.util.*;
import java.io.*;
class a
{
            public static void main(String[]args)
            {
                        try
                        {           int x =0;
                                    int y=5/x;
                       
                        }catch(Exception e){
                                    System.out.println("Exception");
                        }catch(ArithmeticException ae)
                        {
                                    System.out.println("Arithmetic Exception");
                        }
                        System.out.println("finished");
            }
}

Ans: Compilation fails(Arithmetic exception has already caught)

Which collection class allows you to access its elements by associating a key with an element's value, and provides synchronization?

Ans : java.util.HashTable


import java.util.ArrayList; 
import java.util.Collections;
import java.util.HashSet;
import java.util.List; 
import java.util.Set; 
public class Test
{
public static void main(String args[])
{
List list=new ArrayList();
list.add(10);
list.add(40); 
list.add(20);
list.add(15); 
list.add(80); 
Collections.reverse(list); 
System.out.println(list);
}
}
Ans: [80,15,20,40,10]


What is the output of this code?
public class GetSetViewOfKeysFromHashMapExample
{
public static void main(String args[])
{
HashMap hMap=new HashMap();
hMap.put("1","One");
hMap.put("2","Two");
hMap.put("3","Three");
Set st=hMap.keySet();
Iterator itr=st.iterator();
while(itr.hasNext())
System.out.println(itr.next());
st.remove("2");
boolean blnExists=hMap.containsKey("2");
System.out.println(nlnExists);
}
}
Ans: 1 2 3 FALSE or 3 2 1 False



What is the output of below java program?

import java.util.*;

import java.lang.*;
class MainClass

{
public static void main(String args[])
{
int[] arr={1,2,3,4,5,6,7,8,9,10};
System.out.println("array element at 0 is.."+arr[-1]);
}

Ans: run time error, array index out of bounds exception


What will be the output of the program?
import java.util.*;
public class Primes2 {
            public static void main(String[]args){
            Integer[] primes = {2,7,5,3};
            MySort ms= new MySort();
            Arrays.sort(primes, ms);
            for(Integer p2:primes)
            System.out.print(p2+"");
            }
}
static class MySort implements Comparator {
                        public int compare(Integer x, Integer y) {
                        return y.compareTo(x);
                        }
                        public int compare(Object o1, Object o2) {
                        return 0;
                        }
}
ANS: Compilation fails








import java.util.*;
public class Test {
            public static void main(String[] args) {
            List arrayList = new ArrayList();
            arrayList.add(1);
            arrayList.add(2);
            arrayList.add(5);
            for(int i:arrayList){
            if(i==5){
            arrayList.remove(2);
            }
    }
System.out.println(arrayList);
            }
}
ANS: Compilation error

Which of these interface is not of Java’s collection framework?
ANS: SortedList


Which interface does java.util.Hashtable implement ?
ANS: java.util.Map

What is the output of this program ?
public class Test {
            public static void main(String args[]){
            String str1= "Strings are immutable";
            String str2= "Strings are immutable";
            String str3= "Integer are not immutable";
           
            int result = str1.compareTo(str2);
            if(result==0){
            System.out.print("It's zero!");
            }
            result = str2.compareTo(str3);
            if(result==0)
            System.out.print("Its less than zero");
            }
}

ANS: It’s zero!

Map<String,String> obj = new HashMap<String,String>();
            obj.put("City","Goa");
            obj.put("City","Simla");
            obj.put("City","Pune");
            obj.put("CityName","Simla");

or

import java.util.*;
class Ideone {
            public static void main(String[] args) {
                       
Map<String, String> obj = new HashMap<String, String>();
        obj.put("City","Goa");
        obj.put("City","Simla");
        obj.put("City","Pune");
        obj.put("CityName","Simla");
        System.out.println(obj);
            }
}

ANS: Following values will be stored in HashMap {CityName=Simla, City=Pune}


Set uniqueEnpId =  new TreeSet();
            uniqueEnpId.add(113);
            uniqueEnpId.add(111);
            uniqueEnpId.add(112);
            uniqueEnpId.add(111);
            System.out.println(uniqueEnpId);
ANS: [111,112,113]


import java.util.*;
class Employee implements Comparator{
            private String name;
            private int age;
            Employee(){
            }
            Employee(String n, int a){
            name= n;
            age = a;
            }
            public String getEmployeeName(){
            return name;
            }
            public int getEmployeeAge(){
            return age;
            }
            public int compare(Employee d, Employee d1){
            return d1.age = d.age;
            }
}
public class Example {
            public static void main(String[]args){
            List list = new ArrayList();
            list.add(new Employee("Anu",29));
            list.add(new Employee("Binu",25));
            list.add(new Employee("Janu",22));
            list.add(new Employee("Renu",27));
            list.add(new Employee("Tinu",23));
            Collections.sort(list,new Employee());
            for(Employee a:list)
            System.out.print(a.getEmployeeName()+":");
            }
}
ANS: Anu:Renu:Binu:Tinu:Janu: d


import java.util.*;
public class Emp{
            private int age;
            public Emp(int age){
            super();           
            this.age = age;
            }
            public int hashCode(){
            return age;
            }
            public boolean equals(Object obj){
            boolean flag = false;
            Emp emp = (Emp)obj;
            if(emp.age==age)
            flag = true;
            return flag;
}

}
public class TestEmp{
public static void main(String[] args){
            Emp emp1 = new Emp(23);
            Emp emp2 = new Emp(24);
            Emp emp3 =  new Emp(25);
            Emp emp4 = new Emp(26);
            Emp emp5 = new Emp(27);
            HashSet hs = new HashSet();
            hs.add(emp1);
            hs.add(emp2);
            hs.add(emp3);
            hs.add(emp4);
            hs.add(emp5);
            System.out.println(hs.size());
            System.out.println(hs.contains(new Emp(25)));
            System.out.println(hs.remove(new Emp(24)));
            System.out.println(hs.size());
            }
}

ANS: 5 true true 4

 Suppose that you would like to create an instance of a new Map that has an iteration order that is the same as the iteration order of an existing instance of a Map. Which concrete implementation of the Map interface should be used for the new instance?
Ans: LinkedHashMap

How to find the length of the arrayList ArrayList arr=new ArrayList()
Ans: arr.size()

The following method can be used to add elements to Map
Ans: put

public class ThrowsDemo{
            static void throwMethod(){
                        System.out.println("Inside throw Method");
                        throw new IllegalAccessException("demo");
                        }
            public static void main(String[]arg){
                        try{
                        throwMethod();
                        }
                        catch(IllegalAccessException e){
                        System.out.println("Caught"+e);
                        }
            }
}
ANS: Compiler Error

Which statement is true about set variable in the following program
import java.util.*;
public class TestSet{
            enum Example {ONE,TWO,THREE};
            public static void main(String[]arg){
                        Collection col1 = new ArrayList();
                        col1.add(Example.THREE);
                        col1.add(Example.THREE);
                        col1.add(Example.THREE);
                        col1.add(Example.TWO);
                        col1.add(Example.TWO);
                        col1.add(Example.ONE);
                        Set set = new HashSet(col1);
            }
}
ANS: The set variable contains only three elements from col1 collection and the ordering of the elements is NOT guaranteed.

import java.util.*;
public class Test{
            public static void main(String[]arg){
                        List myList = new ArrayList();
                        for(int i=0;i<10;i++)
                        {
                                    myList.add("String"+i);
                        }
                        int count =0;
                        Iterator iter = myList.iterator();
                        while(iter.hasNext())
                        {
                                    count++;
                                    if(count%2==0)
                                                myList.remove(count);
                                                System.out.print(iter.next()+"");
                        }
            }
}
ANS: Exception occurs at runtime because the list is being read and modified simultaneously.

Which collection class allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not snychronized? (choose all that apply.)
ANS: java.util.ArrayList

public class X{
                        public static void main(String[]arg){
                                    try{
                                                badMethod();
                                                System.out.print("A");
                                    }catch(RuntimeException ex){  /*  Line 10 */
                                                System.out.print("B");
                                    }catch(Exception ex1){
                                                System.out.print("C");
                                    }
                                    finally{
                                                            System.out.print("D");
                                    }
                                    System.out.print("E");
                        }
                        public static void badMethod(){
                                    throw new RuntimeException();
                        }
}
ANS: BDE

Which method gives the total number of elements in an ArrayList?
ANS: ArrayList.size()

Find the right syntax in the below Array instantiation statements
ANS: list1 = new Object[5]

import java.util.*;
public class LetterASort{
                        public static void main(String[]arg){
                                    ArrayList strings = new ArrayList();
                                    strings.add("aAaA");
                                    strings.add("AaA");
                                    strings.add("aAa");
                                    strings.add("AAaa");
                                    Collections.sort(strings);
                                    for(String s:strings)
                                                System.out.print(s+"");
                        }
}
ANS: Compilation fails

Public static before(){
                                    Set set = new TreeSet();
                                    set.add("2");
                                    set.add(3);
                                    set.add("1");
                                    Iterator  it = set.iterator();
                                    while(it.hasNext())
                                                System.out.print(it.next()+"");
}
ANS: The before() method will throw an exception at runtime


---- is the default capacity of ArrayList
ANS: 10

1.        Which of the following are false about Collections and Collection?
Ans: Collection is a special type of collection which holds set of collections

2. The following method can be used to add elements to a Map

Ans: put

3.______class is synchronized

Ans: Vector

4. Which collection class allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not?

Ans: java.util.ArrayList

5. Select all checked exceptions. a) ClassCastException b) IndexOutOfBoundException c) FileNotFoundException d) IOException

Ans: c,d

6. Which collection class allows you to access its elements by associating a key with an element's value, and provides synchronization?

Ans: java.util.Hashtable

7. What is the output of below java program?


import java.util.*;

import java.lang.*;

class MainClass

{
public static void main(String args[])
{
int[] arr={1,2,3,4,5,6,7,8,9,10};
System.out.println("array element at 0 is.."+arr[0]);
}

Ans: array element at 0 is..1

**8. Find the right syntax in the below Array instantiation statements

Ans: list1=new Object[5]

9. Select one or more true statements: A. Set does not store duplicate values B. All Set implementations are sorted. C. HashMap and Hashtble both store key value pairs, Hashtable we would use in case of synchronization requirements. D. List implementations dynamically grow in size, allow duplicates and are not sorted

Ans: A,C,D


10. 1. import java.util.*;
      2. public class Example{
      3. public static void main(String[] args){
      4. //insert code here
      5. set.add(new Integer(2));
      6. set.add(new Integer(1));
      7. System.out.println(set);
      8.}
      9.}
Which code, inserted at line 4. guarantees that this program will output[1,2]?
Ans: Set set=new TreeSet();

11. Which method gives the total number of elements in an ArrayList?
Ans: ArrayList.size()

12.


13. 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Employee implements Comparator
{
private String name;
private int age;
Employee(){}
Employee(String n,int a)
{
name=n;
age=a;
}
public String getEmployeeName()
{
return name;
}
public int getEmployeeAge()
{
return age;
}
public int compare(Employee d, Employee d1)
{
return d1.age-d.age;
}
}
What is the output of the above program 
public class Example{
public static void main(String args[])
{
List list=new ArrayList();
list.add(new Employee("Anu",29));
list.add(new Employee("Binu",25));
list.add(new Employee("Janu",22));
list.add(new Employee("Renu",27));
list.add(new Employee("Tinu",23));
Collections.sort(list,newEmployee());
for(Employee a:list)
System.out.println(a.getEmployeeName()+":");
}
}
Ans: Anu:Renu:Binu:Tinu:Janu:

14. public class Foo{
public static void main(String args[]){
try{return;}
finally{System.out.println("Finally");}}}
What would be the output of the code mentioned above?
Ans: Finally

15. Which collection class allows you to access its elements by associating a key with an element's value, and provides synchronization?
Ans: java.util.Hashtable

16. Map<String,String>obj=new HashMap<String,String>();obj.put("City","Goa");
obj.put("City","Simla"); obj.put("City","Pune"); obj.put("CityName","Simla"); Select one or more true statements for above code
Ans: Following values will be stored in HashMap{CityName=Simla,City=Pune}

17. public class ThrowsDemo
{
static void throwMethod()
{
System.out.println("Inside throwMethod"); 
throw new IllegalAccessException("demo");

public static void main(String args[])
{
try{throwMethod(); 
catch(IllegalAccessException e)
{
System.out.println("Caught"+e);
}
}
}
What would be the output of the code mentioned above. Assume the code is present in the main method
Ans: Compilation error

18. 
import java.util.List;
public class Test
{
public static void main(String args[])
{
List myList=new ArrayList();
for(int i=0;i<10;i++)
{
myList.add("String"+i);
}
int count=0;
Iterator iter=myList.iterator();
while(iter.hasNext())
{
count++;
if(count%2==0)
myList.remove(count);
System.out.println(iter.next()+"");
}
}
}
Ans: Exception occurs at runtime because the list is being ready and modified simultaneously


22. What is the output of this program?


import java.util.*;

class Test
{
public static void main(String args[])
{
TreeSet ts=new TreeSet();
ts.add("3");
ts.add("9");
ts.add("1");
ts.add("4");
ts.add("8");
System.out.println(ts);
}
}
Ans: [1,3,4,8,9]

23. What is the output of the following program?


public class Emp

{
private int age;
public Emp(int age)
{
super();
this.age=age;
}
public int hashCode()
{
return age;
}
public boolean equals(Object obj)
{
boolean flag=false;
Emp emp=(Emp)obj;
if(emp.age==age)
flag=true;
return flag;
}
}
public class TestEmp
{
public static void main(String args[])
{
Emp emp1=new Emp(23);
Emp emp2=new Emp(24);
Emp emp3=new Emp(25);
Emp emp4=new Emp(26);
Emp emp5=new Emp(27);
HashSet hs=new HashSet();
hs.add(emp1);
hs.add(emp2);
hs.add(emp3);
hs.add(emp4);
hs.add(emp5);
System.out.println(hs.size());
System.out.println(hs.contains(new Emp(25)));
System.out.println(hs.remove(new Emp(24)));
System.out.println(hs.size());
}
}
Ans: 5 true true 4


**23. Which statement is true about set variable in the following program 
import java.util.*;
public class TestSet
{
enum Example
{
ONE,TWO,THREE
};
public static void main(String a[]) 
{
Collection col1=new ArrayList();
col1.add(Example.THREE);
col1.add(Example.THREE);
col1.add(Example.THREE);
col1.add(Example.TWO);
col1.add(Example.ONE);
Set set=new HashSet(col1);
}
}
Ans: The set variable contains all six elements from col1 collection and the ordering of the elements is NOT preserved

25. Which of them are the correct syntax for instantiating arrays

Ans: int[] arr=new int[3]

26. What will be the output of the following program?

class Gen
{
T obj;
Gen(T o)
{
obj=o;
}
T get()
{
return obj;
}}
public class GenericsDemo
{
public static void main(String args[])
{
Gen i1=new Gen(new Integer(10));
int i=i1.get();
System.out.println(i);
}
}
Ans: 10.0

27. Which collection class allows you to access its elements by associating a key with a key with an element's value, and provides synchronization?

Ans: java.util.Hashtable

28. What is the output of the following program?

public class Test
{
public static void main(String args[])
{
String str1="Strings are immutable";
String str2="Strings are immutable";
String str3="Integers are not immutable";
int result=str1.compareTo(str2);
if(result==0)
{
System.out.println("It's zero!");
}
result=str2.compareTo(str3);
if(result<0)
{
System.out.print("It's less than zero");
}
result=str3.compareTo(str1);
if(result>0)
{
System.out.print("It's greater than zero");
}
}
}
Ans: It's zero!

29. What will be the output of the below program?

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test
{
public static void main(String args[])
{
List myList=new ArrayList();
for(int i=0;i<10;i++)
{
myList.add("String"+i);
}
int count=0;
Iterator iter=myList.iterator();
while(iter.hasNext())
{
count++;
if(count%2==0)
myList.remove(count);
System.out.println(iter.next()+"");
}
}
}
Ans: Exception occurs at runtime because the list is being ready and modified simultaneously


31. How to find the length of arrayList ArrayList arr=new ArrayList()

Ans: arr.size()

32. Which of these interface is not a part of Java's collection framework?

Ans: SortedList

33. Given:

TreeSet map=new TreeSet();
map.add("one");
map.add("two");
map.add("three");
map.add("four");
map.add("one");
Iterator it=map.iterator();
while(it.hasNext())
{
System.out.print(it.next()+"");
}
What is the result?
Ans: four one three two

Which statement is  true for the class java.util.ArrayList?
ANS: The elements in the collection are ordered

Class Maps{
           
            Public static void main(String[]arg){
                        TreeMap obj =new TreeMap();
                        Obj.put(“A”, new Integer(1));
                        Obj.put(“B”, new Integer(2));
                        Obj.put(“C”, new Integer(3));  
System.out.println(obj.entrySet());
            }
}
ANS: {0,1,3,4}

_ _ _  class is synchronized.
ANS: Vector

Which of these interface declares core method that call collections will have?
ANS: Collection

Which of these interface handle sequences?
ANS: List

Which of these  are core interfaces in collection framework. Select the one correct answer.
ANS: MAP


import java.util.ArrayList; 
import java.util.Collections;
import java.util.HashSet;
import java.util.List; 
import java.util.Set; 
public class Test
{
public static void main(String args[])
{
List myArrayList=new ArrayList();
myArrayList.add(1);
myArrayList.add(3); 
myArrayList.add(5);
myArrayList.add(2); 
Collections.reverse(myArrayList); 
System.out.println(myArrayList);
}
}
ANS: [2,5,3,1]

Given:

Import java.util.*;
Class Flubber{
Public static void main(String[] args){
List x = new  ArrayList();
x.add(“x”);
x.add(“xx”);
x.add(“Xx);
// insert code here
For(String s:x)
            System.out.println(s);
}
}
And the output:
Xx
Xx
X
Which code, inserted at // insert code here, will produce the preceding output?(choose all that apply)

ANS:  Compartor c = Collections.reverseOrder(); Collections.sort(x,c);

What is the output of this code?
public class IterateValuesOfHashMapExample
{
public static void main(String args[])
{
HashMap hMap=new HashMap();
hMap.put("1","One");
hMap.put("2","Two");
hMap.put("3","Three");
Collection c = hMap.values();
Iterator itr=c.iterator();
while(itr.hasNext())
System.out.println(itr.next());
}
}
Three Two One


import java.util.*; 
public class SortOf
{
public static void main(String args[])
{
List myArrayList=new ArrayList();
myArrayList.add(1);
myArrayList.add(5);
myArrayList.add(3); 
Collections.Sort(myArrayList); 
myArrayList.add(2); 
Collections.reverse(myArrayList); 
System.out.println(myArrayList);
}
}
[2,5,3,1]



Which code will sort the keys of props hashmap?
HashMap props = new HashMap();
Props.put(“Key45”,”value45”);
Props.put(“Key24”,”value24”);
Props.put(“Key33”,”value33”);
Set s = props.keySet();
// insert code here
ANS: s = new TreeSet(s);


What is the result of attempting to compile and run the following code?
import java.util.*;
public class Test{
            public static void main(String[]arg){
                        Integer a = new Integer(4);
                        Integer b = new Integer(8);
                        Integer c = new Integer(4);
                        TreeSet ts = new TreeSet();
                        ts.add(a);
                        ts.add(b);
                        ts.add(c);
                        System.out.println(ts);
                       
            }
}
ANS: [4, 8]

ArrayList<Integer> arrList = new ArrayList<Integer>();
                        arrList.add(new Integer(10));
                        arrList.add("20");
Select one or more true statements for above code
ANS:  We will get compilation error at the line where we are adding 20

Which of the following is true
ANS:  ArrayList allows null while vector does not allow

Which of the following is / are true?
1)      The Set interface is designed to ensure that implementing class have unique members
2)      Class that implement the list interface may not contain duplicate elements
3)      The map Interface is not part of the Collection framework

ANS:  The Set interface is designed to ensure that implementing classes have unique members


Select all methods which are applicable for both set and list
ANS:  Iterator()

7 comments:

  1. Great post.Thanks for one marvelous posting! I enjoyed reading it;The information was very useful.Keep the good work going on!!
    SEO Services in Pakistan

    ReplyDelete
  2. Hello,
    Nice set of questions on Exception handling and collections that are more in-depth than the standard ones on most interview lists! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging...
    Core Java Training

    ReplyDelete
  3. Such an interesting and informative piece of guidance imparted by you. I am glad to discover this information here and I am sure that this might be beneficial for us.
    Web delopment company in India

    ReplyDelete
  4. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Product prototyping during this lockdown period everyone can use it wisely.
    icp-cat training

    ReplyDelete
  5. If you are running a business or a company and have access to a website, whether small, medium, or big, you need to perform SEO – Search Engine Optimization to grow your business organically. With the correct tactics and techniques, you can steadily improve your business’s online presence, even if it’s domestically or globally. However, designing a website or a web portal is easy with the help of tools and technologies. The hurdles come when your website needs organic reach. For this purpose, you need the digital marketing companies ​to check the technical SEO of your website schema markups pages, loading speed, H tags and offer you the best SEO – search engine optimization services. “Additionally, Bright Edge stated in one of its articles, 53.3 % of traffic on the website comes from organic research, and 50% of revenue comes from this organic traffic. Get a read on seo companies in Pakistan

    ReplyDelete