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

Java

Uploaded by

Omkar Shinde
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Java

Uploaded by

Omkar Shinde
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Web Application , Mobile Applications , Standalone Applications , Enterprise Applications,

Java , Features of OOP , Objects, Diff Object & classes , Data Abstraction , Data Encapsulation
,Inheritance .
Web Applications: Web application is an application which creates a dynamic page and runs on the
side of server. At present time, technologies that are used to create web application in Java
programming language are Struts, Spring, Servlet, Hibernate, JSP, JSF, etc.
Mobile Applications: Mobile application refers to application that is developed for mobile devices. At
present time, platforms that are used to develop mobile applications in Java programming language
are Java ME and Android.
Standalone Applications: Desktop applications and Window based applications are the other name
of standalone applications. We need to install this traditional software on every machine. Media player
and antivirus are the examples of these applications. At current time, for the creation of standalone
applications AWT and swing are used in Java programming language
Enterprise Applications: Enterprise applications are those applications which are distributed in
nature. Banking application is the example of enterprise applications. It gives programmer the
advantage of high level security, clustering and load balancing
Java is an Object Oriented Programming (OOP) language. The fundamental idea behind an OOP is
to combine both data and the functions that operate on the data into a single unit i.e., an object. • An
approach that provides a way of modularizing programs by creating partitioned memory area for both
data and functions that can be used as templates for creating copies of such modules on demand is
known as Object Oriented Programming (OOP).
Features of OOP: 1. OOP emphasis on data rather than procedure. 2. OOP follows bottom-up
approach in program design. 3. Programs in OOP are divided into objects. 4. Objects in OOP may
communicate with each other through functions.
Classes: • A class is a blueprint/template from which individual objects are created. A class is a
collection of objects of similar type of objects. • Classes are user defined data type. Once, class has
been defined, we can create any number of object belonging to that class. • A class consists of data
and methods. A method is a collection of statements that are group together to perform an operation
Objects: • Objects are basic run time entities in OOP. Objects may represent a real-world entity such
as a book, a chair, a place, a bank account, a table etc. • An object is an instance of a class. Objects
are variables of class because it is created by the class data type.
Object Classes
Object is an instance of a class. Class is a blueprint or template from which objects are
created.

Object is a real world entity such as a pen, a laptop, a Class is a group of similar type objects.
keyboard, etc.
Object is a physical entity. Class is a logical entity.

Object is created many times as per requirement Class is declared or created once.

