Applet AWT Swing Java Interview Questions | Eklavya Online

Applet AWT Swing Java Interview Questions

A J2EE component that typically executes in a Web browser but can execute in a variety of otherapplications or devices that support the applet programming model.

A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:

  • Application clients and applets are client components.
  • Java Servlet and JavaServer PagesTM (JSPTM) technology components are web components.
  • Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
  • Resource adapter components provided by EIS and tool vendors.

A J2EE component that typically executes in a Web browser but can execute in a variety of otherapplications or devices that support the applet programming model.

When the applet class file is not in the same directory, codebase is used.

Yes, there are three ways to communicate from an applet to servlet and they are: a) HTTP Communication(Text-based and object-based) b) Socket Communication c) RMI Communication

Applet classes are located in ” java.applet “package.

The Panel and Applet classes use the FlowLayout as their default layout.

Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.

?– init() method – Can be called when an applet is first loaded start() method – Can be called each time an applet is started. paint() method – Can be called when the applet is minimized or maximized. stop() method – Can be used when the browser moves off the applet’s page. destroy() method – Can be called when the browser is finished with the applet.

Panel and Applet classes use the FlowLayout as their default layout.

All AWT event listeners extend the java.util.EventListener interface.

Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane.

When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.

using setSecurityManager() method

The Canvas, Frame, Panel, and Applet classes support painting.

Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.

What is casting?– Casting is used to convert the value of one type to another.

Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser

The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.

  1. a) Servlets are to servers what applets are to browsers. b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.

a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.

The paint() method supports painting via a Graphics object. The repaint() method is used to causepaint() to be invoked by the AWT painting thread.

A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.

?– Using getParameters() method.

Javadoc parses comments in JAVA source files and produced HTML pages for the same. Below is the syntax for the same javadoc [ options ] [ packagenames ] [ sourcefiles ] [ @files ] Arguments can be in any order. Options Command-line options that is doctitle, windowtitle, header, bottom etc

Packagenames: –

A series of names of packages, separated by spaces, such as java.lang java.lang.reflect java.awt. You must separately specify each package you want to document. Javadoc uses -sourcepath to look for these package names. Javadoc does not recursively traverse subpackages.

sourcefiles :-

A series of source file names, separated by spaces, each of which can begin with a path and contain a wildcard such as asterisk (*). The path that precedes the source file name determines where javadoc will look for it. (Javadoc does not use -sourcepath to look for these source file names.)

@files: – One or more files that contain packagenames and sourcefiles in any order, one name per line.

Applets are small applications that are accessed from web server automatically installed, and run from the browser. Once an applet arrives on the client it has limited access to resources thus ensuring security for the end user. An applet is controlled by the software that runs it. Usually, the underlying software is a browser, but it can also be applet viewer. If you run the applet source code from eclipse it runs inside an applet viewer. All applets should inherit from applet class.

Below are sequences of events which occur in applet:

  • The init Method: The init method is called when the applet is first loaded. Init method can be used to initialize color, fonts or any type of one type operation needed for the applet.
  • The start Method: The start method is called when user visits a browser with an applet on it. In start method applet spawns a thread in which it runs the paint method.
  • paint() is called every time when applet has to re-display everything.

The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException

{

// Initialization code…

}

The Observer pattern is a behavioral design pattern that  allows an object (an Observer) to watch another object (a Subject). The subject and observer to have a publish/subscribe relationship. Observers can register to receive events from the Subject.

Some of the practical uses of observer pattern are:

  • When a change to one object requires changing of others, and you don’t know how many objects need to be changed.
  • When an object should be able to notify other objects without making assumptions about who these objects are and not tightly coupling them.
  • When a report is received or an event occurs, a message needs to be sent to the subscribed handlers.

Examples:

  • Programming Swing based GUI applications where the listeners register them with events like button click, property change, etc.
  • Programming a stock market application to know when the price of a stock changes.
  • Programming a order placement or trading application to know the status changes like pending, filled, shipped, rejected, etc.

So, whenever you want to have the state change or other information, instead of polling every few second, register the observers with a subject.

 

Here is some pseudo code of this third scenario

STEP 1: Define the Subject and Observer interfaces

This is the subject interface

package com;

 

public interface ReportExecutor {

public void addHandler(ReportHandler rh);

public void removeHandler(ReportHandler rh);

public void processReport(String message);

}

This is the observer interface

package com;

 

public interface ReportHandler {

//handles report

public void handleMessage(String message);

}

STEP 2: Define the concrete subject and observers

The concrete subject

package com;

 

import java.util.ArrayList;

import java.util.List;

 

public class SalesReportExecutor implements ReportExecutor {

 

//list of observers that register their interest in SalesReport

private List<reporthandler> reportHandlers = new ArrayList<reporthandler>();

@Override

public void addHandler(ReportHandler rh) {

reportHandlers.add(rh);

}

@Override

public void processReport(String message) {

for (ReportHandler reportHandler : reportHandlers) {

reportHandler.handleMessage(message);

}

}

@Override

public void removeHandler(ReportHandler rh) {

reportHandlers.remove(rh);

}

}

The concrete observers

package com;

 

public class LoggingReportHandler implements ReportHandler {

 

@Override

public void handleMessage(String message) {

//handles report by formatting and printing

System.out.println(“Logging report  ” + message);

}

}

 

package com;

 

public class EmailReportHandler implements ReportHandler {

 

@Override

public void handleMessage(String message) {

//handles the report by formatting it differently and emailing.

System.out.println(“Emailing report ” + message);

//logic to email report.

}

}

 

