0% found this document useful (0 votes)
69 views

Core Java

Nested classes allow one class to be defined within another. There are two types of nested classes: non-static (inner) classes and static nested classes. Non-static nested classes can access all variables and methods of the outer class, while static nested classes can only access outer class members through an object. Interfaces allow classes to achieve abstraction and support multiple inheritance by defining methods without implementation. Inheritance allows classes to extend the properties and behaviors of other classes to create subclass hierarchies.

Uploaded by

Amit Thube
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Core Java

Nested classes allow one class to be defined within another. There are two types of nested classes: non-static (inner) classes and static nested classes. Non-static nested classes can access all variables and methods of the outer class, while static nested classes can only access outer class members through an object. Interfaces allow classes to achieve abstraction and support multiple inheritance by defining methods without implementation. Inheritance allows classes to extend the properties and behaviors of other classes to create subclass hierarchies.

Uploaded by

Amit Thube
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Chapter 3rd - Nested Class - It is possible to put the definition of one class inside the definition of another class.

The
class which is defined inside is called nested class. Inner class is a part of nested class. Non-static nested classes are
known as inner classes.

Types of Nested Classes: There are two types of nested classes, Non-static and Static nested classes. The Non- static
nested classes are also known as Inner Classes.

(i) Non-static Nested Class: The nested class for which static modifier is not applied, such a class is known as non-
static nested class. This class can also be refer as inner class, because it is fully within the scope of its enclosing class.
It has access to all the variables and methods of its outer class or enclosing class. Static Nested Class: A class which is
defined as a static inside other enclosing class, such a class is called as Static Nested Class. This type of nested class,
cannot refer any member of its enclosing class directly, that means it must access members of enclosing class
through an object.

Inner Classes - Inner classes are syntactic feature that was added to Java in JDK 1.1. They provide a convenient way
for a developer to define classes within the body of another class. Java inner class or nested class is a class i.e.
declared inside the class or interface. We use inner classes to logically group classes and interfaces in one place so
that it can be more readable and maintainable. Additionally, it can access all the members of outer class including
private data members and methods.

Advantages of Inner Classes: 1. Inner classes can access all members of the outer class including private members. 2.
Inner classes help you hide the implementation of a class completely. 3. Inner classes provides a shorter way of
writing listeners. 4. Inner classes helps us to write optimized code. 5. It requires less code to write.

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 overloading
methods of a class or interface, without having to actually subclass a class. A class that have no name is known as
anonymous inner class in Java. It should be used if you have to override method of class or interface. Java
Anonymous inner class can be created by two ways: 1. Class (may be abstract or concrete) 2. Interface.

OVERVIEW OF INHERITANCE : Object Oriented Programming (OOP) allows you to create new class based on a class
that has been already defined using inheritance. It is an important feature of the OOP's because it supports the
hierarchical classifications, reusability of class and defined to specialization. Using inheritance, a class can be
inherited by another class. This base class is called superclass and the inherited class is called as subclass. Inheritance
represents the 'IS-A relationship', also known as 'parent-child relationship'. To support the concept of multiple
inheritance, Java provides the alternative approach known as Interface. Inheritance is the capability of a class to use
the properties and methods of another class while adding its own functionality. Inheritance can be defined as, "the
process where one object acquires the properties of another". In simple words, the mechanism of deriving a new
class from an old class is called inheritance. A class that is derived from any another class is called a subclass or
derived class or extended class or child class. The class from which a subclass is derived is called super class or base
class or parent class.

Advantages of Inheritance: 1. Reusability of code. 2. Easy and simple to understand since model structure is
provided. 3. Code is easily managed by dividing into parent and child classes. 4. Coding can be done using existing
classes and representing the objects. 5. It's used easily to convert smaller systems into larger systems.

extends Keyword - To inherit a class, we have to simply incorporate the definition of one class into another by using
the 'extends' keyword. The keyword 'extends' specifies that the properties of superclassname are extended to
subclassname. After this the subclass will contain all the methods of super class and it will add the members of its
own. Note that we cannot extend a subclass from more than one super class. Direct multiple inheritance is not
supported in Java.

