Posts

Showing posts with the label Advanced Java Programming

When thread synchronization is necessary ? Explain with suitable example.

 Java Thread synchronization is necessary when we want to allow only one thread to access the shared resource. So Synchronization in Java gives the capability to control the access of multiple threads to any shared resource. //example of java synchronized method class Table{ synchronized void printTable(int n){//synchronized method for(int i=1;i<=5;i++){ System.out.println(n*i); try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);} } } } class MyThread1 extends Thread{ Table t; MyThread1(Table t){ this.t=t; } public void run(){ t.printTable(5); } } class MyThread2 extends Thread{ Table t; MyThread2(Table t){ this.t=t; } public void run(){ t.printTable(100); } } public class TestSynChronization{ public static void main(String args[]){ Table obj = new Table();//only one object MyThread1 t1=new MyThread1(obj); MyThread2 t2=new MyThread2(obj); t1.start(); t2.start(); } }

How CORBA differs from RMI ? Discuss the concepts of IDL briefly.

  The difference between COBRA & RMI are as follows:-  COBRA CORBA has an implementation for many languages. It uses Interface Definition Language (IDL) to separate interface from implementation. CORBA objects are not garbage collected because it is language independent and some languages like C++ do not support garbage collection. CORBA does not support this code-sharing mechanism. CORBA passes objects by reference. CORBA is a peer-to-peer system. CORBA uses Internet Inter-ORB Protocol as its underlying remoting protocol. The responsibility of locating an object implementation falls on the Object Adapter either Basic Object Adapter or Portable Object Adapter. RMI RMI is a Java-specific technology. It uses a Java interface for implementation. RMI objects are garbage collected automatically.    RMI programs can download new classes from remote JVMs. RMI passes objects by remote reference or by value. Java RMI is a server-centric model. RMI uses the Java Remote Method Proto

