Tuesday, October 8, 2013

Java Quiz - 4

1) Write a program to produce the following output:
1
2
BOB
HARRY
5
BOB
7
HARRY
BOB
10
11
VINH
13
14
BOB
HARRY
17
BOB
.......
.......
100

Answer:
For(int i =1;i<=100 ; i++){
     if( (i%12)==0){System.out.println("VINH");  // catch 12 should be checked first
     if((i%3)==0){System.out.println("BOB");
     if((i%3)==0){System.out.println("HARRY");
}

2) What is wrong in the below program?

public class ConnectionManager{
........
........
try{
Class.forname("oracle.jdbc.oracledriver);
 Connection con= DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","SCOTT","Tiger");
Statement stmt = con.createstatement("Select * from Employee");
ResultSet res = stmt.executeQuery();
while(res.next()){
.....
......
}
 --------
-------
}catch(Exception e){
   e.printStackTrace();
}

}

Answer : you need to have a finally block to avoid the memory leaks in java.
finally{
         res.close();
         stmt.close();
        con.close();
}


3) HashMap<String, String> hm = new HashMap<String,Integer>();Will it work?
No. Compilation error because, you cannot associate a <String,String> with <String,Integer>

4)Write a program to display each key with a value from the below code:-
Map<String,String[]> m1 = new HashMap<String,String[]>();      
        String[] strarr={"TOM","David","Robert","Harry"};
        m1.put("mary",strarr);
        m1.put("kally",strarr);
        m1.put("Rossy",strarr);
E.g.
Rossy,TOM
Rossy,David
Rossy,Robert
Rossy,Harry
kally,TOM
kally,David
kally,Robert
kally,Harry
mary,TOM
mary,David
mary,Robert
mary,Harry




Answer:
Map<String,String[]> m1 = new HashMap<String,String[]>();       
        String[] strarr={"TOM","David","Robert","Harry"};
        m1.put("mary",strarr);
        m1.put("kally",strarr);
        m1.put("Rossy",strarr);
        int strlen = strarr.length;
       
        Set s = m1.keySet();
        Iterator itr = s.iterator();
        while(itr.hasNext()){
            String key = (String)itr.next();
           
            for(int i=0;i<=(strlen-1);i++){           
                System.out.println(key +","+strarr[i]);
            }
        }

5)   ===================================================================
       Author_ID      Author_Name                         Book_ID    Book_Name     Author_ID
     =====================================================================
         101                  Shakes Sphere                               1           PoeteryWorks       102
         102                  William WordsWorth                    2           Romeo Juliet         101





         103                  Jhonspace                                      3           Small Poems         102


Find the poet who has maximum number of books?



       





No comments:

Post a Comment