Types of Inheritance : 1. Single Inheritance: In this one class extends another class at single level. In case of single
inheritance there is only a sub class and it's parent class. It is also called simple inheritance or one level inheritance.
2. Multilevel Inheritance: We can create any layers/levels in the inheritance as we want, this is called Multilevel
Inheritance. This hierarchy can be created at any level of inheritance. When a subclass is derived from a derived class
then this mechanism is known as the Multilevel Inheritance. The derived class is called the subclass or child class for
its parent class and this parent class works as the child class for it's just above (parent) class. 3. Hierarchical
Inheritance: When a class has more than one child classes (sub classes) have the same parent class then such kind of
inheritance is known as Hierarchical Inheritance. In case of hierarchical inheritance we derive more than one
subclass from a single super class.

INHERITANCE IN CONSTRUCTOR : The constructors never get inherited to any child class in inheritance. In Java, the
default constructor of a parent class is called automatically by the constructor of its child class. When an object of
the child class is created, the parent class constructor is executed, followed by the child class constructor's
execution. However, if the parent class contains both default and parameterized constructor, then only the default
constructor is called automatically by the child class constructor.

INHERITING DATA MEMBERS AND METHODS - In inheritance one class attributes or methods can be inherited in
another class. in Java extends keyword is used for inheritance. The class whose properties/ attributes and methods
are inherited is called Super class or base class or parent class. Child class/subclass can extend the
attributes/methods of Parent class and also can have its own attributes and methods. Use of 'super' Keyword A
subclass inherits the accessible data fields and methods from its superclass, but the constructors of the superclass
are not inherited in the subclass. They can only be invoked from constructors of the subclass using the keyword
'super'. When invoking a superclass version of an overridden method the super keyword is used. 'super' keyword is
used by subclass to refer its immediate superclass.

INTERFACE : An interface in Java is a blueprint of a class. It has static constants and abstract methods only. An
interface is a way of describing what classes should do, without specifying how they should do it. There are mainly
three reasons to use interface. They are given below: 1. It is used to achieve fully abstraction. 2. By interface, we can
support the functionality of multiple inheritance. 3. It can be used to achieve loose coupling.

A class can implement more than one interface. In Java, an interface is not a class but a set of requirements for the
class that we want to conform to the interface. All the methods of an interface are by default public. So, it is not
required to use the keyword public when declaring a method in an interface. Interfaces can also have more than one
method. Interfaces can also define constants but do not implement methods.

INTERFACE INHERITANCE - Extending Interfaces: An interface can extend another interface, similarly to the way that
a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits
the methods of the parent interface. When any class implements an extended interface, it must implement all the
methods defined within the chain of inherited interfaces. Consider the following program, an interface emp_show
inherits all the members of an interface emp_info. The class emp is implementing an interface emp_show, it must
define the code of all the methods declared in emp_info as well as emp_show.

DYNAMIC METHOD DISPATCH/RUNTIME POLYMORPHISM - Runtime Polymorphism: Polymorphism in Java is a


concept by which different ways can we used to perform different action. Polymorphism implies many forms which
is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. Method
overriding is an example of runtime polymorphism. Types of polymorphism in Java: compile-time polymorphism and
runtime polymorphism. Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time. In this process, an overridden method is called
through the reference variable of a superclass. The determination of the method to be called is based on the object
being referred by the reference variable. We can perform polymorphism in java by method overloading and method
overriding. When reference variable of Parent class refers to the object of Child class, it is known as Upcasting. In
following program, we are creating two classes Bike and Platina. Platina class extends Bike class and overrides its
run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass
object and subclass method overrides the Parent class method, subclass method is invoked at run-time. Since
method invocation is determined by the JVM not compiler, it is known as Run- time Polymorphism.

PABSTRACT CLASS - An abstract class is a class in which one or more methods are declared, but not defined. That
means the body of these methods are omitted. Such methods are called Abstract Methods. Abstract class cannot be
instantiated. Class that is declared with abstract keyword, is known as Abstract Class in Java. Abstract class is a
superclass that only defines a generalized form which will be shared by all of its subclasses. The purpose of abstract
class is to function as base classes which can be extended by subclasses to create a full implementation. When a
class contains one or more abstract methods, then it should be declared abstract. You must use abstract keyword to
make a class abstract.