Data Abstraction: • Data abstraction refers to act of representing essential features without including
background details or explanations. • Classes use the concept of abstraction. They encapsulate all
essential properties of objects that they are to be created. • Since, the class used the concept of data
abstraction they are known as Abstract Data Types (ADT).
Data Encapsulation: • Data encapsulation means wrapping or binding of data and functions into a
single unit. Object Oriented Programming using Java - I An Introduction to Java 1.5 • The data is not
accessible to the outside world and only functions which are wrapped in the class can access it. •
Thus, insulation of data from direct access from program is called data hiding.
Inheritance: • Inheritance is the process by which object of one class can acquire the properties of
the objects of another class. • Inheritance means one class of object inherits the data and behavior
(methods) from another class.
Polymorphism , Dynamic Binding , Static Binding , Dynamic Binding , Message Passing , Adv
& Dis of OOP , OOP , JVM , Java API , Javac , Applet , JDB , Javadoc , Javap , Jar
Polymorphism: • Polymorphism is the ability to take more than one form. In short, polymorphism is
the ability of an object to take on many forms. • The most common use of polymorphism in OOP
occurs when a parent class reference is used to refer to a child class object.
Dynamic Binding: • Binding refers to the linking of a procedure call to the procedure definition (code)
to be executed in response to the call
Static Binding means that the code associated with given procedure call is known at compile time.
Dynamic Binding means that the code associated with given procedure call is not known until the
time of the call at run time. Dynamic binding associated with polymorphism and inheritance.
Message Passing: • In OOP objects are communicate with each other through message passing. A
message for an object is a request for execution of a method. • Message passing involves specifying
the name of object, the name of the method and the information to be sent.
Advantages of OOP: 1. Software is easily developed for complex problems. 2. Using OOP, software
reuse is enhanced. 3. Using OOP, software maintenance cost can be reduced. 4. Modularity is
achieved using OOP. 5. Software has improved performance. 6. Software quality is improved. 7. Data
access is restricted providing better data security.
Disadvantages of OOP: 1. OOP requires intensive testing procedures. 2. Solving a problem using
OOP approach consumes more time than the time taken by structured.
OOP: An approach that provides a way of modularizing programs by creating partitioned memory
area for both data and functions that can be used as templates for creating copies of such modules
on demand is known as Object Oriented Programming (OOP)
Java Virtual Machine (JVM): • A JVM is a virtual machine that enables a computer to run Java
programs as well as programs written in other languages that are also compiled to Java bytecode. • A
Java virtual machine’s main job is to load class files and execute the byte codes they contain. • Fig.
1.5 shows the Java virtual machine contains a class loader, which loads class files from both the
program and the Java API. • Only those class files from the Java API that are actually needed by a
running program are loaded into the virtual machine. The byte codes are executed in an execution
engine.
Java API: • The Java API is set of runtime libraries that give us a standard way to access the system
resources of a host computer. • When we run a Java program, the virtual machine loads the Java API
class files that are referred to by the program’s class files.
Javac is the primary java compiler included in the JDK. javac is used to compile Java source into
bytecode. • The java source code is written in files with extension .java. In order to execute the
program, these files need to be compiled in .class files. javac translates or converts the ".java" file to a
".class" file.
Applet is a Java program that runs in a Web browser. Java AppletViewer is the utility which runs
Applets outside the web browser. • AppletViewer is a standard JDK tool which has following facilities:
1. To create dynamic applet, and 2. To view java applet.
JDB • The Java debugger (jdb) is a tool for Java classes to debug a program in command line. jdb
helps us to find and fix bugs in Java language programs. • Debugging is a technical procedure to find
and remove bugs or defects in a program and get expected results.
Javadoc : The javadoc tool is a document generator tool in Java for generating standard
documentation in HTML format. • javadoc is a tool which comes with JDK and it is used for generating
Java code documentation in HTML format from Java source code, which requires documentation in a
predefined format
Javap • The javap tool of Java is used to get the information of any class. In Java the javap command
disassembles a class file. • The javap command (also known as the Java Disassembler)
disassembles one or more class files.
Jar : jar stands for Java archive. The jar tool is a java application that combines multiple files into a
single JAR archive file. • jar is a general-purpose archiving and compression tool based on ZIP and
the ZLIB compression format
Comments ,Data Types , Tokens ,Variables , Array,Mutator,Accessor , CONSTRUCTORS ,
CONSTRUCTOR OVERLOADING , Static Block.,, Static Field ,Static Methods , Object Class
Advantages of StringBuffer Class
Comments • Comments are non-executable statements and are ignored by the Java compiler. The
comment increases the readability of the programs. • Comments help the person/user reading the
code better understand the intent and functionality of the program.
Data Types• Data types specify the different values that can be stored in the variable. Variables are
nothing but reserved memory locations to store values. • The type of value that a variable can hold is
called as data type. The main purpose of data types in Java is to determine what kind of value we can
store into the variable.
Tokens • The smallest individual units in a Java program are called tokens. Java tokens are smallest
elements of a Java program which are identified by the compiler. • Tokens in Java include variables,
constants, identifiers, keywords, literals, operators, special characters, separators and so on.
Variables • Variables are containers for storing data values. Variables are the basic units used to
store any information in Java. • A variable is an identifier that denotes a storage location used to store
a data value. The value in the variable can be changed during the program’s execution. • Variables
are nothing but reserved memory locations to store values. This means that when we create a
variable we reserve some space in memory.
Loops • There may be a situation when we need to execute a block of code several number of times.
• A loop statement allows us to execute a statement or group of statements multiple times until
conditions become true. • The process of repeatedly performing tasks is known as looping. There is
either entry controlled loop or exit controlled loop.
An array is a group of contiguous memory locations to store the data of common type. An array is a
collection of similar type of elements that have contiguous memory location. • Java array is an object
that contains elements of similar data type. It is a data structure where we store similar elements. We
can store only fixed set of elements in a java array.
Mutator method allows the change in value of class variables. It means that from outside class we
can manipulate the data of a class.
Accessor method just allows to access the data. It does not allow to manipulate the data.
Constructors • A constructor is a special method of a class in Java programming that initializes an
object of that type. • Constructors have the same name as the class itself. A constructor is
automatically called when an object is created.
Constructor Overloading • Constructors can be overloaded. Constructor having the same name
with different parameter list is called as constructor overloading.
Static Block • A class can contain code in a static block that does not exist within a method body.
Static code block executes only once when the class is loaded. • A static block is used to initialize
static attributes. Static blocks are also called static initialization blocks.
Static Field • In certain situations, it may be required to share a common copy of fields among all the
objects of the same class. This is accomplished by declaring the field(s) to be static and such fields
are known as static field(s). • If a field is declared static then there is one field for the entire class
instead of one per object
Static Methods • It is possible to have static methods in a class in the same way as we have static
fields. If you apply static keyword with any method, it is known as static method. • A static method
belongs to the class rather than object of a class. A static method can be invoked without the need for
creating an instance of a class.
Object Class • The object class is the parent class of all the classes in Java by default. In other
words, it is the topmost class of java. • The java.lang.Object class is the root of the class hierarchy.
Every class has Object as a superclass. All objects, including arrays, implement the methods of this
class.
Advantages of StringBuffer Class: 1. Alternative to String class. 2. Can be used wherever a string
is used. 3. More flexible than String.
Difference between String and StringBuffer , Formatting String , Package , Inheritance & Adv ,
Multilevel Inheritance: ,Single Inheritance ,Hierarchical Inheritance, Subclass , Superclass ,
Interface ,Diff Class & Abstract class ,Nested Interfaces ,
Difference between String and StringBuffer: • String objects are constants and immutable whereas
StringBuffer objects are not. • StringBuffer Class supports growable and modifiable string whereas
String class supports constant strings. • Strings once created we cannot modify them. Any such
attempt will lead to the creation of new strings. Whereas StingBuffer objects after creation also can be
able to delete or append any characteres to it. • String values are resolved at run time whereas
StringBuffer values are resolved at compile time.
Formatting String • Formatting strings in Java has always been a problem for developers because
the basic System.out.println() method does not support formatting of Strings while displaying the
result on screen.
Package : A package can be defined as "a group of similar types of classes, interface, enumeration
and sub-packages".
Inheritance can be defined as, “the process where one object acquires the properties of another
class”.
Advantages of Inheritance: 1. Code reusability through inheritance is increased. 2. Inheritance
provides a clear model structure which is easy and simple to understand. 3. Code is easy to manage
and divided into parent and child classes.
Single Inheritance: • When a class extends another one class only then we call it a single
inheritance. • 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.
Multilevel Inheritance: • We can create any layers 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.
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.
Subclass : A class that is derived from another class is called a subclass
Superclass the class from which the subclass is derived is called a superclass

