Java Programming Notes
Java Programming Notes
LIST OF CONTENTS
1
UNIT I
Object Oriented concepts
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviours of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.
2
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
HISTORY OF JAVA
Java History
Java is a high-level programming language originally developed by Sun Microsystems
and released in 1991.
Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions
of UNIX. So java is platform independent.
Java was designed for the development of software for consumer electronic devices like
TVs, VCRs, toasters and such other electronic devices.
1990 → A team of Sun Microsystems headed by James Gosling was decided to develop a
special software that can be used to manipulate consumer electronic devices.
1991 → The team announced a new language named “oak”.
1992 → The team demonstrated the application of their new language to control a list of
home applications.
1993 → The team known as Green Project team came up with the idea of
developing web applets.
1994 → The team developed a web browser called “HotJava” to locate and run applet
programs on internet.
1995 → Oak was renamed Java.
1996 → Sun releases Java Development Kit 1.0.
1997→ Sun releases Java Development Kit 1.1.
1998 → Sun releases the Java 2 with version 1.2.
1999 → Sun releases standard edition (J2SE) and enterprise edition(J2EE).
2000 → J2SE with SDK(software development kit) 1.3 was released.
2002 → J2SE with SDK 1.4 was released.
2004 → J2SE JDK 5.0 was released. This is known as J2SE 5.0.
2
JAVA BUZZWORDS
Object Oriented:
Java is truly object-oriented language. Almost everything in Java is an object.
All program code and data reside within objects and classes.
Java comes with an extensive set off classes, arranged in packages that we can use in our
programs by inheritance.
The object model in java is simple and easy to extend.
Distributed:
Java is designed as a distributed language for creating applications on networks. It has the
ability to share both data and programs.
Java applications can open and access remote objects on internet as easily as they can do
in a local system.
This enables multiple programmers at multiple remote locations to collaborate and
work together on a single project.
3
Multithreaded and Interactive:
Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded
programs. This means that we need not wait for the application to finish one task before
beginning another.
For example we can listen to an audio clip while scrolling a page and at the same time
download an applet from a distant computer.
This feature greatly improves the interactive performance of graphical applications.
High performance
Java performance is impressive for an interpreted language, mainly due to the use of
intermediate byte code. According to sun, java speed is comparable to the native C/C++.
Java architecture is also designed to reduce overheads during runtime. Further, the
incorporation of multithreading enhances the overall execution speed of java programs.
JVM ARCHITECTURE
4
Runtime class libraries: There are a set of core class libraries that are required for the
execution of java programs.``
User interface toolkits: AWT and swing are examples of toolkits that support varied
input methods for the users to interact with application program.
Deployment technologies: JRE comprises the following key deployment
technologies:
Java plug-in: Enables the execution of a java applet on the browser.
Java Web start: Enables remote-deployment of an application.
DATA TYPES
Data types specify the size and type of values that can be stored.
Numeric
Floating Point Types
✓ Floating point type contains fractional parts such as 26.78 and -7.890.
✓ The float type values are single-precision numbers while the double types
represent double-precision numbers.
✓ Floating point numbers are treated as double-precision quantities. We must append f
or F to the numbers. Example: 1.23f 7.67567e5F
5
Double-precision types are used when we need greater precision in storage of floating
point numbers. Floating point data types support a special value known as Not-a-Number
(NaN).
It is used to represent the result of operations such as dividing by zero, where an
actual number is not produced.
Type Size Minimum value Maximum value
Float 4 bytes 3.4e-038 1.7e+0.38
double 8 bytes 3.4e-038 1.7e+308
Character Type
✓ Java provides a character data type called char.
✓ The char type assumes a size of 2 bytes but, basically, it can hold only a single
character.
Boolean Type
✓ It is used to test a particular condition during the execution of the program.
✓ There are only two values that a boolean type can take: true or false.
✓ Boolean type is denoted by the keyword boolean and uses only one bit of storage.
VARIABLES
A variable is an identifier that denotes a storage location used to store a data value. Variable
names may consist of alphabets, digits, the underscore( _ ) and dollar characters, subject
to the following conditions:
They must not begin with a digit.
Uppercase and lowercase are distinct.
It should not be a keyword.
White space is not allowed.
Variable names can be of any length.
A variable must be given a value after it has been declared it is used in an expression.
This can be achieved in two ways:
1. By using an assignment statement
6
2. By using a read statement
We often encounter situations where there is a need to store a value on one type into a variable
of another type.
✓ In such situation, we must cast the value to be stored by proceeding it with the type
name in parentheses. The syntax is
type variable1 = (type) variable2;
The process of converting one data type to another is called casting. Examples: int m= 50;
byte n = (byte)m;
Four integer types can be cast to any other type except Boolean. Casting into a smaller type may
result in loss of data. Similarly, the float and double can be cast to any other type except
Boolean.
From To
byte short, char, int, long, float,
double
short int, long, float, double
char int, long, float, double
int long, float, double
7
long float, double
float Double
Casts that results in no loss of information
ARRAYS
An array is a group of related data items that share a common name. A particular value is
indicated by specifying a number called index number or subscript in square brackets after
the array name.
The arrays can be classified into two types. They are
1. One-dimensional array
2. Two-dimensional array
Creating An Array
Creation of array includes three steps:
1. Declare the array
2. Create memory locations
3. Put values into the memory locations.
One-dimensional array
A list of items can be given one variable name using only one subscript and such variable is
called a single-subscripted variable or a one-dimensional array.
8
arrayname = new type[size];
Array length : In java, all arrays store the allocated size in a variable named length.
To know the size of an array, it can be accessed as arrayname.length
Two-Dimensional Arrays
To store the values in a table form then two dimensional array is used. Two subscript are
needed to access a value in two dimensional array.
9
Creation of two-dimensional array
Arrays are created by using new operator. The general form is
arrayname = new type[row][col];
OPERATORS
10
o Logical operators
o Assignment operators
o Increment and decrement operators
o Conditional operators
o Bitwise operators
o Special operators
Operator Meaning
+ Addition
Subtraction
* Multiplication
Division
% Modulo division
RELATIONAL OPERATORS
❖ Compares two quantities depending on their relation.
❖ Java supports six relational operators.
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
A simple relational expression contains only one relational operator and is of the following
form:
ae-1 relational operator ae-2 where
ae-1 and ae-2 are arithmetic expressions
1
1
LOGICAL OPERATORS
Java has three logical operators.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
A logical operator returns either TRUE or FALSE values.
Logical operator && and || are used to check compound condition (ie for
combining two or more relations)
When an expression combines two or more relational expressions then it is called
logical expression or a compound relational expression
ASSIGNMENT OPERATORS
Used to assign the value of an expression to a variable.
Assignment operators are usually in the form “=”.
v op=exp;
CONDITIONAL OPERATORS
❖ The character pair ?: is used for conditional operator.
❖ It is also called as ternary operator.
General Form exp1 ? exp2: exp3
where exp1, exp2, exp3 are expressions The
operator ?: works as follows
exp1 is evaluated first, if its is true then the exp2 is evaluated. If
exp1 is false, exp3 is evaluated
BITWISE OPERATORS:
12
❖ Bitwise operators are used to manipulate data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or left.
❖ Bitwise operators may not to float or double.
Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
SPECIAL OPERATORS
❖ Java supports special operators
➢ Instance of operator
➢ Dot operator (or) member selection operator (.)
✓ Instance of operator:
❖ Instance of operator is an object reference operator.
❖ Allow us to determine whether the object belongs to a particular class or not.
❖ Return true, if the object on the left-hand side is an instance of the class given
on the right-hand side.
Dot operator
The dot operator (.) is used to access the instance variables and methods of class objects.
It is also used to access classes and sub packages from a package.
1
3
CONTROL STATEMENTS
When a program breaks the sequential flow and jumps to another part of the code, it is called
branching.
❖ When the branching is based on a particular condition, it is known as conditional
branching.
❖ If branching takes place without any decision, it is known as unconditional
branching. if statement
switch statement
Conditional operator statement
if statement
switch statement
Conditional operator statement
IF Statement
The if statement is a powerful decision making statement and is used to control the flow of
execution of statements.
General form if (test expression)
14
1. Simple If Statement
➢ If the test expression is true the statement block will be executed; otherwise the
execution will jump to the statement-x
➢ Statement block may be single statement or a group of statement.
Example
1
5
General form Example
if (test condition1) if (gender == “female”)
{ {
if (test condition2) if (balance>5000)
{ {
True Bonus = 0.03 *
blockstatements-1; balance;
} }
else else
{ {
False block Bonus = 0.02 *
statement-2; balance;
} }
} }
else else
{ {
False block statements-3; Bonus = 0.01 * balance;
} }
Statement-x; balance=balance + bonus;
4. Else if ladder
Else If ladder is a chain of ifs in which the statement associated with each else is an if.
The condition is evaluated from the top to downwards.
➢ As soon as the condition is true, then the statements associated with it are executed
and the control is transferred to the statement -x.
➢ When all the n condition is false, then the final else containing the default-
statement will be executed.
General form Example
If (condition-1) If (marks>79)
statement-1; else grade=”honors”;
if (condition-2) else if (marks>79)
statement -2; else grade=”first”; else
if (condition-3) if (marks>79)
statement -3; grade=”second”; else
….. if (marks>79)
else if (condition n) grade=”third”;
statement -n; else
else grade=”fail”; // Default-stmt
default-statement; System.out.println(“grade=”+grade);
16
The Switch Statement
The switch statement tests the value of a given variable against a list of case
values.
Block1, block2 … are statements lists may contain zero or more statements.
The breakstatement at the end of each block signal the end of a particular case and causes
an exit from the switch statement, transferring the control to the statement -x following
the switch.
The default is an option case; it will be executed if the value of the expression does not
match with any of the case values.
If not present, no action takes place when all matches fail and the control goes to the
statement –x.
class SampleOne
{
public static void main (String args[])
{
System.out.println(“ Java is better than C++”);
}
}
Class declaration
The first line
Class SampleOne declares a class, java is a true object-oriented language and therefore,
everything must be placed inside a class.
class is a keyword and declares that a new class definition follows.
SampleOne is a java identifier that specifies the name of the class to be defined.
Opening Brace
Every class definition in java begins with an opening brace “{“ and ends with a
matching closing brace “}”.
The main line
The third line
public static void main (String args[])
The above line defines a method named main.
18
This is similar to the main() function in C/C++.
Every java application program must include the main() method. This the starting point
for the interpreter to begin the execution of the program.
A java application can have any number of classes but only one of them must include a
main method to initiate the execution.
The line contains a number of keywords public, static and void.
Public : The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes.
Static : Declares this method as one that belongs to the entire class and not a part of any
object of the class. The main methods must always be declared as static since the
interpreter uses this method before any object are created.
Void: The void states that the main method does not return any value.
CONSTRUCTORS
Every class has a constructor. If we do not explicitly write a constructor for a class, the Java
compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked.
The main rule of constructors is that they should have the same name as the class.
A class can have more than one constructor.
They does not return any value and do not specify even void.
Constructors are automatically called during the creation of the objects.
ADVANTAGES OF CONSTRUCTORS:
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
TYPES OF CONSTRUCTORS:
Based on creating objects in JAVA we have two types of constructors.
They are
Default/parameter less/no argument constructor and Parameterized constructor.
Strings, which are widely used in Java programming, are a sequence of characters. In Java
programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.
20
p.toString(); Creates a string representation of object p
s1.indexOf(‘x’) Gives the position of the first occurrence of ‘x’ in the string s1
s1.indexOf(‘x’,’n’); Gives the position ‘x’ that occurs after nth position in the
string s1
String.valueOf(variable Converts the parameter value to string representation.
);
s1.compareTo(s2) Returns negative if s1<s2, positive if s1>s2, zero if s1 and s2
equal.
22
12. What is encapsulation, and how does it enhance data security in a program?
13. What are conditional statements, and why are they used in programming?
14. How do you structure an if-else statement to handle multiple conditions?
15. What is the purpose of the else if statement, and how does it differ from using multiple
if statements?
16. What are the logical operators (&&, ||, !) in Java, and how are they used in conditional
statements?
17. How would you test the correctness of your conditional statements in your code?
18. What are the different types of constructors in Java? Explain each type briefly.
19. How does a parameterized constructor differ from a default constructor? Provide
an example.
20. What is constructor overloading, and how is it implemented in Java?
21. What are the different types of loops available in Java? Describe each type.
22. What factors can affect the efficiency of a loop? How can you optimize
looping statements?
23. How would you test and debug your loop structures to ensure they function correctly?
23
UNIT II
INHERITANCE
When one class acquires the properties of another class it is known as inheritance.
A class that is inherited is called a super class or base class.
The class that does the inheriting is called a subclass or derived class.
Advantage of inheritance is that it allows reusability of coding.
TYPES OF INHERITANCE
Inheritance may take different forms. They are
Single inheritance (one super class, one sub class)
Multilevel inheritance (derived from a derived class)
Multiple Inheritance
Single inheritance
Single class is one in which there exists single base class and single
derived class.
Multiple Inheritance
Multiple inheritances are one supported by JAVA through classes but it is supported by
JAVA through the concept of interfaces.
Defining a subclass
A subclass is defined as follows:
class subclassname extends superclassname
24
{
variables declaration;
methods declaration;
}
The keyword extends signifies that the properties of the super classname are
extended to the subclassname.
SUBCLASS CONSTRUCTOR
A subclass constructor is used to construct the instance variables of both the subclass
and the super class.
The sub class constructor uses the keyword super to invoke the constructor method
of the super class.
The keyword super is used in following conditions. Super may only be used within a
subclass constructor method.
The call to super class constructor must appear as the first statement within the sub class
constructor.
The parameter in the super call must match the order and type of the instance variable
declared in the program.
Public Access:
To declare the variable or method as public, it is visible to the entire class in which it is
defined.
Example:
public int number;
public void sum ( ) {.......................}
Friendly Access:
When no access modifier is specified, the number defaults to a limited version of public
accessibility known as “friendly” level of access.
25
The difference between the “public” and “friendly” access is that the public modifier makes
fields visible in all classes.
While friendly access makes fields visible only in the same package, but not in other package.
Protected Access:
The protected modifier makes the fields visible not only to all classes and
subclasses in the same package but also to subclasses in other packages.
Non-subclasses in other packages cannot access the “protected” members.
Private Access:
Private fields are accessible only with their own class.
They cannot be inherited by subclasses and therefore not accessible in subclasses. A method
declared as private behaves like a method declared as final.
METHOD OVERLOADING
Method overloading is creating methods that have same name, but different parameter lists
and different definitions. Method overloading is used when objects are required to perform
similar tasks but using different input parameters.
26
When a method is called, java matches up the method name first and then the number and
type of parameters to decide which one of the definitions to execute. This process is known
as polymorphism.
Ex:
class room {
float l,b;
room(float x, float y)
{ l=x;
b=y;
} room(float x)
{
l = b = x; }
int area() {
return(l * b); }
}
METHOD OVERRIDING
A method defined in a super class is inherited by its sub class and is used by the objects
created by the sub class.
There may be occasions when we want an object to respond to the same method is called.
This is possible by defining a method in the sub class that has the same name, same
arguments and same return type as a method in the super class.
When the methods are called, the method defined in the sub class is invoked and executed
instead of the one in the super class. This is known as overriding.
Example
class Super { int
Super (int x) {
x;
this.x=x;
void display ()
}
{ System.out.println(“Super x=”+x);
void display () {
System.out.println(“Sub y=”+y);
System.out.println(“x=”+x);
}}
}}
class overridetest {
public static void main (String args[])
class Sub extends Super { int
{ Sub S1=new Sub (100, 200);
y;
S1.display (); } }
Sub (int x, int y)
27
{ super
(x);
this.y=y; } }
28
ABSTRACT METHODS AND CLASSES
In JAVA we have two types of classes. Concrete classes and abstract classes. They are
A concrete class is one which contains fully defined methods. Defined methods are also
known as implemented or concrete methods. With respect to concrete class, we can create
an object of that class directly.
An abstract class is one which contains some defined methods and some undefined
methods. Undefined methods are also known as unimplemented or abstract methods.
Abstract method is one which does not contain any definition. To make the method as
abstract we have to use a keyword called abstract before the function declaration.
ABSTRACT METHODS
When a method is defined as final than that method is not re-defined in a
subclass.
Java allows a method to be re-defined in a sub class and those methods are called
abstract methods.
When a class contains one or more abstract methods, then it should be declared as
abstract class.
When a class is defined as abstract class, it must satisfy following conditions.
o We can’t use abstract classes to instantiate objects directly. For example Op s =
new Op( ) - is illegal because Op is an abstract class.
o The abstract methods of an abstract class must be defined in its sub class.
o We can’t declare abstract constructors or abstract static methods.
Final allows the methods not redefine in the subclass.
Abstract method must always be redefined in a subclass, thus making overriding
compulsory.
This is done using the modifier keyword abstract in the method definition.
29
FINAL VARIABLES AND METHODS
It prevents the subclasses form overriding the member of the superclass. Final variables
and methods are declared as final using the keyword final as a modifier.
Example: size =100 final int
SIZE = 100;
final void showstatus( ){..........................}
Making a method final ensures that the functionality defined in that method will never
be altered in any way.
The value of a final variable can never be changed.
FINAL CLASSES
• A class that cannot be sub-classed is called a final class.
• It prevents a class being further sub-classed for security reasons.
• Any attempt to inherit these classes will cause an error. final
class Aclass
{
}
Final class Bclass extend someclass
{
}
FINALIZER METHODS
• Initialization→ constructor method is used to initialize an object when it is
declared. This process is called initialization.
• Finalization→finalizer method is just opposite to initialization, it automatically
frees up the memory resources used by the objects. This process is known as finalization.
• It acts like a destructor.
• The method can be added to any class.
30
protected void finalize( )
{
// finalization code here }
Here, the keyword protected is a specifier that prevents access to finalize( ) by code
defined outside its class.
PACKAGES
BENEFITS:
The classes contained in the packages of other programs can be easily reused.
In packages, classes can be unique compared with classes in other packages.
That is two classes in two different packages can have the same name.
They may be referred by their fully qualified name, comprising the package name and the
class name.
Packages provide a way to "hide" classes thus preventing other programs or packages
from accessing classes that are meant for internal use only.
Packages also provide a way for separating "design" form "coding".
31
USING PACKAGES
Packages are organized in a hierarchical structure.
o The package named java contains the package awt, which in turns contain various
classes required for implementing graphical user interface. Best and easiest one to
access the class
o Used only once, not possible to access other classes of the package. There
are two ways of accessing the classes stored in a package
1. Using the fully qualified class name. (Using the package name containing the class
and then appending the class name by using the dot operator.)
E.g. java.awt.Color
2. Using the import statement, appear at the top of the file. Imported package class can be
accessed anywhere in the program
Syntax:
import packagename.classname;
Or
import packagename.*
These are known as import statements and must appear at the top of the file, before any class
declarations, import is a keyword.
The first statement allows the specified class in the specified package to be
imported. For example, the statement
import java.awt.Color;
imports the class Color and therefore the class name can now be directly used in the program.
The second statement imports every class contained in the specified package.
For example, the statement import
java.awt.*;
will bring all classes of java.awt package.
32
INTERFACES
Interfaces are basically used to develop user defined data types.
With respect to interfaces we can achieve the concept of multiple inheritances.
With interfaces we can achieve the concept of polymorphism, dynamic binding and hence
we can improve the performance of a JAVA program in turns of memory space and
execution time.
An interface is a construct which contains the collection of purely undefined methods or
an interface is a collection of purely abstract methods.
interface <InterfaceName>
{
variables declaration; methods
declaration;
}
EXTENDING INTERFACES
Interface can also be extended.
An interface can be sub-interfaced from other interfaces.
The new interface will inherit all the member of the super-interface.
Interface can be extended using the keyword extends.
interface name2 extends name1
{
Body of name2
}
33
IMPLEMENTING INTERFACES
Implement the interface using implements keyword.
General form1
General form2
class classname implements
class classname extends supperclass
interfacename
implements interface1,interface2,………..
{
{
body of classname
body of classname
}
}
EXCEPTION HANDLING
Exception types
All exceptions are subclasses of Throwable class. There are two subclasses that partition
exception into two distinct branches, Exception and Error.
Exception – this class is used for exceptional conditions that user program should catch.
The class defined for custom exceptions are subclass to this class. A special subclass
called RuntimeException, Exception of this class is automatically defined for a program.
Error – This class defines exceptions that are not expected under normal circumstances.
Exceptions of this type are used by the Java run-time system to indicate errors having to
be deal by the run-time environment itself.
34
Syntax of Exception Handling Code
The basic concept of exception handling are throwing an exception and catching it. Program
statements to be montiored are placed within try block. If an exception occurs within the
try block, it is thrown. The code to handle the exception is placed within in the catch block.
Any code that must be executed before a method returns is put in a finally block.
The try block can have one or more statements that could generate an exception. If
any one statement generate an exception, the remaining statements in the block are
skipped and execution jumps to the catch block.
The catch block have one or more statements that are necessary to process the
exception. Every try statement should be followed by atleast one catch statement.
A try statement may have multiple catch blocks.
A finally block is added to a try statement to handle an exception that is not handled
or caught by the previous catch statements. A finally block can be
35
used to handle any exception within in a try block. A finally block may be added
immediately after the try block or after the last catch block.
When a finally block is defined, this is guaranteed to executed, regardless of whether
or not an excpetion is thrown.
Nested try statements: the try statement can be nested. Each time a try statement is entered, the
context of that exception is pushed on the stack. If an inner try statement does not have a
catch handler for a particular exception, the stack is unwound and next try statement’s catch
handlers are inspected for a match. This continues until one of the catch statements succeeds,
if no catch statement matches, then the Java run-time system will handle the exception.
36
// body of method
}
where exception-list is a comma separated list of the exceptions that a method can throw.
1. What are the different types of inheritance supported in Java? Can you explain
each type?
2. How do you define a superclass and a subclass in Java? What is the relationship
between them?
3. What is method overriding, and how does it relate to inheritance? Provide
an example.
4. How does inheritance facilitate polymorphism in Java?
5. How do the public, protected, and private access modifiers affect member access in
inheritance?
6. What is a package in Java, and why is it used?
7. How do you implement an interface in a class? What is the syntax?
8. What are default and static methods in interfaces? How do they differ from
regular interface methods?
9. How do you use try-catch blocks to handle exceptions? Provide a code example.
10. What is the purpose of the finally block in exception handling? When is it
executed?
37
11. What is the difference between checked and unchecked exceptions? Can you give
examples of each?
38
UNIT III
MULTITHREADED PROGRAMMING
CREATING THREADS
Creating threads in Java is simple.
Threads are implemented in the form of objects that contain a method called run( ).
The run( ) method is the heart and soul of any thread. It makes up the entire body of the
thread and is the only method in which the thread’s behavior can be implemented.
A typical run( ) would appear as follows:
public void run( )
{
---- ( Statements for implementing thread )
}
The run( ) method should be invoked by an object of the concerned thread. This can be achieved
by creating the thread and initiating it with the help of another thread method called start( ).
38
A NEW THREAD CAN BE CREATED IN TWO WAYS.
By creating a thread class : Define a class that extends thread class and override its
run( ) method with the code required by the thread.
By converting a class to a thread: Define a class that implements Runnable interface.
The Runnable interface has only one method, run( ) , that is to be defined in the method
with the code to be executed by the thread.
The approach to be used depends on what the class we are creating requires.
If it requires to extend another class, then we have no choice but to implement the
Runnable interface, since Java classes cannot have two superclasses.
39
The basic implementation of run( ) will look like this:
public void run( )
{
……..
…….. // Thread code here
}
when we start the new thread, Java calls the thread’s run( ) method, so it is the run( )
where all the action takes place.
I/O STREAMS
A file is a collection of related records, a record is collection of fields and a filed is a group of
characters. Storing and managing data using files is known as file processing which includes
tasks such as creating files, updating files and manipulation of data. Java handles the file
processing in the form of streams. Java also supports to write and read an object from the
secondary storage device, known as object serialization.
Concepts of Streams
In file processing, input refers to the flow of data into a program and output means the flow of
data out of a program.
Java uses the concept of streams to represent the ordered sequence of data, a common
characteristic shared by all the input/output devices.
40
A stream persent a uniform, easy-to-use, object-oriented interface between the program and
the input/output devices.
A stream has a source and a destination, which may he physical devices or programs or other
streams in the same program.
Java streams are classified into two basic types are input stream and output stream. An input
stream extracts data from the source and sends it to the program. An output stream takes data
from the program and sends it to the destination.
Stream Classes
Java Stream
classes
The java.io package contains a large number of stream classes that provide capabilities for
processing all types of data. These classes are classified into two categories based on the type
of data they can process.
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on
characters.
Byte stream and character stream classes contain specialized classes to deal with input and
output operations independently on various types of devices.
41
Byte Stream Classes
Byte stream classes provide functional features for creating and manipulating streams and
files for reading and writing bytes. Java provides two kinds of byte stream classes input
stream and output stream classes.
Input stream classes: Input stream classes are used to read bytes, include a super class known
as InputStream and various subclasses for supporting various input- related functions.
The super class InputStream is an abstract class. The InputStream class defines methods for
performing input functions such as
Reading bytes
Closing streams
Marking positions in streams
Skipping ahead in a stream
Finding the number of bytes in a stream
Output Stream Classes: Output stream classes are derived from the base clas OutputStream.
The OutputStream is an abstract class. The subclasses of the OutputStream can be used for
performing the output operations.
42
The OutputStream includes methods to perform the following operations
1. Writing bytes
2. Closing streams
3. Flusing streams
43
The classes used for various input/output operations in both groups are given below.
44
Object
Interface Interface
DataInput DataOutput
RandomAccessFile
45
ALL THE QUESTIONS
46
UNIT IV
AWT Controls:
COMPONENT
The class Component is the abstract base class for the non menu user-interface controls of
AWT. Component represents an object with graphical representation.
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.
It is basically a screen where the where the components are placed at their specific locations.
Thus it contains and controls the layout of components.
Types of containers:
There are four types of containers in Java AWT:
1. Window
2. Panel
3. Frame
4. Dialog
47
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.
LABEL
Label is a passive control because it does not create any event when accessed by the user. The
label control is an object of Label. A label displays a single line of read- only text. However
the text can be changed by the application programmer but cannot be changed by the end user
in any way.
Field
static int CENTER -- Indicates that the label should be centered.
static int LEFT -- Indicates that the label should be left justified.
static int RIGHT -- Indicates that the label should be right justified.
Constructors
Label(String text) - Constructs a new label with the specified string of text, left justified.
Label(String text, int alignment) - Constructs a new label that presents the specified string of
text with the specified alignment.
48
Methods
void setText(String text) It sets the texts for label with the specified text.
void setAlignment(int alignment) It sets the alignment for label with the specified
alignment.
protected String paramString() It returns the string the state of the label.
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.
When we press a button and release it, AWT sends an instance of ActionEvent to that button
by calling processEvent on the button. The processEvent method of the button receives
the all the events, then it passes an action event by calling its own method
processActionEvent. This method passes the action event on to action listeners that are
interested in the action events generated by the button.
To perform an action on a button being pressed and released, the
ActionListener interface needs to be implemented. The registered new listener can receive
events from the button by calling addActionListener method of the button. The Java
application can use the button's action command as a messaging protocol.
49
CONSTRUCTOR
Button( ) It constructs a new button with an empty string i.e. it has no label.
Button (String text) It constructs a new button with given string as its label.
Methods
void setText (String text) It sets the string message on the button
void setLabel (String label) It sets the label of button with the specified
string.
void addActionListener(ActionListener l) It adds the specified action listener to get the action
events from the button.
protected String paramString() It returns the string which represents the state of
button.
void setActionCommand(String It sets the command name for the action event given
command) by the button.
50
TEXT FIELD
The object of a TextField class is a text component that allows a user to enter a single line
text and edit it. It inherits TextComponent class, which further inherits Component
class.
When we enter a key in the text field (like key pressed, key released or key typed), the event
is sent to TextField. Then the KeyEvent is passed to the registered KeyListener. It
can also be done using ActionEvent; if the ActionEvent is enabled on the text field, then the
ActionEvent may be fired by pressing return key. The event is handled by the
ActionListener interface.
Constructor
TextField(String text) It constructs a new text field initialized with the given string text
to be displayed.
TextField (String text, int It constructs a new text field with the given text and given
columns) number of columns (width).
Methods
boolean echoCharIsSet() It tells whether text field has character set for
echoing or not.
51
AccessibleContext It fetches the accessible context related to the text
getAccessibleContext() field.
void setText(String t) It sets the text presented by this text component to the
specified text.
TEXT AREA
The object of a TextArea class is a multiline region that displays text. It allows the editing of
multiple line text. It inherits TextComponent class.
The text area allows us to type as much text as we want. When the text in the text area
becomes larger than the viewable area, the scroll bar appears automatically which helps us to
scroll the text up and down, or right and left.
Class constructors:
TextArea() It constructs a new and empty text area with no text in it.
TextArea (int row, int column) It constructs a new text area with specified number of rows
and columns and empty string as text.
TextArea (String text) It constructs a new text area and displays the
specified text in it.
TextArea (String text, int row, int It constructs a new text area with the specified text in the
column) text area and specified number of rows and
52
columns.
TextArea (String text, int row, int It construcst a new text area with specified text in text area
column, int scrollbars) and specified number of rows and columns and visibility.
Methods
boolean echoCharIsSet() It tells whether text field has character set for
echoing or not.
void setText(String t) It sets the text presented by this text component to the
specified text.
53
CHECKBOX
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".
Constructor
Checkbox(String label, boolean It constructs a checkbox with the given label and sets
state) the given state.
Checkbox(String label, boolean It constructs a checkbox with the given label, set the
state, CheckboxGroup group) given state in the specified checkbox group.
Method
void addItemListener(ItemListener IL) It adds the given item listener to get the item
events from the checkbox.
54
String getLabel() It fetched the label of checkbox.
boolean getState() It returns true if the checkbox is on, else returns off.
protected void processItemEvent It process the item events occurring in the checkbox
(ItemEvent e) by dispatching them to registered ItemListener
object.
void removeItemListener(ItemListener It removes the specified item listener so that the item
l) listener doesn't receive item events from the
checkbox anymore.
void setState(boolean state) It sets the state of checkbox to the specified state.
CHECKBOXGROUP
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time
only one check box button is allowed to be in "on" state and remaining check box button in
"off" state. It inherits the object class.
CHOICE
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits Component class.
55
Constructor
Methods
void addItemListener(ItemListener l) It adds the item listener that receives item events from
the choice menu.
String getItem(int index) It gets the item (string) at the given index position in
the choice menu.
void insert(String item, int index) Inserts the item into this choice at the specified
position.
56
void remove(int position) It removes an item from the choice menu at the given
index position.
57
void remove(String item) It removes the first occurrence of the item from
choice menu.
void removeAll() It removes all the items from the choice menu.
void select(int pos) It changes / sets the selected item in the choice menu
to the item at given index position.
void select(String str) It changes / sets the selected item in the choice menu to
the item whose string value is equal to string specified
in the argument.
LIST
The object of List class represents a list of text items. With the help of the List class, user can
choose either one item or multiple items. It inherits the Component class.
Constructor
List (int row_num, Boolean It constructs a new scrolling list initialized which
multipleMode) displays the given number of rows.
Methods
void add(String item) It adds the specified item into the end of
scrolling list.
58
void add(String item, int index) It adds the specified item into list at the
59
given index position.
60
array of objects.
void remove(int position) It removes the item at given index position from
the list.
61
void replaceItem(String newVal, int index) It replaces the item at the given index in list
with the new string specified.
void select(int index) It selects the item at given index in the list.
PANEL
The Panel is a simplest container class. It provides space in which an application can
attach any other component. It inherits the Container class.
It doesn't have title bar.
MENU
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a
menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu
bar. It inherits the MenuItem class.
Constructor
Frame()
Constructs a new instance of Frame that is initially invisible.
Frame(GraphicsConfiguration gc)
Constructs a new, initially invisible Frame with the specified GraphicsConfiguration.
62
Frame(String title)
Constructs a new, initially invisible Frame object with the specified title.
63
Frame(String title, GraphicsConfiguration gc)
Constructs a new, initially invisible Frame object with the specified title and a
GraphicsConfiguration.
Methods
void addNotify()
Makes this Frame displayable by connecting it to a native screen resource.
int getCursorType()
Deprecated. As of JDK version 1.1, replaced by Component.getCursor().
Image getIconImage()
Returns the image to be displayed as the icon for this frame.
MenuBar getMenuBar()
Gets the menu bar for this frame.
int getState()
Gets the state of this frame (obsolete).
String getTitle()
Gets the title of the frame.
boolean isResizable()
Indicates whether this frame is resizable by the user.
64
boolean isUndecorated()
Indicates whether this frame is undecorated.
void remove(MenuComponent m)
Removes the specified menu bar from this frame.
void removeNotify()
Makes this Frame undisplayable by removing its connection to its native screen resource.
65
FONTS
In Java, Font is a class that belongs to the java.awt package. It implements the Serializable
interface. FontUIResource is the direct known subclass of the Java Font class.
It represents the font that are used to render the text. In Java, there are two technical terms
that are used to represent font are characters and Glyphs.
There are two types of fonts in Java:
o Physical Fonts
o Logical Fonts
Physical Fonts
Physical fonts are actual Java font library. It contains tables that maps character
sequence to glyph sequences by using the font technology such as TrueType Fonts
(TTF) and PostScript Type 1 Font. Note that all implementation of Java must support TTF.
Using other font technologies is implementation dependent. Physical font includes the name
such as Helvetica, Palatino, HonMincho, other font names. The property of the physical
font is that it uses the limited set of writing systems such as Latin characters or only
Japanese and Basic Latin characters. It may vary as to configuration changes. If any
application requires a specific font, user can bundle and instantiate that font by using the
createFont() method of the Java Font class.
Logical Fonts
Java defines five logical font families that are Serif, SansSerif, Monospaced, Dialog, and
DialogInput. It must be supported by the JRE. Note that JRE maps the logical font names to
physical font because these are not the actual font libraries. Usually, mapping implementation
is locale dependent. Each logical font name map to several physical fonts in order to cover a
large range of characters.
66
o Family name: It is the name of the font family. It determines the typograph design
among several faces.
LAYOUT MANAGER
The Layout managers enable us to control the way in which visual components are arranged in
the GUI forms by determining the size and position of components within the containers.
Types of LayoutManager
There are 4 layout managers in Java
FlowLayout: It arranges the components in a container like the words on a page. It fills
the top line from left to right and top to bottom. The components are arranged in the
order as they are added i.e. first components appears at top left, if the container is not
wide enough to display all the components, it is wrapped around the line. Vertical and
horizontal gap between components can be controlled. The components can be left,
center or right aligned.
BorderLayout: It arranges all the components along the edges or the middle of the
container i.e. top, bottom, right and left edges of the area. The components added to the
top or bottom gets its preferred height, but its width will be the width of the container and
also the components added to the left or right gets its preferred width, but its height will
be the remaining height of the container. The components added to the center gets neither
its preferred height or width. It covers the remaining area of the container.
GridLayout: It arranges all the components in a grid of equally sized cells, adding them
from the left to right and top to bottom. Only one component can be placed in a cell and
each region of the grid will have the same size. When the container is resized, all cells are
automatically resized. The order of placing the components in a cell is determined as they
were added.
GridBagLayout: It is a powerful layout which arranges all the components in a grid of
cells and maintains the aspect ration of the object whenever the container is resized. In
this layout, cells may be different in size. It assigns a consistent horizontal and vertical
gap among components. It allows us to specify a default alignment for components within
the columns or rows.
67
EVENT HANDLING
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The java.awt.event package provides many event classes and Listener interfaces
for event handling.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
One of the key benefits of the Delegation Event Model in Java is that it allows for a high level of
modularity in Java applications. By separating the event source from the event listener, you
can create more flexible and scalable code. This model also allows for easy customization, as
different event listeners can be created to handle different types of events.
The Delegation Event Model in Java consists of three main components: event source, event
object, and event listener.
Event source: This is the object that generates the event. When an event occurs, the event source
creates an event object and passes it to all registered event listeners. Examples of event
sources can be a button, a text field, or any other component of the user interface.
Event object: This is a Java object that encapsulates information about the event that occurred. It
contains details such as the type of event, the source of the event, and any additional data that
may be relevant to the event. The event object is passed to all registered event listeners,
allowing them to respond to the event appropriately.
Event listener: This is an interface that defines methods for responding to events. To handle an
event, an object must implement the appropriate event listener interface and register itself
with the event source. When the event occurs, the event
69
source calls the appropriate method on each registered event listener, passing in the event
object.
There are two types of events that MouseMotionListener can generate. There are two abstract
functions that represent these five events. The abstract functions are:
1. void mouseDragged(MouseEvent e) : Invoked when a mouse button is pressed in the
component and dragged. Events are passed until the user releases the mouse button.
2. void mouseMoved(MouseEvent e) : invoked when the mouse cursor is moved from one
point to another within the component, without pressing any mouse buttons.
Keyboard Events
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. The KeyListener interface is found in java.awt.event package, and it has three
methods.
Interface declaration
70
Following is the declaration for java.awt.event.KeyListener interface:
1. public interface KeyListener extends EventListener
public abstract void keyPressed (KeyEvent e); It is invoked when a key has been
pressed.
public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.
ADAPTER CLASSES
In Java's event handling mechanism, adapter classes are abstract classes provided by the Java
AWT (Abstract Window Toolkit) package for receiving various events. These classes contain
empty implementations of the methods in an event listener interface, providing a convenience
for creating listener objects.
The adapter classes in Java are
WindowAdapter
KeyAdapter
MouseAdapter
FocusAdapter
ContainerAdapter
ComponentAdapter
These adapter classes implement interfaces like WindowListener, KeyListener,
MouseListener, FocusListener, ContainerListener, and ComponentListener respectively,
which contain methods related to specific events.
INNER CLASSES
A Java inner class is a class that is defined inside another class. The concept of inner
class works with nested Java classes where outer and inner classes are used.
71
The main class in which inner classes are defined is known as the outer class and all other
classes which are inside the outer class are known as Java inner classes.
SELF–ASSESSMENT QUESTIONS
1. What is AWT, and how does it differ from Swing?
2. What are the primary components provided by AWT?
3. What is the purpose of the `Frame` class in AWT?
4. What are layout managers in AWT? Name and explain a few common ones.
5. How do you set a layout manager for a container in AWT?
6. How do you perform custom painting in AWT?
7. What is the role of the `Graphics` class in AWT?
8. What is Swing, and how does it enhance AWT?
9. Explain the concept of "lightweight" components in Swing.
10. What is the "look and feel" of a Swing application, and how can it be changed?
11. How do you set a custom look and feel for a Swing application?
12. Discuss the advantages and disadvantages of using Swing over AWT.
13. Can you use AWT components in a Swing application? If so, how?
14. What is event handling in Java?
15. What is an event listener, and how do you implement one in Java?
16. How do you use ActionListener, MouseListener, and KeyListener in your
applications?
17. How do you register an event listener with a component?
18. What is the Event Dispatch Thread, and why is it important in Swing?
19. How do you create and handle custom events in Java?
20. What is the difference between using built-in events and custom events?
72
UNIT V
SWING
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
70
The methods of Component class are widely used in java swing that are given below.
public void setLayout(LayoutManager m) sets the layout manager for the component.
JFrame
The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI.
Unlike Frame, JFrame has the option to hide or close the window with the help of
setDefaultCloseOperation(int) method.
Constructors
JFrame(String title, It creates a JFrame with the specified title and the
GraphicsConfiguration gc) specified GraphicsConfiguration of a screen
71
device.
Methods
JDialog
The JDialog control represents a top level window with a border and a title used to take
some form of input from the user. It inherits the Dialog class.
Unlike JFrame, it doesn't have maximize and minimize buttons.
72
Constructors
JDialog (Frame owner) It is used to create a modeless dialog with specified Frame
as its owner and an empty title.
JDialog (Frame owner, String title, It is used to create a dialog with the specified title,
boolean modal) owner Frame and modality.
JPanel
The JPanel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the JComponents class.
It doesn't have title bar.
Constructors
JPanel() It is used to create a new JPanel with a double buffer and a flow
layout.
JPanel(LayoutManager layout) It is used to create a new JPanel with the specified layout
manager.
JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.
Constructors
73
JButton(String s) It creates a button with the specified text.
Methods
JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or off.
Constructors
74
JToggleButton(Icon icon) It creates an initially unselected toggle button with the
specified image but no text.
JToggleButton(Icon icon, boolean It creates a toggle button with the specified image and
selected) selection state, but no text.
JToggleButton(String text, boolean It creates a toggle button with the specified text and
selected) selection state.
JToggleButton(String text, Icon It creates a toggle button that has the specified text and
icon) image, and that is initially unselected.
JToggleButton(String text, Icon It creates a toggle button with the specified text, image,
icon, boolean selected) and selection state.
Methods
75
JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It
inherits JToggleButton class.
Constructors
JCheckBox(String text, Creates a check box with text and specifies whether or not it is
boolean selected) initially selected.
JCheckBox(Action a) Creates a check box where properties are taken from the Action
supplied.
Methods
JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option
from multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Constructors
76
JRadioButton(String s) Creates an unselected radio button with specified
77
text.
JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.
Methods
JLabel
The object of JLabel 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 an application but a user cannot
edit it directly. It inherits JComponent class.
Constructors
JLabel() Creates a JLabel instance with no image and with an empty string
for the title.
78
JLabel(String s, Icon i, Creates a JLabel instance with the specified text,
int horizontalAlignment) image, and horizontal alignment.
Methods
void setText(String text) It defines the single line of text this component will
display.
void setHorizontalAlignment (int It sets the alignment of the label's contents along the X
alignment) axis.
Icon getIcon() It returns the graphic image that the label displays.
JTextField
The object of a JTextField class is a text component that allows the editing of a single
line text. It inherits JTextComponent class.
Constructors
JTextField(String text) Creates a new TextField initialized with the specified text.
JTextField(String text, int Creates a new TextField initialized with the specified text and
columns) columns.
JTextField(int columns) Creates a new empty TextField with the specified number of
columns.
79
Methods
JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the editing
of multiple line text. It inherits JTextComponent class
Constructors:
JTextArea(int row, int Creates a text area with the specified number of rows and
column) columns that displays no text initially.
JTextArea(String s, int row, int Creates a text area with the specified number of rows and
column) columns that displays specified text.
Methods:
80
void insert(String s, int It is used to insert the specified text on the specified position.
position)
void append(String s) It is used to append the given text to the end of the document.
JList
The object of JList class represents a list of text items. The list of text items can be set up so
that the user can choose either one item or multiple items. It inherits JComponent class.
Constructors:
JList(ary[] listData) Creates a JList that displays the elements in the specified array.
JList(ListModel<ary> Creates a JList that displays elements from the specified, non- null,
dataModel) model.
Methods:
Void addListSelectionListener It is used to add a listener to the list, to be notified each time a
(ListSelectionListener listener) change to the selection occurs.
ListModel getModel() It is used to return the data model that holds a list of items
displayed by the JList component.
JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on the top of a menu. It inherits JComponent class.
Constructors:
81
JComboBox() Creates a JComboBox with a default data model.
Methods:
void removeAllItems() It is used to remove all the items from the list.
JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.
Constructors
JScrollPane() It creates a scroll pane. The Component parameter, when present, sets the
scroll pane's client. The two int parameters, when present, set the vertical
JScrollPane(Component)
and horizontal scroll bar policies (respectively).
JScrollPane(int, int)
82
JScrollPane(Componen
t, int, int)
Methods
void setColumnHeaderView(Component) It sets the column header for the scroll pane.
void setRowHeaderView(Component) It sets the row header for the scroll pane.
void setCorner(String, Component) It sets or gets the specified corner. The int
parameter specifies which corner and must
Component getCorner(String)
be one of the following constants defined in
ScrollPaneConstants:
UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
83
QUESTIONS
1. What is Swing, and how does it differ from AWT?
2. How do you create a `JButton`? Provide an example of how to add it to a
`JFrame`.
3. What is the purpose of `JLabel`, and how can you use it to display text and images?
4. How do you create a `JTextField`, and how can you retrieve user input from it?
5. What is the difference between `JTextArea` and `JTextField`?
6. How do you create a `JCheckBox`, and how can you determine its state?
7. Explain how to use a `JRadioButton` and group them using a `ButtonGroup`.
8. How do you create a `JComboBox` and add items to it?
9. What is the difference between `JList` and `JComboBox`?
10. What is a `JPanel`, and how can it be used to organize components?
11. How do you use layout managers like `FlowLayout`, `BorderLayout`, and
GridLayout` in Swing?
12. How do you create and display a modal dialog using `JDialog`?
13. How do you attach an `ActionListener` to a button?
14. How can you create a custom component by extending `JComponent`?
15. Explain how to override the `paintComponent` method for custom drawing.
84