0% found this document useful (0 votes)
14 views68 pages

Web Technology

An applet is a Java program that runs in a web browser and enhances web pages with dynamic content. The applet life cycle consists of five core methods: init(), start(), stop(), paint(), and destroy(), which manage the applet's execution. Applets can be created using the java.applet.Applet class and can change background and foreground colors using the Color class.

Uploaded by

mondal742405
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views68 pages

Web Technology

An applet is a Java program that runs in a web browser and enhances web pages with dynamic content. The applet life cycle consists of five core methods: init(), start(), stop(), paint(), and destroy(), which manage the applet's execution. Applets can be created using the java.applet.Applet class and can change background and foreground colors using the Color class.

Uploaded by

mondal742405
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

1.What is Applet?

An applet is a Java program that can be embedded into a web


page. It runs inside the web browser and works at client side. An
applet is embedded in an HTML page using the APPLET or OBJECT
tag and hosted on a web server. Applets are used to make the
website more dynamic and entertaining.

Java Applet Class

For Creating any applet in Java, we use the java.applet.Applet


class. It has four Methods in its Life Cycle of Java Applet. The
applet can be executed using the applet viewer utility provided
by JDK. A Java Applet was created using the Applet class, i.e.,
part of java.applet package.

The Applet class provides a standard interface between applets


and their environment. The Applet class is the superclass of an
applet that is embedded in a Web page or viewed by the Java
Applet Viewer. The Java applet class gives several useful
methods to give you complete control over the running of an
Applet. Like initializing and destroying an applet, It also provides
ways that load and display Web Colourful images and methods
that load and play audio and Videos Clips and Cinematic Videos.

In Java, there are two types of Applet

1) Java Applets based on the AWT(Abstract Window Toolkit)


packages by extending its Applet class

2) Java Applets is based on the Swing package by extending its


JApplet Class in it.
2. Explain the Life Cycle Of java Applet Class?

The applet life cycle can be defined as the process of how the
object is created, started, stopped, and destroyed during the
entire execution of its application. It basically has five core
methods namely init(), start(), stop(), paint() and
destroy().These methods are invoked by the browser to execute.

There are five methods of an applet life cycle, and they are:

o init(): The init() method is the first method to run that initializes the applet.
It can be invoked only once at the time of initialization.
o start(): The start() method contains the actual code of the applet and starts
the applet. It is invoked immediately after the init() method is invoked. It
is in an inactive state until the init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop ()
method is invoked whenever the applet is stopped.
o destroy(): The destroy() method destroys the applet after its work is done.
o paint(): The paint() method belongs to the Graphics class in Java. It is used
to draw shapes like circle, square, trapezium, etc., in the applet. It is
executed after the start() method and when the browser or applet
windows are resized.
3. Give example of Constructor of Applet Class.

The Applet class is just like any other class as an Applet


Constructor is simply the subclass constructor of the Applet
class. Therefore, Because the applet constructor is just like or
any other constructor, it cannot be overridden, so Constructors
perform any Necessary initialization for the new object or
Create the new Object for it.

Applet() – It Constructs a new Applet.


Example of Applet: The Applet program using appletviewer-
import java.applet.*;
import java.awt.*;
/*
<applet code="AppletExp1" width=600 height=300>
</applet>
*/
public class AppletExp1 extends Applet {
public void init()
{
System.out.println("Initializing an applet");
}

public void start()


{
System.out.println("Starting an applet");
}
public void stop()

{
System.out.println("Stopping an applet");
}
public void destroy()
{
System.out.println("Destroying an applet");
}
}
Advantage of Applet
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many
plateforms, including Linux, Windows, Mac Os etc.

Drawback of Applet

o Plugin is required at client browser to execute applet.

4. Give Simple example of Applet by applet viewer tool?


To execute the applet by appletviewer tool, create an applet
that contains applet tag in comment and compile it. After that
run it by: appletviewer First.java. Now Html file is not required
but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
}

}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/

To execute the applet by appletviewer tool, write in command


prompt:

c:\>javac First.java
c:\>appletviewer First.java
1. Explain applet architecture?
We know that java provides console-based programming language
environment and window-based programming environment. An
applet is a window-based programming environment. So applet
architecture is different than console base program.
Java applets are essentially java window programs that can run
within a web page. Applete programs are java classes that extend
that java.applet. Applet class and are enabled by reference with
HTML page. You can observed that when applet are combined with
HTML, thet can make an interface more dynamic and powerful than
with HTML alone
While some Applet do not more than scroll text or play movements,
but by incorporating these basic features in a webpage you can make
them dynamic. These dynamic web page can be used in an enterprise
application to view or manipulate data comming from some source
on the server.
The Applet and there class files are distribute through standard
HTTP request and therefore can be sent across firewall with the web
page data. Applete code is referenced automatically each time the
user revisit the hosting website. Therefore keeps full application up
to date on each client desktop on which it is running.
2. What are five methods can be assembled into the skeleton?
3.How to Change Background And Foreground Color of Applet in Java?
The Color class provides various methods to use any color you want in display. It defines
various color constants which can be directly used only by specifying the color of your
choice. In addition, the Color class allows creation of millions of colors. The Color class
contains three primitive colors namely, red, blue and green and all other colors are a
combination of these three colors. One of the constructors that is used to create color of
your choice is
Color (int red, int green, int blue)
where,
red, green, blue can take any value between 0 and 255.
Setting Background and Foreground Color
To set the color of the background of an applet window, setBackground () method is used.
The general form of the setBackground () method is
void setBackground(mycolor)
Similarly, to set the foreground color to a specific color, that is, the color of text,
setForeground () method is used.
The general form of the setForeground () method is
void setForeground(mycolor)
where,
mycolor is one of the color constants or the new color created by the user
The list of color constants is given below:
• Color.red
• Color.orange
• Color.gray
• Color.darkGray
• Color.lightGray
• Color.cyan
• Color.pink
• Color.white
• Color.blue
• Color.green
• Color.black
• Color.yellow
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class ColorApplet extends Applet
{
public static void main(String[] args)
{
Frame ForegroundBackgroundColor = new Frame("Change
Background and Foreground Color of Applet");
ForegroundBackgroundColor.setSize(420, 180);
Applet ColorApplet = new ColorApplet();
ForegroundBackgroundColor.add(ColorApplet);
ForegroundBackgroundColor.setVisible(true);
ForegroundBackgroundColor.addWindowListener(new
WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0); }
});
}
public void paint(Graphics g)
{
Color c = getForeground();
setBackground(Color.yellow);
setForeground(Color.red);
g.drawString("Foreground color set to red", 100, 50);
g.drawString(c.toString(), 100, 80);
g.drawString("Change Background and Foreground Color of
Applet", 50, 100);
}
}
4. How do you extract the directory holding the HTML file that
started the applet and the directory from which the applet's
class file was loaded?
1.What are classes in Java with example?