Interface • An interface in Java is a blueprint of a class. It has static constants and abstract methods
only.It is used to achieve fully abstraction. 2. By interface, we can support the functionality of multiple
inheritance
Nested Interfaces • An interface declared within another interface or class is known as Nested
Interface. • The nested interfaces are used to group related interfaces so that they can be easy to
maintain. The nested interface must be referred by the outer interface or class. I
Marker Interface , Diff class & interface ,Functional Interface, Run Time Error, Logical Error ,
Syntax Error or Compile Time Error , Exception , Diff Exception and Error ,Diff throw & throws
Marker Interface: • An interface that does not contain methods, fields, and constants is known as
marker interface.

Functional Interface: • An interface that contains exactly one abstract method is known as functional
interface. • It can have any number of default, static methods but can contain only one abstract
method. It can also declare methods of object class.
Run Time Error: • Several time program may compile successfully and compiler creates the .class
file of the program but when the time of running the program, it shows the error and that type of error
called run-time error.
Logical Error:This type of error is occurred when there is some mistake in logic of user like user
wants to multiply two numbers and user puts addition mark instead of multiplication then it is called as
logical er
Syntax Error or Compile Time Error: • Errors that are detected by the compiler in compilation are
called as compile errors or syntax errors.
Exception is a condition that is caused by runtime errors in program. We can define exception as “an
event occurs during the execution of a program that interrupts the normal flow of the program".
Difference between Exception and Error in Java: • Exceptions are related to the application and an
error is related to the environment in which the application is running. • An Error cannot be recovered
as it is fatal in nature, whereas Exception that may not be fatal in all cases. • Errors mostly occur at
runtime that's they belong to an unchecked type. Exceptions are the problems which can occur at
runtime and compile time
InputStream ,FileInputStream, FileOutputStream, BufferedInputStream , DataInputStream
BufferedOutputStream , DataOutputStream ,Reader ,Diff reader & inputstream,Writer
,FileReader
InputStream • java.io.InputStream is an abstract class that contains the basic methods for reading
raw bytes of data from a stream. • Although InputStream is an abstract class, many methods in the
class library are only specified to return an InputStream. • Java application uses an input stream to
read data from a source. It may be a file, an array, peripheral device or socket.
FileInputStream • This stream is used for reading data from the files. Objects can be created using
the keyword new and there are several types of constructors available. • Following constructor takes
a file name as a string to create an input stream object to read the file: InputStream f = new
FileInputStream("/java/nirali"); • A FileInputStream obtains input bytes from a file. It is used for reading
streams of raw bytes such as image data. For reading streams of characters, consider using
FileReader
FileOutputStream • It is used to create a file and write data into it. The stream would create a file, if it
doesn't already exist, before opening it for output. • A FileOutputStream is an output stream for writing
data to a file. • If we have to write primitive values then use FileOutputStream. Instead, for
characteroriented data, prefer FileWriter. But we can write byte-oriented as well as characteroriented
data.
BufferedInputStream • Java BufferedInputStream class is used to read information from stream. It
internally uses buffer mechanism to make the performance fast. • The important points about
BufferedInputStream are: 1. When the bytes from the stream are skipped or read, the internal buffer
automatically refilled from the contained input stream, many bytes at a time. 2. When a
BufferedInputStream is created, an internal buffer array is created.
BufferedOutputStream • Java BufferedOutputStream class is used for buffering an output stream. It
internally uses buffer to store data. • It adds more efficiency than to write data directly into a stream.
So, it makes the performance fast. • For adding the buffer in an OutputStream, use the
BufferedOutputStream class
DataInputStream • Java DataInputStream class allows an application to read primitive data from the
input stream in a machine-independent way. • Java application generally uses the data output stream
to write data that can later be read by a data input stream.
DataOutputStream • Java DataOutputStream class allows an application to write primitive Java data
types to the output stream in a machine-independent way. • Java application generally uses the data
output stream to write data that can later be read by a data input stream.
Reader • Java Reader is an abstract class for reading character streams. Reader is the base class of
the character oriented input streams. It provides methods to read a sequence of Unicode characters.

