Posts

Showing posts with the label Advanced Java Programming

What is servlet? Discuss its life cycle.

Servlets are small programs that execute on the server side of a Web connection. Just as applets dynamically extend the functionality of a Web browser, servlets dynamically extend the functionality of a Web server. A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. The Life Cycle of a Servlet Three methods are central to the life cycle of a servlet. These are 1. init( ), 2. service( ), and 3. destroy( ). The init() Method The init method is called only once. It is called only when t

Write a simple Java program that reads data from one file and writes the data to another file.

 We can do this by reading the file using the FileInputStream​ object and write into another file using FileOutputStream​ object. Here is the sample code package java_io_examples; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Vector; public class Filetest { public static void main(String[] args) { try { FileInputStream fin = new FileInputStream("D:\\testout.txt"); int i = 0; String s = ""; while((i=fin.read())!=-1) { s = s + String.valueOf((char)i); } FileOutputStream fout = new FileOutputStream("D:\\newtestout1.txt"); byte[] b = s.getBytes(); fout.write(b); fout.close(); System.out.println("Done reading and writing!!"); } catch(Exception e){ System.out.println(e); } } } #ALTERNATIVE public void readwrite() throws IOException { // Reading data from file File f1=new File("D:/read.txt"); FileReader fr=new FileReader(f1); BufferedReader br=new BufferedReader(fr); String s = br.readLine(); // Writing data

Write an object oriented program in Java to find area of circle.

