BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 2 | P a g e D E P A R T M E N T O F I S E S N E H A K Course outcomes (Course Skill Set): At the end of the course, the student will be able to: CO 1. Apply appropriate collection class/interface to solve the given problem CO 2. Demonstrate the concepts of String operations in Java CO 3. Apply the concepts of Swings to build Java applications CO 4. Develop web based applications using Java servlets and JSP CO 5. Use JDBC to build database application BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 3 | P a g e D E P A R T M E N T O F I S E S N E H A K 1. I mplement a java program to demonstrate creating an ArrayList, adding elements, removing elements ,sorting elements of ArrayList. Also illustrate the use of toArray() method ***************************************************************************************** package prg ram 1; import java.util.*; public class prg ram 1 { public static void main(String[] args) { // Create an array list ArrayList<Integer> list = new ArrayList<Integer>( ); ArrayList<Integer> list1 = new ArrayList<Integer>( ); // Add elements to array list list.add(30); list.add(20); list.add(10); list.add(40); // Display the array list System.out.println("ArrayList: " + list); // Remove an element from array list list.remove(2); System.out.println("Updated ArrayList: " + list); // Access the element int element = list.get(1); System.out.println("Accessed Element: " + element); System.out.print("Iterating over ArrayList: "); // Access the element by iteration for (int i = 0; i < list.size(); i++) System.out.print(list.get(i) + " "); System.out.println("Before sorting:" +list); // Sorting the list Collections.sort(list); System.out.println("After sorting:" +list); //toarray method Object[] arr= list.toArray(); System.out.println("Elements of Arraylist:" +"as Array:" + Arrays.toString(arr)); } } BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 4 | P a g e D E P A R T M E N T O F I S E S N E H A K OUTPUT ************************************** ArrayList: [30, 20, 10, 40] Updated ArrayList: [30, 20, 40] Accessed Element: 20 Iterating over ArrayList: 30 20 40 Before sorting:[30, 20, 40] After sorting:[20, 30, 40] Elements of Arraylist:as Array:[20, 30, 40] BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 5 | P a g e D E P A R T M E N T O F I S E S N E H A K 2. Develop a program to read random numbers between a given range that are multiples of 2 and 5, sort the numbers according to tens place using comparator. *********************************************************************************** import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Random; public class Main { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); Random random = new Random(); // Generate random numbers between 10 and 100 that are multiples of 2 and 5 while (numbers.size() < 10) { int number = random.nextInt(21) * 5; if (number % 2 == 0 && number >= 10 && number <= 100) { numbers.add(number); } } // Sort the numbers according to the tens place Collections.sort(numbers, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(o1 / 10, o2 / 10); } }); // Print the sorted numbers for (int number : numbers) { System.out.println(number); } } } BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 6 | P a g e D E P A R T M E N T O F I S E S N E H A K OUTPUT ********************** 10 10 10 10 20 30 50 60 90 90 BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 7 | P a g e D E P A R T M E N T O F I S E S N E H A K 3. Implement a java program to illustrate storing user defined classes in collection. ************************************************************************************** // A simple mailing list example. import java.util.*; class Address { private String name; private String street; private String city; private String state; private String code; Address(String n, String s, String c,String st, String cd) { name = n; street = s; city = c; state = st; code = cd; } public String toString() { return name + " \ n" + street + " \ n" + city + " " + state + " " + code; } } class MailList { public static void main(String args[]) { LinkedList<Address> ml = new LinkedList<Address>(); // Add elements to the linked list. ml.add(new Address("J.W. West", "11 Oak Ave","Urbana", "IL", "61801")); ml.add (new Address("Ralph Baker", "1142 Maple Lane","Mahomet", "IL", "61853")); ml.add(new Address("Tom Carlton", "867 Elm St","Champaign", "IL", "61820")); // Display the mailing list. for(Address element : ml) System.out.println(element + " \ n"); System.out.println(); } } BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 8 | P a g e D E P A R T M E N T O F I S E S N E H A K OUTPUT ******************** J.W. West 11 Oak Ave Urbana IL 61801 Ralph Baker 1142 Maple Lane Mahomet IL 61853 Tom Carlton 867 Elm St Champaign IL 61820 BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 9 | P a g e D E P A R T M E N T O F I S E S N E H A K 4. Implement a java program to illustrate the use of different types of string class constructors. ********************************************************************************* package program4; import java.io.UnsupportedEncodingException; import java.util .*; public class Program4 { public static void main(String args []) throws UnsupportedEncodingException { char c []= { 'j' , 'a' , 'v' , 'a' }; String s1 = new String(); System. out .println( "default destructor:" + s1 ); // construct one string from another String s2 = new String( c ); String s3 = new String( s2 ); System. out .println( "String object: " + s2 ); System. out .println( "String object:" + s3 ); // Construct string from subset of char array byte ascii []= {65,66,67,68,69,70}; String s4 = new String( ascii ); System. out .println( s4 ); String s5 = new String( ascii ,2,3); System. out .println( s5 ); //Construct string from string builder StringBuilder s6 = new StringBuilder( "Hello" ); System. out .println( s6 .toString()); s6 .append( " World!" ); System. out .println( s6 .toString()); StringBuffer s7 = new StringBuffer( "Hello " ); s7 .insert(1, "Java" ); //now original string is changed System. out .println( " Now orginal string is:" + s7 ); byte [] byteArrayOffsetCharset = {72, 101, 108, 108, 111,113,117}; String str8 = new String( byteArrayOffsetCharset , 6, 1, "UTF - 8" ); System. out .println( "Constructor with a byte array, offset, length, and charset: " + str8 ); } } BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 10 | P a g e D E P A R T M E N T O F I S E S N E H A K OUTPUT ********************************************************************************* default destructor: String object: java String object:java ABCDEF CDE Hello Hello World! Now orginal string is:HJavaello Constructor with a byte array, offset, length, and charset: u BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 11 | P a g e D E P A R T M E N T O F I S E S N E H A K 5. Implement a java program to illustrate the use of different types of character extraction, string comparison, string search and string modification methods. ********************************************************************************* public class StringDemo { public static void main(String[] args) { String S="This is a demo of the getchars method"; int Start=10; int end=14; char buf[]=new char[end - Start]; S.getChars(Start, end, buf, 0); System.out.println(buf); char ch; ch="abc".charAt(1); System.out.println(ch); String s1="Hello"; byte[] barr=s1.getBytes(); for(int i=0;i<barr.length;i++) {System.out.println(barr[i]); } char[]Sh =s1.toCharArray(); for(int i=0;i< Sh.length;i++) {System.out.println(Sh[i]); } String s2="good bye"; String s3="Hello"; System.out.println(s1+"equals"+s2+" - >"+s1.equals(s2)); System.out.println(s1+"equalsIsIgnoreCase"+s3+" - >"+s1.equalsIgnoreCase(s3)); System.out.println(s1.endsWith(s3)); System.out.println(s1.startsWith(s3)); System.out.println(s1+"=="+s2+" - >"+(s1==s2)); String arr[]= {"Now","is","the","time"}; for(int j=0;j<arr.length;j++) { for(int i=j+1;i<arr.length;i++) { if(arr[i].compareTo(arr[j])<0) { String t=arr[j]; arr[j]=arr[i]; arr[i]=t; } } System.out.println(arr[j]); } System.out.println("Indexof(e)="+s1.indexOf('e')); System.out.println("lastIndexOf(bye)="+s2.lastIndexOf("bye")); BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 12 | P a g e D E P A R T M E N T O F I S E S N E H A K String s4="this is a test.this is too"; String Search="is"; String Sub="was"; String result=" "; String s5=s1.concat("two"); System.out.println(s5); String s6="Hello".replace('1', 'w'); System.out.println(s6); String s7=" Helloworld ".trim(); System.out.println(s7); String upper=s1.toUpperCase(); String lower=s1.toLowerCase(); System.out.println(upper); System.out.println(lower); int i; do {i=s4.indexOf(s4); if(i!= - 1) {result=s4.substring(0,i); result=result+Sub; result=result+s4.substring(i+s4.length()); } } while(i!= - 1); } } OUTPUT ************************ demo b 72 101 108 108 111 H e l l o Helloequalsgood bye - >false HelloequalsIsIgnoreCaseHello - >true true true Hello==good bye - >false Now BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 13 | P a g e D E P A R T M E N T O F I S E S N E H A K is the time Indexof(e)=1 lastIndexOf(bye)=5 Hellotwo Hello Helloworld HELLO hello BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 14 | P a g e D E P A R T M E N T O F I S E S N E H A K 6. Implement a java program to illustrate the use of different types of StringBuffer methods public class Program6Demo { public static void main(String[] args) { StringBuffer sb = new StringBuffer("Hello"); System.out.println("Buffer:"+sb); System.out.println("Length:" +sb.length()); System.out.println("Capacity:"+ sb.capacity()); System.out.println("charAt(1)before="+sb.charAt(1)); sb.setCharAt(1, 'i'); System.out.println("charAt(1)After="+sb.charAt(1)); String s; int a=42; int i; StringBuffer sbb=new StringBuffer(40); s=sbb.append("a=").append(a).append("!").toString(); System.out.println(s); sb.insert(2, "like"); System.out.println(sb); sb.reverse(); System.out.println(sb); sb.delete(4, 7); System.out.println("After delete:"+sb); sb.deleteCharAt(0); System.out.println("After delete charAt:"+ sb); sb.replace(5, 7, "wo"); System.out.println("After replace:"+sb); System.out.println("String subString:"+sb.substring(1)); i=sb.indexOf("One"); System.out.println("First Index:"+i); i=sb.lastIndexOf("One"); System.out.println("Last Index:"+i); } } OUTPUT Buffer:Hello Length:5 Capacity:21 charAt(1)before=e charAt(1)After=i a=42! Hilikello ollekiliH After delete:olleiH BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 15 | P a g e D E P A R T M E N T O F I S E S N E H A K After delete charAt:lleiH After replace:lleiHwo String subString:leiHwo First Index: - 1 Last Index: - 1 BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 16 | P a g e D E P A R T M E N T O F I S E S N E H A K 7. Demonstrate a swing event handling application that creates 2 buttons Alpha and Beta and displays the text “Alpha pressed” when alpha button is clicked and “Beta pressed” when beta button is clicked. package program7; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class Program7 { private JFrame frame; JLabel jlab; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Program7 window = new Program7(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public Program7() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { JFrame jfrm = new JFrame("An Event Example"); // Specify FlowLayout for the layout manager. jfrm.setLayout(new GridLayout()); BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 17 | P a g e D E P A R T M E N T O F I S E S N E H A K // Give the frame an initial size. jfrm.setSize(220, 90); // Terminate the program when the user closes the application. jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Make two buttons. JButton jbtnAlpha = new JButton("Alpha"); JButton jbtnBeta = new JButton("Beta"); // Add action listener for Alpha and Beta jbtnAlpha.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { jlab.setText("Alpha was pressed."); } }); jbtnBeta.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { jlab.setText("Beta was pressed."); } }); // Add the buttons to the content pane. jfrm.add(jbtnAlpha); jfrm.add(jbtnBeta); // Create a text - based label. jlab = new JLabel("Press a button."); // Add the label to the content pane. jfrm.add(jlab); // Display the frame. jfrm.setVisible(true); } } OUTPUT ********************** BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 18 | P a g e D E P A R T M E N T O F I S E S N E H A K 8. A program to display greeting message on the browser “Hello UserName”, “How Are You?”, accept username from the client using servlet. Step 1: Set up a Dynamic Web Project: Open Eclipse. Go to "File" > "New" > "Dynamic Web Project". Enter a project name and click "Next". Choose a Target Runtime (e.g., Apache Tomcat) and click "Next". Configure the project settings as desired and click "Finish". 2. Create a Servlet: Right - click on the src folder in your Dynamic Web Project. Go to "New" > "Servlet". Enter a package name (or use the default) and specify a name for your servlet. Click "Next". Configure the servlet settings (such as URL mapping) and click "Next". Optionally, you can select the checkboxes to generate doGet() and/or doPost() methods if you want to handle GET or POST requests. Click "Finish". Add below code under the dopost() String username = request.getParameter("username"); // Set response content type response.setContentType("text/html"); // Get PrintWriter object java.io.PrintWriter out = response.getWriter(); // Generate HTML response out.println("<html>"); out.println("<head>"); out.println("<title>Greeting</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello, " + username + "</h1>"); out.println("<p>How are you?</p>"); out.println("</body>"); out.println("</html>"); Code will look like: import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 19 | P a g e D E P A R T M E N T O F I S E S N E H A K /** * Servlet implementation class GreetingServlet */ public class GreetingServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public GreetingServlet() { super(); // TODO Auto - generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto - generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto - generated method stub String username = request.getParameter("username"); // Set response content type response.setContentType("text/html"); // Get PrintWriter object java.io.PrintWriter out = response.getWriter(); // Generate HTML response out.println("<html>"); out.println("<head>"); out.println("<title>Greeting</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Hello, " + username + "</h1>"); out.println("<p>How are you?</p>"); out.println("</body>"); out.println("</html>"); doGet(request, response); } BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 20 | P a g e D E P A R T M E N T O F I S E S N E H A K } 3. Right click on webapp - > create new html file and write the below code: <!DOCTYPE html> <html> <head> <title>Greeting Form</title> </head> <body> <form action="GreetingServlet" method="post"> Enter your name: <input type="text" name="username"> <input type="submit" value="Submit"> </form> </body> </html> 4. Run the Servlet: To run the servlet, you need to deploy the Dynamic Web Project to a server (e.g., Apache Tomcat). Right - click on your project. Go to "Run As" > "Run on Server". Choose your server (e.g., Apache Tomcat) and click "Next". Click "Finish" to deploy and run your application. OUTPUT ************ Login Page BIS402 ADVANCED JAVA MANUAL 2022 SCHEME 21 | P a g e D E P A R T M E N T O F I S E S N E H A K 9. A servlet program to display the name, USN, and total marks by accepting student detail Step 1: Set up a Dynamic Web Project: Open Eclipse. Go to "File" > "New" > "Dynamic Web Project". Enter a project name and click "Next". Choose a Target Runtime (e.g., Apache Tomcat) and click "Next". Configure the project settings as desired and click "Finish". 2. Create a Servlet: Right - click on the src folder in your Dynamic Web Project. Go to "New" > "Servlet". Enter a package name (or use the default) and specify a name for your servlet. Click "Next". Configure the servlet settings (such as URL mapping) and click "Next". Optionally, you can select the checkboxes to generate doGet() and/or doPost() methods if you want to handle GET or POST requests. Click "Finish". Add below code under the dopost(): // Get student details from request parameters String name = request.getParameter("name"); String usn = request.getParameter("usn"); int totalMarks = Integer.parseInt(request.getParameter("totalMarks")); // Calculate percentage double percentage = (totalMarks / 600.0) * 100; // Set response content type