Writer • Writer is an abstract class for writing to character streams. It is an abstract class. It provides
a stream analogous of OutputStream but it uses characters and not bytes. • The data can be written
into a file, memory buffer, or can be displayed in standard output device.
FileReader • FileReader class is used to read data from the file. It translates bytes from a file into a
character stream
AWT , Swing , Diff AWT & Swing, FlowLayout Manager,BorderLayout Manager
,GridBagLayout Manager ,AWT Controls ,CardLayout Manager
AWT : The AWT is now part of the Java Foundation Classes (JFC) - the standard API for providing a
Graphical User Interface (GUI) for a Java program.• The Java programming language class library
provides a user interface toolkit called the Abstract Window Toolkit
Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) - an API
for providing a Graphical User Interface (GUI) for Java programs. • Swing was developed to provide a
more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT).

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.
BorderLayout Manager • The BorderLayout class implements a common layout style for top-level
windows. • It has four narrow, fixed-width components at the edges and one large area in the center. •
The four sides are referred to as north (upper region), south (lower region), east (left region), and
west (right region). The middle area is called the center (central region
GridLayout Manager • GridLayout lay out components in a two-dimensional grid. When we
instantiate a GridLayout, we define the number of rows and columns. • The Grid layout manager
places items in rows (left to right) and columns (top to bottom). The number of rows and columns is
defined when the Grid layout manager is created.
GridBagLayout Manager • The java.awt.GridBagLayout layout manager is the most powerful and
flexible of all the predefined layout managers but more complicated to use. • Unlike GridLayout where
the component are arranged in a rectangular grid and each component in the container is forced to be
the same size, in GridBagLayout, components are also arranged in rectangular grid but can have
different sizes and can occupy multiple rows or columns,
CardLayout Manager • The CardLayout manager provides the means to manage multiple
components, displaying one at a time. • Components in CardLayout are displayed in the order in
which they are added to the layout or in an arbitrary order by using an assignable name. • The
CardLayout class is unique among the other layout managers in that it stores several different
layouts. Each layout can be thought of as being on a separate index card in a deck that can be
shuffled so that any card is on top at a given time.
AWT Controls: • A GUI is built of graphical elements called components. Controls are components
that allow a user to interact with your application in various ways. • Every AWT controls inherit
properties from Component class. Typical components include such items as buttons, scrollbars, text
fields, and so on. • Components allow the user to interact with the program and provide the user with
visual feedback about the state of the program. • To develop GUI based applications, the fundamental
elements that are needed and are available in two packages java.awt and javax.swing
AWT Hierarchy / AWT Controls , Features Of Swing , JComponent Class , Swing Components
,JTextArea ,Event ,Foreground Events,Background Events , Events,Event Sources , Frame
Awt Hierarchy / Awt Controls : Component: It is an abstract class and all GUI components that
interact with the user are subclasses of component class. It defines various methods for managing
events, such as keyboard and mouse input. It also defines attributes to store current foreground and
background colours and font. Container: It inherits various methods and attributes of component
class and having additional methods of nesting other component objects. A container positions
various GUI components within it, with the help of different layout managers. 3. Panel: Panel is a
window that does not contain a title bar, menu bar or border. It is a superclass of Applet class. Any
screen output written an applet is drawn on the surface of a Panel object.
4. Window: This class is used to create a top level window. Generally, windows objects are not
created directly, subclass of window is used to place on the desktop.
5. Frame: Frame class is a subclass of window and it has title bar, menu bar, borders etc. To create a
normal window within an Java application, Frame class is used.
Features Of Swing : 1. Light Weight: Swing component are independent of native Operating
System's API as Swing API controls are rendered mostly using pure JAVA code instead of underlying
operating system calls. 2. Rich Controls: Swing provides a rich set of advanced controls like Tree,
TabbedPane, slider, color picker, table controls and so on. 3. Borders: We can draw borders in many
different styles around components using the setborder( ) method. 4. Easy mouseless Operation: It
is easy to connect keystrokes to components. 5. Tooltips: We can use the setToolTipText method of
JComponent to give components a tooltip, one of those small windows that appear when the mouse
hovers over a component and gives explanatory text.
JComponent Class • The class JComponent is the base class for all Swing components except top-
level containers. • To use a component that inherits from JComponent, you must place the component
in a containment hierarchy whose root is a top-level Swing container.
Swing Components • Swing components are not implemented by platform specific code. Instead
they are written entirely in Java and therefore, are platform independent. • Swing component is called
light weight, as it does not depend on any non-java system classes. Swing components have their
own view supported by java's look and feel classes.
JTextArea The JTextArea is used to accept several lines of text from the user and it has capabilities
not found in the AWT class. • JTextArea class itself does not handle scrolling but implements the
Scrollable interface which allows it to be placed inside a JScrollPane and thus implement scrolling.
Event Handling • 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 has the code which is known as event handler that is executed
when an event occurs.
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.
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.
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.
Events: • Event is an object that describes a state of change in a source. • Events may be generated
as a consequence of a user interacting with the GUI elements like pressing a button, moving mouse
etc.
Event Sources: • "Source" is an object that generates an event. In the delegation event model
source generates an event and sends it to one or more listeners.
Adapters , When to Use an Anonymous Class , uses of final keyword with example ,
two wrapper classes , is use of 'implements' keyword ,constructors in java , command-line
argument , diff Method Overloading & overinding ,two access specifiers.
Adapters : Adapter pattern is frequently used in modern Java frameworks. It comes into place when
we want to use an existing class, and its interface does not match the one we need, or we want to
create a reusable class that cooperates with unrelated classes with incompatible interfaces. • Adapter
pattern works as a bridge between two incompatible interfaces. This type of design pattern comes
under structural pattern as this pattern combines the capability of two independent interfaces.
When to Use an Anonymous Class? • In general, we should consider using an anonymous class
instead of a local class if: o The class has a very short body. o Only one instance of the class is
needed. o The class is used right after it is defined. o The name of the class does not make your code
any easier to understand.
uses of final keyword with example. The final keyword provides immutability and guarantees that
the declared entity will not be modified. It helps in creating constants, preventing method overriding,
and prohibiting class extension, depending on where it is used. By using the final keyword, we can
enhance code readability, maintainability, and enforce desired behavior in our Java programs.
1) . Final variables: Constants: By declaring a variable as final, we can create a constant whose
value cannot be changed once assigned. It is a common practice to use uppercase letters and
underscores for naming constants.
Example: final int MAX VALUE = 100; final double PI = 3.14159;
two wrapper classes. : Two commonly used wrapper classes in Java are as follows: i. Byte: The
Byte class is the wrapper class for the byte primitive type. It provides methods for converting between
byte values and String objects, parsing String representations of bytes, and performing various
operations on byte values. ii. Float: The Float class is the wrapper class for the float primitive type. It
provides methods for converting between float values and String objects, parsing String
representations of floats, and performing mathematical operations.
is use of 'implements' keyword? : i. Implementing interfaces: By using the implements keyword, a
class can declare that it intends to implement the methods specified by one or more interfaces. This
means the class will provide the necessary method implementations required by the interface(s).
constructors in java : No-argument Constructor: A constructor that has no parameter is called as
no-argument constructor. Parameterized Constructor: A constructor that has parameters is called
as parameterized constructor.
command-line argument : is an argument i.e., passed from console during execution of java
program. The passed arguments are received in java program and they can be further used as an
input. Number of arguments may be zero or many and must be separated by space. JVM wraps all
arguments and supplies them to the main () of programs as an array of Strings.

