Java Notes
Java Notes
Classes Hierarchies
A graphical representation is often used to illustrate the relationships
among the classes (objects) of a community. This graphical
representation shows classes listed in a hierarchical tree-like structure. In
this more abstract class listed near the top of the tree, and more specific
classes in the middle of the tree, and the individuals listed near the
bottom.
In object-oriented programming, classes can be organized into a
hierarchical inheritance structure. A child class inherits properties
from the parent class that higher in the tree.
Method Binding, Overriding, and Exception
In the class hierarchy, both parent and child classes may have the same
method which implemented individually. Here, the implementation of
the parent is overridden by the child. Or a class may provide multiple
definitions to a single method to work with different arguments
(overloading).
The search for the method to invoke in response to a request (message)
begins with the class of this receiver. If no suitable method is found, the
search is performed in the parent class of it. The search continues up the
parent class chain until either a suitable method is found or the parent
class chain is exhausted. If a suitable method is found, the method is
executed. Otherwise, an error message is issued.
UNIT-1 CHAPTER-1
TOPIC: OOP CONCEPTS
OOP stands for Object-Oriented Programming. OOP is a programming
paradigm in which every program is follows the concept of object. In other
words, OOP is a way of writing programs based on the object concept.
The object-oriented programming paradigm has the following core concepts.
Encapsulation
Inheritance
Polymorphism
Abstraction
Encapsulation
Encapsulation is the process of combining data and code into a single unit
(object / class). In OOP, every object is associated with its data and code. In
programming, data is defined as variables and code is defined as methods.
The java programming language uses the class concept to implement
encapsulation.
Inheritance
Inheritance is the process of acquiring properties and behaviors from one
object to another object or one class to another class. In inheritance, we
derive a new class from the existing class. Here, the new class acquires the
properties and behaviors from the existing class. In the inheritance concept,
the class which provides properties is called as parent class and the class
which recieves the properties is called as child class. The parent class is also
known as base class or supre class. The child class is also known as derived
class or sub class.
In the inheritance, the properties and behaviors of base class extended to its
derived class, but the base class never receive properties or behaviors from its
derived class.
In java programming language the keyword extends is used to implement inheritance.
Polymorphism
Abstraction
Abstraction is hiding the internal details and showing only esential functionality. In the
abstraction concept, we do not show the actual implemention to the end user, instead
we provide only esential things. For example, if we want to drive a car, we does not
need to know about the internal functionality like how wheel system works? how brake
system works? how music system works? etc.
UNIT-1 CHAPTER-1
TOPIC: JAVA BUZZWORDS
Java is the most popular object-oriented programming language. Java has many
advanced features, a list of key features is known as Java Buzz Words. The java team
has listed the following terms as java buzz words.
Simple
Secure
Portable
Object-oriented
Robust
Architecture-neutral (or) Platform Independent
Multi-threaded
Interpreted
High performance
Distributed
Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++. In a java programming language, many
complicated features like pointers, operator overloading, structures, unions, etc. have
been removed. One of the most useful features is the garbage collector it makes java
more simple.
Secure
Java is said to be more secure programming language because it does not have
pointers concept, java provides a feature "applet" which can be embedded into a web
application. The applet in java does not allow access to other parts of the computer,
which keeps away from harmful programs like viruses and unauthorized access.
Portable
Portability is one of the core features of java which enables the java programs to run on
any computer or operating system. For example, an applet developed using java runs
on a wide variety of CPUs, operating systems, and browsers connected to the Internet.
Object-oriented
Java is said to be a pure object-oriented programming language. In java, everything is
an object. It supports all the features of the object-oriented programming paradigm. The
primitive data types java also implemented as objects using wrapper classes, but still, it
allows primitive data types to archive high-performance.
Robust
Java is more robust because the java code can be executed on a variety of
environments, java has a strong memory management mechanism (garbage collector),
java is a strictly typed language, it has a strong set of exception handling mechanism,
and many more.
Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do
multiple operations simultaneously.
Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. The byte code is interpreted to any machine code
so that it runs on the native machine.
High performance
Java provides high performance with the help of features like JVM, interpretation, and
its simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to
support the distributed environment of the Internet. Java also supports Remote Method
Invocation (RMI), this feature enables a program to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on
a running system and it has a dynamic memory allocation and deallocation (objects and
garbage collector).
UNIT-1 CHAPTER-1
TOPIC: OVERVIEW OF JAVA
Java is a computer programming language. Java was created based on C
and C++. Java uses C syntax and many of the object-oriented features
are taken from C++. Before Java was invented there were other
languages like COBOL, FORTRAN, C, C++, Small Talk, etc. These
languages had few disadvantages which were corrected in Java. Java
also innovated many new features to solve the fundamental problems
which the previous languages could not solve. Java was invented by a
team of 13 employees of Sun Microsystems, Inc. which is lead by James
Gosling, in 1991. The team includes persons like Patrick Naughton,
Chris Warth, Ed Frank, and Mike Sheridan, etc., Java was developed as
a part of the Green project. Initially, it was called Oak, later it was
changed to Java in 1995.
History of Java
Java programming language has a rich set of data types. The data type is a category
of data stored in variables. In java, data types are classified into two types and they
are as follows.
A variable is a named memory location used to store a data value. A variable can be defined as a
container that holds a data value.
In java, we use the following syntax to create variables.
Local variables
Instance variables or Member variables or Global variables
Static variables or Class variables
Final variables
Local variables
The variables declared inside a method or a block are known as local variables. A local variable is visible
within the method in which it is declared. The local variable is created when execution control enters into
the method or block and destroyed after the method or block execution completed.
Let's look at the following example java program to illustrate local variable in java.
Instance variables or member variables or global variables
The variables declared inside a class and outside any method, constructor or block are known as
instance variables or member variables. These variables are visible to all the methods of the class. The
changes made to these variables by method affects all the methods in the class. These variables are
created separate copy for every object of that class.
Let's look at the following example java program to illustrate instance variable in java.
Static variables or Class variables
A static variable is a variable that declared using static keyword. The instance variables can be static
variables but local variables can not. Static variables are initialized only once, at the start of the program
execution. The static variable only has one copy per class irrespective of how many objects we create.
The static variable is access by using class name.
Let's look at the following example java program to illustrate static variable in java.
Final variables
A final variable is a variable that declared using final keyword. The final variable is initialized only once,
and does not allow any method to change it's value again. The variable created using final keyword acts
as constant. All variables like local, instance, and static variables can be final variables.
Let's look at the following example java program to illustrate final variable in java.
UNIT-1 CHAPTER-1
TOPIC: JAVA ARRAYS
An array is a collection of similar data values with a single name. An array can
also be defined as, a special type of variable that holds multiple values of the same
data type at a time.
In java, arrays are objects and they are created dynamically using new operator.
Every array in java is organized using index values. The index value of an array
starts with '0' and ends with 'zise-1'. We use the index value to access individual
elements of an array.
In java, there are two types of arrays and they are as follows.
Creating an array
In the java programming language, an array must be created using new operator
and with a specific size. The size must be an integer value but not a byte, short, or
long. We use the following syntax to create an array.
In java, an array can also be initialized at the time of its declaration. When an array
is initialized at the time of its declaration, it need not specify the size of the array
and use of the new operator. Here, the size is automatically decided based on the
number of values that are initialized.
Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-
dimensional, 3-dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional
array variable, specify each additional index using another set of square brackets.
We use the following syntax to create two-dimensional array.
When we create a two-dimensional array, it created with a separate index for rows
and columns. The individual element is accessed using the respective row index
followed by the column index. A multidimensional array can be initialized while it
has created using the following syntax.
When an array is initialized at the time of declaration, it need not specify the size
of the array and use of the new operator. Here, the size is automatically decided
based on the number of values that are initialized.
The above statement creates a two-dimensional array of three rows and two
columns.
UNIT-1 CHAPTER-1
TOPIC: JAVA OPERATORS
An operator is a symbol used to perform arithmetic and logical operations. Java provides a rich set of
operators.
In java, operators are clasiffied into the following four types.
Arithmetic Operqators
Relational (or) Comparision Operators
Logical Operators
Assignment Operators
Bitwise Operators
Conditional Operators
Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical operations like addition,
subtraction, multiplication, division, modulus, increment, decrement, etc.,
Note:
The addition operator can be used with numerical data types and character or string data type.
When it is used with numerical values, it performs mathematical addition and when it is used with
character or string data type values, it performs concatination (appending).
The modulus (remainder of the division) operator is used with integer data type only.
The increment and decrement operators are used as pre-increment or pre-
decrement and post-increment or post-decrement.
When they are used as pre, the value is get modified before it is used in the actual expresion and
when it is used as post, the value is get modified after the the actual expression evaluation.
Relational Operators (<, >, <=, >=, ==, !=)
The relational operators are the symbols that are used to compare two values. That means the relational
operators are used to check the relationship between two values. Every relational operator has two
posible results either TRUE or FALSE. In simple words, the relational operators are used to define
conditions in a program. The following table provides information about relational operators.
Logical Operators
The logical operators are the symbols that are used to combine multiple conditions into one condition.
The following table provides information about logical operators.
Note:
The operators &, |, and ^ can be used with both boolean and integer data type values.
When they are used with integers, performs bitwise operations and with boolean,
performs logical operations.
Logical operators and Short-circuit operators both are similar, but in case of short-
circuit operators once the decision is finalized it does not evaluate remaining
expressions.
Assignment Operators
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand
side variable (Lvalue). The assignment operator is used in different variants along with
arithmetic operators. The following table describes all the assignment operators in the java
programming language.
Bitwise Operators
The bitwise operators are used to perform bit-level operations in the java programming
language. When we use the bitwise operators, the operations are performed based on binary
values. The following table describes all the bitwise operators in the java programming
language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Conditional Operators
The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making. In this operator, first, we verify a condition, then we
perform one operation out of the two operations based on the condition result. If the condition is
TRUE the first option is performed, if the condition is FALSE the second option is performed.
The conditional operator is used with the following syntax.
UNIT-1 CHAPTER-1
TOPIC: EXPRESSIONS
In any programming language, if we want to perform any calculation or to frame any condition
etc., we use a set of symbols to perform the task. These set of symbols makes an expression.
In the java programming language, an expression is defined as follows.
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic operations,
logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a
direct value or variable or address of memory location.
Expression Types
In the java programming language, expressions are divided into THREE types. They are as
follows.
Infix Expression
Postfix Expression
Prefix Expression
The above classification is based on the operator position in the expression.
Infix Expression
The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example
Postfix Expression
The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Example
Prefix Expression
The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example
UNIT-1 CHAPTER-1
In java, the default execution flow of a program is a sequential order. But the sequential order of
execution flow may not be suitable for all situations. Sometimes, we may want to jump from line
to another line, we may want to skip a part of the program, or sometimes we may want to
execute a part of the program again and again. To solve this problem, java provides control
statements.
In java, the control statements are the statements which will tell us that in which order the
instructions are getting executed. The control statements are used to control the order of
execution according to our requirements. Java provides several control statements, and they
are classified as follows.
while statement
do-while statement
for statement
for-each statement
Jump Statements
In java, the jump statements are used to terminate a block or take the execution control to the
next iteration. Java provides the following jump statements.
break
continue
return
TOPIC: ITERATIVE STATEMENT
The java programming language provides a set of iterative statements that are used to execute
a statement or a block of statements repeatedly as long as the given condition is true. The
iterative statements are also known as looping statements or repetitive statements. Java
provides the following iterative statements.
while statement
do-while statement
for statement
for-each statement
The for-each statement has the following syntax and execution flow diagram.
TOPIC: JUMP STATEMENT
The java programming language supports jump statements that used to transfer execution
control from one line to another line. The java programming language provides the following
jump statements.
break statement
continue statement
labelled break and continue statements
return statement
The following picture depictes the execution flow of the break statement.
continue statement in java
The continue statement is used to move the execution control to the beginning of the looping
statement. When the continue statement is encountered in a looping statement, the execution
control skips the rest of the statements in the looping block and directly jumps to the beginning
of the loop. The continue statement can be used with looping statements like while, do-while,
for, and for-each.
When we use continue statement with while and do-while statements, the execution control
directly jumps to the condition. When we use continue statement with for statement the
execution control directly jumps to the modification portion (increment/decrement/any
modification) of the for loop. The continue statement flow of execution is as shown in the
following figure.
Labelled break and continue statement in java
The java programming langauge does not support goto statement, alternatively, the break and
continue statements can be used with label.
The labelled break statement terminates the block with specified label. The labbeled contonue
statement takes the execution control to the beginning of a loop with specified label.
Let's look at the following example java code.
return statement in java
In java, the return statement used to terminate a method with or without a value. The return
statement takes the execution control to the calling function. That means the return statement
transfer the execution control from called function to the calling function by carrying a value.
🔔 Java allows the use of return-statement with both, with and without return type methods.
In java, the return statement used with both methods with and without return type. In the case of
a method with the return type, the return statement is mandatory, and it is optional for a method
without return type.
When a return statement used with a return type, it carries a value of return type. But, when it is
used without a return type, it does not carry any value. Instead, simply transfers the execution
control.
Let's look at the following example java code.
TOPIC: SELECTION STATEMENTS
In java, the selection statements are also known as decision making statements or branching
statements or conditional control statements. The selection statements are used to select a part
of the program to be executed based on a condition. Java provides the following selection
statements.
if statement
if-else statement
nested if statement
if-else if statement
switch statement
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of
statements based on that condition result. The if statement checks, the given condition then
decides the execution of a block of statements. If the condition is True, then the block of
statements is executed and if it is False, then the block of statements is ignored. The syntax and
execution flow of if the statement is as follows.
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False
and the condition is evaluated to False. Then the if statement ignores the execution of its block
of statements.
When we enter a number which is divisible by 5, then it produces the output as follows.
Look at the following picture to understand the class and object concept.
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as
variables and behaviors as methods. Following is the syntax of class in the java.
T
he ClassName must begin with an alphabet, and the Upper-case letter is preferred.
The ClassName must follow all naming rules.
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the class is
said to be instantiated. All the objects that are created using a single class have the same
properties and methods. But the value of properties is different for every object. Following is the
syntax of class in the java.
The objectName must begin with an alphabet, and a Lower-case letter is preferred.
The objectName must follow all naming rules.
UNIT-1 CHAPTER-1
A method is a block of statements under a name that gets executes only when it is called. Every
method is used to perform a specific task. The major advantage of methods is code re-usability
(define the code once, and use it many times).
In a java programming language, a method defined as a behavior of an object. That means,
every method in java must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.
Creating a method
A method is created inside the class and it may be created with any access specifier. However,
specifying access specifier is optional.
Following is the syntax for creating methods in java.
NOTE:
The methodName must begin with an alphabet, and the Lower-case letter is preferred.
The methodName must follow all naming rules.
If you don't want to pass parameters, we ignore it.
If a method defined with return type other than void, it must contain the return
statement, otherwise, it may be ignored.
Calling a method
In java, a method call precedes with the object name of the class to which it belongs and a dot
operator. It may call directly if the method defined with the static modifier. Every method call
must be made, as to the method name with parentheses (), and it must terminate with a
semicolon.
NOTE:
The method call must pass the values to parameters if it has.
If the method has a return type, we must provide the receiver.
NOTE:
The objectName must begin with an alphabet, and a Lower-case letter is
preferred.
The objectName must follow all naming rules.
Variable arguments of a method
In java, a method can be defined with a variable number of arguments. That means creating a
method that receives any number of arguments of the same data type.
NOTE: When a method has both the normal parameter and variable-argument,
then the variable argument must be specified at the end in the parameters list.
Constructor
A constructor is a special method of a class that has the same name as the class name. The
constructor gets executes automatically on object creation. It does not require the explicit
method call. A constructor may have parameters and access specifiers too. In java, if you do not
provide any constructor the compiler automatically creates a default constructor.
Let's look at the following example java code.
The String class defined in the package java.lang package. The String class
implements Serializable, Comparable, and CharSequence interfaces.
The string created using the String class can be extended. It allows us to add more characters
after its definition, and also it can be modified.
Let's look at the following example java code.
String siteName=”gmail.com”;
siteName=www.gmail.com”;
It is very important to understand how the constructors get executed in the inheritance concept.
In the inheritance, the constructors never get inherited to any child class.
In java, the default constructor of a parent class called automatically by the constructor of its
child class. That means when we create an object of the child class, the parent class
constructor executed, followed by the child class constructor executed.
Let's look at the following example java code.
However, if the parent class contains both default and parameterized constructor, then only the
default constructor called automatically by the child class constructor.
Let's look at the following example java code.
The parameterized constructor of parent class must be called explicitly using
the super keyword.
UNIT-1 CHAPTER-2
TOPIC: ACCESS MODIFIERS
In Java, the access specifiers (also known as access modifiers) used to restrict the scope or
accessibility of a class, constructor, variable, method or data member of class and interface.
There are four access specifiers, and their list is below.
In java, we can not employ all access specifiers on everything. The following table describes
where we can apply the access specifiers.
Let's look at the following example java code, which generates an error because a class does
not allow private access specifier unless it is an inner class.
In java, the accessibility of the members of a class or interface depends on its access specifiers.
The following table provides information about the visibility of both data members and methods.
Inheritance Concept
The inheritance is a very useful and powerful concept of object-oriented programming. In java,
using the inheritance concept, we can use the existing features of one class in another class.
The inheritance provides a greate advantage called code re-usability. With the help of code re-
usability, the commonly used code in an application need not be written again and again.
Syntax
class <ChildClassName> extends <ParentClassName>{
...
//Implementation of child class
...
}
In a java programming language, a class extends only one class. Extending multiple classes is
not allowed in java.
Let's look at individual inheritance types and how they get implemented in java with an example.
In java, super is a keyword used to refers to the parent class object. The super keyword came
into existence to solve the naming conflicts in the inheritance. When both parent class and child
class have members with the same name, then the super keyword is used to refer to the parent
class version.
In java, the super keyword is used for the following purposes.
TOPIC: POLYMORPHISM
The polymorphism is the process of defining same method with different implementation. That
means creating multiple methods with different behaviors.
In java, polymorphism implemented using method overloading and method overriding.
Ad hoc polymorphism
The ad hoc polymorphism is a technique used to define the same method with different
implementations and different arguments. In a java programming language, ad hoc
polymorphism carried out with a method overloading concept.
In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism. Every function call binded with the
respective overloaded method based on the arguments.
The ad hoc polymorphism implemented within the class only.
Let's look at the following example java code.
Pure polymorphism
The pure polymorphism is a technique used to define the same method with the same
arguments but different implementations. In a java programming language, pure polymorphism
carried out with a method overriding concept.
In pure polymorphism, the method binding happens at run time. Pure polymorphism is also
known as run-time polymorphism. Every function call binding with the respective overridden
method based on the object reference.
When a child class has a definition for a member function of the parent class, the parent class
function is said to be overridden.
The pure polymorphism implemented in the inheritance concept only.
Let's look at the following example java code.
UNIT-1 CHAPTER-2
The method overriding is the process of re-defining a method in a child class that is already
defined in the parent class. When both parent and child classes have the same method, then
that method is said to be the overriding method.
The method overriding enables the child class to change the implementation of the method
which aquired from parent class according to its requirement.
In the case of the method overriding, the method binding happens at run time. The method
binding which happens at run time is known as late binding. So, the method overriding follows
late binding.
The method overriding is also known as dynamic method dispatch or run time
polymorphism or pure polymorphism.
Let's look at the following example java code.
10 Rules for method overriding
While overriding a method, we must follow the below list of rules.
TOPIC:ABSTRACT CLASS
An abstract class is a class that created using abstract keyword. In other words, a class prefixed
with abstract keyword is known as an abstract class.
In java, an abstract class may contain abstract methods (methods without implementation) and
also non-abstract methods (methods with implementation).
We use the following syntax to create an abstract class.
An abstract class can not be instantiated but can be referenced. That means we can not create
an object of an abstract class, but base reference can be created.
In the above example program, the child class objects are created to invoke the overridden
abstract method. But we may also create base class reference and assign it with child class
instance to invoke the same. The main method of the above program can be written as follows
that produce the same output.
In java, the Object class is the super most class of any class hierarchy. The Object class in the
java programming language is present inside the java.lang package.
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't know.
Because it is the superclass of all other classes in java, it can refer to any type of object.
The inheritance is the core and more useful concept Object Oriented Programming. It provides
with inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived class. An
inheritance leads to less development and maintenance costs with lot of benefits and few of
them are listed below.
Benefits of Inheritance
Inheritance helps in code reuse. The child class may use the code defined in the parent
class without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived
class. An inheritance leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be
altered by the derived class.
Costs of Inheritance
Inheritance decreases the execution speed due to the increased time and effort it takes,
the program to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This
means one cannot be used independently of each other.
The changes made in the parent class will affect the behavior of child class too.
The overuse of inheritance makes the program more complex.
UNIT-1 CHAPTER-2
TOPIC:FORMS OF INHERITANCE
The inheritance concept used for the number of purposes in the java programming language.
One of the main purposes is substitutability. The substitutability means that when a child class
acquires properties from its parent class, the object of the parent class may be substituted with
the child class object. For example, if B is a child class of A, anywhere we expect an instance of
A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.
The following are the differnt forms of inheritance in java.
Specialization
Specification
Construction
Eextension
Limitation
Combination
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent class. It
holds the principle of substitutability.
Specification
This is another commonly used form of inheritance. In this form of inheritance, the parent class
just specifies which methods should be available to the child class but doesn't implement them.
The java provides concepts like abstract and interfaces to support this form of inheritance. It
holds the principle of substitutability.
Construction
This is another form of inheritance where the child class may change the behavior defined by
the parent class (overriding). It does not hold the principle of substitutability.
Extension
This is another form of inheritance where the child class may add its new properties. It holds the
principle of substitutability.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It does
not hold the principle of substitutability.
Combination
This is another form of inheritance where the subclass inherits properties from multiple parent
classes. Java does not support multiple inheritance type.
UNIT-1
1. What is a class?
2. What is an object?
3. What is Inheritance?
4. What is method binding?
5. What is method overriding?
6. What are Object oriented concepts.
7. Discuss Java buzzwords.
8. What are data types.
9. What is a variable?
10. What is an array?
11. Discuss about operators?
12. What is an Expression.
13. What are control statements.
14. What is a constructor.
15. Discuss about final and super keyword.
16. What is polymorphism?
17. What are the benefits & costs of Inheritance?
18. What are the forms of Inheritance?
19. What is an abstract class
20. What is string handling?
UNIT-1
1. Discuss about A WAY OF VIEWING WORLD in detail.
2. Explain about OOPS concepts.
3. Write about Java Buzzwords. Explain an overview of Java.
4. Discuss in detail about data types, variables and arrays.
5. Explain about operators in detail.
6. Discuss in detail about control statements.
7. What is Inheritance and explain in detail about it.
8. Write different forms of inheritance. What are the benefits and costs of inheritance.
9. What is polymorphism and explain in detail about it.
10. Write in detail about classes, methods and string handling.
Fill in the blanks:
Built-in Packages
User-defined Packages
Built-in Packages
The built-in packages are the packages from java API. The Java API is a library of pre-defined
classes, interfaces, and sub-packages. The built-in packages were included in the JDK.
There are many built-in packages in java, few of them are as java, lang, io, util, awt, javax,
swing, net, sql, etc.
We need to import the built-in packages to use them in our program. To import a package, we
use the import statement.
User-defined Packages
The user-defined packages are the packages created by the user. User is free to create their
own packages.
NOTE:
NOTE:
When we use IDE like Eclipse, Netbeans, etc. the package structure is created automatically.
In java, the access modifiers define the accessibility of the class and its members. For example,
private members are accessible within the same class members only. Java has four access
modifiers, and they are default, private, protected, and public.
In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The
class acts as a container of data and methods. So, the access modifier decides the accessibility
of class members across the different packages.
In java, the accessibility of the members of a class or interface depends on its access specifiers.
The following table provides information about the visibility of both data members and methods.
NOTE:
The public members can be accessed everywhere.
The private members can be accessed only inside the same class.
The protected members are accessible to every child class (same package or other
packages).
The default members are accessible within the same package but not outside the
package.
Let's look at the following example java code.
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
}
In java, the import keyword used to import built-in and user-defined packages. When a package
has imported, we can refer to all the classes of that package using their name directly.
The import statement must be after the package statement, and before any other statement.
Using an import statement, we may import a specific class or all the classes from a package.
NOTE:
Using one import statement, we may import only one package or a class.
Using an import statement, we can not import a class directly, but it must be a part of a
package.
A program may contain any number of import statements.
Syntax
import packageName.ClassName;
Let's look at an import statement to import a built-in package and Scanner class.
Example
package myPackage;
import java.util.Scanner;
int i = read.nextInt();
In the above code, the class ImportingExample belongs to myPackage package, and it also
importing all the classes like Scanner, Random, Stack, Vector, ArrayList, HashSet, etc. from
the java.util package.
🔔 The import statement imports only classes of the package, but not sub-packages and its
classes.
🔔 We may also import sub-packages by using a symbol '.' (dot) to separate parent package and
sub-package.
import java.util.*;
The above import statement util is a sub-package of java package. It imports all the classes
of util package only, but not classes of java package.
In java, an interface is similar to a class, but it contains abstract methods and static final
variables only. The interface in Java is another mechanism to achieve abstraction.
We may think of an interface as a completely abstract class. None of the methods in the
interface has an implementation, and all the variables in the interface are constants.
All the methods of an interface, implemented by the class that implements it.
The interface in java enables java to support multiple-inheritance. An interface may extend only
one interface, but a class may implement any number of interfaces.
NOTE:
Syntax
interface InterfaceName{
...
members declaration;
...
}
Example
interface HumanInterfaceExample {
void work();
In the above code defines an interface HumanInterfaceExample that contains two abstract
methods learn(), work() and one constant duration.
Every interface in Java is auto-completed by the compiler. For example, in the above example
code, no member is defined as public, but all are public automatically.
The above code automatically converted as follows.
Converted code
interface HumanInterfaceExample {
}
In java, an interface is implemented by a class. The class that implements an interface must
provide code for all the methods defined in the interface, otherwise, it must be defined as an
abstract class.
The class uses a keyword implements to implement an interface. A class can implement any
number of interfaces. When a class wants to implement more than one interface, we use
the implements keyword is followed by a comma-separated list of the interfaces implemented
by the class.
The following is the syntax for defining a class that implements an interface.
Syntax
class className implements InterfaceName{
...
boby-of-the-class
...
}
Example
interface Human {
In the above code defines an interface Human that contains two abstract methods learn(),
work() and one constant duration. The class Programmer implements the interface. As it
implementing the Human interface it must provide the body of all the methods those defined in
the Human interface.
Syntax
class className implements InterfaceName1, InterfaceName2, ...{
...
boby-of-the-class
...
}
Let's look at an example code to define a class that implements multiple interfaces.
Example
interface Human {
void learn(String str);
}
interface Recruitment {
boolean screening(int score);
boolean interview(boolean selected);
}
class Programmer implements Human, Recruitment {
public void learn(String str) {
System.out.println("Learn using " + str);
}
public boolean screening(int score) {
System.out.println("Attend screening test");
int thresold = 20;
if(score > thresold)
return true;
return false;
}
public boolean interview(boolean selected) {
System.out.println("Attend interview");
if(selected)
return true;
return false;
}
public void work() {
System.out.println("Develop applications");
}
}
public class HumanTest {
public static void main(String[] args) {
Programmer trainee = new Programmer();
trainee.learn("Coding");
trainee.screening(30);
trainee.interview(true);
}
}
In the above code defines two interfaces Human and Recruitment, and a class Programmer
implements both the interfaces.
In java, an interface may be defined inside another interface, and also inside a class. The
interface that defined inside another interface or a class is konwn as nested interface. The
nested interface is also refered as inner interface.
🔔 The nested interface declared within an interface is public by default.
🔔 The nested interface declared within a class can be with any access modifier.
🔔 Every nested interface is static by default.
The nested interface cannot be accessed directly. We can only access the nested interface by
using outer interface or outer class name followed by dot( . ), followed by the nested interface
name.
Example
interface OuterInterface{
void outerMethod();
interface InnerInterface{
void innerMethod();
}
}
obj_1.outerMethod();
obj_2.innerMethod();
}
Example
class OuterClass{
interface InnerInterface{
void innerMethod();
}
}
obj.innerMethod();
}
}
In java, an interface is a completely abstract class. An interface is a container of abstract
methods and static final variables. The interface contains the static final variables. The variables
defined in an interface can not be modified by the class that implements the interface, but it may
use as it defined in the interface.
🔔 The variable in an interface is public, static, and final by default.
🔔 If any variable in an interface is defined without public, static, and final keywords then, the
compiler automatically adds the same.
🔔 No access modifier is allowed except the public for interface variables.
🔔 Every variable of an interface must be initialized in the interface itself.
🔔 The class that implements an interface can not modify the interface variable, but it may use
as it defined in the interface.
Example
interface SampleInterface{
}
In java, an interface can extend another interface. When an interface wants to extend another
interface, it uses the keyword extends. The interface that extends another interface has its own
members and all the members defined in its parent interface too. The class which implements a
child interface needs to provide code for the methods defined in both child and parent
interfaces, otherwise, it needs to be defined as abstract class.
🔔 An interface can extend another interface.
🔔 An interface can not extend multiple interfaces.
🔔 An interface can implement neither an interface nor a class.
🔔 The class that implements child interface needs to provide code for all the methods defined in
both child and parent interfaces.
Example
interface ParentInterface{
void parentMethod();
}
obj.childMethod();
obj.parentMethod();
}
STREAMS IN JAVA
In java, the IO operations are performed using the concept of streams. Generally, a stream
means a continuous flow of data. In java, a stream is a logical container of data that allows us to
read from and write to it. A stream can be linked to a data source, or data destination, like a
console, file or network connection by java IO system. The stream-based IO operations are
faster than normal IO operations.
The Stream is defined in the java.io package.
To understand the functionality of java streams, look at the following picture.
In java, the stream-based IO operations are performed using two separate streams input stream
and output stream. The input stream is used for input operations, and the output stream is used
for output operations. The java stream is composed of bytes.
In Java, every program creates 3 streams automatically, and these streams are attached to the
console.
The Java streams support many different kinds of data, including simple bytes, primitive data
types, localized characters, and objects.
Java provides two types of streams, and they are as follows.
Byte Stream
Character Stream
The following picture shows how streams are categorized, and various built-in classes used by
the java IO system.
Both character and byte streams essentially provides a convenient and efficient way to handle
data streams in Java.
In the next tutorial, we will explore different types of streams in java.
BYTE STREAM
In java, the byte stream is an 8 bits carrier. The byte stream in java allows us to transmit 8 bits of data.
In Java 1.0 version all IO operations were byte oriented, there was no other stream (character
stream).
The java byte stream is defined by two abstract classes, InputStream and OutputStream. The
InputStream class used for byte stream based input operations, and the OutputStream class
used for byte stream based output operations.
The InputStream and OutputStream classes have several concreate classes to perform various
IO operations based on the byte stream.
The following picture shows the classes used for byte stream operations.
InputStream class
The InputStream class has defined as an abstract class, and it has the following methods which
have implemented by its concrete classes.
1 int available()
It returns the number of bytes that can be read from the input stream.
2 int read()
It reads the next byte from the input stream.
3 int read(byte[] b)
It reads a chunk of bytes from the input stream and store them in its byte array, b.
4 void close()
It closes the input stream and also frees any resources connected with this input stream.
OutputStream class
The OutputStream class has defined as an abstract class, and it has the following methods
which have implemented by its concrete classes.
1 void write(int n)
2 void write(byte[] b)
It writes a whole byte array(b) to the output stream.
3 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void close()
It closes the output stream and also frees any resources connected with this output stream.
try {
System.out.print("Enter any character: ");
System.out.println("You have entered '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
read.close();
}
}
try {
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
input.close();
}
}
}
out.write(data.getBytes());
System.out.println("Writing data into a file is success!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}
CHARACTER STREAM:
In java, when the IO stream manages 16-bit Unicode characters, it is called a character stream.
The unicode set is basically a type of character set where each character corresponds to a
specific numeric value within the given character set, and every programming language has a
character set.
In java, the character stream is a 16 bits carrier. The character stream in java allows us to
transmit 16 bits of data.
The character stream was introduced in Java 1.1 version. The charater stream
The java character stream is defined by two abstract classes, Reader and Writer. The Reader
class used for character stream based input operations, and the Writer class used for charater
stream based output operations.
The Reader and Writer classes have several concreate classes to perform various IO
operations based on the character stream.
The following picture shows the classes used for character stream operations.
Reader class
The Reader class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
1 int read()
5 String readLine()
It reads a line of text. A line is considered to be terminated by any one
of a line feed ('\n'), a carriage return ('\r'), or a carriage returnfollowed immediately by a linefeed.
6 boolean ready()
It tells whether the stream is ready to be read.
7 void close()
It closes the input stream and also frees any resources connected with this input stream.
Writer class
The Writer class has defined as an abstract class, and it has the following methods which have
implemented by its concrete classes.
1 void flush()
It flushes the output steam by forcing out buffered bytes to be written out.
4 void write(int c)
It writes single character.
7 Writer append(char c)
It appends the specified character to the writer.
S.No. Method with Description
10 void close()
It closes the output stream and also frees any resources connected with this output stream.
name = in.readLine();
try {
char c = (char)input.read();
System.out.println("Data read from a file - '" + c + "'");
}
catch(Exception e) {
System.out.println(e);
}
finally {
input.close();
}
}
}
try {
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
out.close();
}
}
}
Console IO Operations
Reading console input in java
In java, there are three ways to read console input. Using the 3 following ways, we can read
input data from the console.
Example
import java.io.*;
try {
System.out.print("Please enter your name : ");
name = in.readLine();
System.out.println("Hello, " + name + "!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
in.close();
}
}
}
Example
import java.util.Scanner;
Example
import java.io.*;
String name;
Console con = System.console();
if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
}
}
Example
for(int i:list)
System.out.print(i); //prints in same line
System.out.println("");
for(int i:list)
System.out.println(i); //Prints in separate lines
}
}
2. Writing console output using write() method
Alternatively, the PrintStream class provides a method write() to write console output.
The write() method take integer as argument, and writes its ASCII equalent character on to the
console, it also acept escape sequences.
Let's look at the following code to illustrate write() method.
Example
for(int i:list) {
System.out.write(i);
System.out.write('\n');
}
}
}
The File is a built-in class in Java. In java, the File class has been defined in
the java.io package. The File class represents a reference to a file or directory. The File class
has various methods to perform operations like creating a file or directory, reading from a file,
updating file content, and deleting a file or directory.
The File class in java has the following constructors.
1 File(String pathname)
It creates a new File instance by converting the givenpathname string into an abstract pathname.
If the given string isthe empty string, then the result is the empty abstract pathname.
4 File(URI uri)
It creates a new File instance by converting the given file: URI into an abstract pathname.
1 String getName()
It returns the name of the file or directory that referenced by the current File object.
2 String getParent()
It returns the pathname of the pathname's parent, or null if the pathname does not name a
parent directory.
3 String getPath()
It returns the path of curent File.
4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.
S.No. Methods with Description
5 String getAbsolutePath()
It returns the current file or directory path from the root.
6 boolean isAbsolute()
It returns true if the current file is absolute, false otherwise.
7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.
8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.
9 boolean exists()
It returns true if the current file or directory exist; otherwise returns false.
10 boolean canRead()
It returns true if and only if the file specified exists and can be read by the application; false otherwise.
11 boolean canWrite()
It returns true if and only if the file specified exists and the application is allowed to write to the file;
false otherwise.
12 long length()
It returns the length of the current file.
13 long lastModified()
It returns the time that specifies the file was last modified.
14 boolean createNewFile()
It returns true if the named file does not exist and was successfully created; false if the named
file already exists.
15 boolean delete()
It deletes the file or directory. And returns true if and only if the file or directory is successfully
deleted; false otherwise.
16 void deleteOnExit()
It sends a requests that the file or directory needs be deleted when the virtual machine terminates.
17 boolean mkdir()
It returns true if and only if the directory was created; false otherwise.
S.No. Methods with Description
18 boolean mkdirs()
It returns true if and only if the directory was created, along with all necessary parent
directories; false otherwise.
21 boolean setReadOnly()
It sets the file permission to only read operations; Returns true if and only if the operation
succeeded; false otherwise.
22 String[] list()
It returns an array of strings containing names of all the files and directories
in the current directory.
24 File[] listFiles()
It returns an array of file references containing names of all the files and directories in the
current directory.
Example
import java.io.*;
public class FileClassTest {
}
Let's look at the following java code to list all the files in a directory including the files present in
all its subdirectories.
Example
import java.util.Scanner;
import java.io.*;
FileInputStream - It is a built-in class in java that allows reading data from a file.
This class has implemented based on the byte stream. The FileInputStream
class provides a method read() to read data from a file byte by byte.
FileOutputStream - It is a built-in class in java that allows writing data to a file.
This class has implemented based on the byte stream. The FileOutputStream
class provides a method write() to write data to a file byte by byte.
Let's look at the following example program that reads data from a file and writes the
same to another file using FileInoutStream and FileOutputStream classes.
Example
import java.io.*;
public class FileReadingTest {
try {
in = new FileInputStream("C:\\Raja\\Input-File.txt");
out = new FileOutputStream("C:\\Raja\\Output-File.txt");
int c;
while ((c = in.read()) != -1) {
}
System.out.println("Reading and Writing has been success!!!");
}
catch(Exception e){
System.out.println(e);
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
FileReader - It is a built-in class in java that allows reading data from a file. This
class has implemented based on the character stream. The FileReader class
provides a method read() to read data from a file character by character.
FileWriter - It is a built-in class in java that allows writing data to a file. This class
has implemented based on the character stream. The FileWriter class provides a
method write() to write data to a file character by character.
Let's look at the following example program that reads data from a file and writes the
same to another file using FIleReader and FileWriter classes.
Example
import java.io.*;
public class FileIO {
public static void main(String args[]) throws IOException {
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("C:\\Raja\\Input-File.txt");
out = new FileWriter("C:\\Raja\\Output-File.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
System.out.println("Reading and Writing in a file is done!!!");
}
catch(Exception e) {
System.out.println(e);
}
finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
In java, the java.io package has a built-in class RandomAccessFile that enables a file
to be accessed randomly. The RandomAccessFile class has several methods used to
move the cursor position in a file.
A random access file behaves like a large array of bytes stored in a file.
RandomAccessFile Constructors
The RandomAccessFile class in java has the following constructors.
S.No
. Constructor with Description
It creates a random access file stream to read from, and optionally to write to, the file specifie
argument.
Access Modes
Using the RandomAccessFile, a file may created in th following modes.
r - Creates the file with read mode; Calling write methods will result in an
IOException.
rw - Creates the file with read and write mode.
rwd - Creates the file with read and write mode - synchronously. All updates to
file content is written to the disk synchronously.
rws - Creates the file with read and write mode - synchronously. All updates to
file content or meta data is written to the disk synchronously.
RandomAccessFile methods
The RandomAccessFile class in java has the following methods.
S.No
. Methods with Description
1 int read()
S.No
. Methods with Description
It reads byte of data from a file. The byte is returned as an integer in the range 0-255.
2 int read(byte[] b)
It reads byte of data from file upto b.length, -1 if end of file is reached.
4 boolean readBoolean()
It reads a boolean value from from the file.
5 byte readByte()
It reads signed eight-bit value from file.
6 char readChar()
It reads a character value from file.
7 double readDouble()
It reads a double value from file.
8 float readFloat()
It reads a float value from file.
9 long readLong()
It reads a long value from file.
10 int readInt()
It reads a integer value from file.
11 void readFully(byte[] b)
It reads bytes initialising from offset position upto b.length from the buffer.
13 String readUTF()
S.No
. Methods with Description
15 long length()
It returns the length of the file.
16 void write(int b)
It writes the specified byte to the file from the current cursor position.
17 void writeFloat(float v)
It converts the float argument to an int using the floatToIntBits method in class Float, and then
value to the file as a four-byte quantity, high byte first.
18 void writeDouble(double v)
It converts the double argument to a long using the doubleToLongBits method in class Doubl
that long value to the file as an eight-byte quantity, high byte first.
Example
import java.io.*;
// Writing to file
f_ref.writeUTF("Hello, Good Morning!");
// read() method :
System.out.println("Use of read() method : " + f_ref.read());
f_ref.seek(0);
// readBoolean() method :
System.out.println("Use of readBoolean() : " +
f_ref.readBoolean());
// readByte() method :
System.out.println("Use of readByte() : " + f_ref.readByte());
f_ref.writeChar('c');
f_ref.seek(0);
// readChar() :
f_ref.seek(0);
f_ref.writeDouble(d);
f_ref.seek(0);
// read double
System.out.println("Use of readDouble() : " + f_ref.readDouble());
f_ref.seek(0);
f_ref.writeFloat(f);
f_ref.seek(0);
// readFloat() :
System.out.println("Use of readFloat() : " + f_ref.readFloat());
f_ref.seek(0);
// Create array upto geek.length
byte[] arr = new byte[(int) f_ref.length()];
// readFully() :
f_ref.readFully(arr);
f_ref.seek(0);
S.No
. Methods with Description
1 void flush( )
2 String readLine( )
It reads a string value from the keyboard, the input is terminated on pressing enter key.
4 char[ ] readPassword( )
It reads a string value from the keyboard, the string is not displayed; the input is terminated o
key.
8 Reader reader( )
It returns a reference to a Reader connected to the console.
9 PrintWriter writer( )
It returns a reference to a Writer connected to the console.
Let's look at the following example program for reading a string using Console class.
Example
import java.io.*;
String name;
Console con = System.console();
if(con != null) {
name = con.readLine("Please enter your name : ");
System.out.println("Hello, " + name + "!!");
}
else {
System.out.println("Console not available.");
}
}
}
Let's look at the following example program for writing to the console using Console
class.
Example
import java.io.*;
for(int i:list) {
System.out.write(i);
System.out.write('\n');
}
}
}
In java, the Serialization is the process of converting an object into a byte stream so
that it can be stored on to a file, or memory, or a database for future access. The
deserialization is reverse of serialization. The deserialization is the process of
reconstructing the object from the serialized state.
Using serialization and deserialization, we can transfer the Object Code from one Java
Virtual machine to another.
Serialization in Java
In a java programming language, the Serialization is achieved with the help of
interface Serializable. The class whose object needs to be serialized must implement
the Serializable interface.
We use the ObjectOutputStream class to write a serialized object to write to a
destination. The ObjectOutputStream class provides a method writeObject() to
serializing an object.
We use the following steps to serialize an object.
Step 1 - Define the class whose object needs to be serialized; it must implement
Serializable interface.
Step 2 - Create a file reference with file path using FileOutputStream class.
Step 3 - Create reference to ObjectOutputStream object with file reference.
Step 4 - Use writeObject(object) method by passing the object that wants to be
serialized.
Step 5 - Close the FileOutputStream and ObjectOutputStream.
Example
import java.io.*;
oos.writeObject(stud);
oos.close();
fos.close();
System.out.println("The object has been saved to my_data
file!");
}
catch(Exception e) {
System.out.println(e);
}
}
}
Deserialization in Java
In a java programming language, the Deserialization is achieved with the help of
class ObjectInputStream. This class provides a method readObject() to deserializing
an object.
We use the following steps to serialize an object.
Step 1 - Create a file reference with file path in which serialized object is
available using FileInputStream class.
Step 2 - Create reference to ObjectInputStream object with file reference.
Step 3 - Use readObject() method to access serialized object, and typecaste it to
destination type.
Step 4 - Close the FileInputStream and ObjectInputStream.
Example
import java.io.*;
public class DeserializationExample {
try {
FileInputStream fis = new
FileInputStream("my_data.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
fis.close();
ois.close();
Example
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY;
}
Every enum is converted to a class that extends the built-in class Enum.
🔔 Every constant of an enum is defined as an object.
🔔 As an enum represents a class, it can have methods, constructors. It also gets a few
extra methods from the Enum class, and one of them is the values() method.
Example
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY("Holiday");
String msg;
WeekDay(){
System.out.println("Default constructor!");
}
WeekDay(String str){
msg = str;
}
}
In the above example, the constant SUNDAY is created by calling the parameterized
constructor, other constants created by calling default constructor.
Example
enum WeekDay{
MONDAY, TUESDAY, WEDNESSDAY, THURSDAY, FRIDAY, SATURDAY,
SUNDAY("Holiday");
String msg;
WeekDay(){
System.out.println("Default constructor!");
}
WeekDay(String str){
System.out.println("Parameterized constructor!");
msg = str;
}
void printMessage() {
System.out.println("Today is also " + msg);
}
}
1 byte Byte
2 short Short
3 int Interger
4 long Long
5 float Float
6 double Double
7 char Character
8 boolean Boolean
The Java 1.5 version introduced a concept that converts primitive type to corresponding
wrapper type and reverses of it.
Autoboxing in Java
In java, the process of converting a primitive type value into its corresponding wrapper
class object is called autoboxing or simply boxing. For example, converting an int value
to an Integer class object.
The compiler automatically performs the autoboxing when a primitive type value has
assigned to an object of the corresponding wrapper class.
🔔 We can also perform autoboxing manually using the method valueOf( ), which is
provided by every wrapper class.
Let's look at the following example program for autoboxing.
Example - Autoboxing
import java.lang.*;
}
The java generics is a language feature that allows creating methods and class which
can handle any type of data values. The generic programming is a way to write
generalized programs, java supports it by java generics.
The java generics is similar to the templates in the C++ programming language.
🔔 Most of the collection framework classes are generic classes.
🔔 The java generics allows only non-primitive type, it does not support primitive types
like int, float, char, etc.
The java generics feature was introduced in Java 1.5 version. In java, generics used
angular brackets “< >”. In java, the generics feature implemented using the following.
Generic Method
Generic Classes
In the above example code, the method displayData( ) is a generic method that allows a
different type of parameter values for every function call.
Checked Exceptions
Unchecked Exceptions
Checked Exceptions
The checked exception is an exception that is checked by the compiler during the compilation
process to confirm whether the exception is handled by the programmer or not. If it is not
handled, the compiler displays a compilation error using built-in classes.
The checked exceptions are generally caused by faults outside of the code itself like missing
resources, networking errors, and problems with threads come to mind.
The following are a few built-in classes used to handle checked exceptions in java.
IOException
FileNotFoundException
ClassNotFoundException
SQLException
DataAccessException
InstantiationException
UnknownHostException
🔔 In the exception class hierarchy, the checked exception classes are the direct children of the
Exception class.
The checked exception is also known as a compile-time exception.
Let's look at the following example program for the checked exception method.
Unchecked Exceptions
The unchecked exception is an exception that occurs at the time of program execution. The
unchecked exceptions are not caught by the compiler at the time of compilation.
The unchecked exceptions are generally caused due to bugs such as logic errors, improper use
of resources, etc.
The following are a few built-in classes used to handle unchecked exceptions in java.
ArithmeticException
NullPointerException
NumberFormatException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
🔔 In the exception class hierarchy, the unchecked exception classes are the children of
RuntimeException class, which is a child class of Exception class.
The unchecked exception is also known as a runtime exception.
Let's look at the following example program for the unchecked exceptions.
System.out.println(list[6]);
//ArrayIndexOutOfBoundsException
String msg=null;
System.out.println(msg.length()); //NullPointerException
String name="abc";
int i=Integer.parseInt(name); //NumberFormatException
Termination Model
Resumptive Model
Termination Model
In the termination model, when a method encounters an exception, further processing in that
method is terminated and control is transferred to the nearest catch block that can handle the
type of exception encountered.
In other words we can say that in termination model the error is so critical there is no way to get
back to where the exception occurred.
Resumptive Model
The alternative of termination model is resumptive model. In resumptive model, the exception
handler is expected to do something to stable the situation, and then the faulting method is
retried. In resumptive model we hope to continue the execution after the exception is handled.
In resumptive model we may use a method call that want resumption like behavior. We may
also place the try block in a while loop that keeps re-entering the try block util the result is
satisfactory.
CHP-1
UNCAUGHT EXCEPTIONS
In java, assume that, if we do not handle the exceptions in a program. In this case, when an
exception occurs in a particular function, then Java prints a exception message with the help of
uncaught exception handler.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Java programming language has a very strong exception handling mechanism. It allow us to
handle the exception use the keywords like try, catch, finally, throw, and throws.
When an uncaught exception occurs, the JVM calls a special private method
known dispatchUncaughtException( ), on the Thread class in which the exception occurs and
terminates the thread.
The Division by zero exception is one of the example for uncaught exceptions. Look at the
following code.
Example
import java.util.Scanner;
}
}
CHP-1
TRY &CATCH EXCEPTION
In java, the try and catch, both are the keywords used for exception handling.
The keyword try is used to define a block of code that will be tests the occurence of an
exception. The keyword catch is used to define a block of code that handles the exception
occured in the respective try block.
The uncaught exceptions are the exceptions that are not caught by the compiler but
automatically caught and handled by the Java built-in exception handler.
Both try and catch are used as a pair. Every try block must have one or more catch blocks. We
can not use try without atleast one catch, and catch alone can be used (catch without try is not
allowed).
The following is the syntax of try and catch blocks.
Syntax
try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}
Consider the following example code to illustrate try and catch blocks in Java.
Example
import java.util.Scanner;
In the above example code, when an exception occurs in the try block the execution control
transfered to the catch block and the catch block handles it.
Let's look at the following example Java code to illustrate multiple catch clauses.
Example
public class TryCatchExample {
try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[10] = list[2] / list[4];
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has
occured.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}
Example
public class TryCatchExample {
try {
int list[] = new int[5];
list[2] = 10;
list[4] = 2;
list[0] = list[2] / list[4];
try {
list[10] = 100;
}
catch(ArrayIndexOutOfBoundsException aie) {
System.out.println("Problem info: ArrayIndexOutOfBoundsException has
occured.");
}
}
catch(ArithmeticException ae) {
System.out.println("Problem info: Value of divisor can not be ZERO.");
}
catch(Exception e) {
System.out.println("Problem info: Unknown exception has occured.");
}
}
}
In case of nested try blocks, if an exception occured in the inner try block and it's catch blocks
are unable to handle it then it transfers the control to the outer try's catch block to handle it.
CHP-1
THROW,THROWS AND FINALLY
In java, the keywords throw, throws, and finally are used in the exception handling concept.
Let's look at each of these keywords.
The following is the general syntax for using throw keyword in a try block.
Syntax
throw instance;
Here the instace must be throwable instance and it can be created dynamically using new
operator.
Let's look at the following example Java code to illustrate throw keyword.
Example
import java.util.Scanner;
Let's look at the following example Java code to illustrate throws keyword.
Example
import java.util.Scanner;
try {
new ThrowsExample().division();
}
catch(ArithmeticException ae) {
System.out.println("Problem info: " + ae.getMessage());
}
System.out.println("End of the program");
}
}
Let's look at the following example Java code to illustrate throws keyword.
Example
import java.util.Scanner;
}
CHP-1
BUILT IN EXCEPTION
The Java programming language has several built-in exception class that support exception
handling. Every exception class is suitable to explain certain error situations at run time.
All the built-in exception classes in Java were defined a package java.lang.
Few built-in exceptions in Java are shown in the following image.
1 ClassNotFoundException
It is thrown when the Java Virtual Machine (JVM) tries to load a particular class and the specified class cannot be found in
the classpath.
2 CloneNotSupportedException
Used to indicate that the clone method in class Object has been called to clone an object, but that the object's class does
not implement the Cloneable interface.
3 IllegalAccessException
It is thrown when one attempts to access a method or member that visibility qualifiers do not allow.
4 InstantiationException
It is thrown when an application tries to create an instance of a class using the newInstance method in class Class , but
the specified class object cannot be instantiated because it is an interface or is an abstract class.
5 InterruptedException
It is thrown when a thread that is sleeping, waiting, or is occupied is interrupted.
6 NoSuchFieldException
It indicates that the class doesn't have a field of a specified name.
7 NoSuchMethodException
It is thrown when some JAR file has a different version at runtime that it had at compile time, a NoSuchMethodException
occurs during reflection when we try to access a method that does not exist.
S.
No. Exception Class with Description
1 ArithmeticException
2 ArrayIndexOutOfBoundsException
It handles the situations like an array has been accessed with an illegal index. The index is either negative or greater than
or equal to the size of the array.
3 ArrayStoreException
S.
No. Exception Class with Description
It handles the situations like when an attempt has been made to store the wrong type of object into an array of objects
4 AssertionError
It is used to indicate that an assertion has failed
5 ClassCastException
It handles the situation when we try to improperly cast a class from one type to another.
6 IllegalArgumentException
This exception is thrown in order to indicate that a method has been passed an illegal or inappropriate argument.
7 IllegalMonitorStateException
This indicates that the calling thread has attempted to wait on an object's monitor, or has attempted to notify other threads
that wait on an object's monitor, without owning the specified monitor.
8 IllegalStateException
It signals that a method has been invoked at an illegal or inappropriate time.
9 IllegalThreadStateException
It is thrown by the Java runtime environment, when the programmer is trying to modify the state of the thread when it is
illegal.
10 IndexOutOfBoundsException
It is thrown when attempting to access an invalid index within a collection, such as an array , vector , string , and so forth.
11 NegativeArraySizeException
It is thrown if an applet tries to create an array with negative size.
12 NullPointerException
it is thrown when program attempts to use an object reference that has the null value.
13 NumberFormatException
It is thrown when we try to convert a string into a numeric value such as float or integer, but the format of the input string is
not appropriate or illegal.
14 SecurityException
It is thrown by the Java Card Virtual Machine to indicate a security violation.
15 StringIndexOutOfBounds
It is thrown by the methods of the String class, in order to indicate that an index is either negative, or greater than the size
of the string itself.
16 UnsupportedOperationException
S.
No. Exception Class with Description
Example
import java.util.Scanner;
class VoterList{
int age;
VoterList(int age){
this.age = age;
}
void checkEligibility() {
try {
if(age < 18) {
throw new NotEligibleException("Error: Not eligible for vote due to under
age.");
}
System.out.println("Congrates! You are eligible for vote.");
catch(NotEligibleException nee) {
System.out.println(nee.getMessage());
}
}
public static void main(String args[]) {
Process-based multitasking
Thread-based multitasking
It allows the computer to run two or more programs concurrently It allows the computer to run two or more threads concurrently
In this process is the smallest unit. In this thread is the smallest unit.
Process requires seperate address space for each. Threads share same address space.
Process never gain access over idle time of CPU. Thread gain access over idle time of CPU.
New
When a thread object is created using new, then the thread is said to be in the New state. This
state is also known as Born state.
Example
Thread t1 = new Thread();
Runnable / Ready
When a thread calls start( ) method, then the thread is said to be in the Runnable state. This
state is also known as a Ready state.
Example
t1.start( );
Running
When a thread calls run( ) method, then the thread is said to be Running. The run( ) method of a
thread called automatically by the start( ) method.
Blocked / Waiting
A thread in the Running state may move into the blocked state due to various reasons like
sleep( ) method called, wait( ) method called, suspend( ) method called, and join( ) method
called, etc.
When a thread is in the blocked or waiting state, it may move to Runnable state due to reasons
like sleep time completed, waiting time completed, notify( ) or notifyAll( ) method called, resume(
) method called, etc.
Example
Thread.sleep(1000);
wait(1000);
wait();
suspened();
notify();
notifyAll();
resume();
Dead / Terminated
A thread in the Running state may move into the dead state due to either its execution
completed or the stop( ) method called. The dead state is also known as the terminated state.
CHP-2
CREATING THREADS
In java, a thread is a lightweight process. Every java program executes by a thread called the
main thread. When a java program gets executed, the main thread created automatically. All
other threads called from the main thread.
The java programming language provides two methods to create threads, and they are listed
below.
Step-1: Create a class as a child of Thread class. That means, create a class that
extends Thread class.
Step-2: Override the run( ) method with the code that is to be executed by the thread.
The run( ) method must be public while overriding.
Step-3: Create the object of the newly created class in the main( ) method.
Step-4: Call the start( ) method on the object created in the above step.
Example
class SampleThread extends Thread{
Example
class SampleThread implements Runnable{
start( ) It moves thre thread from Ready state to Running state by calling run( ) method. void
currentThread( ) Returns the reference of the thread that currently in running state. void
sleep( long ) moves the thread to blocked state till the specified number of milliseconds. void
yield( ) Tells to the scheduler that the current thread is willing to yield its current use of a processor. void
Thread( )
Thread( String threadName )
Thread( Runnable objectName )
Thread( Runnable objectName, String threadName )
🔔 The Thread class in java also contains methods like stop( ), destroy( ), suspend( ),
and resume( ). But they are depricated.
CHP-2
THREAD PRIORITIES
In a java programming language, every thread has a property called priority. Most of the
scheduling algorithms use the thread priority to schedule the execution sequence. In java, the
thread priority range from 1 to 10. Priority 1 is considered as the lowest priority, and priority 10 is
considered as the highest priority. The thread with more priority allocates the processor first.
The java programming language Thread class provides two methods setPriority(int),
and getPriority( ) to handle thread priorities.
The Thread class also contains three constants that are used to set the thread priority, and they
are listed below.
setPriority( ) method
The setPriority( ) method of Thread class used to set the priority of a thread. It takes an integer
range from 1 to 10 as an argument and returns nothing (void).
The regular use of the setPriority( ) method is as follows.
Example
threadObject.setPriority(4);
or
threadObject.setPriority(MAX_PRIORITY);
getPriority( ) method
The getPriority( ) method of Thread class used to access the priority of a thread. It does not
takes anyargument and returns name of the thread as String.
The regular use of the getPriority( ) method is as follows.
Example
String threadName = threadObject.getPriority();
Look at the following example program.
Example
class SampleThread extends Thread{
public void run() {
System.out.println("Inside SampleThread");
System.out.println("Current Thread: " +
Thread.currentThread().getName());
}
}
threadObject1.setPriority(4);
threadObject2.setPriority(Thread.MAX_PRIORITY);
threadObject1.start();
threadObject2.start();
}
}
In java, it is not guaranteed that threads execute according to their priority because it depends
on JVM specification that which scheduling it chooses.
CHP-2
THREAD SYNCRONIZATION
The java programming language supports multithreading. The problem of shared resources
occurs when two or more threads get execute at the same time. In such a situation, we need
some way to ensure that the shared resource will be accessed by only one thread at a time, and
this is performed by using the concept called synchronization.
🔔 The synchronization is the process of allowing only one thread to access a shared resource
at a time.
In java, the synchronization is achieved using the following concepts.
Mutual Exclusion
Inter thread communication
In this tutorial, we discuss mutual exclusion only, and the interthread communication will be
discussed in the next tutorial.
Mutual Exclusion
Using the mutual exclusion process, we keep threads from interfering with one another while
they accessing the shared resource. In java, mutual exclusion is achieved using the following
concepts.
Synchronized method
Synchronized block
Synchronized method
When a method created using a synchronized keyword, it allows only one object to access it at
a time. When an object calls a synchronized method, it put a lock on that method so that other
objects or thread that are trying to call the same method must wait, until the lock is released.
Once the lock is released on the shared resource, one of the threads among the waiting threads
will be allocated to the shared resource.
In the above image, initially the thread-1 is accessing the synchronized method and other
threads (thread-2, thread-3, and thread-4) are waiting for the resource (synchronized method).
When thread-1 completes it task, then one of the threads that are waiting is allocated with the
synchronized method, in the above it is thread-3.
Example
class Table{
synchronized void printTable(int n) {
for(int i = 1; i <= 10; i++)
System.out.println(n + " * " + i + " = " + i*n);
}
}
Synchronized block
The synchronized block is used when we want to synchronize only a specific sequence of lines
in a method. For example, let's consider a method with 20 lines of code where we want to
synchronize only a sequence of 5 lines code, we use the synchronized block.
The folllowing syntax is used to define a synchronized block.
Syntax
synchronized(object){
...
block code
...
}
Example
import java.util.*;
class NameList {
String name = "";
public int count = 0;
The complete code of a method may be written inside the synchronized block, where it works
similarly to the synchronized method.
CHP-2
INTER THREAD COMMUNICATION
Inter thread communication is the concept where two or more threads communicate to
solve the problem of polling. In java, polling is the situation to check some condition
repeatedly, to take appropriate action, once the condition is true. That means, in inter-
thread communication, a thread waits until a condition becomes true such that other
threads can execute its task. The inter-thread communication allows the synchronized
threads to communicate with each other.
Java provides the following methods to achieve inter thread communication.
wait( )
notify( )
notifyAll( )
The following table gives detailed description about the above methods.
Method Description
void wait( ) It makes the current thread to pause its execution until other thread in the
void notify( ) It wakes up the thread that called wait( ) on the same object.
void notifyAll() It wakes up all the threads that called wait( ) on the same object.
Example
class ItemQueue {
int item;
boolean valueSet = false;
{
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Consummed:" + item);
valueSet = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
notify();
return item;
}
ItemQueue itemQueue;
Consumer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
}
public void run() {
while(true) {
itemQueue.getItem();
}
}
}
class ProducerConsumer{
public static void main(String args[]) {
ItemQueue itemQueue = new ItemQueue();
new Producer(itemQueue);
new Consumer(itemQueue);
}
}
All the methods wait( ), notify( ), and notifyAll( ) can be used only inside the synchronized
methods only.
FILL IN THE BLANKS:
LONG QUESTIONS:
1. Explain in detail about Exceptions.
2. Explain in detail about Multithreading.
3. Explain in detail about how exceptions are handled.
4. Write about built-in exceptions in detail.
5. Explain about the models of exception and the types of
exceptions.
6. Write about the statements which are used to handle an
exception.
7. Explain about nested try statement and multi catch
statement.
8. Explain in detail about synchronization in thread .
9. What is Inter thread communication.Explain in detail
about it.
10. What is thread?Explain in detail about thread model
and how to create a threads.
1. COLLECTION FRAMEWORK
Java collection framework is a collection of interfaces and classes used to
storing and processing a group of individual objects as a single unit. The java
collection framework holds several classes that provide a large number of
methods to store and process a group of objects. These classes make the
programmer task super easy and fast.
Java collection framework was introduced in java 1.2 version.
Java collection framework has the following heirarchy.
Before the collection framework in java (before java 1.2 version), there was a
set of classes like Array, Vector, Stack, HashTable. These classes are
known as legacy classes.
The java collection framework contains List, Queue, Set, and Map as top-level
interfaces. The List, Queue, and Set stores single value as its element,
whereas Map stores a pair of a key and value as its element.
2.COLLECTION INTERFACE
The Collection interface is the root interface for most of the interfaces and
classes of collection framework. The Collection interface is available inside
the java.util package. It defines the methods that are commonly used by
almost all the collections.
The Collection interface defines the following methods.
Example
import java.util.*;
public class CollectionInterfaceExample {
list_1.add(10);
list_1.add(20);
list_2.add("HELLO");
list_2.add("EVERYONE");
list_2.add("WELCOME ");
list_1.addAll(list_2);
System.out.println("Elements of list_1: " + list_1);
list_1.remove(0);
System.out.println(list_1);
list_1.retainAll(list_2);
System.out.println(list_1);
list_1.removeAll(list_2);
System.out.println(list_1);
list_2.clear();
System.out.println(list_2);
}
}
3.ARRAYLIST
The ArrayList class is a part of java collection framework. It is available inside
the java.util package. The ArrayList class extends AbstractList class and
implements List interface.
The elements of ArrayList are organized as an array internally. The default
size of an ArrayList is 10.
The ArrayList class is used to create a dynamic array that can grow or shrunk
as needed.
🔔 The ArrayList is a child class of AbstractList
🔔 The ArrayList implements interfaces like List, Serializable, Cloneable,
and RandomAccess.
🔔 The ArrayList allows to store duplicate data values.
🔔 The ArrayList allows to access elements randomly using index-based
accessing.
🔔 The ArrayList maintains the order of insertion.
Example
public class ArrayList<E> extends AbstractList<E> implements List<E>,
RandomAccess, Cloneable, Serializable
Adding Items
The ArrayList class has the following methods to add items.
Example
import java.util.*;
public class ArrayListExample {
//Appending
list_1.add("HELLO");
System.out.println("list_1: " + list_1);
list_1.add("WORLD");
System.out.println("list_1: " + list_1);
//Inserting at specified index
list_1.add(1, "HIII");
System.out.println("list_1: " + list_1);
Accessing Items
The ArrayList class has the following methods to access items.
Example
import java.util.*;
public static void main(String[] args) {
list_1.add("HELLO");
list_1.add("EVERY");
list_1.add("ONE");
list_1.add("WELCOME");
list_1.add("TO");
list_1.add("CS/IOT");
list_1.add("DEPARTMENT");
}
}
Updating Items
The ArrayList class has the following methods to update or change items.
Example
import java.util.*;
public class ArrayListExample {
list_1.add("HELLO");
list_1.add("EVERY");
list_1.add("ONE");
list_1.add("WELCOME");
list_1.add("TO");
list_1.add("CS/IOT");
list_1.add("DEPARTMENT");
list_1.set(3, ":");
System.out.println("\nList after update: " + list_1);
Removing Items
The ArrayList class has the following methods to remove items.
Example
import java.util.*;
public class ArrayListExample {
list_1.add("HELLO");
list_1.add("ONE");
list_1.add("WELCOME");
list_1.add("TO");
list_1.add("CS/IOT");
list_1.add("DEPARTMENT");
list_1.add("on");
list_1.add("Collection");
list_1.add("framwork");
list_1.add("-");
list_1.add("ArrayList");
list_2.add("HELLO");
list_2.add("WORLD");
list_3.add("JAVA");
list_3.add("PROGRAMMING");
list_3.add("LANGUAGE");
list_1.remove(3);
System.out.println("\nList after removing element from index
3:\n" + list_1);
list_1.remove("WORLD");
System.out.println("\nList after removing \'Tutorial\' element:\
n" + list_1);
list_1.removeAll(list_2);
System.out.println("\nList after removing all elements of list_2
from list_1:\n" + list_1);
list_1.retainAll(list_3);
System.out.println("\nList after removing all elements from
list_1 except elements of list_3:\n" + list_1);
list_1.clear();
System.out.println("\nList after removing all elements from
list_1:\n" + list_1);
}
}
Example
import java.util.*;
public class ArrayListExample {
anotherList = list.clone();
System.out.println("\n\nClonned object elements:\n" +
anotherList);
list.trimToSize();
}
}
Consolidated list of methods
The following table providess a consolidated view of all methods of ArrayList.
Method Description
void add(int index, E element) Inserts the given element at specified index.
boolean addAll(int index, Collection c) Inserts the given collection of elements at specifi
ArrayList subList(int startIndex, int lastIndex) Returns an ArrayList that contails elements from
ArrayList.
int indexOf(E element) Returns the index value of given element first occ
in the ArrayList.
int lastIndexOf(E element) Returns the index value of given element last occ
in the ArrayList.
invoking ArrayList.
boolean remove(Object element) Removes the first occurence of the given elemen
invoking ArrayList.
boolean removeIf(Predicate filter) Removes all the elements from the ArrayList that
ArrayList.
boolean contains(Object element) Returns true if the list contains given element oth
returns false.
comparator.
List[ ] subList(int startIndex, int endIndex) Returns list of elements starting from startIndex t
endIndex-1.
of elements it contains.
4.LINKED LIST
The LinkedList class is a part of java collection framework. It is available
inside the java.util package. The LinkedList class
extends AbstractSequentialList class and implements List and Deque interface.
The elements of LinkedList are organized as the elements of linked list data
structure.
The LinkedList class is used to create a dynamic list of elements that can
grow or shrunk as needed.
🔔 The LinkedList is a child class of AbstractSequentialList
🔔 The LinkedList implements interfaces like List, Deque, Cloneable,
and Serializable.
🔔 The LinkedList allows to store duplicate data values.
🔔 The LinkedList maintains the order of insertion.
Example
public class LinkedList<E> extends AbstractSequentialList<E> implements
List<E>, Deque<E>, Cloneable, Serializable
Operations on LinkedList
The LinkedList class allow us to perform several operations like adding,
accesing, deleting, updating, looping, etc. Let's look at each operation with
examples.
Adding Items
The LinkedList class has the following methods to add items.
Example
import java.util.*;
list_1.addAll(list_2);
Accessing Items
The LinkedList class has the following methods to access items.
Example
import java.util.*;
Updating Items
The LinkedList class has the following methods to update or change items.
Example
import java.util.*;
Removing Items
The LinkedList class has the following methods to remove items.
Example
import java.util.*;
list_1.remove();
System.out.println("\nList after remove()\n" + list_1);
list_1.remove(3);
System.out.println("\nList after remove(index)\n" + list_1);
list_1.removeFirst();
System.out.println("\nList after removeFirst()\n" + list_1);
list_1.removeLast();
System.out.println("\nList after removeLast()\n" + list_1);
System.out.println("\nList after removeFirstOccurrence()\n" +
list_1);
list_1.removeLastOccurrence(7);
System.out.println("\nList after removeLastOccurrence()\n" +
list_1);
list_1.pop();
System.out.println("\nList after pop()\n" + list_1);
list_1.clear();
System.out.println("\nList after clear()\n" + list_1);
}
}
Example
import java.util.*;
to the List.
void add(int index, E element) Inserts the given element at specified index.
specified index.
the list.
void addLast(E element) Inserts the given element at end of the list.
boolean offer(E element) Inserts the given element at end of the list.
of the list.
boolean offerLast(E element) Inserts the given element at end of the list.
invoking list.
list.
LinkedList.
LinkedList.
invoking LinkedList.
returns false.
Method Description
List[ ] subList(int startIndex, int endIndex) Returns list of elements starting from
startIndex to endIndex-1.
invoking LinkedList.
list.
Example
public class HashSet<E> extends AbstractSet<E> implements Set<E>,
Cloneable, Serializable
Operations on HashSet
The HashSet class allow us to perform several operations like adding,
accesing, deleting, updating, looping, etc. Let's look at each operation with
examples.
Adding Items
The HashSet class has the following methods to add items.
Example
import java.util.*;
set.add(10);
set.add(20);
set.add(30);
set.add(50);
anotherSet.addAll(set);
Accessing Items
The HashSet class has no methods to access items, we can access whole set
using its name.
Updating Items
The HashSet class has no methods to update or change items.
Removing Items
The HashSet class has the following methods to remove items.
Example
import java.util.*;
set.add(10);
set.add(20);
set.add(30);
set.add(40);
set.add(50);
anotherSet.addAll(set);
set.remove(20);
anotherSet.removeAll(set);
System.out.println("\nanotherSet after removeAll(set) is\n" +
anotherSet);
set.retainAll(anotherSet);
System.out.println("\nset after retainAll(anotherSet) is\n" +
set);
anotherSet.clear();
System.out.println("\nanotherSet after clear() is\n" +
anotherSet);
Example
import java.util.*;
set.add(10);
set.add(20);
set.add(30);
set.add(40);
set.add(50);
Method Description
boolean remove(Object Removes the first occurence of the given element from th
element)
boolean removeAll(Collection Removes all the elements those are in the specified colle
c) HashSet.
boolean removeIf(Predicate Removes all of the elements of the HashSet collection tha
p)
boolean retainAll(Collection c) Removes all the elements except those are in the specifie
invoking HashSet.
Method Description
int size( ) Returns the total number of elements in the invoking Has
boolean isEmpty( ) Returns true if the HashSet is empty otherwise returns fal
boolean equals( ) Compares the specified object with invoking HashSet coll
boolean contains(Object Returns true if the HashSet contains given element otherw
element)
Object[ ] toArray( ) Returns an array of Object instances that contains all the
HashSet.
Iterator iterator( ) Returns an iterator over the elements in the HashSet. The
elements in any particular order.
6.TREE SET
The TreeSet class is a part of java collection framework. It is available inside
the java.util package. The TreeSet class extends AbstractSet class and
implements NavigableSet, Cloneable, and Serializable interfaces.
The elements of TreeSet are organized using a mechanism called tree. The
TreeSet class internally uses a TreeMap to store elements. The elements in a
TreeSet are sorted according to their natural ordering.
🔔 The TreeSet is a child class of AbstractSet
🔔 The TreeSet implements interfaces like NavigableSet, Cloneable,
and Serializable.
🔔 The TreeSet does not allows to store duplicate data values, but null values
are allowed.
🔔 The elements in a TreeSet are sorted according to their natural ordering.
🔔 The TreeSet initial capacity is 16 elements.
🔔 The TreeSet is best suitable for search operations.
Examplesorting order
public class TreeSet<E> extends AbstractSet<E> implements
NavigableSet<E>, Cloneable, Serializable
Operations on TreeSet
The TreeSet class allow us to perform several operations like adding,
accesing, deleting, updating, looping, etc. Let's look at each operation with
examples.
Adding Items
The TreeSet class has the following methods to add items.
Example
import java.util.*;
set.add(10);
set.add(20);
set.add(15);
set.add(5);
anotherSet.addAll(set);
Accessing Items
The TreeSet class has provides the following methods to access items.
Example
import java.util.*;
System.out.println("\nheadSet(20)\n" + set.headSet(20));
System.out.println("\nheadSet(20, false)\n" +
set.headSet(20, false));
System.out.println("\ntailSet(20)\n" + set.tailSet(20));
Updating Items
The TreeSet class has no methods to update or change items.
Removing Items
The TreeSet class has the following methods to remove items.
Example
import java.util.*;
set.remove(50);
System.out.println("\nset after remove(50) is\n" + set);
set.removeIf(n->n.equals(60));
System.out.println("\nset after removeIf(n->n.equals(60)) is\n"
+ set);
set.pollFirst();
System.out.println("\nset after pollFirst( ) is\n" + set);
set.pollLast();
System.out.println("\nset after pollLast( ) is\n" + set);
set.removeAll(anotherSet);
System.out.println("\nset after removeAll(anotherSet) is\n" +
set);
set.retainAll(anotherSet);
System.out.println("\nset after retainAll(anotherSet) is\n" +
set);
}
}
Other utility methods
The TreeSet class has the following methods to work with elements of it.
int size( ) - Returns the total number of elements in the invoking TreeSet.
boolean isEmpty( ) - Returns true if the TreeSet is empty otherwise
returns false.
TreeSet clone( ) - Returns a copy of the invoking TreeSet.
boolean contains(Object element) - Returns true if the TreeSet contains
given element otherwise returns false.
boolean containsAll(Collection c) - Returns true if the TreeSet contains
given collection of elements otherwise returns false.
boolean equals(Object o) - Compares the specified object with invoking
TreeSet collection for equality.
int hashCode( ) - Returns the hash code of the invoking TreeSet.
Object clone( ) - Returns a shallow copy of invoking TreeSet instance.
Spliterator spliterator( ) - Creates spliterator over the elements in a
TreeSet.
Iterator iterator( ) - Returns an iterator over the elements in the TreeSet.
The iterator does not return the elements in any particular order.
Example
import java.util.*;
}
}
to the TreeSet.
SortedSet subSet(E fromElement, E toElement) Returns a set of elements that lie between
NavigableSet subSet(E fromElement, boolean Returns a set of elements that lie between
fromInclusive, E toElement, boolean toInclusive)
the given range from the invoking TreeSet.
NavigableSet tailSet(E fromElement, boolean inclusive) Returns a set of elements that are greater
NavigableSet headSet(E fromElement, boolean Returns a set of elements that are smaller
inclusive)
than or equal to (if, inclusive is true) the
Method Description
TreeSet.
TreeSet.
predicate.
invoking TreeSet.
returns false.
invoking TreeSet.
TreeSet.
Method Description
particular order.
PRIORITY QUEUE
The PriorityQueue class is a part of java collection framework. It is available
inside the java.util package. The PriorityQueue class
extends AbstractQueue class and implements Serializable interface.
The elements of PriorityQueue are organized as the elements of queue data
structure, but it does not follow FIFO principle. The PriorityQueue elements
are organized based on the priority heap.
The PriorityQueue class is used to create a dynamic queue of elements that
can grow or shrunk as needed.
🔔 The PriorityQueue is a child class of AbstractQueue
🔔 The PriorityQueue implements interface Serializable.
🔔 The PriorityQueue allows to store duplicate data values, but not null values.
🔔 The PriorityQueue maintains the order of insertion.
🔔 The PriorityQueue used priority heap to organize its elements.
Example
public class PriorityQueue<E> extends AbstractQueue<E> implements
Serializable
Operations on PriorityQueue
The PriorityQueue class allow us to perform several operations like adding,
accesing, deleting, updating, looping, etc. Let's look at each operation with
examples.
Adding Items
The PriorityQueue class has the following methods to add items.
Example
import java.util.*;
anotherQueue.addAll(queue);
anotherQueue.offer(25);
Accessing Items
The PriorityQueue class has the following methods to access items.
Example
import java.util.*;
queue.add(10);
queue.add(20);
queue.add(15);
Updating Items
The PriorityQueue class has no methods to update or change items.
Removing Items
The PriorityQueue class has the following methods to remove items.
E remove( ) - Removes the first element from the invoking PriorityQueue.
boolean remove(Object element) - Removes the first occurrence of the
given element from the invoking PriorityQueue.
boolean removeAll(Collection c) - Removes all the elements of specified
collection from the invoking PriorityQueue.
boolean removeIf(Predicate p) - Removes all of the elements of this
collection that satisfy the given predicate.
boolean retainAll(Collection c) - Removes all the elements except those
are in the specified collection from the invoking PriorityQueue.
E poll( ) - Removes the first element from the PriorityQueue, and returns
null if the list is empty.
void clear( ) - Removes all the elements from the PriorityQueue.
Example
import java.util.*;
queue.remove(8);
System.out.println("\nQueue after remove(8) is\n" + queue);
queue.poll();
System.out.println("\nQueue after poll() is\n" + queue);
queue.removeIf(n->n.equals(6));
System.out.println("\nQueue after removeIf(n->n.equals(6) is\
n" + queue);
queue.retainAll(anotherQueue);
System.out.println("\nQueue after retainAll(anotherQueue) is\
n" + queue);
queue.removeAll(anotherQueue);
System.out.println("\nQueue after removeAll(anotherQueue)
is\n" + queue);
queue.clear();
System.out.println("\nQueue after clear() is\n" + queue);
}
}
Example
import java.util.*;
Method Description
PriorityQueue.
boolean offer(E element) Inserts the given element at end of the PriorityQueue.
PriorityQueue.
boolean remove(Object element) Removes the first occurence of the given element
invoking PriorityQueue.
boolean retainAll(Collection c) Removes all the elements except those are in the
PriorityQueue.
returns false.
all
PriorityQueue.
of elements it contains.
ARRAY DEQUE
The ArrayDeque class is a part of java collection framework. It is available
inside the java.util package. The ArrayDeque class
extends AbstractCollection class and implements Deque, Cloneable,
and Serializable interfaces.
The elements of ArrayDeque are organized as the elements of double ended
queue data structure. The ArrayDeque is a special kind of array that grows
and allows users to add or remove an element from both the sides of the
queue.
The ArrayDeque class is used to create a dynamic double ended queue of
elements that can grow or shrunk as needed.
🔔 The ArrayDeque is a child class of AbstractCollection
🔔 The ArrayDeque implements interfaces like Deque, Cloneable,
and Serializable.
🔔 The ArrayDeque allows to store duplicate data values, but not null values.
🔔 The ArrayDeque maintains the order of insertion.
🔔 The ArrayDeque allows to add and remove elements at both the ends.
🔔 The ArrayDeque is faster than LinkedList and Stack.
Example
public class ArrayDeque<E> extends AbstractCollection<E> implements
Deque<E>, Cloneable, Serializable
Operations on ArrayDeque
The ArrayDeque class allow us to perform several operations like adding,
accesing, deleting, updating, looping, etc. Let's look at each operation with
examples.
Adding Items
The ArrayDeque class has the following methods to add items.
Example
import java.util.*;
deque.add(10);
deque.addFirst(5);
deque.addLast(15);
deque.offer(20);
deque.offerFirst(10);
deque.offerLast(30);
anotherDeque.addAll(deque);
System.out.println("\nanotherDeque is\n" +
anotherDeque);
anotherDeque.push(40);
Accessing Items
The ArrayDeque class has the following methods to access items.
Example
import java.util.*;
Updating Items
The ArrayDeque class has no methods to update or change items.
Removing Items
The ArrayDeque class has the following methods to remove items.
Example
import java.util.*;
deque.remove();
System.out.println("\nDeque after remove()\n" + deque);
deque.removeFirst();
System.out.println("\nDeque after removeFirst()\n" +
deque);
System.out.println("\nDeque after removeLast()\n" +
deque);
deque.remove(5);
System.out.println("\nDeque after remove(5)\n" + deque);
deque.poll();
System.out.println("\nDeque after poll()\n" + deque);
deque.pollFirst();
System.out.println("\nDeque after pollFirst()\n" + deque);
deque.pollLast();
System.out.println("\nDeque after pollLast()\n" + deque);
deque.pop();
System.out.println("\nDeque after pop()\n" + deque);
deque.clear();
System.out.println("\nDeque after clear()\n" + deque);
}
}
Example
import java.util.*;
Method Description
ArrayDeque.
ArrayDeque.
Method Description
ArrayDeque.
ArrayDeque.
ArrayDeque.
ArrayDeque.
ArrayDeque.
ArrayDeque.
ArrayDeque.
ArrayDeque.
empty.
ArrayDeque.
ArrayDeque.
ArrayDeque.
predicate.
ArrayDeque.
ArrayDeque is empty.
ArrayDeque is empty.
ArrayDeque is empty.
ArrayDeque.
ArrayDeque.
invoking ArrayDeque.
false.
ArrayDeque.
ArrayDeque.
ArrayDeque.
Method Description
boolean hasNext( ) Returns true if the collection has the next element, otherwise, it returns
false.
Example
import java.util.*;
}
}
Example
import java.util.*;
}
}
Example
import java.util.*;
}
}
Method Description
boolean hasNext( ) Returns true if the list collection has next element, otherwise it returns
false.
boolean hasPrevious( ) Returns true if the list collection has previous element, otherwise it returns
false.
int nextIndex( ) Returns the index of the next element. If there is no next element, returns
Method Description
E previousIndex( ) Returns the index of the previous element. If there is no previous element
Example
import java.util.*;
}
}
MAP INTERFACE
The java collection framework has an interface Map that is available inside
the java.util package. The Map interface is not a subtype of Collection
interface.
🔔 The Map stores the elements as a pair of key and value.
🔔 The Map does not allows duplicate keys, but allows duplicate values.
🔔 In a Map, each key can map to at most one value only.
🔔 In a Map, the order of elements depends on specific implementations, e.g
TreeMap and LinkedHashMap have predictable order, while HashMap does
not.
Interface Description
Map.Entry Describe an element in key and value pair in a map. Entry is sub
interface of Map.
HashMap It implements the Map interface, but it doesn't maintain any order.
ascending order.
Method Description
void putAll(Map map) Inserts the specified map into the invok
V putIfAbsent(K key, V value) Inserts the specified value with the spe
invoking Map.
of invoking Map.
key.
the key.
specified key.
boolean replace(K key, V oldValue, V Used to replaces the oldValue with the
newValue)
newValue for a specified key.
throws an exception.
V merge(K key, V value, BiFunction If the specified key is not already assoc
remappingFunction)
with a value or is associated with null,
V computeIfAbsent(K key, Function Used to compute its value using the giv
mappingFunction)
mapping function, if the specified key is
boolean remove(Object key, Object value) Removes the specified values with the
Map.
Class Description
HashMap It implements the Map interface, but it doesn't maintain any order.
LinkedHashMap It implements the Map interface, it also extends HashMap class. It maintains
TreeMap It implements the Map and SortedMap interfaces. It maintains the ascending
order.
Method Description
Set keySet() It returns a set that contains all the keys from the
invoking Map.
Set valueSet() It returns a set that contains all the values from the
invoking Map.
Set entrySet() It returns a set that contains all the entries from the
invoking Map.
HashMap Class
The HashMap class is a child class of AbstractMap, and it implements the
Map interface. The HashMap is used to store the data in the form of key,
value pair using hash table concept.
Example
import java.util.*;
employeeInfo.put(1, "Raja");
employeeInfo.put(2, "Gouthami");
employeeInfo.put(3, "Heyansh");
employeeInfo.put(4, "Yamini");
employeeInfo.put(5, "ManuTej");
System.out.println("Employee Information\n" +
employeeInfo);
LinkedHashMap Class
The LinkedHashMap class is a child class of HashMap, and it implements the
Map interface. The LinkedHashMap is used to store the data in the form of
key, value pair using hash table and linked list concepts.
Example
import java.util.*;
employeeInfo.put(1, "Raja");
employeeInfo.put(2, "Gouthami");
employeeInfo.put(3, "Heyansh");
employeeInfo.put(5, "ManuTej");
System.out.println("Employee Information\n" +
employeeInfo);
}
TreeMap Class
The TreeMap class is a child class of AbstractMap, and it implements the
NavigableMap interface which is a child interface of SortedMap. The TreeMap
is used to store the data in the form of key, value pair using a red-black tree
concepts.
Example
import java.util.*;
employeeInfo.put(1, "Raja");
employeeInfo.put(4, "Gouthami");
employeeInfo.put(5, "Heyansh");
employeeInfo.put(3, "Yamini");
employeeInfo.put(2, "ManuTej");
System.out.println("Employee Information\n" +
employeeInfo);
}
12.COMPARATORS
The Comparator is an interface available in the java.util package. The
java Comparator is used to order the objects of user-defined classes. The
java Comparator can compare two objects from two different classes.
Using the java Comparator, we can sort the elements based on data members
of a class. For example, we can sort based on roolNo, age, salary, marks, etc.
The Comparator interface has the following methods.
Method Description
int compare(Object obj1, Object obj2) It is used to compares the obj1 with o bj2 .
Example
import java.util.*;
class Student{
String name;
float percentage;
Collections.sort(studList, com);
Example
import java.util.*;
class Student{
String name;
float percentage;
Collections.sort(studList, com);
Example
import java.util.*;
class Student{
String name;
float percentage;
Collections.sort(studList, com);
Method Description
void sort(List list) Sorts the elements of the list as determined by thei
natural ordering.
void sort(List list, Comparator comp) Sorts the elements of the list as determined by
Comparator comp.
void rotate(List list, int n) Rotates list by n places to the right. To rotate left,
void shuffle(List list, Random r) Shuffles the elements in the list by using r as a
void copy(List list1, List list2) Copies the elements of list2 to list1.
List nCopies(int num, Object obj) Returns num copies of obj contained in an
void swap(List list, int idx1, int idx2) Exchanges the elements in the list at the indices
int binarySearch(List list, Object value) Returns the position of value in the list (must be in
int binarySearch(List list, Object value, Returns the position of value in the list ordered
Comparator c)
according to c, or -1 if value is not found.
int indexOfSubList(List list, List subList) Returns the index of the first match of subList in
int lastIndexOfSubList(List list, List subList) Returns the index of the last match of subList in
Object max(Collection c, Comparator comp) Returns the largest element from the collection c
Object min(Collection c, Comparator comp) Returns the smallest element from the collection c
by Comparator comp.
void fill(List list, Object obj) Assigns obj to each element of the list.
boolean replaceAll(List list, Object old, Object Replaces all occurrences of old with new in the list
new)
Collections.sort(list);
System.out.println("List in ascending order => " + list);
Collections.reverse(list);
System.out.println("List in reverse order => " + list);
Collections.shuffle(list);
System.out.println("List after shuffle => " + list);
}
}
14.ARRAYS
The java collection framework has a class Arrays that provides methods for creating
dynamic array and perform various operations like search, asList, campare, etc.
The Arrays class in java is defined in the java.util package. All the methods defined by
Arrays class are static methods.
The Arrays class in java has the following methods.
Method Description
int binarySearch(T[] arr, int fromIndex, int It searches a range of the specified
toIndex, T key, Comparator c)
array for the specified
algorithm.
specified length.
T[] copyOfRange(T[] originalArr, int fromIndex, It copies the specified range of the
int endIndex)
specified array into a
new Arrays.
boolean equals(T[] arr1, T[] arr2) It returns true if the two specified
retruns false.
boolean deepEquals(T[] arr1, T[] arr2) It returns true if the two specified
specified array.
nested arrays.
specified array.
arrays.
element of the
specified array.
void fill(T[] arr, int fromIndex, int toIndex, T It assigns the specified value to each
value)
element of the
The range to
inclusive, to
toIndex, exclusive.
Method Description
function.
compute each
element.
array, in
function
ascending order.
into
Method Description
Example
import java.util.*;
Arrays.fill(arr1, 15);
System.out.print("fill Array1 with 15 => ");
for(int i:arr1)
System.out.print(i + ", ");
Arrays.sort(arr2);
System.out.print("\nArray2 in sorted order => ");
for(int i:arr2)
System.out.print(i + ", ");
}
}
1 Dictionary( )
It's a constructor.
Inserts a key and its value into the dictionary. Returns null on
success; returns the previous value associated with the key
if the key is already exist.
S. No. Methods with Description
5 Enumeration keys( )
Returns an enumeration of the keys contained in the
dictionary.
6 Enumeration elements( )
Returns an enumeration of the values contained in the
dictionary.
7 boolean isEmpty( )
It returns true if dictionary has no elements; otherwise
returns false.
8 int size( )
S. No. Methods with Description
Example
import java.util.*;
dict.put(1, "Rama");
dict.put(2, "Seetha");
dict.put(3, "Heyansh");
dict.put(4, "Varshith");
dict.put(5, "Manutej");
// keys()
System.out.print("\nKeys in Dictionary\n=> ");
for (Enumeration i = dict.keys();
i.hasMoreElements();)
{
System.out.print(" " + i.nextElement());
}
// elements()
System.out.print("\n\nValues in Dictionary\n=> ");
for (Enumeration i = dict.elements();
i.hasMoreElements();)
{
System.out.print(" " + i.nextElement());
}
//get()
System.out.println("\n\nValue associated with
key 3 => " + dict.get(3));
System.out.println("Value associated with key 30
=> " + dict.get(30));
//size()
System.out.println("\nDictionary has " +
dict.size() + " elements");
System.out.println("\nIs Dictionary empty? " +
dict.isEmpty());
}
}
1 Hashtable( )
2 Hashtable(int capacity)
It creates an empty hashtable with the specified
initial capacity.
4 Hashtable(Map m)
It creates a hashtable containing elements
of Map m.
It inserts the specified key and value into the hash table
5 V get(Object key)
S. No. Methods with Description
6 Enumeration keys()
Returns an enumeration of the keys of the hashtable.
7 Set keySet()
Returns a set view of the keys of the hashtable.
8 Collection values()
It returns a collection view of the values contained in th
Hashtable.
9 Enumeration elements()
Returns an enumeration of the values of the hashtable.
10 Set entrySet()
It returns a set view of the mappings contained in the
hashtable.
11 int hashCode()
S. No. Methods with Description
12 Object clone()
It returns a shallow copy of the Hashtable.
13 V remove(Object key)
It returns the value associated with given key and remo
the same.
21 void rehash()
S. No. Methods with Description
22 String toString()
It returns a string representation of the Hashtable objec
25 boolean isEmpty( )
It returns true if Hashtable has no elements; otherwise
S. No. Methods with Description
26 int size( )
It returns the total number of elements in the Hashtable
27 void clear()
It is used to remove all the lements of a Hashtable.
28 boolean equals(Object o)
It is used to compare the specified Object with the
Hashtable.
Example
import java.util.*;
//put(key, value)
for(int i = 1; i <= 5; i++)
table.put(i, num.nextInt(100));
//get(key)
System.out.println("\nValue associated
with key 3 => " + table.get(3));
System.out.println("Value associated with
key 30 => " + table.get(30));
//keySet()
System.out.println("\nKeys => " +
table.keySet());
//values()
System.out.println("\nValues => " +
table.values());
//entrySet()
System.out.println("\nKey, Value pairs as
a set => " + table.entrySet());
//hashCode()
System.out.println("\nHash code => " +
table.hashCode());
//hashCode()
System.out.println("\nTotal number of
elements => " + table.size());
//isEmpty()
System.out.println("\nEmpty status of
Hashtable => " + table.isEmpty());
}
}
1 Properties( )
2 Properties(Properties defaults)
It creates an empty property list with the specified defaults.
1 void load(Reader r)
8 Enumeration propertyNames())
It returns an enumeration of all the keys from the property list.
9 Set stringPropertyNames()
Returns a set view of the keys of the Properties.
Example
import java.io.*;
import java.util.*;
configProperties.setProperty("userName",
"btechsmartclass");
configProperties.setProperty("password", "java");
configProperties.setProperty("email",
"user@btechsmartclass.com");
configProperties.store(fos, "Login
Details");
fos.close();
System.out.println("Configuration
saved!!!");
}
catch(Exception e) {
System.out.println("Something went wrong
while opening file");
}
}
Example
import java.util.*;
public class PropertiesClassExample {
sites.put("search", "www.google.com");
sites.put("learn", "www.btechsmartclass.com");
sites.put("mail", "www.gmail.com");
sites.put("social", "www.facebook.com");
sites.put("watch", "www.youtube.com");
1 Stack( )
It pushes the element onto the stack and returns the same.
2 Object pop( )
It returns the element on the top of the stack and removes
S.No. Methods with Description
the same.
4 Object peek( )
It returns the element on the top of the stack.
5 boolean empty()
It returns true if the stack is empty, otherwise returns false.
Example
import java.util.*;
1 Vector( )
2 Vector(int initialSize)
It creates an empty Vector with specified initail capacity.
4 Vector(Collection c)
It creates a vector that contains the elements of collection c.
1 boolean add(Object o)
4 boolean addAll(Collection c)
S.No. Methods with Description
It appends all of the elements in the specified Collection to the end of the Vector.
9 boolean remove(Object o)
It removes the first occurrence of the specified element in the vector.
13 boolean removeAll(Collection c)
It removes from the vector all of its elements that are contained in the specified Collection.
14 void removeAllElements()
It removes all the elements from the vector.
15 boolean retainAll(Collection c)
It removes all the elements from the vector except elements those are in the given collection.
18 Enumeration elements()
S.No. Methods with Description
19 Object firstElement()
It returns the first element of the Vector.
20 Object lastElement()
It returns the last element of the Vector.
25 int capacity()
It returns the current capacity of the Vector.
26 void clear()
It removes all the elements from the Vector.
27 Object clone()
It returns a clone of the Vector.
29 boolean containsAll(Collection c)
It returns true if all the elements of geven collection found in the Vector, otherwise returns false.
31 boolean equals(Object o)
S.No. Methods with Description
32 int hashCode()
It returns the hash code of the Vector.
33 boolean isEmpty()
It returns true if Vector has no elements, otherwise returns false.
35 int size()
It returns total number of elements in the vector.
36 Object[] toArray()
It returns an array containing all the elements of the Vector.
37 String toString()
It returns a string representation of the Vector.
38 void trimToSize()
It trims the capacity of the vector to be the vector's current size.
Example
import java.util.*;
list.add(10);
list.add(30);
list.add(0, 100);
System.out.println("Vector => " + list);
1 StringTokenizer(String str)
It creates StringTokenizer object for the specified string str with default delimeter.
1 String nextToken()
3 Object nextElement()
It returns the next token from the StringTokenizer object.
4 boolean hasMoreTokens()
It returns true if there are more tokens in the StringTokenizer object. otherwise returns false.
5 boolean hasMoreElements()
It returns true if there are more tokens in the StringTokenizer object. otherwise returns false.
6 int countTokens()
It returns total number of tokens in the StringTokenizer object.
}
21. BIT SET CLASS
The BitSet is a built-in class in java used to create a dynamic array of bits represented by
boolean values. The BitSet class is available inside the java.util package.
The BitSet array can increase in size as needed. This feature makes the BitSet similar to a
Vector of bits.
🔔 The bit values can be accessed by non-negative integers as an index.
🔔 The size of the array is flexible and can grow to accommodate additional bit as needed.
🔔 The default value of the BitSet is boolean false with a representation as 0 (off).
🔔 BitSet uses 1 bit of memory per each boolean value.
The BitSet class in java has the following constructor.
1 BitSet( )
2 BitSet(int noOfBits)
It creates a BitSet object with number of bits that it can hold. All bits are initialized to zero.
It performs AND operation on the contents of the invoking BitSet object with those specified by bitSet.
7 int cardinality( )
It returns the number of bits set to true in the invoking BitSet.
8 void clear( )
It sets all the bits to zeros of the invoking BitSet.
11 Object clone( )
It duplicates the invoking BitSet object.
15 int hashCode( )
It returns the hash code of the invoking BitSet.
17 boolean isEmpty( )
It returns true if all bits in the invoking object are zero, otherwise returns false.
17 int length( )
It returns the total number of bits in the invoking BitSet.
24 int size( )
It returns the total number of bits in the invoking BitSet.
25 String toString( )
It returns the string equivalent of the invoking BitSet object.
Example
import java.util.*;
bSet_1.set(10);
bSet_1.set(5);
bSet_1.set(0);
bSet_1.set(7);
bSet_1.set(20);
bSet_2.set(1);
bSet_2.set(15);
bSet_2.set(20);
bSet_2.set(77);
bSet_2.set(50);
bSet_1.and(bSet_2);
System.out.println("BitSet_1 after and with bSet_2 => " + bSet_1);
bSet_1.andNot(bSet_2);
System.out.println("BitSet_1 after andNot with bSet_2 => " + bSet_1);
bSet_2.set(2);
System.out.println("Bit at index 2 after set in bSet_2 => " +
bSet_2.get(2));
}
}
S.
No. Constructor with Description
1 Date( )
2 Date(long milliseconds)
It creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
4 Date(int year, int month, int date, int hrs, int min) - Depricated
It creates a date object with the specified year, month, date, hours, and minuts.
5 Date(int year, int month, int date, int hrs, int min, int sec) - Depricated
It creates a date object with the specified year, month, date, hours, minuts and seconds.
5 Date(String s) - Depricated
It creates a Date object and initializes it so that it represents the date and time indicated by the string s, which is
interpreted as if by the parse(java.lang.String) method.
1 long getTime()
6 Object clone( )
It duplicates the invoking Date object.
9 int hashCode()
It returns the hash code value of the invoking date object.
10 Instant toInstant()
It converts current date into Instant object.
11 String toString()
It converts this date into Instant object.
Example
import java.time.Instant;
import java.util.Date;
1 Calendar getInstance()
2 Date getTime()
It returns a Date object representing the invoking Calendar's time value.
3 TimeZone getTimeZone()
It returns the time zone object associated with the invoking calendar.
4 String getCalendarType()
It returns an instance of Date object from Instant date.
6 int getFirstDayOfWeek()
It returns the day of the week in integer form.
7 int getWeeksInWeekYear()
It retruns the total weeks in week year.
8 int getWeekYear()
It returns the week year represented by current Calendar.
It returns true if the time represented by the Calendar is before the time represented by when Object.
13 Object clone()
It retruns the copy of the current object.
15 void complete()
It sets any unset fields in the calendar fields.
16 void computeFields()
It converts the current millisecond time value time to calendar field values in fields[].
17 void computeTime()
It converts the current calendar field values in fields[] to the millisecond time value time.
21 Set getAvailableCalendarTypes()
It returns a string set of all available calendar type supported by Java Runtime Environment.
22 Locale[] getAvailableLocales()
It returns an array of all locales available in java runtime environment.
28 int getMinimalDaysInFirstWeek()
It returns required minimum days in integer form.
30 long getTimeInMillis()
It returns the current time in millisecond.
31 int hashCode()
It returns the hash code of the invoking object.
33 boolean isLenient()
It returns true if the interpretation mode of this calendar is lenient; false otherwise.
35 boolean isWeekDateSupported()
It returns true if the calendar supports week date. The default value is false.
44 Instant toInstant()
It converts the current object to an instant.
45 String toString()
It returns a string representation of the current object.
Example
import java.util.*;
1 Random()
2 Random(long seedValue)
It creates a new random number generator using a single long seedValue.
2 Boolean nextBoolean()
It generates the next uniformly distributed pseudo-random boolean value.
3 double nextDouble()
It generates the next pseudo-random double number between 0.0 and 1.0.
5 float nextFloat()
It generates the next pseudo-random float number between 0.0 and 1.0..
6 int nextInt()
It generates the next pseudo-random int number.
S.No. Methods with Description
7 int nextInt(int n)
It generates the next pseudo-random integer value between zero and n.
8 long nextLong()
It generates the next pseudo-random, uniformly distributed long value.
9 double nextGaussian()
It generates the next pseudo-random Gaussian distributed double number with mean 0.0 and standard deviation
11 DoubleStream doubles()
It returns a stream of pseudo-random double values, each conforming between 0.0 and 1.0.
15 IntStream ints()
It returns a stream of pseudo-random integer values.
19 LongStream longs()
It returns a stream of pseudo-random long values.
It retruns an unlimited stream of pseudo-random long values, each conforming to the given start and end.
Example
import java.util.Random;
1 Formatter()
2 Formatter(Appendable a)
It creates a new formatter with the specified destination.
3 Formatter(Appendable a, Locale l)
It creates a new formatter with the specified destination and locale.
4 Formatter(File file)
It creates a new formatter with the specified file.
7 Formatter(Locale l)
It creates a new formatter with the specified locale.
8 Formatter(OutputStream os)
It creates a new formatter with the specified output stream.
11 Formatter(PrintStream ps)
It creates a new formatter with the specified print stream.
12 Formatter(String fileName)
S.No. Constructor with Description
It writes a formatted string to the invoking object's destination using the specified locale, format string, and argum
3 void flush()
It flushes the invoking formatter.
4 Appendable out()
It returns the destination for the output.
5 Locale locale()
It returns the locale set by the construction of the invoking formatter.
6 String toString()
It converts the invoking object to string.
7 IOException ioException()
It returns the IOException last thrown by the invoking formatter's Appendable.
8 void close()
It closes the invoking formatter.
Example
import java.util.*;
public class FormatterClassExample {
1 Scanner(InputStream source)
It creates a new Scanner that produces values read from the specified input stream.
3 Scanner(File source)
It creates a new Scanner that produces values scanned from the specified file.
5 Scanner(String source)
It creates a new Scanner that produces values scanned from the specified string.
6 Scanner(Readable source)
It creates a new Scanner that produces values scanned from the specified source.
7 Scanner(ReadableByteChannel source)
It creates a new Scanner that produces values scanned from the specified channel.
1 String next()
4 boolean nextBoolean()
It reads a boolean value from the user.
5 byte nextByte()
It reads a byte value from the user.
6 double nextDouble()
It reads a double value from the user.
7 float nextFloat()
It reads a floating-point value from the user.
8 int nextInt()
It reads an integer value from the user.
9 long nextLong()
It reads a long value from the user.
10 short nextShort()
It reads a short value from the user.
11 String nextLine()
It reads a string value from the user.
12 boolean hasNext()
It returns true if the invoking scanner has another token in its input.
13 void remove()
It is used when remove operation is not supported by this implementation of Iterator.
14 void close()
It closes the invoking scanner.
Example
import java.util.Scanner;
System.out.println("\n------------------------------------------");
System.out.println("Hello, " + name);
System.out.println("You are " + age + " years old.");
System.out.println("You are earning Rs." + salary + " per month.");
System.out.println("Words from " + name + " - " + msg);
}
}
Swing has about four times the number of User Interface [UI] components as AWT and is
part of the standard Java distribution. By today’s application GUI requirements, AWT is a
limited implementation, not quite capable of providing the components required for
developing complex GUI’s required in modern commercial applications. The AWT
component set has quite a few bugs and really does take up a lot of system resources
when compared to equivalent Swing resources. Netscape introduced its Internet
Foundation Classes [IFC] library for use with Java. Its Classes became very popular with
programmers creating GUI’s for commercial applications.
Swing is a Set Of API ( API- Set Of Classes and Interfaces )
Swing is Provided to Design Graphical User Interfaces
Swing is an Extension library to the AWT (Abstract Window Toolkit)
Includes New and improved Components that have been enhancing the looks and
Functionality of GUIs’
Swing can be used to build(Develop) The Standalone swing GUI Apps Also as Servlets
And Applets
It Employs model/view design architecture
Swing is more portable and more flexible than AWT, The Swing is built on top of the
AWT
Swing is Entirely written in Java
Java Swing Components are Platform-independent And The Swing Components are
lightweight
Swing Supports a Pluggable look and feels And Swing provides more powerful
components
such as tables, lists, Scrollpanes, Colourchooser, tabbedpane, etc
Further Swing Follows MVC.
Many programmers think that JFC and Swing are one and the same thing, but that is not
so.
JFC contains Swing [A UI component package] and quite a number of other items:
Cut and paste: Clipboard support
Accessibility features: Aimed at developing GUI’s for users with disabilities
The Desktop Colors Features Has been Firstly introduced in Java 1.1
Java 2D: it has Improved colors, images, and also texts support
Features Of Swing Class
Pluggable look and feel
Uses MVC architecture
Lightweight Components
Platform Independent
Advanced features such as JTable, JTabbedPane, JScollPane, etc.
Java is a platform-independent language and runs on any client machine, the GUI look
and feel, owned and delivered by a platform-specific O/S, simply does not affect an
application’s GUI constructed using Swing components
Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight
component development. For a component to qualify as lightweight, it must not depend
on any non-Java [O/s based) system classes. Swing components have their own view
supported by Java’s look and feel classes.
Pluggable Look and Feel: This feature enables the user to switch the look and feel of
Swing components without restarting an application. The Swing library supports
components’ look and feels that remain the same across all platforms wherever the
program runs. The Swing library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application
Highly customizable – Swing controls can be customized in a very easy way as visual
appearance is independent of internal representation.
Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane,
slider, colorpicker, and table controls.
Swing Classes Hierarchy
import java.io.*;
import javax.swing.*;
class FirstFrame
frame.setVisible(true);
import java.io.*;
import javax.swing.JFrame;
FirstFrame()
new FirstFrame();
import java.io.*;
import javax.swing.JFrame;
FirstFrame()
this.setSize(600,500);
new FirstFrame();
}
LIMITATIONS OF AWT:
MVC ARCHITECTURE
The Model-View-Controller (MVC) is a well-known design pattern in the web
development field. It is way to organize our code. It specifies that a program or
application shall consist of data model, presentation information and control
information. The MVC pattern needs all these components to be separated as
different objects.
In Java Programming, the Model contains the simple Java classes, the View used to
display the data and the Controller contains the servlets. Due to this separation the
user requests are processed as follows:
1. A client (browser) sends a request to the controller on the server side, for a
page.
2. The controller then calls the model. It gathers the requested data.
3. Then the controller transfers the data retrieved to the view layer.
4. Now the result is sent back to the browser (client) by the view.
o MVC has the feature of scalability that in turn helps the growth of application.
o The components are easy to maintain because there is less dependency.
o A model can be reused by multiple views that provides reusability of code.
o The developers can work with the three layers (Model, View, and Controller)
simultaneously.
o Using MVC, the application becomes more understandable.
o Using MVC, each layer is maintained separately therefore we do not require
to deal with massive code.
o The extending and testing of application is easier.
Let's consider the following code snippet that creates a which is also the first step to
implement MVC pattern.
The above code simply consists of getter and setter methods to the Employee class.
View Layer
As the name depicts, view represents the visualization of data received from the
model. The view layer consists of output of application or user interface. It sends
the requested data to the client, that is fetched from model layer by controller.
Controller Layer
The controller layer gets the user requests from the view layer and processes them,
with the necessary validations. It acts as an interface between Model and View. The
requests are then sent to model for data processing. Once they are processed, the
data is sent back to the controller and then displayed on the view.
Let's consider the following code snippet that creates the controller using the
EmployeeController class.
EmployeeController.java
Main Class Java file
The following example displays the main file to implement the MVC architecture.
Here, we are using the MVCMain class.
MVCMain.java
COMPONENTS OF SWING:
Java Swing is a GUI toolkit and a part of JFC (Java Foundation Class) helpful in developing
window-based applications. Java Swing is lightweight and platform-independent that contains
various components and container classes. Furthermore, the Java swing library is built on the
top of the AWT(Abstract Window Toolkit), an API completely written in Java. In every
application, users can find an interactive and user-friendly interface that gives them the freedom
to use the app.
In Java Swing, there are several components like a scroll bar, button, text field, text area,
checkbox, radio button, etc. These components jointly form a GUI that offers a rich set of
functionalities and allows high-level customization.
1. JButton
2. JLabel
3. JTextField
4. JCheckBox
5. JRadioButton
6. JComboBox
7. JTextArea
8. JPasswordField
9. JTable
10. JList
11. JOptionPane
12. JScrollBar
14. JPopupMenu
15. JCheckboxMenuItem
16. JSeperator
17. JProgressBar
18. JTree
19.JFileChooser
20. JTabbedPane
21. JSlider
JButton:
We use JButton class to create a push button on the UI. The button can include some display
text or images. It yields an event when clicked and double-clicked. We can implement a JButton
in the application by calling one of its constructors.
Syntax:
JButton okBtn = new JButton(“Click”);
Display:
JLabel
We use JLabel class to render a read-only text label or images on the UI. It does not generate
any event.
Syntax:
JLabel textLabel = new JLabel(“This is 1st L...”);
Display:
JTextField
The JTextField renders an editable single-line text box. Users can input non-formatted text in
the box. We can initialize the text field by calling its constructor and passing an optional integer
parameter. This parameter sets the box width measured by the number of columns. Also, it
does not limit the number of characters that can be input into the box.
Syntax:
JTextField txtBox = new JTextField(50);
Display:
JCheckBox
The JCheckBox renders a check-box with a label. The check-box has two states, i.e., on and
off. On selecting, the state is set to "on," and a small tick is displayed inside the box.
Syntax:
CheckBox chkBox = new JCheckBox(“Java Swing”, true);
It returns a checkbox with the label Pepperoni pizza. Notice the second parameter in the
constructor. It is a boolean value that denotes the default state of the check-box. True means
the check-box defaults to the "on" state.
Display:
JRadioButton
A radio button is a group of related buttons from which we can select only one. We use
JRadioButton class to create a radio button in Frames and render a group of radio buttons in the
UI. Users can select one choice from the group.
Syntax:
JRadioButton jrb = new JRadioButton("Easy");
Display:
JComboBox
Syntax:
JComboBox jcb = new JComboBox(name);
Display:
JTextArea
Declaration:
public class JTextArea extends JTextComponent
Syntax:
JTextArea textArea_area=new JTextArea("Ninja! please write something in the text
area.");
Display:
JPasswordField
Declaration:
public class JPasswordField extends JTextField
Syntax:
JPasswordField password = new JPasswordField();
Display:
JTable
In Java, the Swing toolkit contains a JTable Class. It is under package javax.swing.JTable class.
It is used to draw a table to display data.
Syntax:
JTable table = new JTable(table_data, table_column);
Display:
JList
In Java, the Swing toolkit contains a JList Class. It is under package javax.swing.JList
class. It is used to represent a list of items together. We can select one or more than
one items from the list.
Declaration:
public class JList extends JComponent implements Scrollable, Accessible
Syntax:
DefaultListModel<String> list1 = new DefaultListModel<>();
list1.addElement("Apple");
list1.addElement("Orange");
list1.addElement("Banan");
list1.addElement("Grape");
JList<String> list_1 = new JList<>(list1);
Display:
JOptionPane
Declaration:
public class JOptionPane extends JComponent implements Accessible
Syntax:
JOptionPane.showMessageDialog(jframe_obj, "Good Morning, Evening & Night.");
Display:
JScrollBar
Declaration:
public class JScrollBar extends JComponent implements Adjustable, Accessible
Syntax:
JScrollBar scrollBar = new JScrollBar();
Display:
JMenuBar, JMenu and JMenuItem
In Java, the Swing toolkit contains a JMenuBar, JMenu, and JMenuItem class. It is under
package javax.swing.JMenuBar, javax.swing.JMenu and javax.swing.JMenuItem class. The
JMenuBar class is used for displaying menubar on the frame. The JMenu Object is used to pull
down the menu bar's components. The JMenuItem Object is used for adding the labeled menu
item.
Syntax:
JMenuBar menu_bar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menuItem1 = new JMenuItem("Never");
menuItem2 = new JMenuItem("Stop");
menuItem3 = new JMenuItem("Learing");
menu.add(menuItem1);
menu.add(menuItem2);
menu.add(menuItem3);
Display:
JPopupMenu
In Java, the Swing toolkit contains a JPopupMenu Class. It is under package
javax.swing.JPopupMenu class. It is used for creating popups dynamically on a specified
position.
Declaration:
public class JPopupMenu extends JComponent implements Accessible, MenuElement
Syntax:
final JPopupMenu popupmenu1 = new JPopupMenu("Edit");
Display:
JCheckBoxMenuItem
Syntax:
JCheckBoxMenuItem item = new JCheckBoxMenuItem("Option_1");
Display:
JSeparator
Declaration:
public class JSeparator extends JComponent implements SwingConstants, Accessible
Syntax:
jmenu_Item.addSeparator();
Display:
JProgressBar
Declaration:
public class JProgressBar extends JComponent implements SwingConstants, Accessible
Syntax:
JProgressBar progressBar = new JProgressBar(0,2000);
Display:
JTree
In Java, the Swing toolkit contains a JTree Class. It is under package javax.swing.JTreeclass. It
is used for creating tree-structured data. It is a very complex component.
Declaration:
public class JTree extends JComponent implements Scrollable, Accessible
Syntax:
JTree tree = new JTree(tree_style);
Display:
JFileChooser
The JFileChooser class renders a file selection utility. This component lets a user select a file
from the local system.
Syntax:
JFileChooser fileChooser = new JFileChooser();
JButton fileBtn = new JButton(“Select File”);
fileBtn.AddEventListner(new ActionListner(){
fileChooser.showOpenDialog();
})
var selectedFile = fileChooser.getSelectedFile();
The above code creates a file chooser dialog and attaches it to the button. The button click
would open the file chooser dialog. The selected file is returned through the get file method
chosen.
Display:
JTabbedPane
The JTabbedPane is another beneficial component that lets the user switch between tabs in an
application. It is a handy utility as it allows users to browse more content without navigating to
different pages.
Syntax:
JTabbedPane jtabbedPane = new JTabbedPane();
jtabbedPane.addTab(“Tab_1”, new JPanel());
jtabbedPane.addTab(“Tab_2”, new JPanel());
The above code creates a two-tabbed panel with headings Tab_1 and Tab_2.
Display:
JSlider
The JSlider component displays a slider that the user can drag to change its value. The
constructor takes three arguments: minimum, maximum, and initial.
Syntax:
JSlider volumeSlider = new JSlider(0, 100, 20);
var volumeLevel = volumeSlider.getValue();
The above code makes a slider from 0 to 100 with an initial value set to 20. The value
specified by the user is returned by the getValue method.
Display:
SWING Containers
Following is the list of commonly used containers while designed GUI using SWING.
1. Panel: JPanel is the simplest container. It provides space in which any other component
can be placed, including other panels.
2. Frame: A JFrame is a top-level window with a title and a border.
3. Window: A JWindow object is a top-level window with no borders and no menubar.
LAYOUT MANAGERS:
The LayoutManagers are used to arrange components in a particular manner.
The Java LayoutManagers facilitates us to control the positioning and size of the
components in GUI forms. LayoutManager is an interface that is implemented by all
the classes of layout managers. There are the following classes that represent the
layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south,
east, west, and center. Each region (area) may contain one component only. It is
the default layout of a frame or window. The BorderLayout provides five constants
for each region:
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout
with the given rows and columns along with given horizontal and vertical gaps.
o public void next(Container parent): is used to flip to the next card of the
given container.
o public void previous(Container parent): is used to flip to the previous
card of the given container.
o public void first(Container parent): is used to flip to the first card of the
given container.
o public void last(Container parent): is used to flip to the last card of the
given container.
o public void show(Container parent, String name): is used to flip to the
specified card with the given name.
The components may not be of the same size. Each GridBagLayout object maintains
a dynamic, rectangular grid of cells. Each component occupies one or more cells
known as its display area. Each component associates an instance of
GridBagConstraints. With the help of the constraints object, we arrange the
component's display area on the grid. The GridBagLayout manages each
component's minimum and preferred sizes in order to determine the component's
size. GridBagLayout components are also arranged in the rectangular grid but can
have many different sizes and can occupy multiple rows or columns.
Constructor
In this section, we will discuss event processing and how to implement the
delegation event model in Java. We will also discuss the different components of an
Event Model.
But, the modern approach for event processing is based on the Delegation Model. It
defines a standard and compatible mechanism to generate and process events. In
this model, a source generates an event and forwards it to one or more listeners.
The listener waits until it receives an event. Once it receives the event, it is
processed by the listener and returns it. The UI elements are able to delegate the
processing of an event to a separate function.
The key advantage of the Delegation Event Model is that the application logic is
completely separated from the interface logic.
In this model, the listener must be connected with a source to receive the event
notifications. Thus, the events will only be received by the listeners who wish to
receive them. So, this approach is more convenient than the inheritance-based
event model (in Java 1.0).
In the older model, an event was propagated up the containment until a component
was handled. This needed components to receive events that were not processed,
and it took lots of time. The Delegation Event model overcame this issue.
o Events
o Events Sources
o Events Listeners
Events
The Events are the objects that define state change in a source. An event can be
generated as a reaction of a user while interacting with GUI elements. Some of the
event generation activities are moving the mouse pointer, clicking on a button,
pressing the keyboard key, selecting an item from the list, and so on. We can also
consider many other user operations as events.
The Events may also occur that may be not related to user interaction, such as a
timer expires, counter exceeded, system failures, or a task is completed, etc. We
can define events for any of the applied actions.
Event Sources
A source is an object that causes and generates an event. It generates an event
when the internal state of the object is changed. The sources are allowed to
generate several different types of events.
A source must register a listener to receive notifications for a specific event. Each
event contains its registration method. Below is an example:
From the above syntax, the Type is the name of the event, and e1 is a reference to
the event listener. For example, for a keyboard event listener, the method will be
called as addKeyListener(). For the mouse event listener, the method will be
called as addMouseMotionListener(). When an event is triggered using the
respected source, all the events will be notified to registered listeners and receive
the event object. This process is known as event multicasting. In few cases, the
event notification will only be sent to listeners that register to receive them.
From the above syntax, the Type is the name of the event, and e2 is the event
listener's reference. When the specified event occurs, it will be notified to the
registered listener. This process is known as unicasting events.
A source should contain a method that unregisters a specific type of event from the
listener if not needed. Below is an example of the method that will remove the
event from the listener.
From the above syntax, the Type is an event name, and e2 is the reference of the
listener. For example, to remove the keyboard listener,
the removeKeyListener() method will be called.
The source provides the methods to add or remove listeners that generate the
events. For example, the Component class contains the methods to operate on the
different types of events, such as adding or removing them from the listener.
Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners
require two things; first, it must be registered with a source; however, it can be
registered with several resources to receive notification about the events. Second, it
must implement the methods to receive and process the received notifications.
The methods that deal with the events are defined in a set of interfaces. These
interfaces can be found in the java.awt.event package.
For example, the MouseMotionListener interface provides two methods when the
mouse is dragged and moved. Any object can receive and process these events if it
implements the MouseMotionListener interface.
Types of Events
The events are categories into the following two categories:
The Background events are those events that result from the interaction of the end-
user. For example, an Operating system interrupts system failure (Hardware or
Software).
Design Goals
The design goals of the event delegation model are as following:
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
1. Within class
2. Other class
3. Anonymous class
A user interacts with the application by pressing either keys on the keyboard or by using
mouse. A programmer should know which key the user has pressed on the keyboard or
whether the mouse is moved, pressed, or released. These are also called ‘events’. Knowing
these events will enable the programmer to write his code according to the key pressed or
mouse event.
1. Public void keyPressed(KeyEvent ke): This method is called when a key is pressed on
the keyboard. This include any key on the keyboard along with special keys like
function keys, shift, alter, caps lock, home, end etc.
2. Public void keyTyped(keyEvent ke) : This method is called when a key is typed on the
keyboard. This is same as keyPressed() method but this method is called when general
keys like A to Z or 1 to 9 etc are typed. It cannot work with special keys.
3. Public void keyReleased(KeyEvent ke): this method is called when a key is release.
KeyEvent class has the following methods to know which key is typed by the user.
1. Char getKeyChar(): this method returns the key name (or character) related to the key
pressed or released.
2. Int getKeyCode(): this method returns an integer number which is the value of the
key presed by the user.
The follwing are the key codes for the keys on the keyboard. They are defined as
constants in KeyEvent class. Remember VK represents Virtual Key.
package com.myPack;
import java.awt.*;
import
java.awt.event.*;
import javax.swing.*;
{
private static final Font Font =
null; Container c;
JTextArea a;
{
int keycode = ke.getKeyCode();
if(keycode == KeyEvent.VK_F1) str += "F1 Key";
if(keycode == KeyEvent.VK_F2) str += "F2 Key";
if(keycode == KeyEvent.VK_F3) str += "F3 Key";
if(keycode == KeyEvent.VK_PAGE_UP) str += "Page
UP"; if(keycode == KeyEvent.VK_PAGE_DOWN) str +=
"Page Down"; a.setText(str);
str =" " ;
}
public void keyRelease(KeyEvent ke)
{
}
public void keyTyped(KeyEvent ke)
{
}
public static void main(String args[])
{
KeyBoardEvents kbe = new
KeyBoardEvents();
kbe.setSize(400,400);
kbe.setVisible(true);
kbe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void keyReleased(KeyEvent
arg0) {
Output:
1. int getButton(): this method returns a value representing a mouse button, when
it is clicked it retursn 1 if left button is clicked, 2 if middle button, and 3 if right
button is clicked.
2. int getX(); this method returns the horizontal x position of the event relative to
the source component.
3. int getY(); this method returns the vertical y postion of the event relative to the
source component.
Program to create a text area and display the mouse event when the
button on the mouse is clicke, when mouse is moved, etc. is done by
user.
package com.myPack;
import java.awt.*;
import
java.awt.event.*;
import javax.swing.*;
{
String str =" ";
JTextArea ta;
Container c;
int x, y;
MouseEvents()
{
c=getContentPane();
c.setLayout(new FlowLayout());
ta.addMouseListener(this);
ta.addMouseMotionListener(this);
}
{
int i = me.getButton();
if(i==1)
}
public void mouseEntered(MouseEvent me)
{
str += "Mouse Entered";
this.display();
}
public void mouseExited(MouseEvent me)
{
str += "Mouse Exited";
this.display();
}
public void mousePressed(MouseEvent me)
{
x = me.getX();
y= me.getY();
str += "Mouse Pressed at :" +x + "\t" + y;
this.display();
}
public void mouseReleased(MouseEvent me)
{
x = me.getX();
y= me.getY();
str += "Mouse Released at :" +x + "\t" + y;
this.display();
}
public void mouseDragged(MouseEvent me)
{
x = me.getX();
y= me.getY();
str += "Mouse Dragged at :" +x + "\t" + y;
this.display();
}
public void mouseMoved(MouseEvent me)
{
x = me.getX();
y= me.getY();
str += "Mouse Moved at :" +x + "\t" + y;
this.display();
{
ta.setText(str);
str=" ";
}
{
MouseEvents mes = new MouseEvents();
mes.setSize(400,400);
mes.setVisible(true);
mes.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you
inherit the adapter class, you will not be forced to provide the implementation of all
the methods of listener interfaces. So it saves code.
We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.
Additionally, it can access all the members of the outer class, including private data
members and methods.
If all the class objects are a part of the outer object then it is easier to nest that
class inside the outer class. That way all the outer class can access all the objects of
the inner class.
In simple words, a class that has no name is known as an anonymous inner class in
Java. It should be used if you have to override a method of class or interface. Java
Anonymous inner class can be created in two ways:
Advantage of Applet
There are many advantages of applet. They are as follows:
Drawback of Applet
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container which is the subclass of Component.
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet
tag in comment and compile it. After that run it by: appletviewer First.java. Now
Html file is not required but it is for testing purpose only.
SECURITY ISSUES OF APPLET:
Current browsers impose the following restrictions on any applet that is loaded over
the network:
Each browser has a SecurityManager object that implements its security policies.
When a SecurityManager detects a violation, it throws a SecurityException. Your
applet can catch this SecurityException and react appropriately.
APPLETS & APPLICATIONS:
Java Application is just like a Java program that runs on an underlying operating
system with the support of a virtual machine. It is also known as an application program.
The graphical user interface is not necessary to execute the java applications, it can be
run with or without it.
Java Applet is a Java program that can be embedded into a web page. It runs
inside the web browser and works on the client-side. An applet is embedded in an HTML
page using the APPLET or OBJECT tag and hosted on a web server. Applets are used to
make the website more dynamic and entertaining.
Read and It supports the reading and It does not support the reading
Write writing of files on the local and writing of files on the local
Operation computer. computer.
Syntax:
Create a Swing Applet
The second type of program that commonly uses Swing is the applet. Swing-based
applets are similar to AWT-based applets, but with an important difference: A Swing applet
extends JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet includes
all of the functionality found in Applet and adds support for Swing. JApplet is a top-level
Swing container, which means that it is not derived from JComponent. Because JApplet is a
top-level container, it includes the various panes described earlier. This means that all
components are added to JApplet’s content pane in the same way that components are added
to JFrame’s content pane.
Swing applets use the same four life-cycle methods: init( ), start( ), stop( ), and destroy(
). Of course, you need override only those methods that are needed by your applet. Painting is
accomplished differently in Swing than it is in the AWT, and a Swing applet will not normally
override the paint( ) method.
/*
*/
public class MySwingApplet extends JApplet { JButton jbtnAlpha;
JButton jbtnBeta;
JLabel jlab;
try {
});
} catch(Exception exc) {
}
//This applet does not need to override start(), stop(),
//or destroy().
});
});
//Add the buttons to the content pane.
add(jbtnAlpha);
add(jbtnBeta);
}
There are two important things to notice about this applet.
First, MySwingApplet extends JApplet. As explained, all Swing-based applets
extend JApplet rather than Applet. Second, the init( ) method initializes the
Swing components on the event dispatching thread by setting up a call
to makeGUI( ). Notice that this is accomplished through the use
of invokeAndWait( ) rather than invokeLater( ). Applets must
use invokeAndWait( ) because the init( ) method must not return until the entire
initialization process has been completed. In essence, the start( ) method cannot be
called until after initialization, which means that the GUI must be fully
constructed.
Inside makeGUI( ), the two buttons and label are created, and the action listeners
are added to the buttons. Finally, the components are added to the content pane.
Although this example is quite simple, this same general approach must be used
when building any Swing GUI that will be used by an applet.
Painting in Swing
Although the Swing component set is quite powerful, you are not limited to using
it because Swing also lets you write directly into the display area of a frame, panel,
or one of Swing’s other components, such as JLabel. Although many (perhaps
most) uses of Swing will not involve drawing directly to the surface of a
component, it is available for those applications that need this capability. To write
output directly to the surface of a component, you will use one or more drawing
methods defined by the AWT, such as drawLine( ) or drawRect( ).
Painting Fundamentals
The AWT class Component defines a method called paint( ) that is used to draw
output directly to the surface of a component. For the most part, paint( ) is not
called by your program. (In fact, only in the most unusual cases should it ever be
called by your program.) Rather, paint( ) is called by the run-time system
whenever a component must be rendered. This situation can occur for several
reasons. For example, the window in which the component is displayed can be
overwritten by another window and then uncovered. Or, the window might be
minimized and then restored. The paint( ) method is also called when a program
begins running. When writing AWT-based code, an application will
override paint( ) when it needs
to write output directly to the surface of the component.
To paint to the surface of a Swing component, you will create a subclass of the
component and then override its paintComponent( ) method. This is the method
that paints the interior of the component. You will not normally override the other
two painting methods. When overriding paintComponent( ), the first thing you
must do is call super.paintComponent( ), so that the superclass portion of the
painting process takes place. (The only time this is not required is when you are
taking complete, manual control over how a component is displayed.) After that,
write the output that you want to display. The paintComponent( ) method is
shown here:
When drawing to the surface of a component, you must be careful to restrict your
output to the area that is inside the border. Although Swing automatically clips any
output that will exceed the boundaries of a component, it is still possible to paint
into the border, which will then get overwritten when the border is drawn. To
avoid this, you must compute the paintable area of the component. This is the area
defined by the current size of the component minus the space used by the border.
Therefore, before you paint to a component, you must obtain the width of the
border and then adjust your drawing accordingly.
To obtain the border width, call getInsets( ), shown here: Insets getInsets( )
This method is defined by Container and overridden by JComponent. It returns
an Insets object that contains the dimensions of the border. The inset values can be
obtained by using these fields:
int right;
These values are then used to compute the drawing area given the width and the
height of the component. You can obtain the width and height of the component by
calling getWidth( ) and getHeight( ) on the component. They are shown here:
By subtracting the value of the insets, you can compute the usable width and height
of the component.
A Paint Example
Here is a program that puts into action the preceding discussion. It creates a class
called PaintPanel that extends JPanel. The program then uses an object of that
class to display lines whose endpoints have been generated randomly.
// Paint lines to a panel.
// Construct a panel.
PaintPanel() {
y = rand.nextInt(height-ins.bottom); x2 = rand.nextInt(width-
ins.left); y2 = rand.nextInt(height-ins.bottom);
JLabel jlab;
PaintPanel pp;
PaintDemo() {
jfrm.setSize(200, 150);
//Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pp = new PaintPanel();
jfrm.add(pp);
}
});
}
Let’s examine this program closely. The PaintPanel class extends JPanel. JPanel is one of
Swing’s lightweight containers, which means that it is a component that can be added to
the content pane of a JFrame. To handle painting, PaintPanel overrides
the paintComponent( ) method. This enables PaintPanel to write directly to the surface of
the component when painting takes place. The size of the panel is not specified because the
program uses the default border layout and the panel is added to the center. This results in
the panel being sized to fill the center. If you change the size of the window, the size of the
panel will be adjusted accordingly.
Notice that the constructor also specifies a 5-pixel wide, red border. This is
accomplished by setting the border by using the setBorder( ) method, shown here:
Border is the Swing interface that encapsulates a border. You can obtain a border
by calling one of the factory methods defined by the BorderFactory class. The
one used in the program is createLineBorder( ), which creates a simple line
border. It is shown here:
JComponent.
Notice that icons are specified by objects of type Icon, which is an interface
defined by Swing. The easiest way to obtain an icon is to use
the ImageIcon class. ImageIcon implements Icon and encapsulates an image.
Thus, an object of type ImageIcon can be passed as an argument to
the Icon parameter of JLabel’s constructor. There are several ways to provide the
image, including reading it from a file or downloading it from a URL. Here is
the ImageIcon constructor used by the example in this section:
ImageIcon(String filename)
It obtains the image in the file named filename.
The icon and text associated with the label can be obtained by the following
methods:
The icon and text associated with a label can be set by these methods:
Here, icon and str are the icon and text, respectively. Therefore, using setText( ) it
is possible to change the text inside a label during program execution.
The following applet illustrates how to create and display a label containing both
an icon and a string. It begins by creating an ImageIcon object for the
file hourglass.png, which depicts an hourglass. This is used as the second
argument to the JLabel constructor. The first and last arguments for
the JLabel constructor are the label text and the alignment. Finally, the label is
added to the content pane.
import javax.swing.*; /*
*/
public class JLabelDemo extends JApplet {
);
} catch (Exception exc) {
// Create an icon.
JTextField
JTextField is the simplest Swing text component. It is also probably its most
widely used text component. JTextField allows you to edit one line of text. It is
derived from JTextComponent, which provides the basic functionality common
to Swing text components. JTextField uses the Document interface for its model.
Three of JTextField’s constructors are shown here:
JTextField(int cols) JTextField(String str, int cols) JTextField(String str)
Here, str is the string to be initially presented, and cols is the number of columns in
the text field. If no string is specified, the text field is initially empty. If the number
of columns is not specified, the text field is sized to fit the specified string.
JTextField generates events in response to user interaction. For example,
an ActionEvent is fired when the user presses enter. A CaretEvent is fired each
time the caret (i.e., the cursor) changes position. (CaretEvent is packaged
in javax.swing.event.) Other events are also possible. In many cases, your
program will not need to handle these events. Instead, you will simply obtain the
string currently in the text field when it is needed. To obtain the text currently in
the text field, call getText( ).
// Demonstrate JTextField.
import java.awt.*;
*/
);
});
The Swing Buttons
Swing defines four types of buttons: JButton, JToggleButton, JCheckBox,
and JRadioButton. All are subclasses of the AbstractButton class, which
extends JComponent. Thus, all buttons share a set of common traits.
AbstractButton contains many methods that allow you to control the behavior of
buttons. For example, you can define different icons that are displayed for the
button when it is disabled, pressed, or selected. Another icon can be used as
a rollover icon, which is displayed when the mouse is positioned over a button.
The following methods set these icons:
Here, di, pi, si, and ri are the icons to be used for the indicated purpose.
The text associated with a button can be read and written via the following
methods:
String getText( )
JButton
The JButton class provides the functionality of a push button. You have already
seen a simple form of it in the preceding chapter. JButton allows an icon, a string,
or both to be associated with the push button. Three of its constructors are shown
here:
Here, str and icon are the string and icon used for the button.
String getActionCommand( )
The action command identifies the button. Thus, when using two or more buttons
within the same application, the action command gives you an easy way to
determine which button was pressed.
In the preceding chapter, you saw an example of a text-based button. The
following demonstrates an icon-based button. It displays four push buttons and a
label. Each button displays an icon that represents a timepiece. When a button is
pressed, the name of that timepiece is displayed in the label.
*/
JLabel jlab;
);
}
}
add(jb);
add(jb);
add(jb);
// Create and add the label to content pane.
jlab = new JLabel("Choose a Timepiece"); add(jlab);
JToggleButton
A useful variation on the push button is called a toggle button. A toggle button
looks just like a push button, but it acts differently because it has two states:
pushed and released. That is, when you press a toggle button, it stays pressed rather
than popping back up as a regular push button does. When you press the toggle
button a second time, it releases (pops up). Therefore, each time a toggle button is
pushed, it toggles between its two states.
Toggle buttons are objects of
the JToggleButton class. JToggleButton implements AbstractButton. In
addition to creating standard toggle buttons, JToggleButton is a superclass for two
other Swing components that also represent two-state controls. These
are JCheckBox and JRadioButton, which are described later in this chapter.
Thus, JToggleButton defines the basic functionality of all two-state components.
JToggleButton defines several constructors. The one used by the example in this
section is shown here:
JToggleButton(String str)
This creates a toggle button that contains the text passed in str. By default, the
button is in the off position. Other constructors enable you to create toggle buttons
that contain images, or images and text.
Object getItem( )
A reference to the button is returned. You will need to cast this reference
to JToggleButton. The easiest way to determine a toggle button’s state is by
calling the isSelected( ) method
(inherited from AbstractButton) on the button that generated the event. It is
shown here: boolean isSelected( )
Here is an example that uses a toggle button. Notice how the item listener works. It
simply calls isSelected( ) to determine the button’s state.
// Demonstrate JToggleButton.
import java.awt.*;
*/
JLabel jlab;
JToggleButton jtbn;
);
} catch (Exception exc) {
//Create a label.
jlab.setText("Button is off.");
});
add(jlab);
}
The output from the toggle button example is shown here:
Check Boxes
The JCheckBox class provides the functionality of a check box. Its immediate
superclass is JToggleButton, which provides support for two-state buttons, as just
described. JCheckBox defines several constructors. The one used here is
JCheckBox(String str)
It creates a check box that has the text specified by str as a label. Other
constructors let you specify the initial selection state of the button and specify an
icon.
When the user selects or deselects a check box, an ItemEvent is generated. You
can obtain a reference to the JCheckBox that generated the event by
calling getItem( ) on the
ItemEvent passed to the itemStateChanged( ) method defined by ItemListener.
The easiest way to determine the selected state of a check box is to call isSelected(
) on the JCheckBox instance.
The following example illustrates check boxes. It displays four check boxes and a
label. When the user clicks a check box, an ItemEvent is generated. Inside
the itemStateChanged( ) method, getItem( ) is called to obtain a reference to
the JCheckBox object that generated the event. Next, a call
to isSelected( ) determines if the box was selected or cleared.
The getText( ) method gets the text for that check box and uses it to set the text
inside the label.
// Demonstrate JCheckbox.
import java.awt.*; import java.awt.event.*; import javax.swing.*;
/*
*/
JLabel jlab;
}
);
add(cb);
add(jlab);
if(cb.isSelected())
}
}
Radio Buttons
Radio buttons are a group of mutually exclusive buttons, in which only one button
can be selected at any one time. They are supported by the JRadioButton class,
which extends JToggleButton. JRadioButton provides several constructors. The
one used in the example is shown here:
JRadioButton(String str)
Here, str is the label for the button. Other constructors let you specify the initial
selection state of the button and specify an icon.
In order for their mutually exclusive nature to be activated, radio buttons must be
configured into a group. Only one of the buttons in the group can be selected at any
time. For example, if a user presses a radio button that is in a group, any previously
selected button in that group is automatically deselected. A button group is created
by the ButtonGroup class. Its default constructor is invoked for this purpose.
Elements are
then added to the button group via the following method: void
add(AbstractButton ab)
A JRadioButton generates action events, item events, and change events each
time the button selection changes. Most often, it is the action event that is handled,
which means that you will normally implement the ActionListener interface.
Recall that the only method defined by ActionListener is actionPerformed( ).
Inside this method, you can use a number of different ways to determine which
button was selected. First, you can check its action command by
calling getActionCommand( ). By default, the action command is the same as the
button label, but you can set the action command to something else by
calling setActionCommand( ) on the radio button. Second, you can
call getSource( ) on the ActionEvent object and check that reference against the
buttons. Third, you can check each radio button to find out which one is currently
selected by calling isSelected( ) on each button. Finally, each button could use its
own action event handler implemented as either an anonymous inner class or a
lambda expression. Remember, each time an action event occurs, it means that the
button being selected has changed and that one and only one button will be
selected.
The following example illustrates how to use radio buttons. Three radio buttons are
created. The buttons are then added to a button group. As explained, this is
necessary to cause their mutually exclusive behavior. Pressing a radio button
generates an action event, which is handled by actionPerformed( ). Within that
handler, the getActionCommand( ) method gets the text that is associated with the
radio button and uses it to set the text within a label.
// Demonstrate JRadioButton
import java.awt.*;
*/
JLabel jlab;
}
}
);
bg.add(b2);
bg.add(b3);
JTabbedPane
JTabbedPane encapsulates a tabbed pane. It manages a set of components by
linking them with tabs. Selecting a tab causes the component associated with that
tab to come to the forefront. Tabbed panes are very common in the modern GUI,
and you have no doubt used them many times. Given the complex nature of a
tabbed pane, they are surprisingly easy to create and use.
The following example illustrates a tabbed pane. The first tab is titled "Cities" and
contains four buttons. Each button displays the name of a city. The second tab is
titled "Colors" and contains three check boxes. Each check box displays the name
of a color. The third tab is titled "Flavors" and contains one combo box. This
enables the user to select one of three flavors.
// Demonstrate JTabbedPane.
import javax.swing.*;
/*
*/
public class JTabbedPaneDemo extends JApplet {
);
public CitiesPanel() {
public ColorsPanel() {
JCheckBox cb1 = new JCheckBox("Red"); add(cb1);
public FlavorsPanel() {
add(jcb);
Output from the tabbed pane example is shown in the following three illustrations:
JScrollPane
JScrollPane is a lightweight container that automatically handles the scrolling of
another component. The component being scrolled can be either an individual
component, such as a table, or a group of components contained within another
lightweight container, such as a JPanel. In either case, if the object being scrolled
is larger than the viewable area, horizontal and/or vertical scroll bars are
automatically provided, and the component can be scrolled through the pane.
Because JScrollPane automates scrolling, it usually eliminates the need to manage
individual scroll bars.
The viewable area of a scroll pane is called the viewport. It is a window in which
the component being scrolled is displayed. Thus, the viewport displays the visible
portion of the component being scrolled. The scroll bars scroll the component
through the viewport. In its default behavior, a JScrollPane will dynamically add
or remove a scroll bar as needed. For example, if the component is taller than the
viewport, a vertical scroll bar is added. If the component will completely fit within
the viewport, the scroll bars are removed.
JScrollPane defines several constructors. The one used in this chapter is shown
here: JScrollPane(Component comp)
The component to be scrolled is specified by comp. Scroll bars are automatically
displayed when the content of the pane exceeds the dimensions of the viewport.
Here are the steps to follow to use a scroll pane:
The following example illustrates a scroll pane. First, a JPanel object is created,
and 400 buttons are added to it, arranged into 20 columns. This panel is then added
to a scroll pane, and the scroll pane is added to the content pane. Because the panel
is larger than the viewport, vertical and horizontal scroll bars appear automatically.
You can use the scroll bars to scroll the buttons into view.
// Demonstrate JScrollPane.
import java.awt.*;
import javax.swing.*; /*
*/
);
add(jsp, BorderLayout.CENTER);
class JList<E>
JList provides several constructors. The one used here is JList(E[ ] items)
This creates a JList that contains the items in the array specified by items.
JList is based on two models. The first is ListModel. This interface defines how
access to the list data is achieved. The second model is
the ListSelectionModel interface, which defines methods that determine what list
item or items are selected.
Although a JList will work properly by itself, most of the time you will wrap
a JList inside a JScrollPane. This way, long lists will automatically be scrollable,
which simplifies GUI design. It also makes it easy to change the number of entries
in a list without having to change the size of the JList component.
A JList generates a ListSelectionEvent when the user makes or changes a
selection. This event is also generated when the user deselects an item. It is
handled by implementing ListSelectionListener. This listener specifies only one
method, called valueChanged( ), which is shown here:
By default, a JList allows the user to select multiple ranges of items within the list,
but you can change this behavior by calling setSelectionMode( ), which is defined
by JList. It is shown here:
Here, mode specifies the selection mode. It must be one of these values defined by
ListSelectionModel:
SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION
The default, multiple-interval selection, lets the user select multiple ranges of items
within a list. With single-interval selection, the user can select one range of items.
With single selection, the user can select only a single item. Of course, a single
item can be selected in the other two modes, too. It’s just that they also allow a
range to be selected.
You can obtain the index of the first item selected, which will also be the index of
the only selected item when using single-selection mode, by
calling getSelectedIndex( ), shown here:
int getSelectedIndex( )
Indexing begins at zero. So, if the first item is selected, this method will return 0. If
no item is selected, –1 is returned.
Instead of obtaining the index of a selection, you can obtain the value associated
with the selection by calling getSelectedValue( ):
E getSelectedValue( )
It returns a reference to the first selected value. If no value has been selected, it
returns null. The following applet demonstrates a simple JList, which holds a list
of cities. Each time
a city is selected in the list, a ListSelectionEvent is generated, which is handled by
the valueChanged( ) method defined by ListSelectionListener. It responds by
obtaining the index of the selected item and displaying the name of the selected
city in a label.
// Demonstrate JList.
import javax.swing.*; import javax.swing.event.*; import
java.awt.*;
import java.awt.event.*;
/*
*/
);
//Create a JList.
jlst.addListSelectionListener(new ListSelectionListener() {
jlab.setText("Choose a City");
});
// Add the list and label to the content pane.
add(jscrlp);
add(jlab);
JComboBox
Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class. A combo box normally displays one entry, but it
will also display a drop-down list that allows a user to select a different entry. You
can also create a combo box that lets the user enter a selection into the text field.
class JComboBox<E>
Here, E represents the type of the items in the combo box.
Here, obj is the object to be added to the combo box. This method must be used
only with mutable combo boxes.
JComboBox generates an action event when the user selects an item from the
list. JComboBox also generates an item event when the state of selection changes,
which occurs when an item is selected or deselected. Thus, changing a selection
means that two item events will occur: one for the deselected item and another for
the selected item. Often, it is sufficient to simply listen for action events, but both
event types are available for your use.
One way to obtain the item selected in the list is to call getSelectedItem( ) on the
combo box. It is shown here:
Object getSelectedItem( )
You will need to cast the returned value into the type of object stored in the list.
The following example demonstrates the combo box. The combo box contains
entries for "Hourglass", "Analog", "Digital", and "Stopwatch". When a timepiece
is selected, an icon-based label is updated to display it. You can see how little code
is required to use this powerful component.
// Demonstrate JComboBox.
import java.awt.*; import java.awt.event.*; import javax.swing.*;
/*
*/
}
}
);
add(jcb);
//Handle selections.
});
}
Output from the combo box example is shown here:
FILL IN THE BLANKS
1. Swing is a Java Foundation Classes(JFC) library.
2. AWT full form is Abstract Window Toolkit.
3. AWT supports limited number of GUI components.
4. Model – View-Controller(MVC) is a well-known design pattern in the web development.
5. MVC has the feature of scalability that in turn helps the growth of application.
6. Layout Managers are used to arrange components in a particular manner.
7. Delegation Event Model is defined to handle events in GUI programming languages.
8. Events are the objects that define state change in a source.
9. Source is an object that causes and generates an event.
10. Inner class is a class that is declared inside the class or interface.
11. Anonymous Inner class is an inner class without a name and for which only a single object is
created.
12. Applet is a special type of program that is embedded in the webpage to generate the dynamic
content.
13. Swing-based applets are similar to AWT-based applets.
14. AbstractButton contains many methods that allow you to control the behavior of buttons.
15. JButton class provides the functionality of a push button.