Everything in Java is associated with classes and objects, along


with its attributes and methods. For example: in real life, a car is
an object. The car has attributes, such as weight and color,
and methods, such as drive and brake.

A Class is like an object constructor, or a "blueprint" for creating


objects.

Create a Class

To create a class, use the keyword class:

Main.java

Create a class named "Main" with a variable x:

public class Main {

int x = 5;

Create an Object

Example
Create an object called "myObj" and print the value of x:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

}
2 . Define constructors with example?

In Java, a constructor is a block of codes similar to the method. It is


called when an instance of the class is created. At the time of calling
constructor, memory for the object is allocated in the memory. It is a
special type of method which is used to initialize the object.Every
time an object is created using the new() keyword, at least one
constructor is called.

Types of Constructors in Java:

1) No-argument constructor

2) Parameterized Constructor

No-argument constructor: A constructor that has no parameter is


known as the default constructor. If we don't define a constructor in
a class, then the compiler creates a default constructor(with no
arguments) for the class. And if we write a constructor with
arguments or no arguments then the compiler does not create a
default constructor.

Parameterized Constructor: A constructor that has parameters is


known as parameterized constructor. If we want to initialize fields of
the class with our own values, then use a parameterized constructor.

Example:

public class Puppy {

public Puppy() {

public Puppy (String name) {

}
}
The rules for writing constructors are as follows:

1. The constructor (s) of a class must have the same name as the class name in
which it resides.

2. A constructor in Java can not be abstract, final, static, or Synchronized.

3. Access modifiers can be used in constructor declaration to control its access


i.e which other class can call the constructor.

3. Explain static keyword?


The static keyword in Java is mainly used for memory management.
The static keyword in Java is used to share the same variable or
method of a given class. The users can apply static keywords with
variables ,methods, blocks, and nested classes. The static keyword
belongs to the class than an instance of the class. The static keyword
is a non-access modifier in Java that is applicable for the following:
1) Blocks
2) Variables
3) Methods
4) Classes
When a member is declared static, it can be accessed before any
objects of its class are created, and without reference to any object.
For example, in the below java program, we are accessing static
method m1() without creating any object of the Test class.
4. What is an inner class in Java?
Inner classes in Java are declared inside another class (also called the
outer class) and can access private members of the outer class. The
compiler generates a class that is a member of the outer class, and
it's this generated class that has access to private variables or
methods in the scope where it was created (e.g., inside another
method).
Static nested inner classes are similar to other static members
because they have no access to the instance variables of the outer
class. In contrast, non-static inner classes can access the instance
variables of the outer class, and are therefore able to create
instances of the outer class.
1. Types of Inner Classes: Inner classes are classified into four types:
static, non-static, local and anonymous.
2. Static Inner Classes:These are the simplest type of inner classes.
Static inner classes are those that are declared inside a class and
marked static. It should be noted that these classes can only be
accessed using an instance of the outer class. You can take
advantage of static nested classes for grouping related classes
together.
3. Non-static Inner Classes: A non-static inner class as the name
suggests, is associated with an instance of an outer class. All the
members (variables and methods) of the outer class are accessible
from these classes.
4. Local Inner Classes: Local inner classes are defined within a
method. They have access to all the members (variables and
methods) of the enclosing class but they cannot be instantiated
from outside the method in which they are defined.
5. Anonymous Inner Classes: Inner classes that don't have names are
also known as anonymous inner classes. Both the declaration and
instantiation of an anonymous inner class occur simultaneously.
Anonymous inner classes cannot have explicit constructors, just like
all local inner classes. Anonymous inner classes are useful when you
have to use a local inner class only once.
1. How do you declare a class in Java?

Declaring Classes
class MyClass {
// field, constructor, and
// method declarations
}
This is a class declaration. The class body (the area between the
braces) contains all the code that provides for the life cycle of
the objects created from the class: constructors for initializing
new objects, declarations for the fields that provide the state of
the class and its objects, and methods to implement the behavior
of the class and its objects.

The preceding class declaration is a minimal one. It contains only


those components of a class declaration that are required. You
can provide more information about the class, such as the name
of its superclass, whether it implements any interfaces, and so
on, at the start of the class declaration. For example,

class MyClass extends MySuperClass implements YourInterface {


// field, constructor, and
// method declarations
}
means that MyClass is a subclass of MySuperClass and that it
implements the YourInterface interface.

You can also add modifiers like public or private at the very
beginning—so you can see that the opening line of a class
declaration can become quite complicated. The
modifiers public and private, which determine what other classes
can access MyClass, are discussed later in this lesson. The lesson
on interfaces and inheritance will explain how and why you would
use the extends and implements keywords in a class declaration.
For the moment you do not need to worry about these extra
complications.
In general, class declarations can include these components, in
order:

1. Modifiers such as public, private, and a number of others


that you will encounter later. (However, note that
the private modifier can only be applied to Nested Classes.)
2. The class name, with the initial letter capitalized by
convention.
3. The name of the class's parent (superclass), if any,
preceded by the keyword extends. A class can
only extend (subclass) one parent.
4. A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class
can implement more than one interface.
5. The class body, surrounded by braces, {}.
2. Explain Passing Arguments to Methods in Java?

There are mainly two ways of passing arguments to methods:

1) Pass by value , 2) Pass by reference


Pass by value: When the arguments are passed using the pass by
value mechanism, only a copy of the variables are passed which has
the scope within the method which receives the copy of these
variables. The changes made to the parameters inside the methods are
not returned to the calling method. This ensures that the value of the
variables in the calling method will remain unchanged after return from
the calling method.

public class Sum {


static int CaiculateTotal(int n1) {

int total=0;
int marks[] = new int[3]:
try {
BufferedReader br= newBufferedReader( new InputStreamReader(System.in));
for(int i=0; i&lt;n 1; i++) {
marks[i]= Integer.parselnt(br.readLine());
total+=marks[i];
}
}
catch(Exception e) {
System.out.println("Array out of range");
}
return total;
}
public static void main(String args[]) throws IOException {
int n,Max;
System.out.println("Enter the numbers :");
Max = CalculateTotal(3);
System.out.println("Sum of the numbers is:" +Max);
}
}
The output of Program is: 2 , 3 , 4
Sum of the numbers is: 9
In Program the value 3 has been passed to the method Calculate Total. The
argument n1 of Calculate Total method takes its value as 3 and performs the
rest of the execution of program.
Pass by reference : In the pass by reference mechanism, when parameters are passed to the
methods, the calling method returns the changed value of the variables to the called
method. The call by reference mechanism is not used by Java for passing parameters to the
methods. Rather it manipulates objects by reference and hence all object variables are
referenced. Program illustrates the call by reference mechanism in Java.

Program to illustrate pass by reference.

The output of Program is as shown below:


Before SWAP
a = 10 b = 20
After SWAP
a = 20 b = 10
Here, the method swap is invoked with object ob as parameter, and any
manipulation of this object within the method will affect the original objects.
Thus, the values of a and bare interchanged after method swap is called.
3. What is the method of overloading in Java?

If a class has multiple methods having same name but different in parameters,
it is known as Method Overloading. If we have to perform only one operation,
having same name of the methods increases the readability of the program.
There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

1)Method Overloading: changing no. of arguments : In this example, we have


created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create
instance for calling methods.

Output: 22 ,33 .

2) Method Overloading: changing data type of arguments: In this example,


we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double
arguments.

Output: 22, 24.9


4.Explain the Method Overriding in Java?

If subclass (child class) has the same method as declared in the parent class, it
is known as method overriding in Java. In other words, If a subclass provides
the specific implementation of the method that has been declared by one of
its parent class, it is known as method overriding.

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a


method which is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example of method overriding

Output: Bike is running safely


1. Explain the hierarchy of Java Exception classes?

All exception and error types are subclasses of class Throwable,


which is the base class of the hierarchy. One branch is headed by
Exception. This class is used for exceptional conditions that user
programs should catch. NullPointerException is an example of
such an exception. Another branch, Error is used by the Java
run-time system(JVM) to indicate errors having to do with the
run-time environment itself(J RE). StackOverflowError is an
example of such an error. The java.lang.The throwable class is
the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error.

The hierarchy of Java Exception classes is given below:


2.. What is Exception Handling?
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException , IOException , SQLException, RemoteException, etc.
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are
three types of exceptions namely:
1) Checked Exception
2) Unchecked Exception
3) Error
1) Checked Exception: The classes that directly inherit the Throwable class except
Runtime Exception and Error are known as checked exceptions. For example,
IOException , SQLException, etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception
The classes that inherit the Runtime Exception are known as unchecked
exceptions. For example, Arithmetic Exception, Null Pointer Exception, Array
Index Out Of Bounds Exception, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are Out Of Memory Error, Virtual
Machine Error, Assertion Error etc.
3. Give the example Java Exception Handling?
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained. Java
Exception Handling in which we are using a try-catch statement to handle the
exception.
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
// rest code of the program
System.out.println(“rest of the code….”);
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero rest of the code.
4. If an error occurs, use try...catch to catch the error and execute some code to
handle it?
The try statement allows you to define a block of code to be tested for errors while
it is being executed.
The catch statement allows you to define a block of code to be executed, if an
error occurs in the try block.
try {
int[] myNumbers ={1,2,3};
System. out . println (myNumbers [ 10] ) ;
} catch (Exception e) {
System. out. println("Something went wrong.”);
}
1. Explain Internal Working of Java try-catch block?
Java try block is used to enclose the code that might throw an exception. It
must be used within the method. If an exception occurs at the particular
statement in the try block, the rest of the block code will not execute. So, it is
recommended not to keep the code in try block that will not throw an
exception. Java try block must be followed by either catch or finally block. Java
catch block is used to handle the Exception by declaring the type of exception
within the parameter. The declared exception must be the parent class
exception ( i.e., Exception) or the generated exception type. However, the good
approach is to declare the generated type of exception. The catch block must
be used after the try block only. You can use multiple catch block with a single
try block.

The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks: 1.Prints out exception description.

2.Prints the stack trace (Hierarchy of methods where the exception occurred).
3.Causes the program to terminate.
2. Explain throw and throws in Java?

Throw: The throw keyword in Java is used to explicitly throw an exception from
a method or any block of code. We can throw either checked or unchecked
exception. The throw keyword is mainly used to throw custom exceptions.

Syntax:
throw Instance
Example :
throw new ArithmeticException( "/ by zero" ) ;

The flow of execution of the program stops immediately after the throw
statement is executed and the nearest enclosing try block is checked to see if it
has a catch statement that matches the type of exception. If it finds a match,
controlled is transferred to that statement otherwise next enclosing try block is
checked and so on. If no matching catch is found then the default exception
handler will halt the program.

Throws: throw is a keyword in Java which is used in the signature of method to


indicate that this method might throw one of the listed type exceptions. The
caller to these methods has to handle the exception using a try-catch block.

Syntax:
type method _ name (parameters) throws exception _ list
exception _ list is a comma separated list of all the
exceptions which a method might throw.

In a program, if there is a chance of raising an exception then compiler always


warn us about it and compulsorily we should handle that checked exception,
Otherwise we will get compile time error saying unreported exception XXX must
be caught or declared to be thrown. To prevent this compile time error we can
handle the exception in two ways:

• By using try catch


• By using throws keyword

We can use throws keyword to delegate the responsibility of exception handling


caller (It may be a method or JVM) then caller method is responsible to handle
that exception.
3. How to Handle Checked & Unchecked Exceptions in Java.

Checked Exceptions in Java:


In broad terms, a checked exception (also called a logical exception) in Java is
something that has gone wrong in your code and is potentially recoverable. For
example, if there's a client error when calling another API, we could retry from that
exception and see if the API is back up and running the second time. A checked
exception is caught at compile time so if something throws a checked exception
the compiler will enforce that you handle it.
Checked Exception Examples:
Try Catch: You simply wrap the Java code which throws the checked exception
within a try catch block. This now allows you to process and deal with the
exception. With this approach it's very easy to swallow the exception and then
carry on like nothing happened. Later in the code when what the method was
doing is required you may find yourself with our good friend the
NullPointerException.
Throws : We use the keyword throws to throw the checked exception up the stack
to the calling method to handle. This is what FileInputStream has just done to you.
This looks and feels great - no messy exception code we are writing and we no
longer need to handle this exception as someone else can deal with it. The calling
method then needs to do something with it ... maybe throw again.
Unchecked Exceptions in Java: An unchecked exception (also known as an runtime
exception) in Java is something that has gone wrong with the program and is
unrecoverable. Just because this is not a compile time exception, meaning you do not
need to handle it, that does not mean you don’t need to be concerned about it. The most
common Java unchecked exception is the good old NullPointerException which is
when you are trying to access a variable or object that doesn’t exist.
BindException: Because we live in a world where systems are built from lots of
small micro services doing their own thing all talking to each other, generally over
HTTP, this exception is popping up more and more. There isn’t a lot you can do
about it other than find a free port. Only one system can use a single port at any
one time and it’s on a first come, first serve basis. Most web applications default
to port 8080 so the easiest option is to pick another one.
IndexOutOfBoundsException: This is a very common Java unchecked exception
when dealing with arrays. This is telling you; you have tried to access an index in
an array that does not exist. If an array has 10 items and you ask for item 11 you
will get this exception for your efforts.
4. Explain User-defined Custom Exception in Java. Why use custom exceptions?

An exception is an issue (run time error) that occurred during the execution of
a program. When an exception occurred the program gets terminated abruptly
and, the code past the line that generated the exception never gets executed.
Java provides us the facility to create our own exceptions which are basically
derived classes of Exception. Creating our own Exception is known as a
custom exception or user-defined exception. Basically, Java custom
exceptions are used to customize the exception according to user needs. In
simple words, we can say that a User-Defined Exception or custom exception
is creating your own exception class and throwing that exception using the
‘throw’ keyword.
For example, MyException in the below code extends the Exception class

User-defined Custom Exception in Java:Java exceptions cover almost all the


general types of exceptions that may occur in the programming. However, we
sometimes need to create custom exceptions.

Following are a few of the reasons to use custom exceptions:


 To catch and provide specific treatment to a subset of existing Java
exceptions.
 Business logic exceptions: These are the exceptions related to business
logic and workflow. It is useful for the application users or the developers
to understand the exact problem.
 In order to create a custom exception, we need to extend the Exception
class that belongs to java.lang package.
Example: We pass the string to the constructor of the superclass- Exception
which is obtained using the “getMessage()” function on the object created.
class MyException extends Exception {
public MyException(String s)
{
super(s);
}
}
public class Main {
public static void main(String args[])
{
try {
throw new MyException("GeeksGeeks");
}
catch (MyException ex) {
System.out.println("Caught");
System.out.println(ex.getMessage());
}
} }
1. What is Event Handling in Java?
An event can be defined as changing the state of an object or behaviour by
performing actions. Actions can be a button click, cursor movement,
keypress through keyboard or page scrolling, etc. The java.awt.event
package can be used to provide various event classes.
Classification of Events
1. Foreground Events: Foreground events are the events that require user
interaction to generate, i.e., foreground events are generated due to interaction by
the user on components in Graphic User Interface (GUI). Interactions are nothing
but clicking on a button, scrolling the scroll bar, cursor moments, etc.
2. Background Events: Events that don+üt require interactions of users to
generate are known as background events.
Event Handling:It is a mechanism to control the events and to decide what should
happen after an event occur. To handle the events, Java follows the Delegation
Event model. Delegation Event model: It has Sources and Listeners.
Source: Events are generated from the source. There are various sources like
buttons, checkboxes, list, menu-item, choice, scrollbar, text components, windows,
etc., to generate events.
Listeners: Listeners are used for handling the events generated from the source. Each of these
listeners represents interfaces that are responsible for handling events.
To perform Event Handling, we need to register the source with the listener.
Event Handling Within Class:
import java.awt.*;
import java.awt.event.*;
class GFG extends Frame implements ActionListener {
TextField textField;
GFGTop(){
textField = new TextField();
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);
button.addActionListener(this);
add(textField);
add(button);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
textField.setText("GFG!");
}
public static void main(String[] args)
{
new GFGTop();
}
}
2. What is AWT?Why AWT is platform independent?
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface
(GUI) or windows- based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed


according to the view of operating system. AWT is heavy weight i.e. its
components are using the resources of underlying operating system (OS).

The java.awt package provides classes for AWT API such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
The AWT tutorial will help the user to understand Java GUI programming in simple
and easy steps.
AWT is platform-independent:
Java AWT calls the native platform calls the native platform (operating systems)
subroutine for creating API components like TextField, ChechBox, button, etc.
For example, an AWT GUI with components like TextField, label and button will
have different look and feel for the different platforms like Windows, MAC OS, and
Unix. The reason for this is the platforms have different view for their native
components and AWT directly calls the native subroutine that creates those
components.
In simple words, an AWT application will look like a windows application in
Windows OS whereas it will look like a Mac application in the MAC OS.
3. Explain the Hierarchy of AWT?

The hierarchy of Java AWT classes are given below:

Components: All the elements like the button, text fields, scroll bars, etc. are
called components. In Java AWT, there are classes for each component as shown
in above diagram.
Container: The Container is a component in AWT that can contain another
components like buttons, textfields, labels etc. The classes that extends
Container class are known as container such as Frame, Dialog and Panel.
Types of containers:
Window:
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window. We need to create an
instance of Window class to create this container.
Panel: The Panel is the container that doesn't contain title bar, border or menu
bar. It is generic container for holding the components. It can have other
components like button, text field etc. An instance of Panel class creates a
container, in which we can add components.
Frame:
The Frame is the container that contain title bar and border and can have menu
bars. It can have other components like button, text field, scrollbar etc. Frame is
most widely used container while developing an AWT application.
4. Give the example of AWT by Inheritance?
Let's see a simple example of AWT where we are inheriting Frame
class. Here, we are showing Button component on the Frame.

AWTExample1.java

import java.awt.*;

public class AWTExample1 extends Frame {

AWTExample1() {

Button b = new Button("Click Me!!");

b.setBounds(30,100,80,30);

add(b);

setSize(300,300);

setTitle("This is our basic AWT example");


setLayout(null);

setVisible(true);
}

public static void main(String args[]) {


AWTExample1 f = new AWTExample1();

}
1. Explain about Inner Class in Java?
An inner class in Java is defined as a class that is declared inside
another class. Inner classes are often used to create helper
classes, such as views or adapters that are used by the outer class.
Inner classes can also be used to create nested data structures,
such as a linked list.

There are certain advantages associated with inner classes are as


follows:
 Making code clean and readable.
 Private methods of the outer class can be accessed, so bringing
a new dimension and making it closer to the real world.
 Optimizing the code module.

Types of Inner Classes


1. Nested Inner Class
2. Method Local Inner Classes
3. Static Nested Classes
4. Anonymous Inner Classes
1: Nested Inner Class :
It can access any private instance variable of the outer class.
Like any other instance variable, we can have access modifier
private, protected, public, and default modifier. Like class, an
interface can also be nested and can have access specifiers.
2: Method Local Inner Classes :
Inner class can be declared within a method of an outer class
which we will be illustrating in the below example where Inner is
an inner class in outerMethod().
3: Static Nested Classes:
Static nested classes are not technically inner classes. They are
like a static member of outer class.
4: Anonymous Inner Classes :
Anonymous inner classes are declared without any name at all.
They are created in two ways.
1. As a subclass of the specified type
2. As an implementer of the specified interface
2.Explain about Anonymous Inner Class in Java. What is the
difference between regular class(normal classes) and
Anonymous Inner class?
Nested Classes in Java is prerequisite required before adhering
forward to grasp about anonymous Inner class. It is an inner class
without a name and for which only a single object is created. An
anonymous inner class can be useful when making an instance of
an object with certain “extras” such as overriding methods of a
class or interface, without having to actually subclass a class.
The syntax of an anonymous class expression is like the
invocation of a constructor, except that there is a class definition
contained in a block of code.
Syntax:
Test t = new Test()
{
public void test_method(){
........
........
}
};
difference between regular class(normal classes) and Anonymous
Inner class
 A normal class can implement any number of interfaces but the
anonymous inner class can implement only one interface at a
time.
 A regular class can extend a class and implement any number
of interfaces simultaneously. But anonymous Inner class can
extend a class or can implement an interface but not both at a
time.
 For regular/normal class, we can write any number of
constructors but we can’t write any constructor for anonymous
Inner class because the anonymous class does not have any
name and while defining constructor class name and
constructor name must be same .
3.Explain Java Adapter Classes with example?
In JAVA, an adapter class allows the default implementation of listener
interfaces. The notion of listener interfaces stems from the Delegation
Event Model. It is one of the many techniques used to handle events in
Graphical User Interface (GUI) programming languages, such as JAVA.

Pros of using Adapter classes:

o It assists the unrelated classes to work combinedly.


o It provides ways to use classes in different ways.
o It increases the transparency of classes.
o It provides a way to include related patterns in the class.
o It provides a pluggable kit for developing an application.
o It increases the reusability of the class.

The adapter classes are found in java.awt.event,


java.awt.dnd and javax.swing.event packages.
Java WindowAdapter Example: In the following example, we are
implementing the WindowAdapter class of AWT and one its methods
windowClosing() to close the frame window.
import java.awt.*;
import java.awt.event.*;
public class AdapterExample {
Frame f;
AdapterExample() {
f = new Frame ("Window Adapter");
f.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e) {
f.dispose();
}
});
f.setSize (400, 400);
f.setLayout (null);
f.setVisible (true);
}
public static void main(String[] args) {
new AdapterExample();
}}
Java MouseAdapter Example: In the following example, we are
implementing the MouseAdapter class. The MouseListener interface is
added into the frame to listen the mouse event in the frame.
MouseMotionAdapterExample.java
import java.awt.*;
import java.awt.event.*;
public class MouseMotionAdapterExample extends MouseMotionAdapter {
Frame f;
MouseMotionAdapterExample() {
f = new Frame ("Mouse Motion Adapter");
f.addMouseMotionListener (this);
f.setSize (300, 300);
f.setLayout (null);
f.setVisible (true);
}
public void mouseDragged (MouseEvent e) {
Graphics g = f.getGraphics();
g.setColor (Color.ORANGE);
g.fillOval (e.getX(), e.getY(), 20, 20);
}
public static void main(String[] args) {
new MouseMotionAdapterExample();
}
}
Java MouseMotionAdapter Example