PACKAGES - Java is an Object Oriented programming language. Any Java programmer will quickly build large number
of different classes for use in each application that they develop. Initially it may be tempting to store the classes in
the same directory as the end application, but as the complexity of applications grow so will the number of classes.
The answer is to organize the classes into packages. A Java package is a mechanism for organizing Java classes.
Package are used in Java, in-order to avoid name conflicts and to control access of class, interface and enumeration
etc. A package can be defined as, "a group of similar types of classes, interface, enumeration and sub-packages". A
package does not contain the source code of any type of Java file. Each Java source code file is a collection of one or
more classes, or one or more interface with their members.

COLLECTION - Java.util is an important package which contains a large collection of classes and interfaces which
supports a broad range of functionality. It contains Java's most powerful subsystem collections framework.
Collection Framework is a sophisticated hierarchy of classes and interfaces for managing groups of objects. Java
Collections is the standard way of groups of objects that are used by your program. Collections were not part of the
initial Java release. It was added by J2SE 1.2. Before Collections framework, Java had ad hoc classes such as
Dictionary, Vector, Stack and Properties for manipulating groups of objects. Collections altered the architecture of
many utility classes. But it did not deprecate any of the previously used classes. It simply provides a better way
of doing things.

Collection Framework : The Collections Framework defines several interfaces. Collections interfaces determine the
fundamental nature of Collection classes. Goals of Collection Framework: Framework had to be high performance.
Implementations for fundamental collections are highly efficient. Framework had to allow different types of
collections to work in a similar manner. Extending and / or adapting a collection had to be easy. Entire Collection
Framework is built upon a set of standard interfaces. Java has provided several implementations of these interfaces
like LinkedList, HashSet, TreeSet etc. You can use these implementations as it is. But you can implement your own
Collection as Java provides mechanism for integrating standard arrays into the Collections framework.

Collection Interface - Collection in java represents a single unit of objects i.e. a group. The Java Collection interface is
the root of the collection interface hierarchy. The Collection interface is the foundation upon which the collections
framework is built. It declares the core methods that all collections will have. Because all collections implement
Collection, familiarity with its methods is necessary for a clear understanding of the framework. Several of these
methods throw an UnsupportedOperationException.

Chapter 4th - USE OF TRY, CATCH, THROW, THROWS AND FINALLY - Keywords used in Java for Exception handling
are as follows: Try, Catch, Finally, Throw, Throws.

1. Try: This block of code might rise an exception in special block having try keyword. For example, we might suspect
that there might be a "division by zero" operation in the code that will throw an exception. 2. Catch: It is used to
catch an exception when its raised. It is always used with try and used when try block raises an exception. 4. Finally:
It follows try block or try-catch block. Some code in our program that needs to be executed irrespective of whether
or not the exception is thrown. The finally block cannot exist without a try block. 5. Throw: Java provides a keyword
"throw" using which we can explicitly throw the exceptions in the code or to throw custom exceptions. It can be
used to throw the checked or unchecked exceptions. 6. Throws: It is used to declare exceptions but does not throw
an exception. It is used to indicate that an exception might occur in the program or method.

The declaration of exception using the "throws" keyword tells the programmer that there may be an exception
specified after the "throws" keyword and the programmer should provide corresponding handler code for this
exception to maintain the normal flow of the program.

BUILT IN EXCEPTION : These exceptions are available in Java Libraries which explains the error situation. Various
built-in exceptions are Arithmetic exception, FileNotFoundException,
ClassNotFoundException,ArrayIndexOutOfBoundException, NullPointerException etc.
CUSTOM EXCEPTION - The Exception class does not define any methods of its own. It does, of course, Inherit those
methods provided by Throwable. Thus, all exceptions, including those that you create, have the methods defined by
Throwable available to them create. Exception defines four constructors. Two were added by JDK 1.4 to support
chained exceptions, and other two are shown here: 1. Exception() 2. Exception(String msg)