Method Overloading Method Overriding


Overloading means reusing a method name, but with Overriding means providing the specific implementation of
different arguments a method to a subclass which is already provided by its
super class
Overloaded method must have different argument lists Overriding method must have the same argument list
Overloaded method may have different return types. Overriding method must have the same return type,
except that as of Java 5, the return type can be a subclass
which is known as a covariant return.
two access specifiers.: public: The public access specifier allows the declared element to be
accessed from anywhere in the program, including other classes, packages, and even external
programs. It provides the highest level of faccessibility. private: The private access specifier restricts
the accessibility of the declared element to within the same class.
Define an interface shape with abstract
method area(). Inherit interface shape into the setLayout(new FlowLayout());
class triangle. Write a Java Program to add(nameLabel);
calculate area of Triangle. add(nameField);
add(rollLabel);
interface Shape { add(rollField);
double area(); add(displayButton);
} add(clearButton);
add(outputLabel);
class Triangle implements Shape {
double base, height; displayButton.addActionListener(new
ActionListener() {
Triangle(double base, double height) { public void actionPerformed(ActionEvent
this.base = base; e) {
this.height = height; String name = nameField.getText();
} String roll = rollField.getText();
outputLabel.setText("Name: " + name
public double area() { + ", Roll Number: " + roll);
return 0.5 * base * height; }
} });
}
clearButton.addActionListener(new
public class Main { ActionListener() {
public static void main(String[] args) { public void actionPerformed(ActionEvent
Triangle t = new Triangle(5, 10); e) {
System.out.println("Area of Triangle: " + nameField.setText("");
t.area()); rollField.setText("");
} outputLabel.setText("");
} }
});