What are different ways of writing servlet programs ? Write a sample Servlet program using any one way.

   Writing Servlets Program There are three ways to create the servlet 1. By implementing the Servlet interface 2. By inheriting the GenericServlet class 3. By inheriting the HttpServlet class 1.  By implementing the Servlet interface/ Servlet Interface The Servlet interface provides common behavior to all the servlets. The servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods that are used to initialize the servlet, service the requests, and destroy the servlet, and 2 non-life cycle methods that are used to get servlet information and servlet configurations. Example import java.io.*; import javax.servlet.*; public class ServletInt implements Servlet { ServletConfig config=null; public void init(ServletConfig config) { this.config=config; System.out.println("servlet is initialized"); } public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException { res.setContent

How JavaFX differs from Swing ? explain steps of creating GUI using JavaFX.

  JavaFX vs. SWING Swing, AWT, and JavaFX all are a part of JDK and are used to create Graphical User Interface (GUI) with JavaFX being one of the latest entrants in this list. Key differences between JavaFX and Swing are provided below. Swing 1. Swing is the standard toolkit for Java developers in creating GUI 2. Swing has a more sophisticated set of GUI components 3. Swing is a legacy library that fully features and provides pluggable UI components 4. Swing has a UI component library and acts as a legacy 5. Swing does not have support for customization using CSS and XML 6. With Swing, it is very difficult to create beautiful 3-D applications. JavaFX 1. JavaFX provides platform support for creating desktop applications. 2. JavaFX has a decent number of UI components available but lesser than what Swing provides. 3. JavaFX has UI components that are still evolving with a more advanced look and feel. 4. JavaFX has several components built over Swing 5. JavaFX has support for customizati

What causes SQL exception ? How it can be handled ? Explain with example.

 SQL exceptions can occur either if the driver is missing or information about the database is wrong or the SQL query is wrong. SQL exception can be handled by utilizing the information available from the Exception object, which can be caught with an exception. Example import java.sql.*; public class DemoSQLException { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/emp"; static final String user = "root"; static final String pass = "$Arjun12"; public static void main(String[] args) { Connection connection = null; PreparedStatement statement = null; try { Class.forName(JDBC_DRIVER); connection = DriverManager.getConnection(DB_URL, user, pass); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("select employee"); //Invalid SQL Statement while (rs.next()) System.out.println(rs.getInt(1) + " " + rs.getString(2) ); connection.close(); } c

What is the use of action command in event handling ? Explain with example.

Action command is used to handle event caused by the Buttons. Example  import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ActionDemo extends JFrame implements ActionListener { JLabel l1, l2, l3; JTextField t1, t2, t3; JButton b1, b2; public ActionDemo() { super("Handling Action Event"); l1 = new JLabel("Click on button to get result"); t1 = new JTextField(20); b1 = new JButton("Demo Button"); b1.addActionListener(this); setLayout(new FlowLayout(FlowLayout.CENTER, 150, 10)); add(l1); add(t1); add(b1); setSize(400, 300); setVisible(true); } public void actionPerformed(ActionEvent actionEvent) { String str = actionEvent.getActionCommand(); //using action command t1.setText("You have clicked " + str); } public static void main(String[] args) { new ActionDemo(); } } In the above example if clicked on the Demo Button, with the help of the getActionCommand() method we will be ab

What are layout managers? Explain Gridbag layout with suitable example.

Image
  A layout manager   A layout manager is an object that controls the size and position of the components in the container. Every container object has a layout manager object that controls its layout. Actually, layout managers are used to arranging the components in a specific manner.  It is an interface that is implemented by all the classes of layout managers.  There are some classes that represent the layout managers.  The LayoutManagers are used to arrange components in a particular manner. The Java LayoutManagers facilitate us to control the positioning and size of the components in GUI forms. LayoutManager is an interface that is implemented by all the classes of layout managers. Some of the most commonly used layout managers of java are : Flow Layout Border Layout Grid Layout Gridbag layout Card Layout Group Layout G ridbag layout The Gridbag Layout is a flexible layout manager that aligns components vertically and horizontally, without requiring that the components be of the sam

Write a java program that writes objects of Employee class in the file named emp.doc. Create Employee class as of you interest.

 import java.io.*; class Employee implements Serializable { private String name; private int age; public Employee(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Name:" + name + " Age:" + age; } } class RWObject { public static void main(String[] args) { Employee employee1 = new Employee("Arjun", 20); Employee employee2 = new Employee("Ram", 20); try { FileOutputStream fileOutputStream = new FileOutputStream("emp.doc"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); //Write object to file objectOutputStream.writeObject(employee1); objectOutputStream.writeObject(employee2); objectOutputStream.close(); fileOutputStream.close(); FileInputStream fileInputStream = new FileInputStream("emp.doc"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); //Read Objects Employee employee = (Employee) objectInputStream.readOb

Discuss various scopes of JSP objects briefly. Create HTML File with principal, time and rate. Then crate a JSP file that reads values from the HTML form, calculates simple interest and displays it.

   SCOPE OF JSP OBJECTS The availability of a JSP object for use from a particular place of the application is defined as the scope of that JSP object. Every object created on a JSP page will have a scope.  Object scope in JSP is segregated into four parts and they are page, request, session, and application. a) Page Scope- page scope means, the JSP object can be accessed only from within the same page where it was created. JSP implicit objects out, exception, response, pageContext, config, and page have page scope. //Example of JSP Page Scope <jsp:useBean id="employee" class="EmployeeBean" scope="page" /> b) Request Scope-  A JSP object created using the request scope can be accessed from any pages that serves that request. More than one page can serve a single request. Implicit object request has the request scope. //Example of JSP Request Scope <jsp:useBean id="employee" class="EmployeeBean" scope="request" /> c

Write a java program to create login with user id, password, ok button, and cancel button. Handle key events such that pressing 'l' performs login and pressing 'c' clears text boxes and puts focus on user id text box. Assume user table having fields Uid and Password in the database named account. (10)

LoginFrame.java  import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.sql.SQLException; /** * JFrame to handle key events such that pressing 'l' performs login, * ... and pressing 'c' clears text fields and puts focus on user ID * ... text field. */ public class LoginFrame extends JFrame { JLabel userIdLabel, passwordLabel; JTextField userIdTextField; JPasswordField passwordField; JButton okBtn, cancelBtn; JFrame self; public LoginFrame() { self = this; userIdLabel = new JLabel("User ID"); passwordLabel = new JLabel("Password"); userIdTextField = new JTextField(20); passwordField = new JPasswordField(20); okBtn = new JButton("OK"); cancelBtn = new JButton("Cancel"); okBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { new JFrame() { { JLabel messageLabel = new JLabel(); LoginService loginService = new LoginService(); String user = userIdTextField.getText();

What are the uses of the final modifier? Explain each use of the modifier with examples.

 Final Modifier  Final Modifier is a non-access Specifier that is used to restrict a class, variable, and method. If we initialize a variable with the final keyword, then we cannot modify its value. The final modifier keyword makes the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.  It's a modifier that you can apply on variables, methods, and classes and when you apply the final modifier it can make variables immutable, prevent the method from overriding in subclasses, means no polymorphism, and when you make a class final in Java it cannot be extended anymore, taking out Inheritance from the picture.   The java final modifier can be used in the following ways (i) variable → To Create Constants (ii) Method → To prevent Method overriding  (iii) Class → To prevent inheritance. 2nd Part   The use of each modifier is explained below with example:- (i) To Define Constants  We can use the final modifie

What are the uses of final modifier/Keyword? Explain.

The final Modifier The final modifier keyword makes the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.  It's a modifier that you can apply on variables, methods, and classes and when you apply the final modifier it can make variables immutable, prevent the method from overriding in subclasses, means no polymorphism, and when you make a class final in Java it cannot be extended anymore, taking out Inheritance from the picture. There are both pros and cons of using the final modifier in Java and that's why it's very very important for a Java developer to have an in-depth knowledge of the final modifier in Java and that's what you will learn in this article.  Following is a list of uses of the final modifier keyword. Using final to define constants: If you want to make a local variable, class variable (static field), or instance variable (non-static filed) constant, declare it final. A f

Compare JavaFX with swing. Explain HBox and VBox layouts of JavaFX.

Image
  JavaFX vs. SWING Swing, AWT, JavaFX all are a part of JDK and are used to create Graphical User Interface (GUI) with JavaFX being one of the latest entrants in this list. Key differences between JavaFX and Swing is provided below. Swing 1. Swing is the standard toolkit for Java developers in creating GUI 2. Swing has a more sophisticated set of GUI components 3. Swing is a legacy library that fully features and provide pluggable UI components 4. Swing has a UI component library and act as a legacy 5. Swing does not have support for customization using CSS and XML 6. With Swing, it is very difficult to create beautiful 3-D applications. JavaFX 1. JavaFX provides platform support for creating desktop applications. 2. JavaFX has a decent number of UI components available but lesser than what Swing provides. 3. JavaFX has UI components that are still evolving with a more advanced look and feel. 4. JavaFX has several components built over Swing 5. JavaFX has support for customization usin

What Java Mail API? How can you use this API to send email messages?

 The JavaMail is an API that is used to compose, write and read electronic messages (emails). The JavaMail API provides a protocol-independent and platform-independent framework for sending and receiving mails. The java.mail and javax. mail. activation packages contain the core classes of JavaMail API. The JavaMail facility can be applied to many events. It can be used at the time of registering the user (sending notification such as thanks for your interest to my site), forgot password (sending password to the user's email id), sending notifications for important updates etc. So there can be various usage of java mail API. We can use this API in three steps to send email message , they are described below:- STEPS TO SEND EMAIL USING JAVAMAIL API There are following three steps to send email using JavaMail.  They are as follows: 1. Get the session object It stores all the information of host like host name, username, password etc. The javax.mail.Session class provides two methods t

What is row set? Explain cached row set in detail.

 Row set A RowSet is an object that encapsulates a set of rows from either java Database Connectivity (JDBC) result sets or tabular data sources. RowSets support component-based development models like JavaBeans, with a standard set of properties and an event notification mechanism. The support for RowSet was introduced in JDBC 2.0 through the optional packages. However, the implementations of RowSets was standardized in the JDBC RowSet Implementations Specification (JSR-114) by Sun Microsystems, which is available in Java Development Kit (JDK) 5.0. The JDK 5.0 Javadoc provides information about the standard interfaces and base classes for JDBC RowSet implementations. Catched row set  A CachedRowSet object is a container for rows of data that caches its rows in memory, which makes it possible to operate without always being connected to its data source.  A CachedRowSet object typically contains rows from a result set, but it can also contain rows from any file with a tabular format, su

How can we use listener interface to handle events? Compare listener interface with adapter class

 To handle events we must implement event listener interfaces. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. 2nd part Any class which handles events must implement a listener interface for the event type it wishes to handle. A class can implement any number of listener interfaces. To implement a listener interface the class must implement every method in the interface. Sometimes we may want to implement only one or two of the methods in an interface. We can avoid having to write our own implementation of all the methods in an interface by using an adapter class. An adapter class is a class that already implements all the methods in the corresponding interface. Our class must extend the adapter class by inheritance so we can extend only one adapter class in our class because Java does not support multiple inh

Why do we need swing components? Explain the uses of check boxes and radio buttons in GUI programming.

 We need the swing component because java Swing Components are essential building blocks for designing, developing, and implementing an application. These components form the Swing Graphical User Interface widget toolkit for the Java programming language. JRadioButton The class /RadioButton is an implementation of a radio button- an item that can be selected or deselected, and which displays its state to the user. By default it allows us to select multiple radio buttons. To prevent this, we need to create object of ButtonGroup class and add all radio buttons to in that object.  Commonly used constructors defined in JRadioButton class are: • JRadioButton();//creates a radio button with no label • JRadioButton(String text); //creates a radio button with specified label • JRadioButton(String text, boolean state); //creates radio button with specified label and state •  JRadioButton (Icon icn);//creates radio button with specified image icon  • JRadioButton (Icon icn, boolean state);//crea

What is package? How can we create your own packages? Explain.

   Packages Java package is a mechanism of grouping similar type of classes, interfaces, and sub-classes collectively based on functionality. When software is written in the Java programming language, it can be composed of hundreds or even thousands of individual classes. It makes sense to keep things organized by placing related classes and interfaces into packages. A java package is a group of similar types of classes, interfaces, and sub-packages. Package in java can be categorized in two forms, built-in package, and user-defined package. There are many built-in packages such as java, lang, awt, java, swing, net, io, util, SQL, etc. Here, we will have the detailed learning of creating and using user-defined packages.  Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations, and annotations easier, etc.  A Package can be defined as a grouping of related types(classes, interfaces, enum

Write an object oriented program to find the area and perimeter of rectangle .

To calculate the perimeter and area of rectangle​, we need the dimensions of two adjacent sides(length and width) of a rectangle. The area of a rectangle​ is the amount of two-dimensional space inside the boundary on rectangle. The perimeter of a rectangle​ is the linear distance around the boundary of the rectangle. Java program to calculate area and perimeter of a rectangle package com.tcc.java.programs; import java.util.*; public class RectangleAreaPerimeter { public static void main(String args[]) { int length, width, area, perimeter; Scanner in = new Scanner(System.in); System.out.printIn("Enter length of Rectangle"); length = in.nextInt(); System.out.printIn("Enter width of Rectangle"); width = in.nextInt(); // Area of rectangle = length X width area = length*width; // Perimeter of rectangle = 2 X (length X width) perimeter = 2*(length + width); System.out.printIn("Area of Rectangle : "+ area); System.out.printIn("Rectangle of Rectangle : "

Short note on Multithreading.

 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 autosaving 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