The first form creates an exception that has no description. The second form lets you specify a description of the
exception. Although specifying a description when an exception is created is often useful, sometimes it is better to
override toString(). Here's why: The version of toString() defined by Throwable (and inherited by Exception) first
displays the name of the exception followed by a colon, which is then followed by your description. By overriding
toString(), you can prevent the exception name and colon from being displayed. This makes for a cleaner output,
which is desirable in some cases. The following example declares a new subclass of Exception and then uses that
subclass to signal an error condition in a method. It overrides the toString() method, allowing a carefully tailored
description of the exception to be displayed.

THROWABLE CLASS - All exception types are subclasses of the built-in class Throwable. Immediately below
Throwable are two subclasses that partition exceptions into two distinct branches. One branch is headed by
Exception. This class is used for exceptional conditions that user programs should catch. This is also the class that you
will subclass to create your own custom exception types. There is an important subclass of Exception, called
RuntimeException.

READERS AND WRITERS CLASS - Input stream is similar to reader classes and output stream is similar to writer
classes which are designed for unicode characters.

Writer Class functions: abstract void flush(): This method flushes the output steam by forcing out buffered bytes to
be written out. void write(int c): This method writes a characters to the output stream. void write(char[] arr): This
method writes a whole char array to the output stream. abstract void close(): This method closes this output stream
and also frees any resources connected with this output stream.

Reader Class functions: int read(): This method reads a characters from the input stream. int read (char[] ch): This
method reads a chunk of characters from the input stream and store them in its char array, ch. close(): This method
closes this output stream and also frees any system resources connected with it.

FILE CLASS - Although most of the classes defined by java.io operate on streams, file class does not operate on
streams. It directly deals with files and file system. File class does not specify how the information is retrieved from
or stored in files. It also describes the properties of file. File object is used to manipulate such type of information
associated with a disk file. For example, size, permission, date and time of creation and modification of file, directory
path etc. Files are the main source for storing persistent information You must have seen a list of files using a dir
command. The list includes all the files along with their attributes in the specified directory. A directory in Java,
simply is treated as a file with one additional property a list of filenames in that directory that can be seen with the
help of list() method.

FILE INPUT STREAM, FILE OUTPUT STREAM - FileInputStream: This class extends InputStream class to read binary
data from a file. Constructors of FileInputStream: FileInputStream(String path) throws FileNotFoundException.
FileInputStream(File fileObject) throws FileNotFoundException.

BufferedReader CLASS - BufferedReader improves performance by buffering input. The BufferedReader class does
have a method called readLine that does return a line of text as type by the user. The contents of the stream can be
read into a buffer to speed up the execution. The size of the buffer can be set explicitly, if required. In addition to the
methods defined by the Reader class, this class has a method readLine() to read a line from the stream. It has two
forms of constructors. 1. BufferedReader (Reader inStream): This form creates a buffered character stream with a
default buffer size. 2. BufferedReader (Reader inStream, int buffSize): The size of the buffer is passed in buffsize.

Chapter 5th - APPLET INTRODUCTION : Applets are small Java programs that are mainly used in Internet Applications.
They can be transported over the Internet and can be executed using any web browser or an appletviewer. All
Applets are subclasses of Applet class either directly or indirectly. An Applet is a subclass of Panel and Panel is itself a
subclass of Container. The Fig. 5.1 shows hierarchy for Applet class. Applets which use Swing classes for GUI are
inherited from class JApplet. But JApplet inherits Applet so all the features of Applet are also available to JApplet. An
Applet does not need to begin its execution with main(). Applets are not stand alone programs. They can be
executed either in any web browser or in an appletviewer provided by JDK.

Advantages and Disadvantages of Applets - Advantages of Applet: 1 Applets are cross platform and can run on
Windows, Mac OS (Operating System) and Linux platform. 2. Applets can work all the versions of Java Plug-in. 3.
Applets runs in a sandbox, so the user does not need to trust the code, so it can work without security approval. 4.
Applets are supported by most web browsers. 5. Applets are cached in most web browsers, so will be quick to load
when returning to a web page. 6. User can also have full access to the machine if user allows. 7. It works at client
side so less response time. 8. It can be executed by browsers running under many platforms, including Linux,
Windows, Mac OSS etc. 9. It is secured. Disadvantages of Applet: 1. Java plug-in is required to run applet. 2. Java
applet requires JVM so first time it takes significant startup time. 3. If applet is not already cached in the machine, it
will be downloaded from internet and will take time. 4. It is difficult to design and build good user interface in
applets compared to HTML technology.