In the following example, we are implementing the MouseMotionAdapter


class and its different methods to listen to the mouse motion events in the
Frame window.
4. Explain the following AWT classes:
i. Label
ii. Button
iii. TextField?
Label:The object of the Label class is a component for placing text in a
container. It is used to display a single line of read only text. The text can
be changed by a programmer but a user cannot edit it directly.
Button:A button is basically a control component with a label that
generates an event when pushed. The Button class is used to create a
labeled button that has platform independent implementation. The
application result in some action when the button is pushed.
TextField: The textField component allows the user to edit single line of
text.When the user types a key in the text field the event is sent to the
TextField. The key event may be key pressed, Key released or key
typed. The key event is passed to the registered KeyListener.
1. What is interface and package in Java?
A package is an organized set of related classes and interfaces whereas an
interface is a set of fields and abstract methods that mainly allows
implementing abstraction. Thus, this is the main difference between the
package and interface.
Access: Moreover, it is possible to access a package using an import
statement while it is possible to extend an interface using another interface
or by implementing it using a class.
Keyword: Another difference between a package and an interface is that the
import keyword helps to access a package while the implement keyword
helps to access an interface.
Usage: Their respective usage also contributes to a difference between the
package and interface. That is; a package helps to organize the classes and
interfaces to improve maintainability while an interface helps to achieve
abstraction and to implement multiple inheritances.
Conclusion: Package and interface are two concepts in programming
languages such as Java. The main difference between a package and an
interface is that a package is a collection of related classes and interfaces
while an interface is a collection of fields and abstract methods.
2. What is access control mechanism?
An access control mechanism is a security safeguard (i.e., hardware and
software features, physical controls, operating procedures, management
procedures, and various combinations of these) designed to detect and deny
unauthorized access and permit authorized access to an information system
or physical facility.
In Java, access control tells the program how much access a variable, class or
method is given. Access control is important because it affects visibility based
on different access control types.
Access Control Example.java
3. What is Dynamic Method Lookup?
Dynamic method lookup is the process of determining which method
definition a method signature denotes during runtime, based on the type of
the object. However, a call to a private instance method is not polymorphic.
Such a call can only occur within the class, and gets bound to the private
method implementation at compile time.
Dynamic method lookup is the process of determining which method
definition a method signature denotes during runtime, based on the type of
the object. However, a call to a private instance method is not polymorphic.
Such a call can only occur within the class, and gets bound to the private
method implementation at compile time.
4. Does importing a package make sub-packages class files available to the
application?
No. Importing a package does not make sub-packages class files available to
the application.
1. Explain package with example?

A java package is a group of similar types of classes, interfaces and


sub-packages. Package in java can be categorized in two form, built-
in package and user-defined package. There are many built-in
packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-
defined packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so
that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
4) One package can be defined in another package.
Types of Packages:
There are two types of packages available in Java.
1. Built-in packages: Built-in packages are already defined in java API.
For example: java.util,java.io,java,lang,java.awt, java.applet, java.net,
etc.
2. User-defined packages: The package we create according to our
need is called user defined package.
Creating a Package
We can create our own package by creating our own classes and
interfaces together. The package statement should be declared at the
beginning of the program.
example of java package
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile java package


javac -d directory javafilename

For example: javac -d . Simple.java


2. Explain interface with example?
Interface in Java: An interface in Java is a blueprint of a class. It has
static constants and abstract methods. The interface in Java is a
mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.
 Interface is similar to a class, but it contains only abstract
methods.
 By default, the variables declared in an interface are public,
static and final.
 The interface is a mechanism to achieve full abstraction.
 An interface does not contain any constructor.

Syntax:

interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}

Java Interface Example: In this example, the Printable


interface has only one method, and its implementation is provided in
the A6 class.

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}
Output: Hello
3. Explain Dynamic Method look up and write program for usage of
java.io.ObjectStreamClass.lookup() method?
The following example shows the usage of
java.io.ObjectStreamClass.lookup() method.
Dynamic method lookup is the process of determining which method
definition a method signature denotes during runtime, based on the
type of the object. However, a call to a private instance method is not
polymorphic. Such a call can only occur within the class, and gets
bound to the private method implementation at compile time.
4. What will happen if we are not implementing all the methods
of an interface in class which implements an interface?

• A class which implements an interface should implement all the