Write a Java program to accept the details of setTitle("Student Details");


student & display on console by clicking on setSize(300, 200);
Display button. Clear button should clear all
the controls setDefaultCloseOperation(JFrame.EXIT_ON_CL
import javax.swing.*; OSE);
import java.awt.*; setVisible(true);
import java.awt.event.*; }

public class StudentDetails extends JFrame { public static void main(String[] args) {
JTextField nameField, rollField; new StudentDetails();
JButton displayButton, clearButton; }
JLabel nameLabel, rollLabel, outputLabel; }

StudentDetails() {
nameLabel = new JLabel("Name:");
rollLabel = new JLabel("Roll Number:");
nameField = new JTextField();
rollField = new JTextField();
displayButton = new JButton("Display");
clearButton = new JButton("Clear");
outputLabel = new JLabel();
Define a class Emp with a member Eid and Write a Java Program to copy the contents
display() method, inherit Emp class into the from one file into another file. While copying,
EmpName class, EmpName class having a change the case of cell the alphabets &
member Ename & display() method. Write a replace all the digits by '*'
Java program to accept details of employee
[Eid, Ename] & display it. (Use super import java.io.*;
keyword). import java.nio.file.*;
public class FileCopyWithModification {
import java.util.Scanner; public static void main(String[] args) {
String inputFilePath = "input.txt";
class Emp { String outputFilePath = "output.txt";
int Eid; try {
String content = new
Emp(int Eid) { String(Files.readAllBytes(Paths.get(inputFilePath
this.Eid = Eid; )));
} StringBuilder modifiedContent = new
StringBuilder();
void display() {
System.out.println("Employee ID: " + Eid); for (char ch : content.toCharArray()) {
} if (Character.isDigit(ch)) {
} modifiedContent.append('*');
} else if (Character.isLowerCase(ch)) {
class EmpName extends Emp {
String Ename; modifiedContent.append(Character.toUpperCase
(ch));
EmpName(int Eid, String Ename) { } else if (Character.isUpperCase(ch)) {
super(Eid);
this.Ename = Ename; modifiedContent.append(Character.toLowerCase
} (ch));
} else {
void display() { modifiedContent.append(ch);
super.display(); }
System.out.println("Employee Name: " + }
Ename);
} Files.write(Paths.get(outputFilePath),
} modifiedContent.toString().getBytes());
System.out.println("File copied and
public class Main { modified successfully!");
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); } catch (IOException e) {
System.out.print("Enter Employee ID: "); System.err.println("An error occurred: " +
int Eid = sc.nextInt(); e.getMessage());
sc.nextLine(); }
System.out.print("Enter Employee Name: "); }
String Ename = sc.nextLine(); }
EmpName emp = new EmpName(Eid,
Ename);
emp.display();
sc.close();
}
}
Define user define exception zeronumber Write a Java program to accept n number
Exc. Write a Java program to accept a from user & store only perfect numbers into
number from user. If it is zero then throw user array & display that array
define exception "Number is zero" otherwise
calculate the sum of first & last digit of given import java.util.Scanner;
number. (use Static keyword)
public class PerfectNumbers {
import java.util.Scanner; public static void main(String[] args) {
class ZeroNumberExc extends Exception { Scanner sc = new Scanner(System.in);
ZeroNumberExc(String message) { System.out.print("Enter the number of
super(message); elements: ");
} int n = sc.nextInt();
} int[] numbers = new int[n];
int[] perfectNumbers = new int[n];
public class NumberSum { int count = 0;
static int calculateSum(int number) {
int lastDigit = number % 10; System.out.println("Enter " + n + " numbers:
int firstDigit = ");
Integer.parseInt(Integer.toString(number).substri for (int i = 0; i < n; i++) {
ng(0, 1)); numbers[i] = sc.nextInt();
return firstDigit + lastDigit; }
}
for (int i = 0; i < n; i++) {
public static void main(String[] args) { int sum = 0;
Scanner sc = new Scanner(System.in); for (int j = 1; j < numbers[i]; j++) {
System.out.print("Enter a number: "); if (numbers[i] % j == 0) {
int number = sc.nextInt(); sum += j;
}
try { }
if (number == 0) { if (sum == numbers[i]) {
throw new ZeroNumberExc("Number perfectNumbers[count] = numbers[i];
is zero"); count++;
} else { }
int sum = calculateSum(number); }
System.out.println("Sum of first and
last digit: " + sum); System.out.print("Perfect Numbers: ");
} for (int i = 0; i < count; i++) {
} catch (ZeroNumberExc e) { System.out.print(perfectNumbers[i] + " ");
System.out.println(e.getMessage()); }
} sc.close();
sc.close(); }
} }
}
Write a java program to copy the content Write a java program using swing to accept
from one file to another file, while copying details of employee (eno, ename, esal) and
change the case of alphabets. display it by clicking on a button
import javax.swing.*;
import java.io.*; import java.awt.*;
import java.nio.file.*; import java.awt.event.*;
public class FileCopyChangeCase { public class EmployeeDetails extends JFrame {
public static void main(String[] args) { JTextField enoField, enameField, esalField;
String inputFilePath = "input.txt"; JButton displayButton;
String outputFilePath = "output.txt"; JLabel enoLabel, enameLabel, esalLabel,
outputLabel;
try { EmployeeDetails() {
String content = new enoLabel = new JLabel("Employee No:");
String(Files.readAllBytes(Paths.get(inputFilePath enameLabel = new JLabel("Employee
))); Name:");
StringBuilder modifiedContent = new esalLabel = new JLabel("Employee
StringBuilder(); Salary:");
enoField = new JTextField();
for (char ch : content.toCharArray()) { enameField = new JTextField();
if (Character.isLowerCase(ch)) { esalField = new JTextField();
displayButton = new JButton("Display");
modifiedContent.append(Character.toUpperCase outputLabel = new JLabel();
(ch)); setLayout(new FlowLayout());
} else if (Character.isUpperCase(ch)) { add(enoLabel);
add(enoField);
modifiedContent.append(Character.toLowerCase add(enameLabel);
(ch)); add(enameField);
} else { add(esalLabel);
modifiedContent.append(ch); add(esalField);
} add(displayButton);
} add(outputLabel);
displayButton.addActionListener(new
Files.write(Paths.get(outputFilePath), ActionListener() {
modifiedContent.toString().getBytes()); public void actionPerformed(ActionEvent
System.out.println("File copied and case e) {
changed successfully!"); String eno = enoField.getText();
String ename = enameField.getText();
} catch (IOException e) { String esal = esalField.getText();
System.err.println("An error occurred: " + outputLabel.setText("Employee No: " +
e.getMessage()); eno + ", Name: " + ename + ", Salary: " + esal);
} }
} });
} setTitle("Employee Details");
setSize(300, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CL
OSE);
setVisible(true);
}
public static void main(String[] args) {
new EmployeeDetails();
}
}
Define abstract class shape with abstract Write a java program to give Red colour at
method area(). Write a java program to the background of TextField by clicking on a
calculate area of circle button.

abstract class Shape { import javax.swing.*;


abstract double area(); import java.awt.*;
} import java.awt.event.*;

class Circle extends Shape { public class ChangeTextFieldColor extends


double radius; JFrame {
JTextField textField;
Circle(double radius) { JButton button;
this.radius = radius;
} ChangeTextFieldColor() {
textField = new JTextField(20);
double area() { button = new JButton("Change Color");
return Math.PI * radius * radius;
} setLayout(new FlowLayout());
} add(textField);
add(button);
public class Main {
public static void main(String[] args) { button.addActionListener(new
Circle circle = new Circle(5); ActionListener() {
System.out.println("Area of Circle: " + public void actionPerformed(ActionEvent
circle.area()); e) {
} textField.setBackground(Color.RED);
} }
});
Write a Java program to count number of
vowels from given string. setTitle("Change TextField Color");
import java.util.Scanner; setSize(300, 100);

public class VowelCount { setDefaultCloseOperation(JFrame.EXIT_ON_CL


public static void main(String[] args) { OSE);
Scanner sc = new Scanner(System.in); setVisible(true);
System.out.print("Enter a string: "); }
String str = sc.nextLine();
int count = 0; public static void main(String[] args) {
for (int i = 0; i < str.length(); i++) { new ChangeTextFieldColor();
char ch = str.charAt(i); }
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == }
'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch ==
'O' || ch == 'U') {
count++;
}
}
System.out.println("Number of vowels: " +
count);
sc.close();
}
}
Write a Java program to accept a number Write a Java program using AWT to change
from user. If it is zero then thro user defined background color of table to 'RED' by
exception "Number is zero". Otherwise clicking on button.
calculate its factorial.
import java.awt.*;
import java.util.Scanner; import java.awt.event.*;
import javax.swing.*;
class ZeroNumberException extends Exception {
ZeroNumberException(String message) { public class TableColorChange extends Frame {
super(message); Button button;
} JTable table;
} JScrollPane scrollPane;

public class FactorialCalculator { TableColorChange() {


static long calculateFactorial(int number) { button = new Button("Change Color");
long factorial = 1; String[][] data = {{"1", "Alice"}, {"2", "Bob"},
for (int i = 1; i <= number; i++) { {"3", "Charlie"}};
factorial *= i; String[] columns = {"ID", "Name"};
} table = new JTable(data, columns);
return factorial; scrollPane = new JScrollPane(table);
}
button.setBounds(100, 250, 150, 30);
public static void main(String[] args) { scrollPane.setBounds(30, 50, 300, 150);
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: "); add(button);
int number = sc.nextInt(); add(scrollPane);

try { button.addActionListener(new
if (number == 0) { ActionListener() {
throw new public void actionPerformed(ActionEvent
ZeroNumberException("Number is zero"); e) {
} else { table.setBackground(Color.RED);
System.out.println("Factorial: " + }
calculateFactorial(number)); });
}
} catch (ZeroNumberException e) { setSize(400, 400);
System.out.println(e.getMessage()); setLayout(null);
} setVisible(true);
sc.close(); }
}
} public static void main(String[] args) {
new TableColorChange();
}
}
Write a java program to delete the files List<String> lines = new ArrayList<>();
having extension.txt. (Use command line String line;
arguments while ((line = br.readLine()) != null) {
lines.add(line); }
import java.io.File; Collections.reverse(lines);
for (String reversedLine : lines) {
public class DeleteTxtFiles { System.out.println(reversedLine); }
public static void main(String[] args) { } catch (IOException e) {
if (args.length == 0) { System.out.println("Error reading file.");}}}
System.out.println("Please provide the
directory path."); Write a java program to accept employee
return; name from user if it is not valid then throw
} user defined exception "InvalidName"
otherwise display a name
File directory = new File(args[0]);
if (!directory.exists() || import java.util.Scanner;
!directory.isDirectory()) { class InvalidName extends Exception {
System.out.println("Invalid directory public InvalidName(String message) {
path."); super(message);
return; }
} }
public class EmployeeName {
File[] files = directory.listFiles((dir, name) -> public static void main(String[] args) {
name.endsWith(".txt")); Scanner scanner = new
if (files != null) { Scanner(System.in);
for (File file : files) { System.out.print("Enter employee name: ");
if (file.delete()) { String name = scanner.nextLine();
System.out.println("Deleted: " + try {
file.getName()); if (name.isEmpty() || !name.matches("[a-
} else { zA-Z ]+")) {
System.out.println("Failed to delete: throw new InvalidName("Invalid name:
" + file.getName()); Name must only contain letters and spaces.");
}}}}} }
System.out.println("Employee name: " +
) Write a java program to display contents of name);
file in reverse order } catch (InvalidName e) {
import java.io.*; System.out.println(e.getMessage());
import java.util.*; }
}
public class ReverseFileContent { }
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Please provide the
file path.");
return;
}
File file = new File(args[0]);
if (!file.exists() || !file.isFile()) {
System.out.println("Invalid file path.");
return; }
try (BufferedReader br = new
BufferedReader(new FileReader(file))) {
Define abstract class shape with abstract
method area(). Write a java program to submitButton.addActionListener(new
calculate area of rectangle ActionListener() {
public void actionPerformed(ActionEvent
abstract class Shape { e) { String rno = fieldRno.getText();
abstract double area(); String name = fieldName.getText();
class Rectangle extends Shape { String percentage =
double length, width; fieldPercentage.getText();
Rectangle(double length, double width) { resultLabel.setText("Roll No: " + rno +
this.length = length; ", Name: " + name + ", Percentage: " +
this.width = width;} percentage);
double area() { }
return length * width; }} });
public class Main { frame.add(labelRno);
public static void main(String[] args) { frame.add(fieldRno);
Rectangle rectangle = new Rectangle(5, frame.add(labelName);
10); frame.add(fieldName);
System.out.println("Area of rectangle: " + frame.add(labelPercentage);
rectangle.area());}} frame.add(fieldPercentage);
frame.add(submitButton);
Write a java program using swing to accept frame.add(resultLabel);
student details (rno, name, percentage) and frame.setVisible(true);}}
display in by clicking on a button
Write a java program to change the text color
import javax.swing.*; of Label to Red by clicking on a button.
import java.awt.*; import javax.swing.*;
import java.awt.event.ActionEvent; import java.awt.*;
import java.awt.event.ActionListener; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StudentDetails { public class ChangeLabelColor {
public static void main(String[] args) { public static void main(String[] args) {
JFrame frame = new JFrame("Student JFrame frame = new JFrame("Change
Details"); Label Color");
frame.setSize(300, 300); frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_
frame.setDefaultCloseOperation(JFrame.EXIT_ ON_CLOSE);
ON_CLOSE); frame.setLayout(new FlowLayout());
frame.setLayout(new FlowLayout()); JLabel label = new JLabel("Click button to
change color");
JLabel labelRno = new JLabel("Roll JButton button = new JButton("Change
Number:"); Color");
JTextField fieldRno = new JTextField(15); button.addActionListener(new
JLabel labelName = new JLabel("Name:"); ActionListener() {
JTextField fieldName = new JTextField(15); public void actionPerformed(ActionEvent
JLabel labelPercentage = new e) {
JLabel("Percentage:"); label.setForeground(Color.RED);
JTextField fieldPercentage = new }
JTextField(15); });
frame.add(label);
JButton submitButton = new frame.add(button);
JButton("Submit"); frame.setVisible(true);
JLabel resultLabel = new JLabel(""); }}

You might also like