CODE import java.util.Scanner; /* * Java Program to calculate area of circle */ public class Circle { public static void main(String args[]) { // creating scanner to accept radius of circle Scanner scanner = new Scanner(System.in); System.out.println("Welcome in Java program to calculate area of circle"); System.out.println("Formula for calculating area of circle is 'PI*R^2'"); System.err.println("Please enter radius of circle:"); float radius = scanner.nextFloat(); double area = area(radius); System.out.println("Area of Circle calculate by Java program is : " + area); scanner.close(); } public static double area(float radius) { double interest = Math.PI * radius * radius; return interest; } } Output Welcome in Java program to calculate area of circle Formula forcalculating area of circle is 'PI*R^2' Please enter radius of circle: 2 Area of Circle calculate by Java program is : 12.566370614359172

Write a Java program using JDBC to extract name of those students who live in Kathmandu district, assuming that the student table has four attributes (ID, name, district, and age).

package JDBC; import java.sql.*; public class Q3_2072 { static final String db_url="jdbc:mysql://localhost:3306/students"; public static void main(String[] args) { Connection conn=null; Statement statement=null; ResultSet resultSet=null; try{ //connection to database conn=DriverManager.getConnection(db_url,"root",""); //sql query String sql="Select *from student where address='dhading'"; //executing sql statement resultSet=statement.executeQuery(sql); ResultSetMetaData metaData=resultSet.getMetaData(); int numOfCols=metaData.getColumnCount(); System.out.println("Students------------"); //getting column names for(int i=1;i<=numOfCols;i++){ System.out.printf("%-8s\t", metaData.getColumnName(i)); System.out.println(); } //executing query while(resultSet.next()){ for(int i=1;i<=numOfCols;i++){ System.out.printf("%-8s\t", resultSet.getObject(i)); System.out.println(); } } }catch(SQLException e){ e.printStack

What is java beans? Differentiate it with java classes

.A java bean is a reusable software component written in java that can be manipulated visually in an application builder tool.This idea is that one can start with a collection of such components, and quickly wire them together to form complex programs without actually writing any new code. A JavaBean is a software component that is written in a java programming language. It is similar to a java except for following differences: ● A JavaBean must adhere to certain conventions regarding property and event interface definitions whereas java classes need to be. ● A builder tool must be able to analyze how a Bean works through the introspection process. This is not necessary for java classes. ● Java Beans must be customizable. It should allow its state to be manipulated at design time. This is not necessary to be true in the case of java classes. ● JavaBeans must implement Serializable interface which is not necessary for java classes. ● Every JavaBean must have one public no-argument const

Discuss any five event classes in java.

Image
Every time a user interacts with a component on the GUI, events are generated. Events are objects that store information like the type of event that occurred, the source of the event, etc. Once the event is generated, then the event is passed to other objects, which handle or react to the event, called event listeners. Some event classes that represent the event and their corresponding listeners are: Five of the many important event classes are: (1) ActionEvent:  In Java, most components have a special event called an ActionEvent. This is loosely speaking the most common or canonical event for that component. A good example is a click for a button. To have any component listen for an ActionEvent, we must register the component with an ActionListener as: component.addActionListener(new MyActionListener()); and then write the public void actionPerformed(ActionEvent e); method for the component to react to the event. (2) ItemEvent:  It is generated in case of JRadioButton, JCheckBox, JChe

Explain the importance of exception handling with suitable example.

 An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. So we have to handle exceptions. Exception handling is the ability of a program to intercept run-time errors, take corrective measures, and then continue. Java exception handling enables our Java applications to handle errors sensibly. Exception handling is a very important yet often neglected aspect of writing robust Java applications or components. When an error occurs in a Java program it usually results in an exception being thrown. How we throw, catch and handle these exception matters. There are several ways to do so. Exception handling is important for a program because it signals that some error or exceptional situation has occurred, and that it doesn't make sense to continue the program flow until the exception has been handled. Advantages of Exception Handling: ● Exception handling allows us to control the normal flow of the program by using exceptiohandl

Discuss the use of event listeners to handle events with suitable example.

When keys are pressed or mouse buttons are clicked, some events are generated. If we specify what to do when an event is generated, then it is known as event handling. Event handling is basically an automatic notification that some action has occurred. There are three things that are done in event handling: i. Create a class that represents the event handler. ii. ii. Implement an appropriate interface called “event listener interface” in the above class. iii. iii. Register the event handler The event listeners listen for a particular event and whenever the event occurs they fire the action that is registered for them. A suitable example of using event listener to handle mouse click event is given below: import java.awt.event.*; import javax.swing.*; public class EventListener extends JFrame implements ActionListener { public EventListener(){ JButton btn = new JButton("Click Me"); add(btn); btn.addActionListener(this); //registering the event handler setSize(100, 100); setVisi

Discuss any five exception classes in Java.

Image
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the Exception class, there is another subclass called Error which is derived from the Throwable class. The Exception class has two main subclasses: IOException class and RuntimeException class. There are many subclasses of RuntimeException class such as ArithmeticException, NullPointerException, IndexOutOfBoundsException, IllegalArgumentException, ClassCastException, etc. The ArrayIndexOutOfBoundsException class extends IndexOutOfBoundsException class. The exception hierarchy is shown below: Some of the exception classes in Java are discussed below: 1.ArithmeticException class: This class deals with exceptional arithmetic conditions such as the divide-by-zero exception. The constructors for this class are: a. public ArithmeticException() b. public ArithmeticException(String s) //Code Example p ublic class ExceptionTest { public static void main(Strin

Why multithreading is important in programming? Discuss.

Multithreading is the ability to run multiple threads concurrently. Thus multithreaded programs can do many things at once. A thread is a separate unit of execution performing a particular task in a multithreaded program. A thread is implemented by a particular method in programming language such as Java. With multithreading, we can achieve multitasking. If we have multiple CPUs, then each thread of a program can run on different CPUs allowing parallelism. If we have only one CPU, then the threads take turns in their run and this context switching of threads takes less time than multiprocessing systems. For example, in word processors such as MS-Word, one thread may be receiving input, another thread may be performing grammar check, and another thread may be auto-saving the data, and so on. While one thread is waiting, another thread is scheduled to run in single CPU systems. Further, in multithreading, all the threads of a program share the same memory space whereas if it has been mul

What is a Java bean? How is it different from Java class?

A Java bean is a Java class that should follow the following conventions: a. It should have a no argument constructor. b. It should be serializable i.e. it must implement the java.io.Serializable interface. Serializability ensures that the object’s state can be written into streams such as files (called serialization) and can be restored later into object as well (called deserialization). c. It should provide methods to set and get the values of the properties, known as getter and setter methods. A Java bean is different from a Java class in the sense that a Java class definition does not have any restriction whereas a Java bean class definition has. Thus a Java bean class is just a Java class with the properties mentioned above. An example of a Java bean class is: package bsccsit; import java.io.Serializable; public class JavaBeanClassEmployee implements Serializable { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } pu

Write a program using swing components to multiply two numbers. Use text fields for inputs and output. Your program should display the result when the user presses a button.

 The code for the Java program is given below: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MultiplyUsingSwing extends JFrame implements ActionListener { JLabel l1 = new JLabel("First No:"); JTextField t1 = new JTextField(10); JLabel l2 = new JLabel("Second No:"); JTextField t2 = new JTextField(10); JTextField t3 = new JTextField(10); JButton b = new JButton("Add"); String fno = ""; String sno = ""; public MultiplyUsingSwing() { setLayout(new FlowLayout()); setSize(250, 250); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(l1); add(t1); add(l2); add(t2); t3.setEditable(false); add(t3); add(b); b.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { int f = Integer.parseInt(t1.getText()); int s = Integer.parseInt(t2.getText()); int r = f + s; t3.setText("" + r); } public static void main(String[] args) { new MultiplyUsingSwing(); } }

How can you handle events using adapter classes? Discuss.

Adapter classes such as KeyAdapter, MouseAdapter, MouseMotionAdapter, WindowAdapter, etc provides the default (generally empty) implementation of all methods for many of the event listener interfaces such as KeyListener, MouseListener, MouseMotionListener, WindowListener, etc. Adapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface. For example, the KeyListener interface contains three methods KeyPressed(), KeyReleased() and KeyTyped(). If we implement this interface, we have to give implementation of all these three methods. However, by using the KeyAdapter class, we can override only the method that is needed. This can be shown in the code example given below. Here we are writing a GUI program that accepts user input in a text field and displays the key typed in another text field when the pressed key is released. The first program uses KeyListener interface and the second program uses KeyAdapter class.

Discuss any five classes to handle files in java.

Image
File handling implies performing I/O on files. In Java, file I/O is performed through streams. A stream means the flow of data irrespective of the device. There are two kinds of streams: byte streams and character streams. InputStream and OutputStream are two abstract classes in Java that are provided to read/write in byte streams i.e. they perform read/write as a sequence of 8-bit bytes. FileInputStream and FileOutputStream are two concrete classes derived from InputStream and OutStream that are used to perform the actual read/write on files. Similarly, there are Reader and Writer named abstract classes in Java that are provided to read/write in character streams i.e. they perform read/write in 16-bit characters. FileReader and FileWriter are two concrete classes derived from Reader and Writer that are used to perform the actual read/write on files. Further, there is a separate class named RandomAccessFile which allows files to be read/written randomly. The classes used for file handl

Write a program using components to add two numbers. Use text fields for inputs and output. Your program should display the result when the user presses a button.

package classPractise; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; class Add extends JFrame{ private JLabel lblFirstNum; private JLabel lblSecondNum; private JLabel result; private JTextField firstNum; private JTextField secondNum; private JButton btnAdd; public Add(){ setSize(400,300); setLayout(new FlowLayout()); lblFirstNum=new JLabel("Enter First Number:"); firstNum=new JTextField(10); add(lblFirstNum); add(firstNum); lblSecondNum=new JLabel("Enter First Number:"); secondNum=new JTextField(10); add(lblSecondNum); add(secondNum); btnAdd= new JButton("Add"); add(btnAdd); result=new JLabel(); add(result); btnAdd.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { int a,b,sum; a=Integer.parseInt(firstNum.getText()); b=Integer.parseInt(secondNum.getText()); sum=a+b; result.setText("Sum="+sum); } }); } } public class AddNum { public stat

What are exceptions? Why is it important to handle exceptions? Discuss different keywords that are used to handle exceptions.

  An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. Importance of handling exceptions. ● First, it lets the user know, in a relatively friendly manner, that something has gone wrong and that they should contact the technical support department or that someone from tech support has been notified. As we all know there's a HUGE difference between receiving a rather nasty, tech riddled notice that says something like "Object not set to reference of an object" etc. ... and receiving a nice popup type window that says "There has been an issue. Please contact the helpdesk". ● Second, it allows the programmer to put in some niceties to aid in the debugging of issues. For instance ... in my code, I typically write a custom error handler

Write a program to design an interface containing fields User ID, Password and Account type, and buttons login, cancel, edit by mixing border layout and flow layout. Add events handling to the button login and cancel such that clicking in login checks for matching user id and password in the database and opens another window if login is successful and displays appropriate message if login is not successful. Clicking in cancel terminates our program.

 Let us suppose we have a database named user and a table named user_table with fields user_id and password. Now the complete code for the above task is given below: //UserInterfaceDesign.java import java.awt.*; import java.awt.event.*; import java.sql.*; import javax.swing.*; public class UserInterfaceDesign extends JFrame { JLabel user_id_label = new JLabel("User ID:"); JTextField user_id_field = new JTextField(10); JLabel password_label = new JLabel("Password:"); JPasswordField password_field = new JPasswordField(10); JLabel account_type_label = new JLabel("Account Type:"); JRadioButton account_type_radio_button1 = new JRadioButton("Savings"); JRadioButton account_type_radio_button2 = new JRadioButton("Current"); ButtonGroup account_type_button_group = new ButtonGroup(); JButton login_button = new JButton("LogIn"); JButton cancel_button = new JButton("Cancel"); JButton edit_button = new JButton("Edit");

What is internal frame? Write a program that displays an internal frame within some parent frame.

Internal frame is a frame that is inside another frame. The JInternalFrame class is used to display a JFrame-like window within another window. Usually, we add internal frames to a desktop pane. The desktop pane, in turn, might be used as the content pane of a JFrame. The desktop pane is an instance of JDesktopPane, which is a subclass of JLayeredPane that has added API for managing multiple overlapping internal frames. In the program below, we are just displaying five frames inside another frame. //MyInternalFrame.java import javax.swing.*; public class MyInternalFrame extends JFrame { public MyInternalFrame() { for(int i=0; i<5; i++) { JInternalFrame frame = new JInternalFrame("Internal Frame" + i); frame.setLocation(i*50+10, i*50+10); frame.setSize(200, 150); this.add(frame); frame.setVisible(true); } setVisible(true); setSize(800, 600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new MyInternalFrame(); } }

Write a java program using TCP that enables chatting between client and server.

 Here we create two classes ServerChat and ClientChat that utilize ServerSocket and Socket classes. Sockets use the TCP/IP protocol by default. Below is the code that performs the actual chatting: //ServerChat.java import java.io.*; import java.net.*; import java.util.Scanner; public class ServerChat { public static void main(String[] args) throws IOException { //create a server socket ServerSocket serverSocket = new ServerSocket(8000); //listen for client request Socket socket = serverSocket.accept(); //create data input and output streams DataInputStream inputFromClient = new DataInputStream(socket.getInputStream()); DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream()); Scanner sc = new Scanner(System.in); String msg; while (true) { msg = inputFromClient.readUTF(); System.out.println("Client says:" + msg); System.out.println("(From Server) Input message to client:"); msg = sc.nextLine(); outputToClient.writeUTF(msg); } } } //ClientChat.

Why adapter classes are important? Compare it with listener interface with suitable example.

The Adapter class provides the default modification of all methods of an interface; we don't need to modify all the methods of the interface so we can say it reduces coding burden. Sometimes or often we need a few methods of an interface. For that the Adapter class is very helpful since it already modifies all the methods of an interface and by implementing the Adapter class, we only need to modify the required methods. Advantages of the Adapter class ● Assists unrelated classes to work together. ● Provides a way to use classes in multiple ways. ● Increases the transparency of classes. ● Its provides a way to include related patterns in a class. ● It provides a pluggable kit for developing applications. ● It makes a class highly reusable. Comparison between adapter class and listener interface In an adapter class, there is no need for implementation of all the methods presented in an interface. It is used when only some methods of defined by its interface have to be overridden. In