methods (abstract) otherwise compiler will throw an error.
• The type Example must implement the inherited abstract
method Javalnterface.show()
• If we declare class as abstract no need to implement methods.
• No need of overriding default and static methods.
1. What are the 4 types of Java applications?
Java is a high level secured object oriented programming language. Java has
developed by sun micro-systems and latterly hand over to the oracle
corporation. Java is widely used in mobile phones to enterprise servers,
computing platforms. Java is platform independent software that is which
can work every platform.
Types of Java Applications
1. Standalone applications
2. Web applications
3. Enterprise applications
4. Mobile applications
Standalone Applications : A program is run by as separate computer process
without adding an existing files process is known as standalone application.
And also it does not require operating systems process. AWT (Abstract
Window Toolkit) and swing are used to create stand alone application.
Web Applications: Web application is a client server software application
which is run by the client. Web application includes mail, online retail sales,
Wikipedia information's. Servlet, jsp, jsf which are used to create web
applications.
Enterprise Application: Enterprise application is related to middle ware
applications. To enable software application and hardware systems we are
using technologies and services across the enterprises. So we are calling it as
enterprise application. Enterprise applications are mainly designed for
corporate sides such as banking business systems.
Mobile Application:
Mobile application is developed for run the mobile phones and tablets.
2. What is Java and what are their components?
It is a simple programming language. Java makes writing, compiling, and
debugging programming easy. It helps to create reusable code and modular
programs. Java is a class-based, object-oriented programming language and
is designed to have as few implementation dependencies as possible. A
general-purpose programming language made for developers to write once
run anywhere that is compiled Java code can run on all platforms that
support Java. Java applications are compiled to byte code that can run on any
Java Virtual Machine. The syntax of Java is similar to c/c++.
There are three main components of the Java programming language:
1. Java Virtual Machine (JVM): JVM is an engine that provides a runtime
environment to drive the Java code or applications. It is the centre of the
programming language and performs the operation of converting Java
bytecode into machine language. It provides numerous libraries, frameworks,
and tools.
2. Java Runtime Environment (JRE): JRE is a runtime environment that is
required to execute Java programs and applications. If a user wants to run a
Java program in their machine, they must have JRE installed on the machine.
It's platform-dependent, meaning the JRE installed must be compatible with
the user's operating system and architecture.
3. Java Development Kit (JDK): JDK is the core component of the Java
environment. It contains JRE along with Java compiler, Java debugger, and
other classes. It's used for Java development to provide the entire
executables and binaries as well as the tools to compile and debug a Java
program.
3. What are the differences between C++ and Java?
4. What are the Operators in Java?
Java operators are symbols that are used to perform operations on
variables and manipulate the values of the operands. Each operator
performs specific operations
Types of Java Operators:
1. Unary Operators
2. Arithmetic Operators
3. Assignment Operators
4. Logical Operators
5. Shift Operators
6. Bitwise Operators
7. Ternary Operators
8. Relational Operators

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive ^

OR

bitwise inclusive |

OR

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<=


>>= >>>=
1. What are the characteristics of java?
Simple: • Java is Easy to write and more readable and eye catching.
• Java has a concise, cohesive set of features that makes it easy to learn and
use.
• Most of the concepts are drew from C++ thus making Java learning simpler.
Secure: • Java program cannot harm other system thus making it secure.
• Java provides a secure means of creating Internet applications.
• Java provides secure way to access web applications.
Portable: • Java programs can execute in any environment for which there is
a Java run-time system. (JVM)
• Java programs can be run on any platform (Linux, Window, Mac)
• Java programs can be transferred over world wide web (e.g. applets)
Object-oriented: • Java programming is object-oriented programming
language.
• Like C++ java provides most of the object-oriented features.
• Java is pure OOP. Language. (While C++ is semi object oriented)
Robust: • Java encourages error-free programming by being strictly typed
and performing run-time checks.
Multithreaded: • Java provides integrated support for multithreaded
programming.
Architecture-neutral: • Java is not tied to a specific machine or operating
system architecture.
• Machine Independent i.e. Java is independent of hardware.
Interpreted: Java supports cross-platform code through the use of Java
bytecode.
Bytecode can be interpreted on any platform by JVM.
High performance: Bytecodes are highly optimized.
JVM can executed them much faster.
Distributed: • Java was designed with the distributed environment.
• Java can be transmitted, run over internet.
Dynamic: • Java programs carry with them substantial amounts of run-time
type information that is used to verify and resolve accesses to objects at run
time.
2.What is the difference between JDK, JRE, and JVM?
JVM is an acronym for Java Virtual Machine; it is an
abstract machine which provides the runtime
environment in which Java bytecode can be executed.
It is a specification which specifies the working of Java
Virtual Machine. Its implementation has been provided
by Oracle and other companies. Its implementation is
known as JRE.
JVMs are available for many hardware and software
platforms (so JVM is platform dependent). It is a
runtime instance which is created when we run the
Java class. There are three notions of the JVM:
specification, implementation, and instance.
JRE stands for Java Runtime Environment. It is the
implementation of JVM. The Java Runtime Environment
is a set of software tools which are used for developing
Java applications. It is used to provide the runtime
environment. It is the implementation of JVM. It
physically exists. It contains a set of libraries + other
files that JVM uses at runtime.
JDK is an acronym for Java Development Kit. It is a
software development environment which is used to
develop Java applications and applets. It physically
exists. It contains JRE + development tools. JDK is an
implementation of any one of the below given Java
Platforms released by Oracle Corporation:
1. Standard Edition Java Platform
2. Enterprise Edition Java Platform
3. Micro Edition Java Platform
3. What is a data type in Java?
Data types are divided into two groups:
1. Primitive data types: The primitive data types include boolean,
char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
There are five types of non-primitive data types in Java. They are as
follows:

Class and objects: A class in Java is a user defined data type i.e. it is
created by the user. It acts a template to the data which consists of
member variables and methods. An object is the variable of the class,
which can access the elements of class i.e. methods and variables.

Interface: An interface is similar to a class however the only difference


is that its methods are abstract by default i.e. they do not have body.
An interface has only the final variables and method declarations. It
is also called a fully abstract class.

String: A string represents a sequence of characters for example "Java


point", "Hello world", etc. String is the class of Java.

Array: An array is a data type which can store multiple homogenous


variables i.e., variables of same type in a sequence. They are stored in
an indexed manner starting with index 0. The variables can be either
primitive or non-primitive data types.
4. What are the 3 jump statements in Java?
Jump statements help amend the flow of execution by jumping to
another piece of code in the program. That's why it is also known as
branching statements, as they create a different branch to the flow
of execution.
Following are the Jump statements in Java:
1) Break Statement
2) Continue Statement
3) Return Statement
Break Statement: The break statement is commonly used with the
iteration statements such as for loop, while loop, and do-while loop.
Break statements in Java generally used in 3 ways;
 Exiting a Loop: A break statement uses to exit an existing loop,
especially an infinite loop.
 As a form of Goto :In Java, this construct transfers the control
from one part of the program to another. Java does not use
goto statements as it generates a lot of unmaintainable codes.
Instead, it uses break as a form of goto.
 In a Switch Case: A break statement is used in switch case