STEP 3: Finally, the JMS listener class that uses the subject. The JMS Listener class listens on a queue for presence of a report.

package com.mgl.mts.fix;

 

import javax.jms.Message;

import javax.jms.TextMessage;

 

public class MyAppListener {

 

public void onMessage(Message message) {

if (message instanceof TextMessage) {

 

ReportExecutor executor = new SalesReportExecutor();

executor.addHandler(new LoggingReportHandler());

executor.addHandler(new EmailReportHandler());

executor.processReport(message.toString());

 

} else {

throw new IllegalArgumentException(“Message must be of type TextMessage”);

}

}

}

RowSet is a interface that adds support to the JDBC API for the JavaBeans component model. A rowset, which can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. The RowSet interface provides a set of JavaBeans properties that allow a RowSet instance to be configured to connect to a JDBC data source and read some data from the data source. A group of setter methods (setInt, setBytes, setString, and so on) provide a way to pass input parameters to a rowset’s command property. This command is the SQL query the rowset uses when it gets its data from a relational database, which is generally the case. Rowsets are easy to use since the RowSet interface extends the standard java.sql.ResultSet interface so it has all the methods of ResultSet. There are two clear advantages of using RowSet over ResultSet

  • RowSet makes it possible to use the ResultSet object as a JavaBeans component. As a consequence, a result set can, for example, be a component in a Swing application.
  • RowSet be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a RowSet object implementation (e.g. JdbcRowSet) with the data of a ResultSet object and then operate on the RowSet object as if it were the ResultSet object.

Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

There are a number of high level conceptual architectures as discussed below. These individual architectures can be mixed and matched to produce hybrid architectures.

Model-View-Controller Architecture

Most web and stand-alone GUI applications follow this pattern. For example, Struts and Spring MVC frameworks and Swing GUI.

 

  • The model represents the core business logic and state.
  • The view renders the content of the model state by adding display logic.
  • The controller translates the interaction with the view into action to be performed by the model.

The actions performed by a model include executing the business logic  and changing the state of the model.Based on the user interactions, the controller selects an appropriate view to render.The controller decouples the model from the view.

Service Oriented Architecture (SOA)

The business logic and application state are exposed as reusable services.

An Enterprise Service Bus (ESB) is used as an orchestration and mediation layer to decouple the applications from the services.

 

The above architecture has 5 tiers. The application tier could be using a typical MVC architecture.

  • The service orchestration tier could be using ESB products like OracleService Bus, TIBCO, etc and BPM products like Lombardi BPM, Pega BPM, etc.
  • In the abovediagram, the ESB integrates with the BPM via messaging queues.
  • The service tier consists of individual services that can be accessed through SOAP or RESTful web services.
  • The SOA implementation requires change agents to drive adoption of new approaches.
  • The BPM,application integration, and real-time information all contribute to dynamically changing how business users do their jobs.

So, it needs full support from the business, requiring  restructuring and also it can take some time to realize the benefits of SOA. Cloud computing is at the leading edge of its hype and as a concept compliments SOA as an architectural style. Cloud computing is expected to provide a computing capability that can scale up (to massive proportions) or scale down dynamically based on demand. This implies a very large pool of computing resources either be within the enterprise intranet or on the Internet (i.e on the cloud).

User Interface (UI) Component Architecture

This architecture is driven by a user interface that is made up of a number of discrete components.Each component calls a service that encapsulates business logic and hides lower level details. Components can be combined to form new composite components allowing richer functionality. These components can also be shared across a number ofapplications.

For example, JavaScript widgets, Java Server Faces (JSF) components, etc.

 

RESTful data composition Architecture

The user interface can be built by calling a number of underlying services that are each responsible for building part of a page.

 

The user interface translates and combine the data in different formats like XML(translate to HTML using XSLT), JSON (Java Script Object Notation), ATOM (feed for mail messages and calendar applications), RSS (for generating RSS feeds), etc.

HTML composition Architecture

In this architecture, multiple applications output fragments of HTML that are combined to generate the final user interface.

 

For example, Java portlets used inside a portal application server to aggregate individual content..

Plug-in Architecture

In this architecture, a core application defines an interface, and the functionality will be implemented as a set of plug-ins that conform to that interface.

 

For example, the the Eclipse RCP framework, Maven build tool, etc use this architecture.

Event Driven Architecture (EDA)

The EDA pattern decouples the interactions between the event publishers and the event consumers. Many to many communications are achieved via a topic, where one specific event can be consumed by many subscribers. The EDA also supports asynchronous operations and acknowledgments through event messaging.

This architecture requires effective monitoring in place to track queue depth, exceptions, and other possible problems. The traceability, isolation, and debugging of an event can be difficult in some cases. This architecture is useful in scenarios where the business process is inherently asynchronous, multiple consumers are interested in an event(e.g. order status has changed to partially-filled ), no immediate acknowledgment is required (e.g. an email is sent with the booking details and itinerary), and real-time request/response is not required (e.g. a long running report can be generated asynchronously and made available later via online or via email).

 

 

 

Most conceptual architectures use a hybrid approach using a combination of different architectures based on the benefits of each approach and its pertinence to your situation. Here is a sample hybrid approach depicting an online trading system.

 

 

 

FIX is a Financial Information eXchange protocol. You could also notice a number of synchronous calls using XML/HTTP or SOAP/HTTP and asynchronous calls using JMS. The above diagram also depicts that an enterprise architecture can be complex with a number of moving parts. So, it is imperative that all these moving parts are properly monitored and tested for any potential performance issues. Most of these services will be running as a cluster or a load balanced service with either active/active or active.passive configuration for high availability and scalability.