APPLET LIFE CYCLE - Applet can override a set of methods from the base class Applet. These methods provides the
mechanism to control the execution of an applet. Applet class resides in java.applet package. Applet runs in the
browser and its lifecycle method are called by JVM, when it is loaded and destroyed. Here, are the lifecycle methods
of an Applet:

1. init() : This method is called to initialized an applet.

2. start() : This method is called after the initialization of the applet.

3. stop() : This method can be called multiple times in the life cycle of an Applet.

4. destroy(): This method is called only once in the life cycle of the applet when applet is destroyed.

1. init() Method: The life cycle of an applet is begin on that time when the applet is first loaded into the browser and
called the init() method.

The init() method is called only one time in the Life cycle of an Applet.

The init() method is basically called to read the PARAM tag in the HTML file.

The init() method retrieve the passed parameter through the PARAM tag of HTML file using get Parameter() method.
All the initialization such as initialization of variables and the objects like image, sound file are loaded in the init()
method. After the initialization of the init() method user can interact with the Applet.

2. start() Method: The start method of an applet is called after the initialization method init(). This method may be
called multiple times when the Applet needs to be started or restarted.

For example, if the user wants to return to the Applet, in this situation the start Method() of an Applet will be called
by the web browser and the user will be back on the applet. In the start method user can interact within the applet.
In the start method, user can interact within the applet.

3. stop() Method: The stop method can be called multiple times in the life cycle of applet like the start() method. Or
should be called at least one time.

Syntax: 3. stop() Method: There is only miner difference between the start() method and stop() method. For
example, the stop() method is called by the web browser on that time. When the user leaves one applet to go
another applet and the start() method is called on that time when the user wants to go back into the first program or
Applet. In the start method, user can interact within the applet.

4. destroy() Method: The destroy() method is called only one time in the life cycle of Applet like init() method. This
method is called only on that time when the browser needs to Shutdown. When the applet programs terminate, the
destroy function is invoked which makes an applet to be in dead state. The destroy() method is called only one time
in the life cycle of Applet like init() method.

5. Display State (paint() Method): The applet is said to be in display state when the paint method is called. This
method can be used when we want to display output in the screen. This method can be called any number of times.
Paint() method is must in all applets when we want to draw something on the applet window. paint() method takes
Graphics object as argument.

paint() method is called each time you want to redraw the output of applet. This situation may occur for various
reasons. For example, the window in which the applet is running may be overwritten by some other window and
then uncovered again or the applet window may be minimized and restored again. This method takes an object of
Graphics class as a parameter. This parameter will contain the graphics context. This context is used whenever the
output to the applet is required.

LAYOUT MANAGERS - Layout means the arrangement of components within the container. In other way wecan say
that placing the components at a particular position within the container. The task of layouting the controls are done
automatically by the Layout Manager. Layout manager is an object which determines the way that components are
arranged in a frame window. All of the components that we have shown so far have been positioned by the default
layout manager. A layout manager automatically arranges our controls within a window by using some type of
algorithm. A layout manager is an instance of any class that implements the LayoutManager interface. The layout
manager is set by the setLayout() method. If no call to setLayout() is made, then the default layout manager is used.
Whenever, a container is resized for sized for the first time). the layout manager is used to position each of the
components within it. The setLayout() method has the following general form: Syntax: void setLayout
(LayoutManager layoutObj) Here, layoutobj is a reference to the desired layout manager. If we wish to disable the
layout manager and position components manually, pass null for layoutObj. If we do this, we will need to determine
the shape and position of each component manually, using the setBounds() method defined by Component.
Normally, we will want to use a layout manager. The layout manager automatically positions all the components
within the container. Default values are provided otherwise. Java has several predefined Layout Manager Classes.
Layout manager classes are founded in the java.awt package same as the classes used for displaying graphical
components. The java.awt package provides five layout manager classes as given below:1. FlowLayout Manager: The
FlowLayout is one the most popular and simplest layout manager. FlowLayout Manager places components in a
container from left to right in the order in which they were added to the container.