statements to bypass all the other cases and jumps out of the
switch statement.
Continue Statement: Unlike break, the continue statement in java can
only work inside loops. It doesn't come out of the loop like a break.
Instead, it forces the next iteration of the loop to bypass all the
statements falling under it.
Return Statement: Return statements are the jump statements used
inside methods (or functions) only. Any code in the method which is
written after the return statement might be treated as unreachable
by the compiler. Then return statement terminates the execution of
the current method and passes the control to the calling method.
1. What is common and how do the following streams differ:
InputStream, OutputStream, Reader,Writer?
The base class InputStream represents classes that receive data from
various sources:
- an array of bytes
- a string (String)
-a file
- a pipe (pipe): data is placed from one end and extracted from the
other
- a sequence of different streams that can be combined into one
stream
- other sources (e.g. internet connection)
The class OutputStream is an abstract class that defines stream byte
output. In this category are classes that determine where your data
goes: to an array of bytes (but not directly to String; it is assumed
that you can create them from an array of bytes), to a file or channel.

Character streams have two main abstract classes, Reader and Writer,
which control the flow of Unicode characters. The Reader class is an
abstract class that defines character streaming input. The Writer class
is an abstract class that defines character stream output. In case of
errors, all class methods throw an IOException .
2. Which super structure class allows reading data from an input byte
stream in the format of primitive data types?
To read byte data (not strings), the DatalnputStream class is used . In
this case, you must use the classes from the InputStream group .
To convert a string to a byte array suitable for placement into a
ByteArraylnputStream stream, the getBytes () method is provided in
the Stringclass. The resulting ByteArraylnputStream is an
InputStream stream suitable for passing a DatalnputStream .

When reading characters byte from the Data InputStream formatted


stream using the readByte () method, any resulting value will be
considered valid, so the return value is not applicable to identify the
end of the stream. Instead, you can use the available () method ,
which tells you how many characters are left.
The DatalnputStream class allows you to read elementary data from
a stream through the Datalnput interface , which defines methods
that convert elementary values into a sequence of bytes. Such
streams make it easy to save binary data to a file.
Constructor: DatalnputStream (lnputStream stream)
Methods: readDouble (), readBoolea(), readlnt ()

3. What class add-on allows you to speed up reading / writing by


using a buffer?
To do this, use classes that allow you to buffer stream:
java.io.BufferedlnputStream (InputStream in) ||
BufferedlnputStream (InputStream in, int size),

java.io.BufferedOutputStream (OutputStream out) I I


BufferedOutputStream (OutputStream out, int size),

java.io.BufferedReader (Reader r)||BufferedReader (Reader in, int sz),

java.io.BufferedWriter (Writer out)llBufferedWriter (Writer out, int


sz)
4. What are the I/0 streams Java programming language?
I/0 streams in Java programming language represent input
sources from which data is read, and output destinations to
which data is written. Streams support different kinds of
data including bytes, characters, primitive types and
objects.
Byte Streams - java.io package has two abstract classes
InputStream and OutputStream that represents input
stream and output stream of byte data type.
Character Streams - java.io package has two abstract
classes Reader and Writer that represents input stream and
output stream of character data type.
Primitive data streams- java.io package has two interfaces
classes Datalnput and DataOutput that represents input
stream and output stream of primitive data type.
Object streams- java.io package has two interfaces
Objectlnput and ObjectOutput that represents input stream
and output stream of object data type.
1. What are the Ways to read input from the console in
Java?
In Java, there are four different ways for reading input from
the user in the command line environment(console).
1. Using Buffered Reader Class
This is the Java classical method to take input, Introduced
in JDKI.O. This method is used by wrapping the System.in
(standard input stream) in an InputStreamReader which is
wrapped in a Buffered Reader, we can read input from the
user in the command line.
2. Using Scanner Class:
This is probably the most preferred method to take input.
The main purpose of the Scanner class is to parse primitive
types and strings using regular expressions, however, it is
also can be used to read input from the user in the
command line.
Convenient methods for parsing primitives (nextlnt(),
nextFloat(), ...) from the tokenized input.
3. Using Console Class:
It has been becoming a preferred way for reading user's
input from the command line. In addition, it can be used for
reading password-like input without echoing the characters
entered by the user; the format string syntax can also be
used (like System.out.printf()).
4. Using Command line argument:
Most used user input for competitive coding. The command-
line arguments are stored in the String format. The parselnt
method of the Integer class converts string argument into
Integer. Similarly, for float and others during execution. The
usage of args[] comes into existence in this input form. The
passing of information takes place during the program run.
The command line is given to args[]. These programs have
to be run on cmd.
2. Explain Console writer() method in Java with Examples?
The writer() method of Console class in Java is used to
retrieves the unique PrintWriter object which is associated
with the console.
Syntax:
public PrintWriter writer()
Parameters: This method does not accept any parameter.
Return value: This method returns the PrintWriter which is
associated with the console.
3. Give example of Java Reading from Text File and Java
Writing to Text File?
Reader is the abstract class for reading character
streams. It implements the following fundamental
methods:

• read(): reads a single character.

• read(char[]): reads an array of characters.

• skip(long): skips some characters.

• close(): closes the stream.

FileReader is a convenient class for reading text files


using the default character encoding of the operating
system.

Java Reading from Text File Example:

The following small program reads every single character


from the file MyFile.txt and prints all the characters to the
output console:
package net.codejava.io;
import java.io.FileReader;
import java.io.IOException;

