· 8 years ago · Jan 14, 2018, 07:46 AM
11)Program to print the following patterns :
2a) 1
3 12
4 123
5 12345
6import java.util.Scanner;
7
8public class MainClass
9{
10 public static void main(String[] args)
11 {
12 Scanner sc = new Scanner(System.in);
13 System.out.println("Enter the number of rows you want to print:");
14 int rows = sc.nextInt();
15 for (int i = 1; i <= rows; i++)
16 {
17 for (int j = 1; j <= i; j++)
18 {
19 System.out.print(j+" ");
20 }
21
22 System.out.println();
23 }
24 sc.close();
25 }
26b)54321
27 5432
28 543
29 54
30 5
31PROGRAM:
32import java.util.Scanner;
33
34public class MainClass
35{
36 public static void main(String[] args)
37 {
38 Scanner sc = new Scanner(System.in);
39 System.out.println("Enter the number of rows you want:");
40 int rows = sc.nextInt();
41 for (int i = 1; i <= rows; i++)
42 {
43 for (int j = rows; j >= i; j--)
44 {
45 System.out.print(j+" ");
46 }
47
48 System.out.println();
49 }
50 sc.close();
51 }
52}
53c) x
54 xxx
55 xxxxx
56 xxxxxxx
57 xxxxx
58 xxx
59PROGRAM:
60
612) Write a java program to take the input from user and determine if it is a prime number or not.
62PROGRAM:
63import java.util.*;
64public class Main
65{
66public static void main(String []args)
67{
68int n,i,flag=0;
69for(i=2;i<n;i++)
70{
71if(n%i==0)
72{
73System.out.println("Not a prime number");
74flag=1;
75break;
76}
77}
78else if(flag==0)
79{
80System.out.println("The number is a prime number");
81}
82}
83}
843)Write a java program to display the fibonacci series till less than 200 using only 2 variables.
85PROGRAM:
86import java.util.*;
87public class Main
88{
89public static void main(String args[])
90{
91Scanner sc=new Scanner(System.in);
92int n1=0,n2=1;
93count=sc.nextInt();
94for(int i=0;i<count;i++)
95{
96num1+=num2;
97num2+=num1;
98}
99System.out.println(num1+" "+num2);
100}
101}
1024).Write Java program to check if a name is palindrome.
103PROGRAM:
104import java.util.*;
105public class Main
106{
107public static void main(String args[])
108{
109Scanner sc=new Scanner(System.in);
1105)Write Java program to check if a number is Armstrong number or not? (input 153 output true, 123 output false)
111PROGRAM:
112import java.util*;
113public class Main
114{
115public static void main(String[] args)
116{
117Scanner sc=new Scanner(System.in);
118int n=sc.nextInt();
119int temp=0,sum=0,rem=0;
120temp=n;
121while(n!=0)
122{
123rem=n%10;
124sum=sum+(rem*rem*rem);
125n=n/10;
126}
127if(temp==sum)
128{
129System.out.println("The number is an armstrong number");
130}
131else
132{
133System.out.println("The number is not an armstrong number");
134}
135}
136}
1377.How to find factorial of number in Java using iteration?
138import java.util.*;
139public class Main
140{
141public static void main(String []args)
142{
143
144 Scanner sc=new Scanner(System.in);
145
146int n=sc.nextInt();
147 int fact=1;
148for(int i=1;i<=n;i++)
149{
150fact=fact*i;
151}
152System.out.println(fact);
153}
1548.Write a Java code to take a character as a input from user and determine if it is a vowel or a consonant using conditional construct.
155PROGRAM:
156import java.util.*;
157public class Main{
158public static void main(String[] args)
159{
160Scanner sc=new Scanner(System.in);
161char a=sc.next();
162if(a=='a' ||a=='e' ||a=='i' ||a=='o' ||a=='u' ||a=='A' ||a=='E' ||a=='I' ||a=='O' ||a=='U')
163{
164System.out.println("The given character is a vowel");
165}
166else
167{
168System.out.println("The given character is a consonant");
169}
170}
171}
1729)Write a switch case java code to create calculator with + - / * functionalities only.
173import java.util.*;
174public class Main
175{
176public static void main(String[] args)
177{
178Scanner sc=new Scanner(System.in);
179int a=sc.nextInt();
180int b=sc.nextInt();
181int c=0;
182String calc=sc.next();
183switch(calc)
184{
185case +: c=a+b;
186 System.out.println("The sum of two numbers is:"+c);
187case -: c=a-b;
188 System.out.println("The subtraction of two numbers is:"+c);
189case *: c=a*b;
190 System.out.println("The multiplication of two numbers is:"+c);
191case /: c=a/b;
192 System.out.println("The division of two numbers is:"+c);
193default: System.out.println("Invalid choice");
194}
195}
196}
19710. Write a java code to copy one array into another.
198import java.util.*;
199public class Main
200{
201public static void main(String args[])
202{
203Scanner sc=new Scanner(System.in);
204System.out.println("Enter the size of the array:");
205int n=sc.nextInt();
206int a[]=new int[n];
207int b[]=new int[n];
208for(int i=0;i<n;i++)
209{
210a[i]=sc.nextInt();
211}
212for(int i=0;i<n;i++)
213{
214b[i]=a[i];
215}
216System.out.println(b[i]);
217}
218}
21911. Write a java code to compare the length of two arrays and display the longer array.
220import java.util.*;
221 class stringLength {
222public void mystring()
223{
224 Scanner sc=new Scanner(System.in);
225 System.out.println("Enter the first string:");
226 String s1=sc.next();
227 System.out.println("Enter the second string:");
228 String s2=sc.next();
229 int n=s1.length();
230 int m=s2.length();
231 if(n>m)
232 {
233 System.out.println("First string is the largest string");
234 }
235 else if(n<m){
236 System.out.println("second string is the largest string");
237 }
238 else
239 {
240 System.out.println("Invalid Input");
241 }
242}
243}
244public class array
245{
246public static void main(String [] args)
247{
248 stringLength sl=new stringLength();
249 sl.mystring();
250}
251}
252
25312. Write a java code to display a reverse String array.
254import java.io.*;
255import java.util.*;
256public class Main
257{
258public static void main(String args[])
259{
260Scanner sc=new Scanner(System.in);
261String s1=sc.next();
262StringBuilder sb=new StringBuilder();
263sb.append(s1);
264String s2=sb.reverse();
265System.out.println(s2);
266}
267
268}
269
27013. Write the difference between checked and unchecked exception with example code
271
272In Java, there two types of exceptions:
273
2741) Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
275
276For example, consider the following Java program that opens file at locatiobn �C:\test\a.txt� and prints first three lines of it. The program doesn�t compile, because the function main() uses FileReader() and FileReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException
277
278import java.io.*;
279
280class Main {
281 public static void main(String[] args) {
282 FileReader fr = new FileReader("C:\\test\\a.txt");
283 BufferedReader br = new BufferedReader(fr);
284
285 // Print first 3 lines of file "C:\test\a.txt"
286 for (int counter = 0; counter < 3; counter++)
287 System.out.println(br.readLine());
288
289 br.close();
290 }
291}
292
293To fix the above program, we either need to specify list of exceptions using throws, or we need to use try-catch block. We have used throws in the below program. Since FileNotFoundException is a subclass of IOException, we can just specify IOException in the throws list and make the above program compiler-error-free.
294
295import java.io.*;
296
297class Main {
298 public static void main(String[] args) throws IOException {
299 FileReader fr= new FileReader("C:\\test\\a.txt");
300 BufferedReader br= new BufferedReader(fr);
301
302 // Print first 3 lines of file "C:\test\a.txt"
303 for (int counter = 0; counter < 3; counter++)
304 System.out.println(br.readLine());
305
306 br.close();
307 }
308}
309---------------------------------------------------------------------------------------------------------------------------------------------------------------------
310
31114. Write the difference between throw and throws with example code
312
3131. Throws clause is used to declare an exception, which means it works similar to the try-catch block. On the other hand throw keyword is used to throw an exception explicitly.
3142. If we see syntax wise than throw is followed by an instance of Exception class and throws is followed by exception class names.
315For example:
316 throw new ArithmeticException("Arithmetic Exception");
317 throws ArithmeticException;
3183. Throw keyword is used in the method body to throw an exception, while throws is used in method signature to declare the exceptions that can occur in the statements present in the method.
3194. You can throw one exception at a time but you can handle multiple exceptions by declaring them using throws keyword.
320
321public class Example{
322 void checkAge(int age){
323 if(age<18)
324 throw new ArithmeticException("Not Eligible for voting");
325 else
326 System.out.println("Eligible for voting");
327 }
328 public static void main(String args[]){
329 Example1 obj = new Example1();
330 obj.checkAge(13);
331 System.out.println("End Of Program");
332 }
333}
334
335------------------------------------------------------------------------
336public class Example1{
337 int division(int a, int b) throws ArithmeticException{
338 int t = a/b;
339 return t;
340 }
341 public static void main(String args[]){
342 Example1 obj = new Example1();
343 try{
344 System.out.println(obj.division(15,0));
345 }
346 catch(ArithmeticException e){
347 System.out.println("You shouldn't divide number by zero");
348 }
349 }
350}
351---------------------------------------------------------------------------------------------------------------------------------------------------------------------
35215. Write a note or nested try�catch block with example code
353
354class NestingDemo{
355 public static void main(String args[]){
356 //main try-block
357 try{
358 //try-block2
359 try{
360 //try-block3
361 try{
362 int arr[]= {1,2,3,4};
363 /* I'm trying to display the value of
364 * an element which doesn't exist. The
365 * code should throw an exception
366 */
367 System.out.println(arr[10]);
368 }catch(ArithmeticException e){
369 System.out.print("Arithmetic Exception");
370 System.out.println(" handled in try-block3");
371 }
372 }
373 catch(ArithmeticException e){
374 System.out.print("Arithmetic Exception");
375 System.out.println(" handled in try-block2");
376 }
377 }
378 catch(ArithmeticException e3){
379 System.out.print("Arithmetic Exception");
380 System.out.println(" handled in main try-block");
381 }
382 catch(ArrayIndexOutOfBoundsException e4){
383 System.out.print("ArrayIndexOutOfBoundsException");
384 System.out.println(" handled in main try-block");
385 }
386 catch(Exception e5){
387 System.out.print("Exception");
388 System.out.println(" handled in main try-block");
389 }
390 }
391}
392
393---------------------------------------------------------------------------------------------------------------------------------------------------------------------
39416. Write a note on MultiThreading and MultiTasking
395
3961) In multitasking, several programs are executed concurrently e.g. Java compiler and a Java IDE like Netbeans or Eclipse, while in multi-threading multiple threads execute either same or different part of program multiple times at the same time.
397
3982) Multi-threading is more granular than multi-tasking. In multi-tasking, CPU switches between multiple programs to complete their execution in real time, while in multi-threading CPU switches between multiple threads of the same program. Remember, switching between multiple processes has more context switching cost than switching between multiple threads of the same program.
399
4003) Process are heavyweight as compared to threads, they require their own address space, which means multi-tasking is heavy compared to multithreading. Inter-process communication is expensive and limited and context switching from one process to another is expensive and limited.
401---------------------------------------------------------------------------------------------------------------------------------------------------------------------
40217. Write a short note on Deque and give example code.
403
404The java.util.Deque interface is a subtype of the java.util.Queue interface. The Deque is related to the double-ended queue that supports addition or removal of elements from either end of the data structure, it can be used as a queue (first-in-first-out/FIFO) or as a stack (last-in-first-out/LIFO).
405
406// Java program to demonstrate working of
407// Deque in Java
408import java.util.*;
409
410public class DequeExample
411{
412 public static void main(String[] args)
413 {
414 Deque deque = new LinkedList<>();
415
416 // We can add elements to the queue in various ways
417 deque.add("Element 1 (Tail)"); // add to tail
418 deque.addFirst("Element 2 (Head)");
419 deque.addLast("Element 3 (Tail)");
420 deque.push("Element 4 (Head)"); //add to head
421 deque.offer("Element 5 (Tail)");
422 deque.offerFirst("Element 6 (Head)");
423 deque.offerLast("Element 7 (Tail)");
424
425 System.out.println(deque + "\n");
426
427 // Iterate through the queue elements.
428 System.out.println("Standard Iterator");
429 Iterator iterator = deque.iterator();
430 while (iterator.hasNext())
431 System.out.println("\t" + iterator.next());
432
433
434 // Reverse order iterator
435 Iterator reverse = deque.descendingIterator();
436 System.out.println("Reverse Iterator");
437 while (reverse.hasNext())
438 System.out.println("\t" + reverse.next());
439
440 // Peek returns the head, without deleting
441 // it from the deque
442 System.out.println("Peek " + deque.peek());
443 System.out.println("After peek: " + deque);
444
445 // Pop returns the head, and removes it from
446 // the deque
447 System.out.println("Pop " + deque.pop());
448 System.out.println("After pop: " + deque);
449
450 // We can check if a specific element exists
451 // in the deque
452 System.out.println("Contains element 3: " +
453 deque.contains("Element 3 (Tail)"));
454
455 // We can remove the first / last element.
456 deque.removeFirst();
457 deque.removeLast();
458 System.out.println("Deque after removing " +
459 "first and last: " + deque);
460
461 }
462}
463---------------------------------------------------------------------------------------------------------------------------------------------------------------------
46418. Write a short note on Generics and all types of Parameters used in Generics with example code.
465
466// A Simple Java program to show working of user defined
467// Generic classes
468
469// We use < > to specify Parameter type
470class Test<T>
471{
472 // An object of type T is declared
473 T obj;
474 Test(T obj) { this.obj = obj; } // constructor
475 public T getObject() { return this.obj; }
476}
477
478// Driver class to test above
479class Main
480{
481 public static void main (String[] args)
482 {
483 // instance of Integer type
484 Test <Integer> iObj = new Test<Integer>(15);
485 System.out.println(iObj.getObject());
486
487 // instance of String type
488 Test <String> sObj =
489 new Test<String>("Hello");
490 System.out.println(sObj.getObject());
491 }
492}
493---------------------------------------------------------------------------------------------------------------------------------------------------------------------
49419. Write a short note on Map Interface.
495
496The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types.
497
498A Map cannot contain duplicate keys and each key can map to at most one value. Some implementations allow null key and null value (HashMap and LinkedHashMap) but some do not (TreeMap).
499
500The order of a map depends on specific implementations, e.g TreeMap and LinkedHashMap have predictable order, while HashMap does not.
501Exampled class that implements this interface is HashMap, TreeMap and LinkedHashMap.
502
503Why and When Use Maps:
504Maps are perfectly for key-value association mapping such as dictionaries. Use Maps when you want to retrieve and update elements by keys, or perform lookups by keys. Some examples:
505
506A map of error codes and their descriptions.
507A map of zip codes and cities.
508A map of managers and employees. Each manager (key) is associated with a list of employees (value) he manages.
509A map of classes and students. Each class (key) is associated with a list of students (value).
510
511Methods of Map:
512
513public Object put(Object key, Object value) :- is used to insert an entry in this map.
514public void putAll(Map map) :- is used to insert the specified map in this map.
515public Object remove(Object key) :- is used to delete an entry for the specified key.
516public Object get(Object key) :- is used to return the value for the specified key.
517public boolean containsKey(Object key) :- is used to search the specified key from this map.
518public Set keySet() :- returns the Set view containing all the keys.
519public Set entrySet() :- returns the Set view containing all the keys and values.
520
521---------------------------------------------------------------------------------------------------------------------------------------------------------------------
52220. Write the difference between LinkedList and ArrayList.
523
5241. ArrayList:-Implemented with the concept of dynamic array.
525
526ArrayList<Type> arrL = new ArrayList<Type>();
527
528Here Type is the data type of elements in ArrayList
529to be created
5302. LinkedList:-Implemented with the concept of doubly linked list.
531
532LinkedList<Type> linkL = new LinkedList<Type>();
533
534Here Type is the data type of elements in LinkedList
535to be created
536Comparision between ArrayList and LinkedList:-
537
538Insertions are easy and fast in LinkedList as compared to ArrayList because there is no
539risk of resizing array and copying content to new array if array gets full which makes
540adding into ArrayList of O(n) in worst case, while adding is O(1) operation in LinkedList
541in Java. ArrayList also needs to be update its index if you insert something anywhere except
542at the end of array.
543Removal also better in LinkedList than ArrayList due to same reasons as insertion.
544LinkedList has more memory overhead than ArrayList because in ArrayList each index only
545holds actual object (data) but in case of LinkedList each node holds both data and address
546of next and previous node.
547Both LinkedList and ArrayList require O(n) time to find if an element is present or not. However we can do Binary Search on ArrayList if it is sorted and therefore can search in O(Log n) time.
548
549---------------------------------------------------------------------------------------------------------------------------------------------------------------------
55021. Write a note on Dynamic array in java.
551
552When the size of an array is unknown at the run time we need to create dynamic array. In java there are plenty of ways in which we can build array dynamically .
553For example, we can use arraylist
554
555import java.util.ArrayList;
556import java.util.Iterator;
557
558public class fruits {
559 public static void main(String[] args) {
560 ArrayList fruits = new ArrayList();
561 fruits.add("apple");
562 fruits.add("orange");
563 fruits.add("mango");
564 fruits.add(1,"grape"); // adding element in the index 1 i.e adding as second element
565 System.out.println(fruits.size());
566 for(int i=0;i<fruits.size();i++)
567 System.out.println(fruits.get(i));
568 }
569}
570---------------------------------------------------------------------------------------------------------------------------------------------------------------------
57122. What is the purpose of the System class?
572
573The java.lang.System class contains several useful utilities for mostly used operation. System class cannot be instantiated.
574
575Facilities provided by System:
576 -standard output
577 -error output streams
578 -standard input and access to externally defined properties and environment variables.
579 -A utility for quickly copying particular portion of an array.
580 -used to loading files and libraries.
581Standard Fields of System class are:
582 -static PrintStream err -- "standard" error output stream.
583 -static InputStream in -- "standard" input stream.
584 -static PrintStream out -- "standard" output stream.
585
586---------------------------------------------------------------------------------------------------------------------------------------------------------------------
58723. Which is the abstract parent class of FileWriter ?
588
589 OutputStreamWriter
590---------------------------------------------------------------------------------------------------------------------------------------------------------------------
59124. Which class is used to read streams of characters from a file?
592
593 FileReader
594---------------------------------------------------------------------------------------------------------------------------------------------------------------------
59525. Which class is used to read streams of raw bytes from a file?
596
597 FileInputStream
598---------------------------------------------------------------------------------------------------------------------------------------------------------------------
59926. What are the differences between FileInputStream/FileOutputStream and RandomAccessFile
600
601RandomAccessFile treats the file as an array of bytes where it has the internal pointer. The fact that it treats it like a large array of bytes is what is unique about this class. FileInputStream however just reads the stream and returns the data. It is more suited to reading raw data like images etc. It does not treat the file as a large array, it just keeps tabs of where in the file it has read so far. With FileInputStream you would actually have to read the data and place it into an array to get the same style of access as RandomAccessFile.
602
603---------------------------------------------------------------------------------------------------------------------------------------------------------------------
60427. Write a note on Channels and Buffer with example.
605
606Buffers provide a mechanism to store a fixed amount of primitive data elements in an in-memory container. In the NIO, all data is handled with buffers. When data is read, it is read directly into a buffer. When data is written, it is written into a buffer.
607Buffers work with channels. Channels are portals through which I/O transfers take place, and buffers are the sources or targets of those data transfers.
608ByteBuffer is defined in the java.nio package and FileChannel in the java.nio.channels package. To read a file and move data to a target � the file is read into a buffer through a channel and then the data is moved from the buffer to the target. To write to a file from a source � the source data is moved into a buffer and then written to the file through a channel.
609
6101.Open the file you want to read/write using RandomAccessFile in read/write mode.
6112.Call the getChannel() method of RandomAccessFile to get the FileChannel. The position of the returned channel will always be equal to this object's file-pointer offset as returned by the getFilePointer() method.
6123.Create a ByteBuffer using ByteBuffer.allocate() method.
6134.Store the data into ByteBuffer using various put() method e.g. putInt(), putLong().
6145.Flip the Buffer so that Channel can read data from the buffer and write into a file. The flip() method changes the pointers and allows you to read data from the buffer.
6156.Call the write() method of FileChannel.
6167.Close the FileChannel
6178.Close the RandomAccessFile.
618
619 public static void fileChannelRead() throws IOException {
620 RandomAccessFile randomAccessFile = new RandomAccessFile("./temp.txt","rw");
621 FileChannel fileChannel = randomAccessFile.getChannel();
622 ByteBuffer byteBuffer = ByteBuffer.allocate(512);
623 Charset charset = Charset.forName("US-ASCII");
624 while (fileChannel.read(byteBuffer) > 0) {
625 byteBuffer.rewind();
626 System.out.print(charset.decode(byteBuffer));
627 byteBuffer.flip();
628 }
629 fileChannel.close();
630 randomAccessFile.close();
631 }
632
633---------------------------------------------------------------------------------------------------------------------------------------------------------------------
63428. What is the difference between System.out ,System.err and System.in?
635
636System.out's main purpose is giving standard output.
637
638System.err's main purpose is giving standard error.
639
640System.in's main purpose is giving standard input.
641---------------------------------------------------------------------------------------------------------------------------------------------------------------------
642 REPEATED QUESTIONS
643---------------------------------------------------------------------------------------------------------------------------------------------------------------------
64429. What is the purpose of the System class?
645
64630. Which is the abstract parent class of FileWriter ?
647
64831. Which class is used to read streams of characters from a file?
649
65032. Which class is used to read streams of raw bytes from a file?
651
65233. What are the differences between FileInputStream/FileOutputStream and RandomAccessFile
653
65434. Write a note on Channels and Buffer with example.
655
656---------------------------------------------------------------------------------------------------------------------------------------------------------------------
657
65835. Write a note on PreparedStatement and ResultSetMetaData interfaces with code snippets.
659
660The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query.
661Example of parameterized query:
662 String sql="insert into emp values(?,?,?)";
663we are passing parameter (?) for the values. Its value will be set by calling the setter methods of PreparedStatement.
664Improves performance: The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once.
665
666import java.sql.*;
667class PreparedStatementDemo{
668public static void main(String args[]){
669try{
670Class.forName("oracle.jdbc.driver.OracleDriver");
671Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","pass");
672PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
673stmt.setInt(1,101);//1 specifies the first parameter in the query
674stmt.setString(2,"Sasi");
675int i=stmt.executeUpdate();
676System.out.println(i+" records inserted");
677con.close();
678}catch(Exception e){ System.out.println(e);}
679}
680}
681
682//ResultSetMetaData
683The metadata means data about data i.e. we can get further information from the data.
684If you have to get metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object.
685
686import java.sql.*;
687class ResultSetMetaData{
688public static void main(String args[]){
689try{
690Class.forName("oracle.jdbc.driver.OracleDriver");
691Connection con=DriverManager.getConnection(
692"jdbc:oracle:thin:@localhost:1521:xe","system","pass");
693
694PreparedStatement ps=con.prepareStatement("select * from emp");
695ResultSet rs=ps.executeQuery();
696ResultSetMetaData rsmd=rs.getMetaData();
697
698System.out.println("Total columns: "+rsmd.getColumnCount());
699System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
700System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
701
702con.close();
703}catch(Exception e){ System.out.println(e);}
704}
705}
706
707---------------------------------------------------------------------------------------------------------------------------------------------------------------------
70836. Write a note on DDL, DML, DQL, DDL with code snippets.
709---------------------------------------------------------------------------------------------------------------------------------------------------------------------
71037. Write a note on HTML , CSS and Javascript.
711---------------------------------------------------------------------------------------------------------------------------------------------------------------------
71238. Write a code to fetch the data from H2 and put it in any collection object and display it.
713
714import java.sql.Connection;
715import java.sql.DriverManager;
716import java.sql.SQLException;
717import java.sql.Statement;
718
719public class H2jdbcCreateDemo {
720 // JDBC driver name and database URL
721 static final String JDBC_DRIVER = "org.h2.Driver";
722 static final String DB_URL = "jdbc:h2:~/test";
723
724 // Database credentials
725 static final String USER = "niit";
726 static final String PASS = "niit";
727
728 public static void main(String[] args) {
729 Connection conn = null;
730 Statement stmt = null;
731 try {
732 // STEP 1: Register JDBC driver
733 Class.forName(JDBC_DRIVER);
734
735 //STEP 2: Open a connection
736 System.out.println("Connecting to database...");
737 conn = DriverManager.getConnection(DB_URL,USER,PASS);
738
739 //STEP 3: Execute a query
740 System.out.println("Creating table in given database...");
741 stmt = conn.createStatement();
742 String sql = "CREATE TABLE REGISTRATION " +
743 "(id INTEGER not NULL, " +
744 " first VARCHAR(255), " +
745 " last VARCHAR(255), " +
746 " age INTEGER, " +
747 " PRIMARY KEY ( id ))";
748 stmt.executeUpdate(sql);
749 System.out.println("Created table in given database...");
750
751 // STEP 4: Clean-up environment
752 stmt.close();
753 conn.close();
754 } catch(SQLException se) {
755 //Handle errors for JDBC
756 se.printStackTrace();
757 } catch(Exception e) {
758 //Handle errors for Class.forName
759 e.printStackTrace();
760 } finally {
761 //finally block used to close resources
762 try{
763 if(stmt!=null) stmt.close();
764 } catch(SQLException se2) {
765 } // nothing we can do
766 try {
767 if(conn!=null) conn.close();
768 } catch(SQLException se){
769 se.printStackTrace();
770 } //end finally try
771 } //end try
772 System.out.println("Goodbye!");
773 }
774}
775
776---------------------------------------------------------------------------------------------------------------------------------------------------------------------
77739. Describe the different approaches of String processing.
778
779---------------------------------------------------------------------------------------------------------------------------------------------------------------------
780 REPEATED QUESTIONS
781---------------------------------------------------------------------------------------------------------------------------------------------------------------------
78240. What is the difference between System.out ,System.err and System.in?
783
78441. What is the purpose of the System class?
785
78642. Which is the abstract parent class of FileWriter ?
787
78843. Which class is used to read streams of characters from a file?
789
79044. Which class is used to read streams of raw bytes from a file?
791
79245. What are the differences between FileInputStream/FileOutputStream and RandomAccessFile
793
79446. Write a note on Channels and Buffer with example.
795
796---------------------------------------------------------------------------------------------------------------------------------------------------------------------