When one row is filled, layout advances to the next row. It is analogous to lines of text in a paragraph. Components
managed by a FlowLayout are always set to their preferred size (both width and height) regardless of the size of the
parent container. Whenever, the container is resized then the components in the container are also adjusted from
the top-left corner. The FlowLayout is the default layout manager for a Panel and JPanel.

What is an Event? Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface components. The events
can be broadly classified into two categories: 1. Foreground Events: Those events which require the direct
interaction of user. They are generated as consequences of a person interacting with the graphical components in
Graphical User Interface. For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page etc. 2. Background Events: Those events that require the
interaction of end user are known as background events. Operating system interrupts, hardware or software failure,
timer expires, an operation completion are the example of background events.

Event Handling: An event is a signal to the program that something has happened. The code that performs a task in
response to an event is called event handler. Event handling is a process of responding to events that can occur at
any time during execution of a program. Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs. This mechanism have the code which is known as event handler that is executed
when an event occurs. Each event must return a Boolean value (true or false), indicating whether the event should
be made available to other event handlers. An Event is an object that describes a state change in a source. It can be
generated as a consequence of a user interacting with the elements in a GUI. Any object capable of rising an event is
an event source. Event handlers are procedures that are called when a corresponding event occurs.

Listeners : It is an object that watch for (i.e. listen for) events and handles them when they occur. It is basically a
consumer that receives events from the source. To sum up, the job of an event listener is to implement the
interface, register with the source and provide the event handling. Listeners The Event listener represent the
interfaces responsible to handle events. Java provides us various Event listener classes but we will discuss those
which are more frequently used. Every method of an event listener method has a single argument as an object which
is subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent,
where MouseEvent derives from EventObject. EventListner interface is a marker interface which every listener
interface has to extend. This class is defined in java.util package.

Listeners : It is an object that watch for (i.e. listen for) events and handles them when they occur. It is basically a
consumer that receives events from the source. To sum up, the job of an event listener is to implement the
interface, register with the source and provide the event handling.

Listeners - The Event listener represent the interfaces responsible to handle events. Java provides us various Event
listener classes but we will discuss those which are more frequently used. Every method of an event listener method
has a single argument as an object which is subclass of EventObject class. For example, mouse event listener
methods will accept instance of MouseEvent, where MouseEvent derives from EventObject. EventListner interface is
a marker interface which every listener interface has to extend. This class is defined in java.util package.

SWING - The swing components are defined in the package javax.swing. This package provides more powerful and
flexible components.

SWING Swing is a Java foundation class's library and it is an extension to do Abstract Windowing Toolkit (AWT).
Swing is an extension to the AWT components which provides feature of pluggable look and feel for the
components. It provides classes to design lightweight components. Swing is the next-generation GUI toolkit which
Sun Microsystems is developing to enable enterprise development in Java. Swing is actually part of a large family of
Java products which is known as Java Foundation Classes (JFC). Swing is used to create large-scale Java applications
with a wide array of powerful components which can you easily extend or modify these components to control their
appearance and behavior based on the current "look and feel" library that is being used. Swing is a set of classes, this
provides more powerful and flexible components than are possible with the AWT. In addition to the familiar
components, such as buttons, check boxes, and labels, Swing supplies several exciting additions, including tabbed
panes, scroll panes, trees, and tables. Unlike AWT components, Swing components are not implemented by
platform- specific code. Instead, they are written entirely in Java and, therefore, are platform- independent. The
term lightweight is used to describe such elements. The number of classes and interfaces in the Swing packages is
substantial. Swing is the set of packages built on top of the AWT that provide us with a great number of pre-built
classes that is, over 250 classes and 40 UI components.

Advantages and Disadvantages of Swing 1. Swing provides paint debugging support when you build your own
component. Advantages: 3. Swing components follow the Model-View-Controller (MVC) paradigm and thus 2. Swing
components are lightweight. can provide a much more flexible UI. 4. Swing provides both additional components like
JTable, JTree etc and added functionality to replacement of AWT components. 5. Swing provides built-in double
buffering. Disadvantages: 1. It can be slower than AWT (all components are drawn), when you are not careful about
programming. 2. Swing components might not behave exactly like native components which look like native
components. 3. It requires Java 2 or a separate JAR file.
Programs –