public class TextFileReadingExample1 {


public static void main(String[] args) {
try {
FileReader reader = new FileReader("MyFile.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writer is the abstract class for writing character streams.
It implements the following fundamental methods:
• write(int): writes a single character.
• write(char[]): writes an array of characters.
• write(String): writes a string.
• close(): closes the stream.
FileWriter is a convenient class for writing text files using
the default character encoding of the operating system.
Java Writing to Text File Example:
In the following example, a FileWriter is used to write two
words "Hello World" and "Good Bye! " to a file named
MyFile.txt:
package net.codejava.io;

import java.io.FileWriter;
import java.io.IOException;

public class TextFileWritingExample1 {

public static void main(String[] args) {


try {
FileWriter writer = new
FileWriter("MyFile.txt", true);
writer.write("Hello World");
writer.write("\r\n");
writer.write("Good Bye!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}

}
4. Explain byte stream and character stream with
examples?
Byte Streams:
Java byte streams are used to perform input and output of
8-bit bytes. Though there are many classes related to byte
streams but the most frequently used classes are,
FilelnputStream and FileOutputStream. Following is an
example which makes use of these two classes to copy an
input file into an output file –

Character Streams:
Java Byte streams are used to perform input and output of
8-bit bytes, whereas Java Character streams are used to
perform input and output for 16-bit Unicode. Though there
are many classes related to character streams but the
most frequently used classes are, FileReader and
FileWriter. Though internally FileReader uses Filel
nputStream and FileWriter uses FileOutputStream but here
the major difference is that FileReader reads two bytes at
a time and FileWriter writes two bytes at a time.
1.State difference between HTML and XHTML?
HTML XHTML

HTML stands for Hypertext Markup XHTML stands for Extensible


Language. Hypertext Markup Language.

It was developed in 1991. It was released in 2000.

It is extended from XML and


It is extended from SGML. HTML.

The format is a markup


The format is a document file format. language.

All tags and attributes are not


necessarily to be in lower or upper In this, every tag and attribute
case. should be in lower case.

Doctype is not necessary to write at Doctype is very necessary to


the top. write at the top of the file.

It is not necessary to close the tags It is necessary to close the tags


in the order they are opened. in the order they are opened.

Filename extension used are .html, Filename extension are .xhtml,


.htm. .xht, .xml.
2. What are elements and tags, and what are the
differences between them?
HTML Tags: Tags are the starting and ending parts of an HTML element. They
begin with < symbol and end with > symbol. Whatever is written inside < and
> are called tags.
Example: <b> </b>
HTML elements: Elements enclose the contents in between the tags. They
consist of some kind of structure or expression. It generally consists of a start
tag, content, and an end tag.
Example: <b>This is the content.</b>
Difference between HTML Tag & HTML Element:

3. Are <b> and <strong> tag same? If not, then why?


HTML strong tag: The strong tag is one of the elements of HTML used in
formatting HTML texts. It is used to show the importance of the text by
making it bold or highlighting it semantically.
Syntax: <strong> Contents... </strong>
HTML bold tag: The bold tag or <b> is also one of the formatting elements of
HTML. The text written under the <b> tag makes the text bold presentation
ally to draw attention.
Syntax: <b> Contents... </b>
The main difference between the <bold> tag & <strong> tag is that the strong
tag semantically emphasizes the important word or section of words while
the bold tag is just offset text conventionally styled in bold.
4. How do you create frames in HTML?
To use frames on a page we use <frameset> tag instead of tag. The
<frameset> tag defines, how to divide the window into frames. The rows
attribute of <frameset> tag defines horizontal frames and the cols attribute
defines vertical frames. Each frame is indicated by <frame> tag and it defines
which HTML document shall open into the frame.
Example:
Following is the example to create three horizontal frames –
1. How to implement various types of lists in HTML?
The List can be used to store the information in short, either in bulleted form
or numbered format, that visually help to look at a glance. In other words, it is
used to group together related items or lists, & used to structure and show
important information where each list item is displayed on the new line.
HTML lists allow the content to follow a proper semantic structure. All the tags
in the list require opening and closing tags. There are 3 types of lists in HTML,
namely:
 Unordered List
 Ordered List
 Description List
We will explore all the List types in HTML, along with their implementation
through the examples.
Unordered List: An Unordered list is used to create a list of related items, in
bulleted or unordered format. It starts with the <ul> tag, followed by the <li>
tag to show list items inside <ul> tag.
Syntax:
<ul>
<li>Item1</li>
...
</ul>
We can also use different CSS properties to create a list with different styles.
It can have one of the following values :
 circle: It gives a circle list item marker.
 square: It gives square as list item marker.
 disc: This is the default filled circular bullet item marker.
 none: This is used to unmark list items.
Ordered Lists: The Ordered lists have an order which is either numerical or
alphabetical. The <ol> tag is used to create ordered lists in HTML and just like
unordered list, we use <li> tag to define or show lists inside <ol> tag.
Syntax:
<ol>
<li>Item1</li>
<li>Item2</li>
<li>Item3</li>
</ol>
Description List: A description list is a type of list where each item has a
description. It is also known as a definition list. The <dl> tag is used to create
description list, the <dt> tag defines the item, and the <dd> tag describes
each item in list. Syntax: <dl> Contents... </dl>
2.GIve an example of the following:
1) Unordered List
2) Ordered List
3) Description List ?
1) Unordered List:

2) Ordered List:

3) Description List:
3. Explain HTML Tables with examples?
HTML Table is an arrangement of data in rows and columns, or possibly in a
more complex structure.Tables are widely used in communication, research,
and data analysis. Tables are useful for various tasks such as presenting text
information and numerical data. It can be used to compare two or more
items in the tabular form layout. Tables are used to create databases.
Defining Tables in HTML: An HTML table is defined with the "table" tag. Each
table row is defined with the "tri' tag. A table header is defined with the "th"
tag. By default, table headings are bold and centered. A table data/cell is
defined with the "td" tag.
<!DOCTYPE html>
<html>

<head>
<title>HTML Tables</title>
</head>

<body>
<table border = "1">
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>

<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>

</body>
</html>
4. Explain HTML style sheet with example?
Cascading Style Sheets (CSS) provide easy and effective
alternatives to specify various attributes for the HTML tags. Using
CSS, you can specify a number of style properties for a given HTML
element. Each property has a name and a value, separated by a colon
(:). Each property declaration is separated by a semi-colon (;).
Example
First let's consider an example of HTML document which makes use
of <font> tag and associated attributes to specify text color and font
size –
<!DOCTYPE html>
<html>

<head>
<title>HTML CSS</title>
</head>

<body>
<p><font color = "green" size = "5">Hello, World!</font></p>
</body>

</html>
We can re-write above example with the help of Style Sheet as
follows −
<!DOCTYPE html>
<html>

<head>
<title>HTML CSS</title>
</head>

<body>
<p style = "color:green; font-size:24px;" >Hello, World!</p>
</body>

</html>
This will produce the following result -
Hello, World!
4. What are the String Comparison Methods?
The String class includes a number of methods that compare strings or
substrings within strings.
i. equals(Object anObject)
ii. equalslgnoreCase(String str)
iii. regionMatches( )
iv. startsWith( ) methods
v. endsWith( ) methods
vi. equals( ) Versus ==
vii. compareTo( )
viii. compareTolgnoreCase(String str)
3. What is the difference between Array List and Linked List?

ArrayList LinkedList

1. ArrayList internally uses 1. LinkedList internally uses


a dynamic array to store a doubly linked list to store
the elements. the elements.

2. Manipulation with 2. Manipulation with LinkedList


ArrayList is slow because is faster than ArrayList
it internally uses an array. because it uses a doubly
If any element is removed linked list, so no bit shifting
from the array, all the is required in memory.
other elements are shifted
in memory.

3. An ArrayList class can act 3. LinkedList class can act as a


as a list only because it list and queue both because
implements List only. it implements List and Deque
interfaces.

4. ArrayList is better for 4. LinkedList is better for


storing and manipulating data.
accessing data.

5. The memory location for 5. The location for the elements


the elements of an of a linked list is not
ArrayList is contiguous. contagious.
4. What is the difference between Iterator and List Iterator?

You might also like