· 6 years ago · Nov 07, 2019, 02:10 AM
1aAn anagram is a word or a phrase made by transposing the letters of another word or phrase; for example, "parliament" is an anagram of "partial men," and "software" is an anagram of "swear oft." Write a program that figures out whether one string is an anagram of another string. The program should ignore white space and punctuation.
2Answer: Anagram
3
4
5public class Anagram {
6
7 public static boolean areAnagrams(String string1,
8 String string2) {
9
10 String workingCopy1 = removeJunk(string1);
11 String workingCopy2 = removeJunk(string2);
12
13 workingCopy1 = workingCopy1.toLowerCase();
14 workingCopy2 = workingCopy2.toLowerCase();
15
16 workingCopy1 = sort(workingCopy1);
17 workingCopy2 = sort(workingCopy2);
18
19 return workingCopy1.equals(workingCopy2);
20 }
21
22 protected static String removeJunk(String string) {
23 int i, len = string.length();
24 StringBuilder dest = new StringBuilder(len);
25 char c;
26
27 for (i = (len - 1); i >= 0; i--) {
28 c = string.charAt(i);
29 if (Character.isLetter(c)) {
30 dest.append(c);
31 }
32 }
33
34 return dest.toString();
35 }
36
37 protected static String sort(String string) {
38 char[] charArray = string.toCharArray();
39
40 java.util.Arrays.sort(charArray);
41
42 return new String(charArray);
43 }
44
45 public static void main(String[] args) {
46 String string1 = "Cosmo and Laine:";
47 String string2 = "Maid, clean soon!";
48
49 System.out.println();
50 System.out.println("Testing whether the following "
51 + "strings are anagrams:");
52 System.out.println(" String 1: " + string1);
53 System.out.println(" String 2: " + string2);
54 System.out.println();
55
56 if (areAnagrams(string1, string2)) {
57 System.out.println("They ARE anagrams!");
58 } else {
59 System.out.println("They are NOT anagrams!");
60 }
61 System.out.println();
62 }
63}
64
65/* define a student class with necessary fields and methods */
66class Student {
67 /* declare the fields of the class */
68 int roll;
69 float percent;
70
71 /* declare the methods */
72 void setData(int roll_no, float percentage) { // stores the input data
73 roll = roll_no;
74 percent = percentage;
75 }
76 void getData() { // displays the stored data
77 System.out.println("Student Info :- ");
78 System.out.println("Roll : " + roll + " Percentage : " + percent);
79 }
80}
81
82public class StudentInfo {
83 public static void main(String args[]) {
84 Student stud1 = new Student();//create an object to store a student's info
85 // call setData() to store student's roll and percentage
86 stud1.setData(7, 73.67f);
87 Student stud2 = new Student(); // stud2 stores info about another student
88 stud2.setData(11, 87.43f);
89 /* display the information about 2 students */
90 stud1.getData();
91 stud2.getData();
92 }
93}
94
95JAVA INHERITENCE
96The Superclass Person.java
97/*
98 * Superclass Person has name and address.
99 */
100public class Person {
101 // private instance variables
102 private String name, address;
103
104 // Constructor
105 public Person(String name, String address) {
106 this.name = name;
107 this.address = address;
108 }
109
110 // Getters and Setters
111 public String getName() {
112 return name;
113 }
114 public String getAddress() {
115 return address;
116 }
117 public void setAddress(String address) {
118 this.address = address;
119 }
120
121 // Describle itself
122 public String toString() {
123 return name + "(" + address + ")";
124 }
125}
126The Subclass Student.java
127/*
128 * The Student class, subclass of Person.
129 */
130public class Student extends Person {
131 // private instance variables
132 private int numCourses; // number of courses taken so far
133 private String[] courses; // course codes
134 private int[] grades; // grade for the corresponding course codes
135 private static final int MAX_COURSES = 30; // maximum number of courses
136
137 // Constructor
138 public Student(String name, String address) {
139 super(name, address);
140 numCourses = 0;
141 courses = new String[MAX_COURSES];
142 grades = new int[MAX_COURSES];
143 }
144
145 // Describe itself
146 @Override
147 public String toString() {
148 return "Student: " + super.toString();
149 }
150
151 // Add a course and its grade - No validation in this method
152 public void addCourseGrade(String course, int grade) {
153 courses[numCourses] = course;
154 grades[numCourses] = grade;
155 ++numCourses;
156 }
157
158 // Print all courses taken and their grade
159 public void printGrades() {
160 System.out.print(this);
161 for (int i = 0; i < numCourses; ++i) {
162 System.out.print(" " + courses[i] + ":" + grades[i]);
163 }
164 System.out.println();
165 }
166
167 // Compute the average grade
168 public double getAverageGrade() {
169 int sum = 0;
170 for (int i = 0; i < numCourses; i++ ) {
171 sum += grades[i];
172 }
173 return (double)sum/numCourses;
174 }
175}
176The Subclass Teacher.java
177/*
178 * The Teacher class, subclass of Person.
179 */
180public class Teacher extends Person {
181 // private instance variables
182 private int numCourses; // number of courses taught currently
183 private String[] courses; // course codes
184 private static final int MAX_COURSES = 5; // maximum courses
185
186 // Constructor
187 public Teacher(String name, String address) {
188 super(name, address);
189 numCourses = 0;
190 courses = new String[MAX_COURSES];
191 }
192
193 // Describe itself
194 @Override
195 public String toString() {
196 return "Teacher: " + super.toString();
197 }
198
199 // Return false if the course already existed
200 public boolean addCourse(String course) {
201 // Check if the course already in the course list
202 for (int i = 0; i < numCourses; i++) {
203 if (courses[i].equals(course)) return false;
204 }
205 courses[numCourses] = course;
206 numCourses++;
207 return true;
208 }
209
210 // Return false if the course cannot be found in the course list
211 public boolean removeCourse(String course) {
212 boolean found = false;
213 // Look for the course index
214 int courseIndex = -1; // need to initialize
215 for (int i = 0; i < numCourses; i++) {
216 if (courses[i].equals(course)) {
217 courseIndex = i;
218 found = true;
219 break;
220 }
221 }
222 if (found) {
223 // Remove the course and re-arrange for courses array
224 for (int i = courseIndex; i < numCourses-1; i++) {
225 courses[i] = courses[i+1];
226 }
227 numCourses--;
228 return true;
229 } else {
230 return false;
231 }
232 }
233}
234A Test Driver (TestPerson.java)
235/*
236 * A test driver for Person and its subclasses.
237 */
238public class TestPerson {
239 public static void main(String[] args) {
240 /* Test Student class */
241 Student s1 = new Student("Tan Ah Teck", "1 Happy Ave");
242 s1.addCourseGrade("IM101", 97);
243 s1.addCourseGrade("IM102", 68);
244 s1.printGrades();
245 System.out.println("Average is " + s1.getAverageGrade());
246
247 /* Test Teacher class */
248 Teacher t1 = new Teacher("Paul Tan", "8 sunset way");
249 System.out.println(t1);
250 String[] courses = {"IM101", "IM102", "IM101"};
251 for (String course: courses) {
252 if (t1.addCourse(course)) {
253 System.out.println(course + " added.");
254 } else {
255 System.out.println(course + " cannot be added.");
256 }
257 }
258 for (String course: courses) {
259 if (t1.removeCourse(course)) {
260 System.out.println(course + " removed.");
261 } else {
262 System.out.println(course + " cannot be removed.");
263 }
264 }
265 }
266}
267
268JAVA HEXADECIMAL
269/**
270 * This program reads a hexadecimal number input by the user and prints the
271 * base-10 equivalent. If the input contains characters that are not
272 * hexadecimal numbers, then an error message is printed.
273 */
274
275public class Hex2Dec {
276
277 public static void main(String[] args) {
278 String hex; // Input from user, containing a hexadecimal number.
279 long dec; // Decimal (base-10) equivalent of hexadecimal number.
280 int i; // A position in hex, from 0 to hex.length()-1.
281 TextIO.put("Enter a hexadecimal number: ");
282 hex = TextIO.getlnWord();
283 dec = 0;
284 for ( i = 0; i < hex.length(); i++ ) {
285 int digit = hexValue( hex.charAt(i) );
286 if (digit == -1) {
287 TextIO.putln("Error: Input is not a hexadecimal number.");
288 return; // Ends the main() routine.
289 }
290 dec = 16*dec + digit;
291 }
292 TextIO.putln("Base-10 value: " + dec);
293 } // end main
294
295 /**
296 * Returns the hexadecimal value of a given character, or -1 if it is not
297 * a valid hexadecimal digit.
298 * @param ch the character that is to be converted into a hexadecimal digit
299 * @return the hexadecimal value of ch, or -1 if ch is not
300 * a legal hexadecimal digit
301 */
302 static int hexValue(char ch) {
303 switch (ch) {
304 case '0':
305 return 0;
306 case '1':
307 return 1;
308 case '2':
309 return 2;
310 case '3':
311 return 3;
312 case '4':
313 return 4;
314 case '5':
315 return 5;
316 case '6':
317 return 6;
318 case '7':
319 return 7;
320 case '8':
321 return 8;
322 case '9':
323 return 9;
324 case 'a': // Note: Handle both upper and lower case letters.
325 case 'A':
326 return 10;
327 case 'b':
328 case 'B':
329 return 11;
330 case 'c':
331 case 'C':
332 return 12;
333 case 'd':
334 case 'D':
335 return 13;
336 case 'e':
337 case 'E':
338 return 14;
339 case 'f':
340 case 'F':
341 return 15;
342 default:
343 return -1;
344 }
345 } // end hexValue
346
347}
348
349JAVA FX TO ADD TWO NUMBER
3501. import java.awt.BorderLayout;
3512. import java.awt.EventQueue;
3523.
3534. import javax.swing.JFrame;
3545. import javax.swing.JPanel;
3556. import javax.swing.border.EmptyBorder;
3567. import javax.swing.GroupLayout;
3578. import javax.swing.GroupLayout.Alignment;
3589. import javax.swing.JLabel;
35910. import javax.swing.JTextField;
36011. import javax.swing.JButton;
36112. import java.awt.event.ActionListener;
36213. import java.awt.event.ActionEvent;
36314.
36415. public class example extends JFrame {
36516.
36617. private JPanel contentPane;
36718. private JTextField textField;
36819. private JTextField textField_1;
36920.
37021. public static void main(String[] args) {
37122. EventQueue.invokeLater(new Runnable() {
37223. public void run() {
37324. try {
37425. example frame = new example();
37526. frame.setVisible(true);
37627. } catch (Exception e) {
37728. e.printStackTrace();
37829. }
37930. }
38031. });
38132. }
38233.
38334. public example() {
38435. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
38536. setBounds(100, 100, 392, 300);
38637. contentPane = new JPanel();
38738. contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
38839. setContentPane(contentPane);
38940.
39041. JLabel lblFirstNumber = new JLabel("First Number");
39142.
39243. textField = new JTextField();
39344. textField.setColumns(10);
39445.
39546. JLabel lblSecondNumber = new JLabel("Second Number");
39647.
39748. textField_1 = new JTextField();
39849. textField_1.setColumns(10);
39950.
40051. JLabel lblResult = new JLabel("Result : ");
40152.
40253. JLabel lblNewLabel = new JLabel();
40354.
40455. JButton btnAdd = new JButton("ADD");
40556. btnAdd.addActionListener(new ActionListener() {
40657. public void actionPerformed(ActionEvent arg0) {
40758. String first=textField.getText();
40859. String second=textField_1.getText();
40960. int sum=Integer.parseInt(first)+Integer.parseInt(second);
41061. lblNewLabel.setText(sum+"");
41162. }
41263. });
41364. GroupLayout gl_contentPane = new GroupLayout(contentPane);
41465. gl_contentPane.setHorizontalGroup(
41566. gl_contentPane.createParallelGroup(Alignment.LEADING)
41667. .addGroup(gl_contentPane.createSequentialGroup()
41768. .addGap(61)
41869. .addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
41970. .addComponent(lblResult)
42071. .addComponent(lblSecondNumber)
42172. .addComponent(lblFirstNumber))
42273. .addGap(29)
42374. .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
42475. .addComponent(btnAdd)
42576. .addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
42677. .addComponent(textField_1)
42778. .addComponent(textField, GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))
42879. .addComponent(lblNewLabel))
42980. .addContainerGap(88, Short.MAX_VALUE))
43081. );
43182. gl_contentPane.setVerticalGroup(
43283. gl_contentPane.createParallelGroup(Alignment.LEADING)
43384. .addGroup(gl_contentPane.createSequentialGroup()
43485. .addGap(33)
43586. .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
43687. .addComponent(lblFirstNumber)
43788. .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
43889. .addGap(18)
43990. .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
44091. .addComponent(lblSecondNumber)
44192. .addComponent(textField_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
44293. .addGap(18)
44394. .addComponent(btnAdd)
44495. .addGap(35)
44596. .addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
44697. .addComponent(lblResult)
44798. .addComponent(lblNewLabel))
44899. .addContainerGap(70, Short.MAX_VALUE))
449100. );
450101. contentPane.setLayout(gl_contentPane);
451102. }
452103. }
453OR
4541. int num1 = Integer.parseInt(jTextField1.getText());
4552. int num2 = Integer.parseInt(jTextField2.getText());
4563. int output= num1+num2;
4574. jLabel.setText(""+output);
458FILE HANDLING
459Word count:-
460package File;
461
462import java.io.BufferedReader;
463import java.io.File;
464import java.io.FileReader;
465import java.io.IOException;
466
467public class FileWordCount
468{
469 public static void main(String[] args) throws IOException
470 {
471 File f1=new File("input.txt"); //Creation of File Descriptor for input file
472 String[] words=null; //Intialize the word Array
473 int wc=0; //Intialize word count to zero
474 FileReader fr = new FileReader(f1); //Creation of File Reader object
475 BufferedReader br = new BufferedReader(fr); //Creation of BufferedReader object
476 String s;
477 while((s=br.readLine())!=null) //Reading Content from the file
478 {
479 words=s.split(" "); //Split the word using space
480 wc=wc+words.length; //increase the word count for each word
481 }
482 fr.close();
483 System.out.println("Number of words in the file:" +wc); //Print the word count
484 }
485}
486FIND VOWEl
487package File;
488import java.io.BufferedReader;
489import java.io.File;
490import java.io.FileReader;
491import java.io.IOException;
492
493public class FileVowelsWord
494{
495
496 public static void main(String[] args) throws IOException
497 {
498 File f1=new File("input.txt"); //Creation of File Descriptor for input file
499 String[] words=null; //Intialize the word Array
500 FileReader fr = new FileReader(f1); //Creation of File Reader object
501 BufferedReader br = new BufferedReader(fr); //Creation of BufferedReader object
502 String s;
503 int flag=0; //Intialize the flag variable
504 while((s=br.readLine())!=null)
505 {
506 words=s.split(" "); //Split the word using space
507 for(int i=0;i<words.length;i++)
508 {
509 for(int j=0;j<words[i].length();j++)
510 {
511 char ch=words[i].charAt(j); //Read the word char by char
512 if(ch == 'a' || ch == 'e' || ch == 'i' ||ch == 'o' || ch == 'u') //Checking for vowels
513 {
514 flag=1; //If vowels persent set flag as one
515 }
516 }
517 if(flag==1)
518 {
519 System.out.println(words[i]); //Print the vowels word
520 }
521 flag=0;
522 }
523
524
525 }
526
527 }
528
529}
530FIND WORD
531package File;
532
533import java.io.BufferedReader;
534import java.io.File;
535import java.io.FileReader;
536import java.io.IOException;
537
538public class FileWordSearch
539{
540 public static void main(String[] args) throws IOException
541 {
542 File f1=new File("input.txt"); //Creation of File Descriptor for input file
543 String[] words=null; //Intialize the word Array
544 FileReader fr = new FileReader(f1); //Creation of File Reader object
545 BufferedReader br = new BufferedReader(fr); //Creation of BufferedReader object
546 String s;
547 String input="Java"; // Input word to be searched
548 int count=0; //Intialize the word to zero
549 while((s=br.readLine())!=null) //Reading Content from the file
550 {
551 words=s.split(" "); //Split the word using space
552 for (String word : words)
553 {
554 if (word.equals(input)) //Search for the given word
555 {
556 count++; //If Present increase the count by one
557 }
558 }
559 }
560 if(count!=0) //Check for count not equal to zero
561 {
562 System.out.println("The given word is present for "+count+ " Times in the file");
563 }
564 else
565 {
566 System.out.println("The given word is not present in the file");
567 }
568
569 fr.close();
570 }
571
572
573}
574
575REPEATED CHARACTER:
576package String;
577
578public class CountWords
579{
580
581 public static void main(String[] args)
582 {
583 String input="Welcome to Java Session Session Session"; //Input String
584 String[] words=input.split(" "); //Split the word from String
585 int wrc=1; //Variable for getting Repeated word count
586
587 for(int i=0;i<words.length;i++) //Outer loop for Comparison
588 {
589 for(int j=i+1;j<words.length;j++) //Inner loop for Comparison
590 {
591
592 if(words[i].equals(words[j])) //Checking for both strings are equal
593 {
594 wrc=wrc+1; //if equal increment the count
595 words[j]="0"; //Replace repeated words by zero
596 }
597 }
598 if(words[i]!="0")
599 System.out.println(words[i]+"--"+wrc); //Printing the word along with count
600 wrc=1;
601
602 }
603
604 }
605
606}
607ADDING TWO NUMBER IN JAVAFX
608import java.awt.FlowLayout;
609import java.awt.event.ActionListener;
610import java.awt.event.ActionEvent;
611import javax.swing.JFrame;
612import javax.swing.JButton;
613import javax.swing.JOptionPane;
614public class ButtonFrame extends JFrame{
615 private JButton plainJButton;
616 // you will have to declare sum here so that your actionPerformed() method can "sees" it
617 private int sum;
618
619 public ButtonFrame(){
620 super("Testing buttons");
621 setLayout( new FlowLayout() );
622
623 String fNumber =
624 JOptionPane.showInputDialog("Enter first integer");
625 int n1 = Integer.parseInt( fNumber );
626
627 String sNumber =
628 JOptionPane.showInputDialog("Enter second integer");
629 int n2 = Integer.parseInt( sNumber );
630
631 sum = n1 + n2;
632plainJButton = new JButton("Addition Button");
63326 add( plainJButton );
63427
63528 ButtonHandler handler = new ButtonHandler();
63629 plainJButton.addActionListener( handler );
63730 }
63831
63932 private class ButtonHandler implements ActionListener{
64033 public void actionPerformed( ActionEvent event ){
64134
64235 JOptionPane.showMessageDialog(null, "The sum is"+ sum,
64336 "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE);
64437 }
64538 }
64639 }
647Random number java
648import java.util.Random;
649
650public class generateRandom{
651
652 public static void main(String args[])
653 {
654 // create instance of Random class
655 Random rand = new Random();
656
657 // Generate random integers in range 0 to 999
658 int rand_int1 = rand.nextInt(1000);
659 int rand_int2 = rand.nextInt(1000);
660
661 // Print random integers
662 System.out.println("Random Integers: "+rand_int1);
663 System.out.println("Random Integers: "+rand_int2);
664
665 // Generate Random doubles
666 double rand_dub1 = rand.nextDouble();
667 double rand_dub2 = rand.nextDouble();
668
669 // Print random doubles
670 System.out.println("Random Doubles: "+rand_dub1);
671 System.out.println("Random Doubles: "+rand_dub2);
672 }
673}
674--------------------------------------------------------------SERVLET--------------------------------------------------------------
675
676Registration :
6771. CREATE TABLE "REGISTERUSER"
6782. ( "NAME" VARCHAR2(4000),
6793. "PASS" VARCHAR2(4000),
6804. "EMAIL" VARCHAR2(4000),
6815. "COUNTRY" VARCHAR2(4000)
6826. )
6837. /
684
685
686
6871. import java.io.*;
6882. import java.sql.*;
6893. import javax.servlet.ServletException;
6904. import javax.servlet.http.*;
6915.
6926. public class Register extends HttpServlet {
6937. public void doPost(HttpServletRequest request, HttpServletResponse response)
6948. throws ServletException, IOException {
6959.
69610. response.setContentType("text/html");
69711. PrintWriter out = response.getWriter();
69812.
69913. String n=request.getParameter("userName");
70014. String p=request.getParameter("userPass");
70115. String e=request.getParameter("userEmail");
70216. String c=request.getParameter("userCountry");
70317.
70418. try{
70519. Class.forName("oracle.jdbc.driver.OracleDriver");
70620. Connection con=DriverManager.getConnection(
70721. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
70822.
70923. PreparedStatement ps=con.prepareStatement(
71024. "insert into registeruser values(?,?,?,?)");
71125.
71226. ps.setString(1,n);
71327. ps.setString(2,p);
71428. ps.setString(3,e);
71529. ps.setString(4,c);
71630.
71731. int i=ps.executeUpdate();
71832. if(i>0)
71933. out.print("You are successfully registered...");
72034.
72135.
72236. }catch (Exception e2) {System.out.println(e2);}
72337.
72438. out.close();
72539. }
72640.
72741. }
728
729
730Xml file
7311. <web-app>
7322.
7333. <servlet>
7344. <servlet-name>Register</servlet-name>
7355. <servlet-class>Register</servlet-class>
7366. </servlet>
7377.
7388. <servlet-mapping>
7399. <servlet-name>Register</servlet-name>
74010. <url-pattern>/servlet/Register</url-pattern>
74111. </servlet-mapping>
74212.
74313. <welcome-file-list>
74414. <welcome-file>register.html</welcome-file>
74515. </welcome-file-list>
74616.
74717. </web-app>
748
749
750
751
752
753SEARCH
7541. <html>
7552. <body>
7563. <form action="servlet/Search">
7574. Enter your Rollno:<input type="text" name="roll"/><br/>
7585.
7596. <input type="submit" value="search"/>
7607. </form>
7618. </body>
7629. </html>
763
764
7651. import java.io.*;
7662. import java.sql.*;
7673. import javax.servlet.ServletException;
7684. import javax.servlet.http.*;
7695.
7706. public class Search extends HttpServlet {
7717.
7728. public void doGet(HttpServletRequest request, HttpServletResponse response)
7739. throws ServletException, IOException {
77410.
77511. response.setContentType("text/html");
77612. PrintWriter out = response.getWriter();
77713.
77814. String rollno=request.getParameter("roll");
77915. int roll=Integer.valueOf(rollno);
78016.
78117. try{
78218. Class.forName("oracle.jdbc.driver.OracleDriver");
78319. Connection con=DriverManager.getConnection(
78420. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
78521.
78622. PreparedStatement ps=con.prepareStatement("select * from result where rollno=?");
78723. ps.setInt(1,roll);
78824.
78925. out.print("<table width=50% border=1>");
79026. out.print("<caption>Result:</caption>");
79127.
79228. ResultSet rs=ps.executeQuery();
79329.
79430. /* Printing column names */
79531. ResultSetMetaData rsmd=rs.getMetaData();
79632. int total=rsmd.getColumnCount();
79733. out.print("<tr>");
79834. for(int i=1;i<=total;i++)
79935. {
80036. out.print("<th>"+rsmd.getColumnName(i)+"</th>");
80137. }
80238.
80339. out.print("</tr>");
80440.
80541. /* Printing result */
80642.
80743. while(rs.next())
80844. {
80945. out.print("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"
81046. </td><td>"+rs.getString(3)+"</td><td>"+rs.getString(4)+"</td></tr>");
81147.
81248. }
81349.
81450. out.print("</table>");
81551.
81652. }catch (Exception e2) {e2.printStackTrace();}
81753.
81854. finally{out.close();}
81955.
82056. }
82157. }
822
8231. <web-app>
8242.
8253. <servlet>
8264. <servlet-name>Search</servlet-name>
8275. <servlet-class>Search</servlet-class>
8286. </servlet>
8297.
8308. <servlet-mapping>
8319. <servlet-name>Search</servlet-name>
83210. <url-pattern>/servlet/Search</url-pattern>
83311. </servlet-mapping>
83412.
83513. </web-app>
836
837
838
839UPLOAD A FILE
8401. <html>
8412. <body>
8423. <form action="go" method="post" enctype="multipart/form-data">
8434. Select File:<input type="file" name="fname"/><br/>
8445. <input type="submit" value="upload"/>
8456. </form>
8467. </body>
8478. </html>
848
8491. import java.io.*;
8502. import javax.servlet.ServletException;
8513. import javax.servlet.http.*;
8524. import com.oreilly.servlet.MultipartRequest;
8535.
8546. public class UploadServlet extends HttpServlet {
8557.
8568. public void doPost(HttpServletRequest request, HttpServletResponse response)
8579. throws ServletException, IOException {
85810.
85911. response.setContentType("text/html");
86012. PrintWriter out = response.getWriter();
86113.
86214. MultipartRequest m=new MultipartRequest(request,"d:/new");
86315. out.print("successfully uploaded");
86416. }
86517. }
866
867
868
869LOGIN
8701. <form action="servlet1" method="post">
8712. Name:<input type="text" name="username"/><br/><br/>
8723. Password:<input type="password" name="userpass"/><br/><br/>
8734. <input type="submit" value="login"/>
8745. </form>
875
876FirstServlet.java
8771. import java.io.IOException;
8782. import java.io.PrintWriter;
8793.
8804. import javax.servlet.RequestDispatcher;
8815. import javax.servlet.ServletException;
8826. import javax.servlet.http.HttpServlet;
8837. import javax.servlet.http.HttpServletRequest;
8848. import javax.servlet.http.HttpServletResponse;
8859.
88610.
88711. public class FirstServlet extends HttpServlet {
88812. public void doPost(HttpServletRequest request, HttpServletResponse response)
88913. throws ServletException, IOException {
89014.
89115. response.setContentType("text/html");
89216. PrintWriter out = response.getWriter();
89317.
89418. String n=request.getParameter("username");
89519. String p=request.getParameter("userpass");
89620.
89721. if(LoginDao.validate(n, p)){
89822. RequestDispatcher rd=request.getRequestDispatcher("servlet2");
89923. rd.forward(request,response);
90024. }
90125. else{
90226. out.print("Sorry username or password error");
90327. RequestDispatcher rd=request.getRequestDispatcher("index.html");
90428. rd.include(request,response);
90529. }
90630.
90731. out.close();
90832. }
90933. }
910
911LoginDao.java
9121. import java.sql.*;
9132.
9143. public class LoginDao {
9154. public static boolean validate(String name,String pass){
9165. boolean status=false;
9176. try{
9187. Class.forName("oracle.jdbc.driver.OracleDriver");
9198. Connection con=DriverManager.getConnection(
9209. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
92110.
92211. PreparedStatement ps=con.prepareStatement(
92312. "select * from userreg where name=? and pass=?");
92413. ps.setString(1,name);
92514. ps.setString(2,pass);
92615.
92716. ResultSet rs=ps.executeQuery();
92817. status=rs.next();
92918.
93019. }catch(Exception e){System.out.println(e);}
93120. return status;
93221. }
93322. }
934
935WelcomeServlet.java
936
9371. import java.io.IOException;
9382. import java.io.PrintWriter;
9393.
9404. import javax.servlet.ServletException;
9415. import javax.servlet.http.HttpServlet;
9426. import javax.servlet.http.HttpServletRequest;
9437. import javax.servlet.http.HttpServletResponse;
9448.
9459. public class WelcomeServlet extends HttpServlet {
94610. public void doPost(HttpServletRequest request, HttpServletResponse response)
94711. throws ServletException, IOException {
94812.
94913. response.setContentType("text/html");
95014. PrintWriter out = response.getWriter();
95115.
95216. String n=request.getParameter("username");
95317. out.print("Welcome "+n);
95418.
95519. out.close();
95620. }
95721.
95822. }
959
960JSP-
961Getting form values:-
962<%@ page language="java"%>
963<%@ page import="java.lang.*"%>
964<html>
965<body>
966<H1><center>Result for <%=request.getParameter("a1")%></center></H1>
967<%
968int i=Integer.parseInt(request.getParameter("t1"));
969int j=Integer.parseInt(request.getParameter("t2"));
970int k=0;
971String str=request.getParameter("a1");
972
973if(str.equals("add"))
974 k=i+j;
975if(str.equals("mul"))
976 k=i*j;
977if(str.equals("div"))
978 k=i/j;
979%>
980Result is <%=k%>
981</body>
982</html>
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002Create a JSP application that allows the user to enter the name of the city. While submission of this
1003form, they retrieves and responses the weather report for the user entered the city.
1004Code:
1005HTML Code:
1006<head>
1007<title>Weather</title>
1008<meta charset="UTF-8">
1009<meta name="viewport" content="width=device-width, initial-scale=1.0">
1010</head>
1011<body>
1012<form name="myform" action="CityWeather.jsp">
1013City: <input type="text" name="city">
1014<br><br>
1015<input type="submit" value="Get Weather">
1016</form>
1017</body>
1018</html>
1019JSP Code:
1020<%--
1021Document : newjsp
1022Created on : Oct 16, 2018, 11:56:43 PM
1023Author : VarunPC
1024--%>
1025<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
1026<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>
1027<%@page contentType="text/html" pageEncoding="UTF-8"%>
1028<!DOCTYPE html>
1029<html>
1030<head>
1031<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
1032<title>JSP Page</title>
1033<style>
1034td{
1035align-content: center;
1036}
1037</style>
1038</head>
1039<body>
1040<h1>Weather!!</h1>
1041<c:catch var ="catchException">
1042<sql:setDataSource url="jdbc:derby://localhost:1527/WeatherDB"
1043driver="org.apache.derby.jdbc.ClientDriver" var="mydata"/>
1044<p>Connected to Weather Database</p>
1045<br>
1046<sql:query dataSource="${mydata}" var="result">
1047select * from weather where city = ?
1048<sql:param value="${param.city}"/>
1049</sql:query>
1050<table border="1">
1051<tr>
1052<th></th>
1053<th>S.No</th>
1054<th>City</th>
1055<th>Average Temperature(C)</th>
1056<th>Average Rainfall(mm)</th>
1057</tr>
1058<c:forEach var="row" items="${result.rows}">
1059<tr>
1060<td></td>
1061<td>1</td>
1062<td><c:out value="${row.city}"/></td>
1063<td><c:out value="${row.average_temperature}"/></td>
1064<td><c:out value="${row.average_rainfall}"/></td>
1065</tr>
1066</c:forEach>
1067</c:catch>
1068</table>
1069<c:if test = "${catchException != null}">
1070<p>The exception is : ${catchException} <br />
1071There is an exception: ${catchException.message}</p>
1072</c:if>
1073</body>
1074</html>
1075
1076
1077
1078
1079------------------------- ---------------------------- --------------------------------- -------------------- -------------------------
1080ADD, DELETE MODIFY USING PHP
1081
1082
1083
1084
1085
1086
1087
1088
1089Even Odd:-
1090public class PrintEvenOddTester {
1091
1092 public static void main(String... args) {
1093 Printer print = new Printer();
1094 Thread t1 = new Thread(new TaskEvenOdd(print, 10, false));
1095 Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));
1096 t1.start();
1097 t2.start();
1098 }
1099
1100}
1101
1102class TaskEvenOdd implements Runnable {
1103
1104 private int max;
1105 private Printer print;
1106 private boolean isEvenNumber;
1107
1108 TaskEvenOdd(Printer print, int max, boolean isEvenNumber) {
1109 this.print = print;
1110 this.max = max;
1111 this.isEvenNumber = isEvenNumber;
1112 }
1113
1114 @Override
1115 public void run() {
1116
1117 //System.out.println("Run method");
1118 int number = isEvenNumber == true ? 2 : 1;
1119 while (number <= max) {
1120
1121 if (isEvenNumber) {
1122 //System.out.println("Even :"+ Thread.currentThread().getName());
1123 print.printEven(number);
1124 //number+=2;
1125 } else {
1126 //System.out.println("Odd :"+ Thread.currentThread().getName());
1127 print.printOdd(number);
1128 // number+=2;
1129 }
1130 number += 2;
1131 }
1132
1133 }
1134
1135}
1136
1137class Printer {
1138
1139 boolean isOdd = false;
1140
1141 synchronized void printEven(int number) {
1142
1143 while (isOdd == false) {
1144 try {
1145 wait();
1146 } catch (InterruptedException e) {
1147 e.printStackTrace();
1148 }
1149 }
1150 System.out.println("Even:" + number);
1151 isOdd = false;
1152 notifyAll();
1153 }
1154
1155 synchronized void printOdd(int number) {
1156 while (isOdd == true) {
1157 try {
1158 wait();
1159 } catch (InterruptedException e) {
1160 e.printStackTrace();
1161 }
1162 }
1163 System.out.println("Odd:" + number);
1164 isOdd = true;
1165 notifyAll();
1166 }
1167
1168}
1169
1170
1171User Defined Exception:-
1172class MyException extends Exception
1173{
1174 //store account information
1175 private static int accno[] = {1001, 1002, 1003, 1004};
1176
1177 private static String name[] =
1178 {"Nish", "Shubh", "Sush", "Abhi", "Akash"};
1179
1180 private static double bal[] =
1181 {10000.00, 12000.00, 5600.0, 999.00, 1100.55};
1182
1183 // default constructor
1184 MyException() { }
1185
1186 // parametrized constructor
1187 MyException(String str) { super(str); }
1188
1189 // write main()
1190 public static void main(String[] args)
1191 {
1192 try {
1193 // display the heading for the table
1194 System.out.println("ACCNO" + "\t" + "CUSTOMER" +
1195 "\t" + "BALANCE");
1196
1197 // display the actual account information
1198 for (int i = 0; i < 5 ; i++)
1199 {
1200 System.out.println(accno[i] + "\t" + name[i] +
1201 "\t" + bal[i]);
1202
1203 // display own exception if balance < 1000
1204 if (bal[i] < 1000)
1205 {
1206 MyException me =
1207 new MyException("Balance is less than 1000");
1208 throw me;
1209 }
1210 }
1211 } //end of try
1212
1213 catch (MyException e) {
1214 e.printStackTrace();
1215 }
1216 }
1217}
1218
1219
1220Exceptions:-
1221class NumberFormat_Demo
1222{
1223 public static void main(String args[])
1224 {
1225 try {
1226 // "akki" is not a number
1227 int num = Integer.parseInt ("akki") ;
1228
1229 System.out.println(num);
1230 } catch(NumberFormatException e) {
1231 System.out.println("Number format exception");
1232 }
1233 }
1234}
1235
1236
1237
1238
1239
1240
1241
1242
1243JAVA FIBONACCI
1244
1245
1246import java.util.*;
1247import java.io.*;
1248class Fibonacci extends Thread
1249{
1250 private PipedWriter out = new PipedWriter();
1251 public PipedWriter getPipedWriter()
1252 {
1253 return out;
1254 }
1255 public void run()
1256 {
1257 Thread t = Thread.currentThread();
1258 t.setName("Fibonacci");
1259 System.out.println(t.getName() + " thread started");
1260 int fibo1=0,fibo2=1,fibo=0;
1261 while(true)
1262 {
1263 try
1264 {
1265 fibo = fibo1 + fibo2;
1266 if(fibo>50)
1267 {
1268 out.close();
1269 break;
1270 }
1271 out.write(fibo);
1272 sleep(100);
1273 }
1274 catch(Exception e)
1275 {
1276 System.out.println("Fibonacci:"+e);
1277 }
1278 fibo1=fibo2;
1279 fibo2=fibo;
1280 }
1281 System.out.println(t.getName() + " thread exiting");
1282 }
1283}
1284class Prime extends Thread
1285{
1286 private PipedWriter out1 = new PipedWriter();
1287 public PipedWriter getPipedWriter()
1288 {
1289 return out1;
1290 }
1291 public void run()
1292 {
1293 Thread t= Thread.currentThread();
1294 t.setName("Prime");
1295 System.out.println(t.getName() + " thread Started...");
1296 int prime=1;
1297 while(true)
1298 {
1299 try
1300 {
1301 if(prime>100000)
1302 {
1303 out1.close();
1304 break;
1305 }
1306 if(isPrime(prime))
1307 out1.write(prime);
1308 prime++;
1309 sleep(0);
1310 }
1311 catch(Exception e)
1312 {
1313 System.out.println(t.getName() + " thread exiting.");
1314 System.exit(0);
1315 }
1316 }
1317 }
1318 public boolean isPrime(int n)
1319 {
1320 int m=(int)Math.round(Math.sqrt(n));
1321 if(n==1 || n==2)
1322 return true;
1323 for(int i=2;i<=m;i++)
1324 if(n%i==0)
1325 return false;
1326 return true;
1327 }
1328}
1329public class PipedIo
1330{
1331 public static void main(String[] args) throws Exception
1332 {
1333 Thread t=Thread.currentThread();
1334 t.setName("Main");
1335 System.out.println(t.getName() + " thread Started...");
1336 Fibonacci fibonacci = new Fibonacci();
1337 Prime prime = new Prime();
1338 PipedReader fpr = new PipedReader(fibonacci.getPipedWriter());
1339 PipedReader ppr = new PipedReader(prime.getPipedWriter());
1340 fibonacci.start();
1341 prime.start();
1342 int fib=fpr.read(), prm=ppr.read();
1343 System.out.println("The numbers common to PRIME and FIBONACCI:");
1344 while((fib!=-1) && (prm!=-1))
1345 {
1346 while(prm<=fib)
1347 {
1348 if(fib==prm)
1349 System.out.println(prm);
1350 prm=ppr.read();
1351 }
1352 fib=fpr.read();
1353 }
1354 System.out.println(t.getName() + " thread exiting");
1355 }
1356}
1357
1358
1359LAB ASSESSMENT 5
1360NAME: ANSHUL SACHDEV Registration Number: 16BCE0291
1361________________________________________
1362Question-1:
1363Write a program to demonstrate the knowledge of students in basic Java concepts.
1364Eg., Write a program to read the First name and Last name of a person, his weight and height using command line arguments. Calculate the BMI Index which is defined as the individual's body mass divided by the square of their height.
1365Category BMI Range-Kg/m2
1366Underweight <18.5
1367Normal (healthy weight) 18.5 to 25
1368Overweight 25 to 30
1369Obese Class Over 30
1370Display the name and display his category based on the BMI value thus calculated.
1371CODE:
1372import java.util.Scanner;
1373
1374public class BMI {
1375public static void main(String[] args) {
1376 Scanner sc = new Scanner(System.in);
1377 String firstname=sc.next();
1378 String lastname=sc.next();
1379 float weight=Float.valueOf(sc.next());
1380 float height=Float.valueOf(sc.next());
1381 float bmi=weight/(height*height);
1382 String category="";
1383 if(bmi<18.5){
1384 category="Underweight";
1385 }
1386 if(bmi>=18.5 && bmi<=25){
1387 category="Normal (healthy weight)";
1388 }
1389 if(bmi>25 && bmi<=30){
1390 category="Overweight";
1391 }
1392 if(bmi>30){
1393 category="Obese Class";
1394 }
1395 System.out .println("name: "+firstname+" "+lastname);
1396 System.out.println("category: "+category);
1397}
1398OUTPUT:
1399
1400
1401________________________________________
1402Question-2:
1403Write a program to demonstrate the knowledge of students in multidimensional arrays and looping constructs.
1404Eg., If there are 4 batches in BTech(IT) learning ‘ITE2005’ course, read the count of the slow learners (who have scored <25) in each batch. Tutors should be assigned in the ratio of 1:4 (For every 4 slow learners, there should be one tutor). Determine the number of tutors for each batch. Create a 2-D jagged array with 4 rows to store the count of slow learners in the 4 batches. The number of columns in each row should be equal to the number of groups formed for that particular batch ( Eg., If there are 23 slow learners in a batch, then there should be 6 tutors and in the jagged array, the corresponding row should store 4, 4, 4, 4, 4,3). Use for-each loop to traverse the array and print the details. Also print the number of batches in which all tutors have exactly 4 students.
1405CODE:
1406import java.util.*;
1407
1408public class multiDimensionalArray {
1409 public static void main(String[] args) {
1410 Scanner scan=new Scanner(System.in);
1411 int[][] array=new int[4][];
1412 int[] b=new int[4];
1413 int y,i,k,c=4;
1414 for( i=0;i<4;i++)
1415 {
1416 System.out.println("Enter the number of slow learners in batch "+(i+1));
1417 b[i]=scan.nextInt();
1418 y=b[i]/4;
1419 if(b[i]%4!=0){
1420 y++;
1421 c--;
1422 }
1423 System.out.println("number of tutors in batch "+(i+1)+" are "+y);
1424 array[i]=new int[y];
1425 for(k=0;k<y-1;k++){
1426 array[i][k]=4;
1427 }
1428 if(b[i]%4!=0)
1429 array[i][k]=b[i]%4;
1430 else
1431 array[i][k]=4;
1432 }
1433 System.out.println("Number of batches with all tutors having 4 students are "+c);
1434 System.out.println("The slow learner distribution is as follows:");
1435 for(int q[]:array){
1436 for(int m:q)
1437 System.out.print(m+",");
1438 System.out.println();
1439 }
1440 }
1441}
1442
1443OUTPUT:
1444
1445________________________________________
1446Question-3:
1447Write a program to demonstrate the knowledge of students in String handling.
1448Eg., Write a program to read a chemical equation and find out the count of the reactants and the products. Also display the count of the number of molecules of each reactant and product.
1449 Eg., For the equation, 2NaOH + H2SO4 -> Na2SO4+ 2H2O, the O/P should be as follows.
1450 Reactants are 2 moles of NaOH, 1 mole of H2SO4.
1451 Products are 1 mole of Na2SO4 and 2 moles of H2O.
1452
1453CODE:
1454import java.util.Scanner;
1455import java.util.regex.Matcher;
1456import java.util.regex.Pattern;
1457
1458class Coeff{
1459 public static String extractCoeff(String str) {
1460 String pattern = "^\\d";
1461 Pattern r = Pattern.compile(pattern);
1462 Matcher m = r.matcher(str);
1463 if(m.find()){
1464 return m.group(0);
1465 }
1466 else{
1467 return "1";
1468 }
1469 }
1470 public static String removeCoeff(String str) {
1471 String pattern = "[^\\d](.*)";
1472 Pattern r = Pattern.compile(pattern);
1473 Matcher m = r.matcher(str);
1474 if (m.find()) {
1475 return m.group(0);
1476 }
1477 else {
1478 return str;
1479 }
1480 }
1481}
1482
1483public class StringHandle {
1484 public static void main(String args[]){
1485 int i;
1486 Scanner sc = new Scanner(System.in);
1487 System.out.print("Enter equation: ");
1488 String eq = sc.nextLine();
1489 sc.close();
1490 String arrow = "(\\s->\\s)|(\\s->)|(->\\s)|(->)";
1491 String[] words = eq.split(arrow);
1492 String[] reactant = words[0].split("\\+");
1493 String[] product = words[1].split("\\+");
1494 String[] rmoles = new String[10];
1495 String[] pmoles = new String[10];
1496 for(i = 0; i<reactant.length; i++) {
1497 reactant[i] = reactant[i].replaceAll("\\s+","");
1498 rmoles[i] = Coeff.extractCoeff(reactant[i]);
1499 }
1500 for (i = 0; i<product.length; i++) {
1501 product[i] = product[i].replaceAll("\\s+", "");
1502 pmoles[i] = Coeff.extractCoeff(product[i]);
1503 }
1504 System.out.print("(1) Reactants are ");
1505 if(reactant.length> 1) {
1506 for(i = 0; i<reactant.length; i++){
1507 if(i == 0)
1508 System.out.print(rmoles[i] + " mole/s of " + Coeff.removeCoeff(reactant[i]));
1509 else if(i == reactant.length-1)
1510 System.out.print(" and " + rmoles[i] + " mole/s of " + Coeff.removeCoeff(reactant[i]));
1511 else
1512 System.out.print(", " + rmoles[i] + " mole/s of " + Coeff.removeCoeff(reactant[i]));
1513 }
1514 }
1515 else {
1516 System.out.print(rmoles[0] + " mole/s of " + Coeff.removeCoeff(reactant[0]));
1517 }
1518 System.out.println();
1519 System.out.print("(2) Products are ");
1520 if (product.length> 1) {
1521 for (i = 0; i<product.length; i++) {
1522 if (i == 0)
1523 System.out.print(pmoles[i] + " mole/s of " + Coeff.removeCoeff(product[i]));
1524 else if (i == product.length - 1)
1525 System.out.print(" and " + pmoles[i] + " mole/s of " + Coeff.removeCoeff(product[i]));
1526 else
1527 System.out.print(", " + pmoles[i] + " mole/s of " + Coeff.removeCoeff(product[i]));
1528 }
1529 } else {
1530 System.out.print(pmoles[0] + " mole/s of " + Coeff.removeCoeff(product[0]));
1531 }
1532 }
1533}
1534OUTPUT:
1535
1536________________________________________
1537Question-4:
1538Write a program to demonstrate the knowledge of students in advanced concepts of Java string handling.
1539Eg., (Bioinformatics: finding genes) Biologists use a sequence of letters A, C, T, and G to model a genome. A gene is a substring of a genome that starts after a triplet ATG and ends before a triplet TAG, TAA, or TGA. Furthermore, the length of a gene string is a multiple of 3 and the gene does not contain any of the triplets ATG, TAG, TAA, and TGA. Write a program that prompts the user to enter a genome and displays all genes in the genome. If no gene is found in the input sequence, displays no gene. Here are the sample runs:
1540Enter a genome string: TTATGTTTTAAGGATGGGGCGTTAGTT
1541O/P: TTT
1542 GGGCGT
1543CODE:
1544import java.util.Scanner;
1545
1546public class Genes {
1547 public static void main(String[] args) {
1548 Scanner sc = new Scanner(System.in);
1549 System.out.print("Enter sequence: ");
1550 String in = sc.nextLine();
1551
1552 String[] arr = in.split("ATG|TAG|TAA|TGA");
1553
1554 System.out.println("Gene sequence is: ");
1555 int found = 0;
1556 if(in.indexOf(arr[0]) != 0)
1557 {
1558 System.out.println(arr[0]);
1559 }
1560 for(int i = 1; i < arr.length; i++){
1561 if(arr[i].length()%3 == 0)
1562 {
1563 found = 1;
1564 System.out.println(arr[i]);
1565 }
1566 }
1567 if(found == 0)
1568 System.out.println("No genes");
1569 }
1570}
1571OUTPUT:
1572
1573________________________________________
1574Question-5:
1575Write a program to demonstrate the knowledge of students in working with classes and objects.
1576Eg.,Create a class Film with string objects which stores name, language and lead_actor and category (action/drama/fiction/comedy). Also include an integer data member that stores the duration of the film. Include parameterized constructor, default constructor and accessory functions to film class. Flim objects can be initialized either using a constructor or accessor functions. Create a class FilmMain that includes a main function. In the main function create a vector object that stores the information about the film as objects. Use the suitable methods of vector class to iterate the vector object to display the following
1577a. The English film(s) that has Arnold as its lead actor and that runs for shortest duration.
1578b. The Tamil film(s) with Rajini as lead actor.
1579c. All the comedy movies.
1580CODE:
1581import java.util.Vector;
1582
1583class Film{
1584 String name;
1585 String language;
1586 String lead_actor;
1587 String category;
1588 int duration;
1589
1590 Film(){
1591 name = null;
1592 language = null;
1593 lead_actor = null;
1594 category = null;
1595 duration = 0;
1596 }
1597
1598 Film(String n, String lang, String actor, String cat, int dur){
1599 name = n;
1600 language = lang;
1601 lead_actor = actor;
1602 category = cat;
1603 duration = dur;
1604 }
1605}
1606
1607public class FilmMain {
1608 public static void main(String[] args) {
1609
1610 Film films;
1611 Vector<Film> Films = new Vector<Film>();
1612
1613 films = new Film();
1614 films.name = "Terminator";
1615 films.language = "English";
1616 films.lead_actor = "Arnold";
1617 films.duration = 10;
1618 films.category = "Action";
1619 Films.add(films);
1620
1621 films = new Film();
1622 films.name = "Terminator 2";
1623 films.language = "English";
1624 films.lead_actor = "Arnold";
1625 films.duration = 20;
1626 films.category = "Action";
1627 Films.add(films);
1628
1629 films = new Film();
1630 films.name = "Robot 1";
1631 films.language = "Tamil";
1632 films.lead_actor = "Rajini";
1633 films.duration = 10;
1634 films.category = "Comedy";
1635 Films.add(films);
1636
1637 films = new Film();
1638 films.name = "Robot 2";
1639 films.language = "Tamil";
1640 films.lead_actor = "Rajini";
1641 films.duration = 30;
1642 films.category = "Comedy";
1643 Films.add(films);
1644
1645 int min = 9999999;
1646 int imin = 0;
1647
1648 for(int i = 0; i < 4; i++){
1649 films = Films.get(i);
1650 if(films.lead_actor.equals("Arnold"))
1651 if(films.duration < min){
1652 min = films.duration;
1653 imin = i;
1654 }
1655 if(films.category.equals("Comedy"))
1656 System.out.println(films.name + " is a Comedy movie");
1657 }
1658
1659 films = Films.get(imin);
1660 System.out.println("Shortest Arnold film is " + films.name + " and duration: " + min);
1661 }
1662}
1663OUTPUT:
1664
1665________________________________________
1666Question-6:
1667Write a program to demonstrate the knowledge of students in creation of abstract classes and working with abstract methods.
1668Eg., Define an abstract class ‘Themepark’ and inherit 2 classes ‘Queensland’ and ‘Wonderla’ from the abstract class. In both the theme parks, the entrance fee for adults is Rs. 500 and for children it is Rs. 300. If a family buys ‘n’ adult tickets and ‘m’ children tickets, define a method in the abstract class to calculate the total cost. Also, declare an abstract method playGame() which must be redefined in the subclasses.
1669In Queensland, there are a total of 30 games. Hence create a Boolean array named ‘Games’ of size 30 which initially stores false values for all the elements. If the player enters any game code that has already been played, a warning message should be displayed and the user should be asked for another choice. In Wonderla, there are a total of 40 different games. Thus create an integer array with 40 elements. Here, the games can be replayed, until the user wants to quit. Finally display the total count of games that were repeated and count of the games which were not played at all.
1670CODE:
1671import java.util.Scanner;
1672
1673abstract class Themepark{
1674 int afee = 500, cfee = 300;
1675 int calc(int n, int m){
1676 return (n*afee) + (m*cfee);
1677 }
1678 abstract void playGame(int j);
1679}
1680
1681class Queensland extends Themepark{
1682 int i;
1683 Boolean games[] = new Boolean[30];
1684
1685 Queensland(){
1686 System.out.println("Welcome to Queensland!");
1687 for(i = 0; i < games.length; i++){
1688 games[i] = false;
1689 }
1690 }
1691
1692 void playGame(int j){
1693 if(games[j] == true){
1694 System.out.println("Error: You've already played this game");
1695 }
1696 else{
1697 System.out.println("Playing Game " + j + " at Queensland");
1698 games[j] = true;
1699 }
1700 }
1701}
1702
1703class Wonderla extends Themepark{
1704 int i;
1705 Boolean games[] = new Boolean[40];
1706
1707 Wonderla(){
1708 System.out.println("Welcome to Wonderla!");
1709 for(i = 0; i < games.length; i++){
1710 games[i] = false;
1711 }
1712 }
1713
1714 void playGame(int j){
1715 if(games[j] == true){
1716 System.out.println("Error: You've already played this game");
1717 }
1718 else{
1719 System.out.println("Playing Game " + j + " at Queensland");
1720 games[j] = true;
1721 }
1722 }
1723
1724}
1725
1726public class AmusementParks {
1727 public static void main(String[] args) {
1728 Scanner sc = new Scanner(System.in);
1729 int i;
1730
1731 System.out.println("----Welcome to the Amusement Park----");
1732 System.out.println("Select a park:\n1. Queensland\n2. Wonderla");
1733 int c = sc.nextInt();
1734
1735 switch(c){
1736 case 1:
1737 Queensland q = new Queensland();
1738 System.out.print("Select a game (0 - 29): ");
1739 while(sc.hasNextInt()){
1740 i = sc.nextInt();
1741 q.playGame(i);
1742 }
1743 break;
1744
1745 case 2:
1746 Wonderla w = new Wonderla();
1747 System.out.print("Select a game (0 - 39): ");
1748 while(sc.hasNextInt()){
1749 i = sc.nextInt();
1750 w.playGame(i);
1751 }
1752 break;
1753
1754 default:
1755 System.out.println("Invalid");
1756 break;
1757 }
1758 }
1759}
1760OUTPUT:
1761
1762________________________________________
1763Question-7:
1764Write a program to demonstrate the knowledge of students in Java Exception handling.
1765Eg., Read the Register Number and Mobile Number of a student. If the Register Number does not contain exactly 9 characters or if the Mobile Number does not contain exactly 10 characters, throw an IllegalArgumentException. If the Mobile Number contains any character other than a digit, raise a NumberFormatException. If the Register Number contains any character other than digits and alphabets, throw a NoSuchElementException. If they are valid, print the message ‘valid’ else ‘invalid’
1766
1767CODE:
1768import java.util.*;
1769public class ExceptionDemo {
1770 public static void main(String args[]) {
1771 Scanner sc = new Scanner(System.in);
1772 String regNo = sc.nextLine();
1773 String mNo = sc.nextLine();
1774 try {
1775 if(regNo.length() != 9 || mNo.length() != 10)
1776 throw new IllegalArgumentException("invalid");
1777 if(!mNo.matches("^\\d+$"))
1778 throw new NumberFormatException("invalid");
1779 if(!regNo.matches("^\\w+$"))
1780 throw new NoSuchElementException("invalid");
1781 System.out.println("valid");
1782 } catch (Exception e) {
1783 System.out.println(e);
1784 }
1785 }
1786}
1787OUTPUT:
1788
1789
1790________________________________________
1791
1792Question-8:
1793Write a program to demonstrate the knowledge of students in working with user-defined packages and sub-packages.
1794Eg., Within the package named ‘primespackage’, define a class Primes which includes a method checkForPrime() for checking if the given number is prime or not. Define another class named TwinPrimes outside of this package which will display all the pairs of prime numbers whose difference is 2. (Eg, within the range 1 to 10, all possible twin prime numbers are (3,5), (5,7)). The TwinPrimes class should make use of the checkForPrime() method in the Primes class.
1795CODE:
1796
1797FILE-1: TwinPrimes.java
1798package ques;
1799import java.util.Scanner;
1800import primespackage.Prime;
1801
1802public class TwinPrimes {
1803 public static void main(String args[]) {
1804 int i;
1805 Scanner sc = new Scanner(System.in);
1806 System.out.print("Enter first number: ");
1807 int n1 = sc.nextInt();
1808 System.out.print("Enter second number: ");
1809 int n2 = sc.nextInt();
1810 sc.close();
1811 System.out.println("Twin prime numbers are: ");
1812 //checking twins prime
1813 for(i = n1; i <= n2; i++) {
1814 if(Prime.checkPrime(i) & Prime.checkPrime(i+2) & i > 1)
1815 {
1816 System.out.println("(" + i + "," + (i+2) + ")");
1817 }
1818 }
1819 }
1820}
1821
1822FILE-2: Prime.java
1823package primespackage;
1824public class Prime {
1825 public static boolean checkPrime(int num) {
1826 int temp;
1827 boolean isPrime = true;
1828 for (int i = 2; i <= num / 2; i++) {
1829 temp = num % i;
1830 if (temp == 0) {
1831 isPrime = false;
1832 break;
1833 }
1834 }
1835 return isPrime;
1836 }
1837}
1838OUTPUT:
1839
1840
1841
1842________________________________________
1843Question-9:
1844Write a program to demonstrate the knowledge of students in File handling.
1845Eg., Define a class ‘Donor’ to store the below mentioned details of a blood donor.
1846 Name, age, Address, Contactnumber, bloodgroup, date of last donation
1847 Create ‘n’ objects of this class for all the regular donors at Vellore. Write these objects to a file. Read these objects from the file and display only those donors’ details whose blood group is ‘A+ve’ and had not donated for the recent six months.
1848CODE:
1849import java.io.*;
1850import java.nio.file.Files;
1851import java.nio.file.NoSuchFileException;
1852import java.nio.file.Paths;
1853import java.text.ParseException;
1854import java.text.SimpleDateFormat;
1855import org.joda.time.LocalDate;
1856import org.joda.time.Period;
1857import java.util.ArrayList;
1858import java.util.Date;
1859import java.util.Iterator;
1860import java.util.Scanner;
1861import java.util.regex.Matcher;
1862import java.util.regex.Pattern;
1863
1864public class Donor implements Serializable{
1865 String name,addr,contact,bldgrp;
1866 Date date;
1867
1868 public static void main(String[] args) throws IOException{
1869
1870 // arraylist for retrieving and adding donors
1871 ArrayList<Donor> ad = new ArrayList<Donor>();
1872
1873 int n, i; // counter variables
1874
1875 // format for date and time
1876 SimpleDateFormat ft = new SimpleDateFormat("MM-dd-yyyy");
1877 String temp;
1878
1879 // patten for blood group
1880 String pattern = "[A|B|O|AB][+|-]";
1881 Matcher m;
1882 Pattern r = Pattern.compile(pattern);
1883
1884 // delete existing file first
1885 try{
1886 Files.deleteIfExists(Paths.get("donations.txt"));
1887 }
1888 catch(NoSuchFileException e)
1889 {
1890 System.out.println("Error: No such file/directory exists");
1891 }
1892 catch(IOException e)
1893 {
1894 System.out.println("Error: Invalid permissions.");
1895 }
1896 System.out.println("Success: Deletion successful.");
1897
1898 Scanner sc = new Scanner(System.in);
1899 System.out.print("Enter number of donors: ");
1900 n = sc.nextInt();
1901 sc.nextLine();
1902 Donor d;
1903 System.out.println("----------------------");
1904 for(i = 0; i < n; i++){
1905 d = new Donor(); // initializing new donor
1906 //taking input from user
1907 System.out.print("Name: ");
1908 d.name = sc.nextLine();
1909 System.out.print("Address: ");
1910 d.addr = sc.nextLine();
1911 System.out.print("Contact: ");
1912 d.contact = sc.nextLine();
1913 d.bldgrp = "";
1914 m = r.matcher(d.bldgrp);
1915 while(!m.find()){
1916 System.out.print("Blood Group (only A or B or O or AB [+|-] (all caps): ");
1917 d.bldgrp = sc.nextLine();
1918 m = r.matcher(d.bldgrp);
1919 }
1920 boolean flag = false;
1921 while(!flag){
1922 System.out.print("Date (MM-dd-yyyy): ");
1923 temp = sc.nextLine();
1924 try {
1925 d.date = ft.parse(temp);
1926 flag = true;
1927 } catch (ParseException e) {
1928 flag = false;
1929 System.out.println("Unparseable using " + ft);
1930 }
1931 }
1932
1933
1934 // adding donor object to array list
1935 ad.add(d);
1936 }
1937 try{
1938 FileOutputStream fos = new FileOutputStream("donations.txt"); // creating file to write to
1939 ObjectOutputStream oos = new ObjectOutputStream(fos);
1940 // serialization
1941 oos.writeObject(ad);
1942 oos.close();
1943 fos.close();
1944 System.out.println("Success: File successfully written");
1945 }catch (IOException ioe)
1946 {
1947 ioe.printStackTrace();
1948 }
1949
1950
1951 // reading data from file
1952 ad.clear();
1953 FileInputStream fis = new FileInputStream("donations.txt");
1954 ObjectInputStream ois = new ObjectInputStream(fis);
1955 try{
1956 ad = (ArrayList<Donor>)ois.readObject();
1957 }catch (ClassNotFoundException e){
1958 System.out.println(e);
1959 }
1960
1961 // defining current time and period
1962 LocalDate donor_date;
1963 LocalDate current = LocalDate.now();
1964 Period p;
1965
1966 System.out.println("---------------------------------------------");
1967 System.out.println("---------------------------------------------");
1968 // iterating through the arraylist
1969 System.out.println("\n" + "Donors who haven't donated in 6 months and \"A+\"" + "\n");
1970 Iterator<Donor> itr = ad.iterator();
1971 i = 0;
1972 while(itr.hasNext()){
1973 d = new Donor();
1974 d = (Donor)itr.next();
1975 donor_date = new LocalDate(d.date);
1976 p = new Period(donor_date,current);
1977
1978 // if more than 6 months and blood group is A+, print details
1979 if((p.getMonths() > 6 | p.getYears() >= 1) && d.bldgrp.equals("A+"))
1980 {
1981 System.out.println("Donor " + (i+1));
1982 System.out.println("----------------------");
1983 System.out.println(d.name); // name
1984 System.out.println(d.addr); // address
1985 System.out.println(d.contact); // contact
1986 System.out.println(d.bldgrp); // blood group
1987 System.out.println(d.date); // date
1988 System.out.println("\n");
1989 }
1990 }
1991 }
1992}
1993OUTPUT:
1994
1995________________________________________
1996Question-10:
1997Write a program to demonstrate the knowledge of students in multithreading.
1998Eg., Three students A, B and C of B.Tech-IT II year contest for the PR election. With the total strength of 240 students in II year, simulate the vote casting by generating 240 random numbers (1 for student A, 2 for B and 3 for C) and store them in an array. Create four threads to equally share the task of counting the number of votes cast for all the three candidates. Use synchronized method or synchronized block to update the three count variables. The main thread should receive the final vote count for all three contestants and hence decide the PR based on the values received.
1999CODE:
2000MULTITHREADVOTE.JAVA
2001import elections.Vote;
2002import elections.count;
2003import java.util.*;
2004
2005public class MultiThreadVote {
2006 public static void main(String[] args) {
2007 Vector votevec = new Vector(240); // creating a vote array for 240 votes
2008 Vote a = new Vote(1, votevec);
2009 a.start();
2010 Vote b = new Vote(2, votevec);
2011 b.start();
2012 Vote c = new Vote(3, votevec);
2013 c.start();
2014 try{
2015 a.join();
2016 b.join();
2017 c.join();
2018 System.out.println("Voting has ended!");
2019 }catch(Exception e){System.out.println(e);}
2020 count ac = new count(1, votevec);
2021 count bc = new count(2, votevec);
2022 count cc = new count(3, votevec);
2023 ac.start();
2024 bc.start();
2025 cc.start();
2026 try{
2027 ac.join();
2028 bc.join();
2029 cc.join();
2030 System.out.println("Counting has ended!");
2031 }catch(Exception e){System.out.println(e);}
2032 int av = ac.count;
2033 int bv = bc.count;
2034 int cv = cc.count;
2035 System.out.println("elections.Vote Vector:" + "\n" + votevec);
2036 System.out.println(av + " votes for A");
2037 System.out.println(bv + " votes for B");
2038 System.out.println(cv + " votes for C");
2039 if(av >= bv && av >= cv){
2040 if(av == bv || av == cv)
2041 System.out.println("Tie in elections!");
2042 else
2043 System.out.println("A has won the elections!");
2044 }
2045 else if(bv >= av && bv >= cv){
2046 if(av == bv || bv == cv)
2047 System.out.println("Tie in elections!");
2048 else
2049 System.out.println("B has won the elections!");
2050 }
2051 else if(cv >= av && cv >= bv){
2052 if(cv == bv || cv == av)
2053 System.out.println("Tie in elections!");
2054 else
2055 System.out.println("C has won the elections!");
2056 }
2057 }
2058}
2059
2060Vote.java
2061package elections;
2062import java.util.*;
2063public class Vote extends Thread{
2064 Random rand = new Random(); // generating a random number
2065 int max = 750; // max wait time for thread
2066 int min = 100; // min wait time for thread
2067 int v, s;
2068 Vector vec;
2069 public Vote(int v, Vector vec)
2070 {
2071 this.v = v;
2072 this.vec = vec;
2073 }
2074 public void run() {
2075 try
2076 {
2077 // while voting print id
2078 while(vec.size() < 240) { // ensure size of vote vector is below 240
2079 System.out.println("Thread " + this.getId() + " is Voting");
2080 vec.add(v);
2081 s = rand.nextInt((max - min) + 1) + min;
2082 System.out.println("Thread " + this.getId() + " is sleeping for " + s);
2083 Thread.sleep(s); // create random delay between threads
2084 }
2085 }
2086 catch(InterruptedException e)
2087 {
2088 System.out.println("Voting Exception: " + e);
2089 }
2090 }
2091}
2092
2093
2094
2095Count.java
2096package elections;
2097
2098import java.util.*;
2099
2100public class count extends Thread{
2101 Vector vec;
2102 int k, i;
2103 public int count = 0;
2104 public count(int k, Vector vec){
2105 this.k = k;
2106 this.vec = vec;
2107 }
2108 public void run(){
2109 try{
2110 for(i = 0; i < vec.capacity(); i++){
2111 if(vec.elementAt(i).equals(k)) // check if elements match
2112 count++;
2113 }
2114 }
2115 catch(Exception e){
2116 System.out.println(e);
2117 }
2118 }
2119}
2120OUTPUT:
2121
2122________________________________________
2123Question-11:
2124Write a program to demonstrate the knowledge of students in creating and deploying applets.
2125Eg., Draw a ball, filled with default color. Move the ball from top to bottom of the window continuously with its color changed for every one second. The new color of the ball for the next second should be obtained by adding 20 to the current value of Red component, for the second time by adding 20 to the blue component, and for the third time by adding 20 to the blue component, till all reach the final limit 225, after which the process should be repeated with the default color.
2126CODE:
2127import java.applet.*;
2128import java.awt.*;
2129
2130public class applet extends Applet implements Runnable{
2131
2132 int x = 190, y =0, r=20;
2133 int dx = 0, dy =14 ;
2134 private static Color startColor;
2135 Color c;
2136 int red=0,green=0,blue=0;
2137 Thread t;
2138 boolean stopFlag;
2139 @Override
2140 public void start()
2141 {
2142 t = new Thread(this);
2143 stopFlag=false;
2144 t.start();
2145 }
2146 @Override
2147 public void paint(Graphics g)
2148 {
2149 startColor =new Color(red,green,blue);
2150 g.setColor(startColor);
2151 g.fillOval(x-r, y-r, r*2, r*2);
2152 }
2153 @Override
2154 public void run()
2155 {
2156 while(true)
2157 {
2158 if(stopFlag)
2159 break;
2160 if(red>225)
2161 red=0;
2162 if(blue>225)
2163 blue=0;
2164 if(green>225)
2165 green=0;
2166 if ((y + r + dy > bounds().height))
2167 y=0;
2168 try
2169 {
2170 Thread.sleep(100);
2171 }
2172 catch(Exception e)
2173 {
2174 System.out.println(e);
2175 }
2176
2177 // Move the circle.
2178 y += dy;
2179 c=new Color(red=red+20,green,blue);
2180 repaint();
2181 try
2182 {
2183 Thread.sleep(100);
2184 }
2185 catch(Exception e)
2186 {
2187 System.out.println(e);
2188 }
2189
2190 c=new Color(red,green=green+20,blue);
2191 repaint();
2192
2193 try
2194 {
2195 Thread.sleep(100);
2196 }
2197 catch(Exception e)
2198 {
2199 System.out.println(e);
2200 };
2201 // print circle again n again.
2202 repaint();
2203 c=new Color(red,green,blue=blue+20);
2204 repaint();
2205
2206 try
2207 {
2208 Thread.sleep(100);
2209 }
2210 catch(Exception e)
2211 {
2212 System.out.println(e);
2213 }
2214 }
2215 }
2216 @Override
2217 public void stop()
2218 {
2219 stopFlag=true;
2220 t=null;
2221 }
2222}
2223OUTPUT:
2224
2225________________________________________
2226Question-12:
2227CHECKSUM
2228Write a program to demonstrate the knowledge of students in Java Network Programming.
2229Eg., Develop a UDP based client-server application to notify the client about the integrity of data sent from its side.
2230CODE:
2231package checksum;
2232import java.util.Scanner;
2233
2234public class Checksum {
2235
2236 public static long convertDtoB(long d){
2237 if(d==0){
2238 return 0;
2239 }
2240 else{
2241 return (d%2+10*convertDtoB(d/2));
2242 }
2243 }
2244
2245 public static long comp(long d){
2246
2247 if(d==0){
2248 return 1;
2249 }
2250 else{
2251 return 0;
2252 }
2253 }
2254
2255 public static long convertBtoD(long b){
2256 long s=0;
2257 long base=1;
2258 while(b!=0){
2259 long r = b%10;
2260 b=b/10;
2261 s=s+r*base;
2262 base=2*base;
2263 }
2264 return s;
2265 }
2266
2267 public static long complement(long d){
2268 if(d/10==0){
2269 return comp(d%10);
2270 }
2271 long s = (comp(d%10) + 10*(complement(d/10)) );
2272 return s;
2273 }
2274
2275 public static void main(String[] args) {
2276 Scanner sc = new Scanner(System.in);
2277 System.out.println("Enter data to send(in 16 bit form)");
2278 String s = sc.nextLine();
2279 long[] check = new long[s.length()/16];
2280 char[] chArr = s.toCharArray();
2281 int k=0;
2282 for(int i=0;i<chArr.length/16;i++){
2283 String st = "";
2284 for(int j=0;j<16;j++){
2285 st+=chArr[k];
2286 k++;
2287 }
2288 check[i]=Long.parseLong(st);
2289 }
2290 long tempSum = 0;
2291 for(int i=0;i<chArr.length/16;i++){
2292 tempSum += convertBtoD(check[i]);
2293 }
2294 long sum = convertDtoB(tempSum);
2295 System.out.println("Sum :"+sum);
2296 System.out.println("Checksum is :"+complement(sum));
2297 }
2298}
2299OUTPUT:
2300
2301________________________________________
2302Question-13:
2303Write a program to demonstrate the knowledge of students in Remote method invocation.
2304Eg., Develop an RMI application to invoke a remote method that takes two numbers and returns true if one number is an exact multiple of the other and false otherwise.
2305Eg., 5 and 25 -> true
2306 26 and 13 -> true
23074 and 18 -> false
2308*Out of Syllabus*
2309________________________________________
2310Question-14:
2311Write a program to demonstrate the knowledge of students in working with Java collection framework.
2312Eg., Assume only a maximum of 3 courses can be registered by a student for week end semester classes. Create a hashmap ‘h1’ with ‘n’ key-value pairs where keys are the names of students and values are the courses registered by them. Create another hashmap ‘h2’ with ‘m’key-value pairs where keys are the names of courses offered for B.Tech-IT and values are the names of faculty handling the courses. Write appropriate code to
2313- Add or remove a student from h1
2314- Iterate over the maps and display the key-value pairs stored in them
2315- Given a student name, fetch the names of all those who teach him/her.
2316 Eg:, if the elements of h1 are
2317Stud name Courses registered
2318A Python, maths, c
2319B c, c++
2320C C++, physics,chemistry
2321And if the elements of h2 are
2322Course name Faculty
2323Python 111
2324Maths 222
2325C 333
2326C++ 444
2327Physics` 555
2328Chemistry 666
2329Digital electronics 777
2330For the student “B”, faculty should be displayed as 333 and 444.
2331CODE:
2332import java.util.*;
2333
2334public class JavaCollectionsFrameworkDEMO {
2335 private static HashMap<String, String[]> h1;
2336 private static HashMap<String, String> h2;
2337
2338 public static void showh1(HashMap<String, String[]> h1)
2339 {
2340 for (Map.Entry<String,String[]> entry : h1.entrySet())
2341 {
2342 System.out.println("Student: " + entry.getKey());
2343 System.out.print("Subjects: ");
2344 for(String s:h1.get(entry.getKey())){
2345 System.out.print(s+ " , ");
2346 }
2347 System.out.println();
2348 }
2349 }
2350 public static void showh2(HashMap<String, String> h2)
2351 {
2352 for (Map.Entry<String,String> entry : h2.entrySet())
2353 {
2354 System.out.println("Subject: " + entry.getKey());
2355 System.out.println("Teacher: " + entry.getValue());
2356 }
2357 }
2358 public static void main(String[] args){
2359 h1 = new HashMap<String, String[]>();
2360 h2= new HashMap<String,String>();
2361 h1.put("A",new String[] {"PYTHON","MATHS","C"});
2362 h1.put("B",new String[] {"C","C++"});
2363 h1.put("C",new String[] {"C++","PHYSICS","CHEMISTRY"});
2364 h2.put("PYTHON", "111");
2365 h2.put("MATHS", "222");
2366 h2.put("C", "333");
2367 h2.put("C++", "444");
2368 h2.put("PHYSICS", "555");
2369 h2.put("CHEMISTRY", "666");
2370 h2.put("DIGITAL ELECTRONICS", "777");
2371 showh1(h1);
2372 showh2(h2);
2373 System.out.println("Enter the name of the student whose techer you want to know:");
2374 Scanner scan=new Scanner(System.in);
2375 String q=scan.nextLine();
2376 for(String s:h1.get(q))
2377 {
2378 System.out.println(h2.get(s));
2379 }
2380 System.out.println("now press 1 to remove or 2 to add a student to h1");
2381
2382 int choice=scan.nextInt();
2383 scan.nextLine();
2384 if(choice==1)
2385 {
2386 System.out.println("Enter the student you want to delete:");
2387 String z=scan.nextLine();
2388 h1.remove(z);
2389 System.out.println("Element removed");
2390 showh1(h1);
2391 }
2392 if(choice==2)
2393 {
2394 System.out.println("Enter the name of student:");
2395 String name=scan.nextLine();
2396 System.out.println("Enter the subjects");
2397 String subjects=scan.nextLine();
2398 String s[]=subjects.split(",");
2399 h1.put(name,s);
2400 showh1(h1);
2401 }
2402 }
2403}
2404OUTPUT:
2405
2406________________________________________
2407Question-15:
2408Write a program to demonstrate the knowledge of students in Servlet programming.
2409Eg., Assume two cookies are created whenever a VIT student visits the VIT webpage-one for his/her name and the other for his campus. For subsequent visits, he/she should be greeted with the message similar to the one below
2410“Hi Ajay from Chennai Campus!!”.
2411Write a servlet program to do the needful.
2412CODE:
2413Index.html
2414<form action="servlet1" method="post">
2415Name:<input type="text" name="userName"/><br/>
2416Campus:<input type="text" name="campus"/><br/>
2417<input type="submit" value="go"/>
2418</form>
2419FirstServelt.java
2420import java.io.*;
2421import javax.servlet.*;
2422import javax.servlet.http.*;
2423
2424
2425public class FirstServlet extends HttpServlet {
2426
2427 public void doPost(HttpServletRequest request, HttpServletResponse response){
2428 try{
2429
2430 response.setContentType("text/html");
2431 PrintWriter out = response.getWriter();
2432
2433 String n=request.getParameter("userName");
2434 String campus=request.getParameter("campus");
2435 out.print("Hi "+n+ " from "+campus+ " Capmus!!");
2436
2437 Cookie ck=new Cookie("uname",n);//creating cookie object
2438 response.addCookie(ck);//adding cookie in the response
2439
2440 Cookie ck2=new Cookie("campus",campus);//creating cookie object
2441 response.addCookie(ck2);
2442
2443 //creating submit button
2444 out.print("<form action='servlet2' method='post'>");
2445 out.print("<input type='submit' value='go'>");
2446 out.print("</form>");
2447
2448 out.close();
2449
2450 }catch(Exception e){System.out.println(e);}
2451 }
2452}
2453
2454SecondServelt.java
2455import java.io.*;
2456import javax.servlet.*;
2457import javax.servlet.http.*;
2458
2459public class SecondServlet extends HttpServlet {
2460
2461public void doPost(HttpServletRequest request, HttpServletResponse response){
2462 try{
2463
2464 response.setContentType("text/html");
2465 PrintWriter out = response.getWriter();
2466
2467 Cookie ck[]=request.getCookies();
2468 out.print("Hi "+ck[0].getValue()+" from "+ck[1].getValue()+" Capmus!!");
2469
2470 out.close();
2471
2472 }catch(Exception e){System.out.println(e);}
2473 }
2474
2475
2476}
2477
2478OUTPUT:
2479
2480
2481
2482________________________________________
2483
2484JAVA PROGRAMMING
2485LAB ASSESMENT – 5
2486
2487NAME: VARUN NAMBIAR
2488REG NO: 16BCE0809
248912th Feb
2490Q1. Write a program to demonstrate the knowledge of students in multithreading. Eg., Three students A, B and C of B.Tech- II year contest for the PR election. With the total strength of 240 students in II year, simulate the vote casting by generating 240 random numbers (1 for student A, 2 for B and 3 for C) and store them in an array. Create four threads to equally share the task of counting the number of votes cast for all the three candidates. Use synchronized method or synchronized block to update the three count variables. The main thread should receive the final vote count for all three contestants and hence decide the PR based on the values received.
2491CODE:
2492import java.util.*;
2493class counting{
2494 synchronized public int count_votes(int[] arr, int n){
2495 int count=0;
2496 for(int i=0;i<arr.length;i++)
2497 if(arr[i]==n)
2498 count++;
2499 return count;
2500 }
2501 }
2502
2503class thread1 extends Thread{
2504 public int freq;
2505 int[] votes;
2506 counting c;
2507 thread1(counting c,int[] votes){
2508 this.c=c;
2509 this.votes=votes;
2510 }
2511 public void run(){
2512 freq=c.count_votes(votes,1);
2513 }
2514 public int output(){
2515 return (c.count_votes(votes,1));
2516 }
2517 }
2518
2519class thread2 extends Thread{
2520 public int freq;
2521 int[] votes;
2522 counting c;
2523 thread2(counting c,int[] votes){
2524 this.c=c;
2525 this.votes=votes;
2526 }
2527 public void run(){
2528 freq=c.count_votes(votes,2);
2529 }
2530 public int output(){
2531 return c.count_votes(votes,2);
2532 }
2533 }
2534
2535class thread3 extends Thread{
2536 public int freq;
2537 int[] votes;
2538 counting c;
2539 thread3(counting c,int[] votes){
2540 this.c=c;
2541 this.votes=votes;
2542 }
2543 public void run(){
2544 freq=c.count_votes(votes,3);
2545 }
2546 public int output(){
2547 return c.count_votes(votes,3);
2548 }
2549 }
2550
2551class thread4 extends Thread{
2552 int a;
2553 int b;
2554 int c;
2555 thread4(int a,int b,int c){
2556 this.a=a;
2557 this.b=b;
2558 this.c=c;
2559 }
2560 public void run(){}
2561 public String output(){
2562 return ((a>b)?((a>c)?("A"):("C")):((b>c)?("B"):("C")));
2563 }
2564
2565}
2566
2567class elec{
2568 public static void main(String[] args){
2569 Random rand = new Random();
2570 int[] votes = new int[240];
2571 System.out.println();
2572 for(int i=0;i<votes.length;i++){
2573 votes[i] = rand.nextInt(3)+1;
2574 }
2575 counting c = new counting();
2576 thread1 t1 = new thread1(c,votes);
2577 t1.start();
2578 int v1=t1.output();
2579 thread2 t2 = new thread2(c,votes);
2580 t2.start();
2581 int v2=t2.output();
2582 thread3 t3 = new thread3(c,votes);
2583 t3.start();
2584 int v3=t3.output();
2585 System.out.println();
2586 System.out.println("A: "+v1);
2587 System.out.println("B: "+v2);
2588 System.out.println("C: "+v3);
2589 System.out.println();
2590 thread4 t4 = new thread4(v1,v2,v3);
2591 t4.start();
2592 String winner=t4.output();
2593 System.out.println("Winner is "+winner);
2594 }
2595}
2596
2597
2598
2599
2600CODE SNAPSHOT
2601
2602
2603OUTPUT:
2604
2605QUES.3.
2606Write a program to demonstrate the knowledge of students in File handling. Eg., Define a class ‘Donor’ to store the below mentioned details of a blood donor. Name, age, Address, Contact number, blood group, date of last donation Create ‘n’ objects of this class for all the regular donors at Vellore. Write these objects to a file. Read these objects from the file and display only those donors’ details whose blood group is ‘A+ve’ and had not donated for the recent six months.
2607CODE:
2608import java.util.*;
2609import java.text.ParseException;
2610import java.text.SimpleDateFormat;
2611import java.time.*;
2612import java.io.*;
2613import java.io.FileReader;
2614class last{
2615 public static void main(String a[])throws IOException{
2616
2617 FileWriter fw=new FileWriter("input.txt");
2618 String name;
2619 int age;
2620 String address;
2621 String num;
2622 String bg;
2623 String ld;
2624 SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
2625 Date d1=null;
2626 Date date2=null;
2627 Scanner scan=new Scanner(System.in);
2628
2629 for(int i=0;i<2;i++){
2630 String in="";
2631 System.out.println("name");
2632 name=scan.nextLine();
2633 System.out.println("age");
2634 age=scan.nextInt();
2635 scan.nextLine(); // skip the newline character
2636
2637 System.out.println("address");
2638 address=scan.nextLine();
2639 System.out.println("number");
2640 num=scan.nextLine();
2641 System.out.println("bg");
2642 bg=scan.nextLine();
2643 System.out.println("ld");
2644 ld=scan.nextLine();
2645
2646 in="name: "+name+" age: "+age+" address: "+address+" num: "+num+" bloodgroup: "+bg+" lastdate: "+ld+"\n";
2647 fw.write(in);
2648 }
2649
2650 fw.close();
2651
2652 FileReader fr=new FileReader("input.txt");
2653 String s="";
2654 int i;
2655 while((i=fr.read())!=-1)
2656 s+=(char)i;
2657 fr.close();
2658String arr[]=s.split("\n");
2659
2660for(int k=0;k<arr.length;k++){
2661 String ar[]=arr[k].split(" ");
2662 String date=ar[11];
2663 try {
2664 //Parsing the String
2665 d1 = dateFormat.parse(date);
2666 date2 = dateFormat.parse("21-02-2019");
2667
2668 } catch (ParseException e) {
2669 // TODO Auto-generated catch block
2670 e.printStackTrace();
2671}
2672long d=date2.getTime()-d1.getTime();
2673d=((((d/60)/60)/24)/1000)/30;
2674
2675 if(ar[9].equals("A+")&d>6) //condition of A+ and 6 months
2676 System.out.println(arr[k]);
2677}
2678 }
2679 }
2680
268119th Feb
26821. Java Program to Replace First Letter of Every Word with Capital Letter.
2683Code:
2684CODE:
2685import java.io.FileReader;
2686import java.util.*;
2687import java.io.*;
2688public class q1 {
2689 public static void main(String args[])throws Exception{
2690 FileReader fr=new FileReader("input.txt");
2691 String s="";
2692 int i;
2693 while((i=fr.read())!=-1)
2694 s+=(char)i;
2695 fr.close();
2696 String arr[]=s.split(" ");
2697 for(int j=0;j<arr.length;j++){
2698 String a=arr[j].substring(0,1).toUpperCase()+arr[j].substring(1);
2699 arr[j]=a;
2700 }
2701 String st="";
2702
2703 for(int j=0;j<arr.length;j++){
2704 st+=arr[j];
2705 st+=" ";
2706 }
2707 System.out.println(st);
2708 FileWriter fw=new FileWriter("input.txt");
2709 fw.write(st);
2710 fw.close();
2711
2712 }
2713}
2714
2715FILE:
2716
2717
2718
2719OUTPUT:
2720
2721
2722FILE AFTER:
2723
2724
2725
27262. Java Program to Reverse the Contents of a File and Print it
2727CODE:
2728import java.util.*;
2729import java.io.*;
2730import java.io.FileReader;
2731
2732class q2{
2733 public static void main(String a[])throws Exception{
2734 FileReader fr=new FileReader("input1.txt");
2735 String s="";
2736 int i;
2737 while((i=fr.read())!=-1)
2738 s+=(char)i;
2739 fr.close();
2740 String st="";
2741 for(int j=0;j<s.length();j++){
2742 st+=s.charAt(s.length()-1-j);
2743 }
2744 FileWriter fw=new FileWriter("input.txt");
2745 fw.write(st);
2746 fw.close();
2747
2748 }
2749}
2750FILE BEFORE:
2751
2752OUTPUT:
2753
2754FILE AFTER:
2755
2756
27574. Java Program to Convert the Content of File to LowerCase.
2758CODE:
2759import java.util.*;
2760import java.io.*;
2761import java.io.FileReader;
2762
2763class q4{
2764 public static void main(String a[])throws Exception{
2765 FileReader fr=new FileReader("input.txt");
2766 String s="";
2767 int i;
2768 while((i=fr.read())!=-1)
2769 s+=(char)i;
2770 fr.close();
2771 String st="";
2772 for(int j=0;j<s.length();j++){
2773 st+=s.substring(j,j+1).toLowerCase();
2774 }
2775 FileWriter fw=new FileWriter("input.txt");
2776 fw.write(st);
2777 fw.close();
2778
2779 }
2780}
2781
2782FILE BEFORE:
2783
2784OUTPUT:
2785
2786FILE AFTER:
2787
2788
27895. Java Program to Create and Count Number of Characters in a File.
2790CODE:
2791import java.io.*;
2792import java.util.*;
2793class q5{
2794 public static void main(String[] args) throws Exception{
2795 Scanner s = new Scanner(System.in);
2796 System.out.println("Enter the string to enter into file: ");
2797 String str=s.nextLine();
2798 FileWriter fw=new FileWriter("fl.txt");
2799 System.out.println("Writing the file... ");
2800 fw.write(str);
2801 fw.close();
2802 FileReader fr=new FileReader("fl.txt");
2803 int i;
2804 int c=0;
2805 System.out.println("Reading the file... ");
2806 while((i=fr.read())!=-1){
2807 if(i!=32)
2808 c++;
2809 }
2810 System.out.println("Number of characters in the file are: "+c);
2811 }
2812}
2813
2814
2815
2816
2817
2818
2819
2820OUTPUT:
2821
2822
28236. Java Program to Join Lines of Two given Files and Store them in a new file
2824CODE:
2825import java.io.*;
2826import java.util.*;
2827class q6{
2828 public static void main(String[] args) throws Exception{
2829 FileReader fr1=new FileReader("file1.txt");
2830 int i;
2831 String s1 = "";
2832 System.out.println();
2833 System.out.println("Reading 1st file... ");
2834 while((i=fr1.read())!=-1){
2835 s1+=(char)i;
2836 }
2837 s1=s1.substring(0,(s1.length()-1)).concat(" ");
2838 fr1.close();
2839 System.out.println("Contents of 1st file: " + s1);
2840 System.out.println();
2841 String s2 = "";
2842 FileReader fr2=new FileReader("file2.txt");
2843 System.out.println("Reading 2nd file... ");
2844 while((i=fr2.read())!=-1){
2845 s2+=(char)i;
2846 }
2847 fr2.close();
2848 System.out.println("Contents of 2nd file: " + s2);
2849 System.out.println("Creating and writing merged contents onto new file...");
2850 System.out.println();
2851 String s3 = s1 +""+ s2;
2852 FileWriter fw = new FileWriter("output.txt");
2853 fw.write(s3);
2854 fw.close();
2855 System.out.print("Contents of ouput file: " + s3);
2856 System.out.println();
2857 }
2858}
2859OUTPUT:
2860
2861
2862
2863JAVA COLLECTIONS:
2864ARRAY LIST
2865
2866 import java.util.*;
2867 class TestJavaCollection1{
2868 public static void main(String args[]){
2869 ArrayList<String> list=new ArrayList<String>();
2870 list.add("Ravi");
2871 list.add("Vijay");
2872 list.add("Ravi");
2873 list.add("Ajay");
2874 Iterator itr=list.iterator();
2875 while(itr.hasNext()){
2876 System.out.println(itr.next());
2877 }
2878 }
2879 }
2880
2881LIST ITERATOR
2882
2883CODE:
2884
2885import java.util.*;
2886class ListIteratorExample1{
2887public static void main(String args[]){
2888List<String> al = new ArrayList<String>();
2889al.add("Amit");
2890al.add("Vijay");
2891al.add("Kumar");
2892al.add(1,"Sachin");
2893ListIterator<String> itr = al.listIterator();
2894while(itr.hasNext()){
2895
2896 System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
2897 }
2898 System.out.println("Traversing elements in backward direction");
2899 while(itr.hasPrevious()){
2900
2901 System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
2902 }
2903}
2904OUTPUT:
2905
2906HASHSET
2907
2908CODE:
2909 import java.util.*;
2910 class HashSet3{
2911 public static void main(String args[]){
2912 HashSet<String> set=new HashSet<String>();
2913 set.add("Ravi");
2914 set.add("Vijay");
2915 set.add("Arun");
2916 set.add("Sumit");
2917 System.out.println("An initial list of elements: "+set);
2918 set.remove("Ravi");
2919 System.out.println("After invoking remove(object) method: "+set);
2920 HashSet<String> set1=new HashSet<String>();
2921 set1.add("Ajay");
2922 set1.add("Gaurav");
2923 set.addAll(set1);
2924 System.out.println("Updated List: "+set);
2925 set.removeAll(set1);
2926 System.out.println("After invoking removeAll() method: "+set);
2927 set.removeIf(str->str.contains("Vijay"));
2928 System.out.println("After invoking removeIf() method: "+set);
2929 set.clear();
2930 System.out.println("After invoking clear() method: "+set);
2931 }
2932 }
2933
2934
2935
2936
2937OUTPUT:
2938
2939TREESET
2940CODE1:
2941 import java.util.*;
2942 class TreeSet4{
2943 public static void main(String args[]){
2944 TreeSet<String> set=new TreeSet<String>();
2945 set.add("A");
2946 set.add("B");
2947 set.add("C");
2948 set.add("D");
2949 set.add("E");
2950 System.out.println("Initial Set: "+set);
2951
2952 System.out.println("Reverse Set: "+set.descendingSet());
2953
2954 System.out.println("Head Set: "+set.headSet("C", true));
2955
2956 System.out.println("SubSet: "+set.subSet("A", false, "E", true));
2957
2958 System.out.println("TailSet: "+set.tailSet("C", false));
2959 }
2960 }
2961
2962output:
2963
2964
2965
2966
2967
2968
2969
2970
2971MAP INTERFACE
2972
2973CODE:
2974import java.util.*;
2975class MapExample2{
2976public static void main(String args[]){
2977Map<Integer,String> map=new HashMap<Integer,String>();
2978map.put(100,"Amit");
2979map.put(101,"Vijay");
2980map.put(102,"Rahul");
2981for(Map.Entry m:map.entrySet()){
2982System.out.println(m.getKey()+" "+m.getValue());
2983}
2984map.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(System.out::println);
2985map.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())).forEach(System.out::println);
2986}
2987}
2988
2989OUTPUT:
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020HASHMAP
3021
3022CODE:
3023 import java.util.*;
3024 class HashMap1{
3025 public static void main(String args[]){
3026 HashMap<Integer,String> hm=new HashMap<Integer,String>();
3027 System.out.println("Initial list of elements: "+hm);
3028 hm.put(100,"Amit");
3029 hm.put(101,"Vijay");
3030 hm.put(102,"Rahul");
3031
3032 System.out.println("After invoking put() method ");
3033 for(Map.Entry m:hm.entrySet()){
3034 System.out.println(m.getKey()+" "+m.getValue());
3035 }
3036
3037 hm.putIfAbsent(103, "Gaurav");
3038 System.out.println("After invoking putIfAbsent() method ");
3039 for(Map.Entry m:hm.entrySet()){
3040 System.out.println(m.getKey()+" "+m.getValue());
3041 }
3042 HashMap<Integer,String> map=new HashMap<Integer,String>();
3043 map.put(104,"Ravi");
3044 map.putAll(hm);
3045 System.out.println("After invoking putAll() method ");
3046 for(Map.Entry m:map.entrySet()){
3047 System.out.println(m.getKey()+" "+m.getValue());
3048 }
3049 map.remove(100);
3050 System.out.println("Updated list of elements: "+map);
3051
3052 }
3053 }
3054
3055OUTPUT:
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065JDBC SERVLET:
3066QUES1
3067<!DOCTYPE html>
3068<!--
3069To change this license header, choose License Headers in Project Properties.
3070To change this template file, choose Tools | Templates
3071and open the template in the editor.
3072-->
3073<html>
3074 <head>
3075 <title>TODO supply a title</title>
3076 <meta charset="UTF-8">
3077 <meta name="viewport" content="width=device-width, initial-scale=1.0">
3078 </head>
3079 <body>
3080 <form action="NewServlet" method="post">
3081 <p> Teacher's Name <input type="text" name="username"></p>
3082 <p>Password <input type="password" name="pass"></p>
3083 <input type="submit" value="submit">
3084 </form>
3085 </body>
3086</html>
3087
3088
3089
3090
3091
3092*******************************************************************************************
3093
3094
3095
3096import java.io.IOException;
3097import java.io.PrintWriter;
3098import java.sql.*;
3099import javax.servlet.ServletException;
3100import javax.servlet.http.HttpServlet;
3101import javax.servlet.http.HttpServletRequest;
3102import javax.servlet.http.HttpServletResponse;
3103
3104/**
3105 *
3106 * @author 16bce2065
3107 */
3108public class NewServlet extends HttpServlet {
3109
3110
3111 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
3112 throws ServletException, IOException {
3113 response.setContentType("text/html;charset=UTF-8");
3114 try (PrintWriter out = response.getWriter()) {
3115 /* TODO output your page here. You may use following sample code. */
3116 out.println("<!DOCTYPE html>");
3117 out.println("<html>");
3118 out.println("<head>");
3119 out.println("<title>Servlet NewServlet</title>");
3120 out.println("</head>");
3121 out.println("<body>");
3122 /* out.println("<h1>Servlet NewServlet at " + request.getParameter("username") + "</h1>");
3123 out.println("<h1>Servlet NewServlet at " + request.getParameter("pass"));*/
3124
3125 Class.forName("com.mysql.jdbc.Driver");
3126 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test","lol","karan1122");
3127 Statement st = conn.createStatement();
3128 ResultSet rs = st.executeQuery("Select * from test");
3129
3130 float sum=0;
3131 float avg=0;
3132 int num_stud=0;
3133 while(rs.next()){
3134 String id=rs.getString("reg");
3135 String name=rs.getString("name");
3136 float m1=rs.getInt("m1");
3137 float m2=rs.getInt("m2");
3138 float m3=rs.getInt("m3");
3139 sum+=m1+m2+m3;
3140 num_stud++;
3141 out.println(id+" "+name);
3142 out.println("<br>");
3143 out.println("Average of "+name+" is:"+((m1+m2+m3)/3)+"<br><br>");
3144 /* out.println(id+"<br>");
3145 out.println(name+"<br></h1>");*/
3146
3147 }
3148 num_stud*=3;
3149
3150 avg=sum/num_stud;
3151 out.println("Average of class is: "+avg);
3152 out.println("</body>");
3153 out.println("</html>");
3154
3155 }
3156 catch(Exception e){
3157 e.printStackTrace();
3158 }
3159 }
3160
3161 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
3162 /**
3163 * Handles the HTTP <code>GET</code> method.
3164 *
3165 * @param request servlet request
3166 * @param response servlet response
3167 * @throws ServletException if a servlet-specific error occurs
3168 * @throws IOException if an I/O error occurs
3169 */
3170 @Override
3171 protected void doGet(HttpServletRequest request, HttpServletResponse response)
3172 throws ServletException, IOException {
3173 processRequest(request, response);
3174 }
3175
3176 /**
3177 * Handles the HTTP <code>POST</code> method.
3178 *
3179 * @param request servlet request
3180 * @param response servlet response
3181 * @throws ServletException if a servlet-specific error occurs
3182 * @throws IOException if an I/O error occurs
3183 */
3184 @Override
3185 protected void doPost(HttpServletRequest request, HttpServletResponse response)
3186 throws ServletException, IOException {
3187 processRequest(request, response);
3188 }
3189
3190 /**
3191 * Returns a short description of the servlet.
3192 *
3193 * @return a String containing servlet description
3194 */
3195 @Override
3196 public String getServletInfo() {
3197 return "Short description";
3198 }// </editor-fold>
3199
3200}
3201
3202
3203
3204
3205
3206
3207
3208QUES2.
3209
3210
3211import java.io.IOException;
3212import java.io.PrintWriter;
3213import java.sql.*;
3214import javax.servlet.ServletException;
3215import javax.servlet.http.HttpServlet;
3216import javax.servlet.http.HttpServletRequest;
3217import javax.servlet.http.HttpServletResponse;
3218
3219/**
3220 *
3221 * @author 16bce2065
3222 */
3223public class q2servlet extends HttpServlet {
3224
3225
3226 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
3227 throws ServletException, IOException {
3228 response.setContentType("text/html;charset=UTF-8");
3229 try (PrintWriter out = response.getWriter()) {
3230 /* TODO output your page here. You may use following sample code. */
3231 out.println("<!DOCTYPE html>");
3232 out.println("<html>");
3233 out.println("<head>");
3234 out.println("<title>Servlet NewServlet</title>");
3235 out.println("</head>");
3236 out.println("<body>");
3237 /* out.println("<h1>Servlet NewServlet at " + request.getParameter("username") + "</h1>");
3238 out.println("<h1>Servlet NewServlet at " + request.getParameter("pass"));*/
3239
3240 Class.forName("com.mysql.jdbc.Driver");
3241 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test","lol","karan1122");
3242 Statement st = conn.createStatement();
3243 ResultSet rs = st.executeQuery("Select * from emp");
3244
3245
3246
3247 while(rs.next()){
3248 String id=rs.getString("id");
3249 String name=rs.getString("name");
3250 String designation=rs.getString("designation");
3251 int salary=rs.getInt("salary");
3252 out.println("Name: "+name);
3253 out.println("<br>");
3254 out.println("Designation: " +designation);
3255 out.println("<br>");
3256 if(designation.equals("supervisor")){
3257 out.println("ID: "+id);
3258 out.println("<br>");
3259 out.println("Salary: "+salary);
3260 }
3261 out.println("<br>");
3262 out.println("<br>");
3263
3264 /* out.println(id+"<br>");
3265 out.println(name+"<br></h1>");*/
3266
3267 }
3268
3269 out.println("</body>");
3270 out.println("</html>");
3271
3272 }
3273 catch(Exception e){
3274 e.printStackTrace();
3275 }
3276 }
3277
3278 // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
3279 /**
3280 * Handles the HTTP <code>GET</code> method.
3281 *
3282 * @param request servlet request
3283 * @param response servlet response
3284 * @throws ServletException if a servlet-specific error occurs
3285 * @throws IOException if an I/O error occurs
3286 */
3287 @Override
3288 protected void doGet(HttpServletRequest request, HttpServletResponse response)
3289 throws ServletException, IOException {
3290 processRequest(request, response);
3291 }
3292
3293 /**
3294 * Handles the HTTP <code>POST</code> method.
3295 *
3296 * @param request servlet request
3297 * @param response servlet response
3298 * @throws ServletException if a servlet-specific error occurs
3299 * @throws IOException if an I/O error occurs
3300 */
3301 @Override
3302 protected void doPost(HttpServletRequest request, HttpServletResponse response)
3303 throws ServletException, IOException {
3304 processRequest(request, response);
3305 }
3306
3307 /**
3308 * Returns a short description of the servlet.
3309 *
3310 * @return a String containing servlet description
3311 */
3312 @Override
3313 public String getServletInfo() {
3314 return "Short description";
3315 }// </editor-fold>
3316
3317}
3318
3319
3320**************************************************************************************************
3321
3322
3323<!DOCTYPE html>
3324<!--
3325To change this license header, choose License Headers in Project Properties.
3326To change this template file, choose Tools | Templates
3327and open the template in the editor.
3328-->
3329<html>
3330 <head>
3331 <title>TODO supply a title</title>
3332 <meta charset="UTF-8">
3333 <meta name="viewport" content="width=device-width, initial-scale=1.0">
3334 </head>
3335 <body>
3336 <div>TODO write content</div>
3337 <form method='post' action='q2servlet.java'>
3338 <button name="sub">View Details</button>
3339 </form>
3340 </body>
3341</html>