Q.1 Define an abstract class shape with abstract method() area() and volume().Write a java program to calculate
area and volume of cone and cylinder .
import java.util.*;
abstract class shape{
final float PI= 3.14f;
Scanner sc = new Scanner(System.in);
abstract void area();
abstract void volume();
}
class Cylinder extends shape
{
float a,r,h,v;
void accept(){
System.out.println("Please Enter a radius , height");
r = sc.nextFloat();
h = sc.nextFloat();
}
void area(){
a = (2*PI*r*h)+(2*PI*r*r);
System.out.println("Area of Cylinder :"+ a);
}
void volume(){
v = PI*r*r*h;
System.out.println("Volume of Cylinder :"+ v);
}
}
class Cone extends shape{
float a,r,h,v;
void accept(){
System.out.println("Please radius, Height");
r= sc.nextFloat();
h= sc.nextFloat();
}
void area(){
a= PI*r*(r+(float)Math.sqrt(h*h+r+r));
System.out.println("Area of cone is"+a);
}

void volume() {
v = PI*r*r*(h/3);
System.out.println("Volume cone is :"+v);
}
}
public class test{
public static void main(String[] args) {
Cylinder s1 = new Cylinder();
Cone s2 = new Cone();
s1.accept();
s2.accept();
s1.area();
s1.volume();
s2.area();
s2.volume();
}
}

Q.2 define an interface shape with abstract method area(). Write a java program to calculate an area of circle and
retangle(use final keyword).
import java.util.*;
interface Shape
{
void area();
}
class Circle implements Shape
{
final float PI=3.14f;
float ac,r;
Scanner s=new Scanner(System.in);
void accept()
{
System.out.println("Enter the Radius ");
r=s.nextFloat();
}
public void area()
{
ac=PI*r*r;
}
public void show()
{
System.out.println("Area of circle is :"+ac);
}

}
class Sphere implements Shape
{
final float PI=3.14f;
float as,r;
Scanner s=new Scanner(System.in);
void accept()
{
System.out.println("Enter the Radius ");
r=s.nextFloat();
}
public void area()
{
as=4*PI*r*r;
}
public void show()
{
System.out.println("Area of Sphere is :"+as);
}
}
class Slip22
{
public static void main(String args[])
{
Circle s1=new Circle();
Sphere s2=new Sphere();
s1.accept();
s1.area();
s2.accept();
s2.area();
s1.show();
s2.show();
}
}

Q.3 Write a package for games in java, which have two classes Indoor and Outdoor.use a fucntion display() to
generate the list of players for specific games.(use parametarize constructor, finalize() method and array of
objects).
package games;
public class Indoor
{
protected String player;
public Indoor(){ }
public Indoor(String p)
{
player = p;
}
public void display()
{
System.out.println(player);
}
protected void finalize()
{
System.out.println("\nTerminating Indoor Class");
}
}
package games;
public class Outdoor
{
protected String player;
public Outdoor(0)
public Outdoor(String p)
{
player = p;
}
public void display()
{
System.out.println(player);
}
protected void finalize()
{
System.out.println("\nTerminating Outdoor Class");
}
}
Main
package testgame;
import games.*;
import java.util.*;
class Games
{
public static void main(String args[])
{
int n,m,i;
Scanner sc=new Scanner(System.in);
System.out.println("How many indoor players you want ");
n=s.nextInt();
System.out.println("How many outdoor players you want ");
m=s.nextInt();
Indoor in[]=new Indoor[n];
Outdoor out[]-new Outdoor[];
for(i=0;i<n;i++)
{
System.out.println("Enter indoor player name :");
String name=s.next();
in[i]-new Indoor (name);
}
for(1-8;1cm;i++)
{
System.out.println("Enter outdoor player name:");
String name=s.next();
out[i]=new Outdoor (name);
}
System.out.println("Indoor Players: ");
for(i=0;i<n;i++)
{
in[i].display();
}
System.out.println("Outdoor Players: ");
for(i=0;i<m;i++)
{
out [1].display();
}
}
protected void finalize()
{
System.out.println("Finalize is called");
}
}

Q.4 Write a java program to read the content of Imp.txt, Display the content of file in encoded format(use
command line argument)
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.io.Bufferedwriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Encod
{
public static void main(String[] args)
{
try
{
File f1 = new File("temp.txt");
Writer w1 = new Bufferedwriter(new OutputStreamWriter
(new FileOutputStream(f1), StandardCharsets.UTF_8)); w1.append("\n Make a Great Day Ahead ......").append("\r\
n");
w1.append("UTF-8 Demo").append("\r\n"); w1.append("\n Happy Cycling .......").append("\r\n");
w1.flush();
w1.close();
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
Q.5 Write a java program accept a string from a user, if its length is less than 7, then throw user defined exception
“Invalid String” Otherwise Display the String in UpperCase.
import java.io.*;
class InvalidString extends Exception
{
String str;
InvalidString(String s)
{
this.str=s;
}
public String toString()
{
return "Invalid String !";
}
class MyString
{
String str1;
void accept(String s)
{
str1=s;
}
void display()
{
System.out.println("");
}
}
class Temp
{
public static void main(String arg[]) throws Exception{
System.out.println("Enter
String :"); BufferedReader br = new BufferedReader
(newInputStreamReader(System.in));
String str br.readLine();
Try
{
if(str.length()<7)
throw new InvalidString(str);
else
str=str.toUpperCase();
System.out.println("String in uppercase :"+str);
}
catch (InvalidString s)
{
System.out.println("Invalid String");
}
}
}
Q.6 write a java program to accept a email address of a user and throw a user defined exception "Invalid email
exception" if it not contain @Symbol
import java.io.*;
class InvalidEmail extends Exception
(
String str;
InvalidEmail (String s)
{
this.stres;
} public String toString()
{
return "Invalid Email address as it does not contain @ 1";
}
}
class MyEmail
{
String str1;
void accept(String s)
{
stries;
}
void display()
{
System.out.println("");
}
}
class EMain
{
public static void main(String arg[]) throws Exception
{
System.out.println("Enter Emailaddress :"); BufferedReader br = new BufferedReader (new
InputStreamReader(System.in));
String str=br.readLine();
try
{
if(str.contains("@"))
System.out.println("Email address is valid");
else
throw new InvalidEmail(str);
}
catch (InvalidEmail s)
{
System.out.println("Invalid Email");
}
}
}
Q.7 Write a java program to display the content of file in reverse order.
import java.io.File;
import java.io.IOException; import java.io.PrintWriter;
import java.util.Scanner; public class ReverseFile
{
public static void main(String[] args) throws IOException
{
try
{
String in "input.txt";
String out = "output.txt"; File sourceFile=new File(in);
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(out);
while(content.hasNextLine())
{
String s=content.nextLine(); StringBuffer buffer = new StringBuffer(s);
buffer-buffer.reverse(); String ans-buffer.toString();
Dwriter.println(ans);
}
content.close();
pwriter.close();
System.out.println("File is copied successfully!");
}
catch (Exception e)
{
System.out.println("Something went wrong");
}
}
}
Q.8 Write a java program to display "hello world" with setting font Times new roman color blue background color
red on the frame.
import java.awt.*;
class Hello extends Frame
{
Label l;
Hello()
{
l=new Label("Hello java");
l.setFont(new Font("Georgia", Font. BOLD, l4));
add(l);
l. setForeground (Color.RED); setBackground (Color.BLUE); setSize(300, 300); setLayout(new FlowLayout());
setVisible(true);
}
public static void main(String a[])
{
new Hello();
}
}
Q.9 Write a java program to accept the details of employee(Eno,Ename,Sal) from the user and display it on the
next frame(use AWT)
import java.applet.Applet;
import java.awt.*; public class Slip10 extends Applet
{
public void paint (Graphics g)
{
g.drawRect(100,150, 90, 120);
g.drawRect(130, 230, 20,40);
g.drawLine(150, 100, 100, 150); g.drawLine(150, 100, 190, 150); g.drawLine(150, 50, 150, 100); g.drawRect(150,
50, 20, 20);
}
}

You might also like