0% found this document useful (0 votes)
15 views440 pages

Basic and Advanced Java Programming Lecture Notes

The document provides an introduction to Java, detailing its history, core features, and programming basics. It covers Java's characteristics such as simplicity, object-orientation, robustness, security, and portability, along with common misconceptions about the language. Additionally, it discusses Java's program structure, including comments, keywords, identifiers, and variable types.

Uploaded by

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

Basic and Advanced Java Programming Lecture Notes

The document provides an introduction to Java, detailing its history, core features, and programming basics. It covers Java's characteristics such as simplicity, object-orientation, robustness, security, and portability, along with common misconceptions about the language. Additionally, it discusses Java's program structure, including comments, keywords, identifiers, and variable types.

Uploaded by

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

Chapter – 1: Introduction to Java

History of Java

The Java “White Paper” Buzzwords


1) Simple
2) Object-Oriented
3) Distributed
4) Robust
5) Secure
6) Architecture-Neutral
7) Portable
8) Interpreted
9) High-Performance
10) Multithreaded
11) Dynamic

Simple
▪ The syntax for Java is, indeed, a cleaned-up version of C++ syntax.
▪ There is no need for header files, pointer arithmetic (or even a pointer syntax),
structures, unions, operator overloading, virtual base classes, and so on.
▪ Another aspect of being simple is being small. One of the goals of Java is to enable
the construction of software that can run stand-alone on small machines.

COMPILED BY: BAL KRISHNA NYAUPANE 1


▪ The size of the basic interpreter and class support is about 40K; the basic standard
libraries and thread support (essentially a self-contained microkernel) add another
175K.
Object-Oriented
▪ Object-oriented design is a programming technique that focuses on the data -objects
and on the interfaces to those objects.
▪ The major difference between Java and C++ lies in multiple inheritance, which Java
has replaced with a simpler concept of interfaces. Java has a richer capacity for
runtime introspection than C++.
Distributed
▪ Java has an extensive library of routines for coping with TCP/IP protocols like HTTP
and FTP.
▪ Java applications can open and access objects across the Net via URLs with the same
ease as when accessing a local file system.
Robust
▪ Java is intended for writing programs that must be reliable in a variety of ways.
▪ Java puts a lot of emphasis on early checking for possible problems, later dynamic
(runtime) checking, and eliminating situations that are error-prone.
▪ The single biggest difference between Java and C/C++ is that Java has a pointer
model that eliminates the possibility of overwriting memory and corrupting data.
Secure
▪ Java enables the construction of virus-free, tamper-free systems.
▪ Java browser plug-ins no longer trust remote code unless it is digitally signed and
users have agreed to its execution.

Architecture-Neutral
▪ The compiler generates an architecture-neutral object file format. The compiled code
is executable on many processors, given the presence of the Java runtime system.
▪ The Java compiler does this by generating bytecode instructions which have nothing
to do with a particular computer architecture. Rather, they are designed to be both
easy to interpret on any machine and easy to translate into native machine code on the
fly.
▪ Virtual machines have the option of translating the most frequently executed bytecode
sequences into machine code—a process called just-in-time compilation.
Portable
▪ Unlike C and C++, there are no “implementation-dependent” aspects of the
specification. The sizes of the primitive data types are specified, as is the behavior of
arithmetic on them.
▪ The libraries that are a part of the system define portable interfaces. For example,
there is an abstract Window class and implementations of it for UNIX, Windows, and
the Macintosh.
▪ The Java libraries do a great job of letting you work in a platform-independent
manner. You can work with files, regular expressions, XML, dates and times,
databases, network connections, threads, and so on, without worrying about the
underlying operating system. Not only are your programs portable, but the Java APIs
are often of higher quality than the native ones.

COMPILED BY: BAL KRISHNA NYAUPANE 2


Interpreted
▪ The Java interpreter can execute Java bytecodes directly on any machine to which the
interpreter has been ported.
▪ Since linking is a more incremental and lightweight process, the development process
can be much more rapid and exploratory.
High-Performance
▪ While the performance of interpreted bytecodes is usually more than adequate, there
are situations where higher performance is required. The bytecodes can be translated
on the fly (at runtime) into machine code for the particular CPU the application is
running on.
▪ A just-in-time compiler can monitor which code is executed frequently and optimize
just that code for speed. A more sophisticated optimization is the elimination (or
“inlining”) of function calls. The just-in-time compiler knows which classes have
been loaded. It can use inlining when, based upon the currently loaded collection of
classes, a particular function is never overridden, and it can undo that optimization
later if necessary.
Multithreaded
▪ The benefits of multithreading are better interactive responsiveness and real-time
behavior.
▪ Concurrent programming is never easy, but Java has done a very good job making it
manageable.
Dynamic
▪ In a number of ways, Java is a more dynamic language than C or C++. It was
designed to adapt to an evolving environment.
▪ Libraries can freely add new methods and instance variables without any effect on
their clients.
▪ In Java, finding out runtime type information is straightforward.

Common Misconceptions about Java


▪ Java is an extension of HTML: Java is a programming language; HTML is a way to
describe the structure of a web page. They have nothing in common except that there
are HTML extensions for placing Java applets on a web page.
▪ I use XML, so I don’t need Java: Java is a programming language; XML is a way to
describe data. You can process XML data with any programming language, but the
Java API contains excellent support for XML processing. In addition, many important
XML tools are implemented in Java.
▪ Java is an easy programming language to learn: No programming language as
powerful as Java is easy. You always have to distinguish between how easy it is to
write toy programs and how hard it is to do serious work.
▪ Java will become a universal programming language for all platforms. This is
possible in theory. Anything that happens in a browser is controlled by JavaScript.
Windows programs are written in C++ or C#. Java has the edge in server-side
programming and in cross-platform client applications.

COMPILED BY: BAL KRISHNA NYAUPANE 3


▪ Java is interpreted, so it is too slow for serious applications. In the early days of
Java, the language was interpreted. Nowadays, the Java virtual machine uses a just-in-
time compiler. The “hot spots” of your code will run just as fast in Java as they would
in C++, and in some cases even faster.
▪ All Java programs run inside a web page. All Java applets run inside a web browser.
That is the definition of an applet—a Java program running inside a browser. But
most Java programs are standalone applications that run outside of a web browser. In
fact, many Java programs run on web servers and produce the code for web pages.
▪ JavaScript is a simpler version of Java. JavaScript, a scripting language that can be
used inside web pages, was invented by Netscape and originally called LiveScript.
JavaScript has a syntax that is reminiscent of Java, and the languages’ names sound
similar, but otherwise they are unrelated.

Java Jargon

▪ Java Development Kit (JDK) is a software development environment used for


developing Java applications and applets. It includes the Java Runtime Environment
(JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), and other tools needed in Java development.
▪ Java Runtime Environment: JRE (Java Runtime Environment) is an installation
package that provides an environment to only run (not develop) the java program (or
application) onto your machine. JRE is only used by those who only want to run Java
programs that are end-users of your system.

COMPILED BY: BAL KRISHNA NYAUPANE 4


▪ Java Virtual Machine (JVM) is an engine that provides runtime environment to drive
the Java Code or applications. It converts Java bytecode into machines language. JVM
is a part of Java Runtime Environment (JRE).

▪ What is Java Bytecode?


• Byte Code can be defined as an intermediate code generated by the compiler after
the compilation of source code (JAVA Program). As soon as a java program is
compiled, java bytecode is generated. In more clear terms, java bytecode is the
machine code in the form of a .class file. With the help of java bytecode, we
achieve platform independence in java.

Java Program Structure

COMPILED BY: BAL KRISHNA NYAUPANE 5


Documentation Section
▪ It is optional to write in your Java program.
▪ It contains basic information about the class, variables, methods, author’s name,
program name, version, company name, date of creation, etc.
▪ The compiler does not execute of contents of the documentation section and it ignores
the statements written in it.
▪ We use comments to write in it and comments can be single-line, multi-line, and
documentation comments.
▪ Example single-line comment:
// This example for writing single line comment.
▪ Example multi-line comment:
/* It is an example for writing Multi-line comment */
▪ Example documentation comment:
/** It is an example for documentation comment */

Package Statements
▪ It is optional to write in your Java program.
▪ Note that we cannot use more than one package statement in our Java program.
▪ It should be mentioned before any Interface and class definition.
▪ “package” keyword is used for declaring the package name in the program.
▪ For example,
1. package exam; // where exam is name of package.
2. package [Link]; // root is the parent directory of exam.

Import Statements
▪ It contains predefined classes, methods, interfaces.
▪ “import” keyword is used to import predefined classes or interfaces.
▪ Keyword “import” imports the classes defined in different packages.
▪ It is written between classes declaration and package statements.
▪ For example,
import [Link]; // Import only the Scanner class present in util package.
import [Link].*; // Import all classes of [Link] package.

Class Definition
▪ Without a class, we cannot create a Java program.
▪ At least one class must be present in java program.
▪ You can create more than one class.
▪ For defining a class, we use “class” keyword and after that, write the name of the
class.
▪ Example for defining a class:

class addTwoNumber{ // addTwoNumber is name of class.


// body of class
} // end of class.

COMPILED BY: BAL KRISHNA NYAUPANE 6


Interface Statements
▪ It is an optional statement.
▪ “interface” keyword is used to create interface.
▪ Interface contains methods declaration and constants.
▪ Example for defining an interface:
interface record { // record is the name of interface.
void getData ();
void calculateData (); // getData and calculateData are methods.
}

Main Method Class


▪ Most important section of Java program and without this Java program would not be
able to execute.
▪ It is written inside a class and inside main () method, we call methods and instantiate
classes.
▪ Example for defining the structure of main method:
public class student { // student is name of class.
public static void main (String [] args) { // structure of main method

}// end of main function.


} // end of class

COMPILED BY: BAL KRISHNA NYAUPANE 7


Chapter – 2: Java Programming Basics
Comments in Java

Java keywords
In the Java programming language, a keyword is any one of 67 reserved words that have a
predefined meaning in the language. Of these 67 keywords, 16 of them are only contextually
reserved, and can sometimes be used as an identifier, unlike standard reserved words. The
keywords const and goto are reserved, even they are not currently in use. Currently they are
no longer supported in Java.

COMPILED BY: BAL KRISHNA NYAUPANE 1


Java Identifiers

Java’s Primitive Data Types

COMPILED BY: BAL KRISHNA NYAUPANE 2


Variables and Constants

Dynamic Initialization: Java allows variables to be initialized dynamically, using any


expression valid at the time the variable is declared.

COMPILED BY: BAL KRISHNA NYAUPANE 3


Scope and Lifetime of Variables
In programming, scope of variable defines how a specific variable is accessible within the
program or across classes. In programming, a variable can be declared and defined inside a
class, method, or block. It defines the scope of the variable i.e., the visibility or accessibility
of a variable. Variable declared inside a block or method are not visible to outside.

The lifetime of a variable refers to how long the variable exists before it is destroyed.
Destroying variables refers to deallocating the memory that was allotted to the variables
when declaring it. There are three types of variables:
1. Instance variables
2. Class variables
3. Local variables
Instance Variables: A variable which is declared inside a class and outside all the methods
and blocks is an instance variable. They are known as instance variables because every
instance of the class (object) contains a copy of these variables. The general scope of an
instance variable is throughout the class except in static methods. The lifetime of an instance
variable is until the object stays in memory. Instance variables are non-static variables and
are declared in a class outside of any method, constructor, or block.
• As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
• Unlike local variables, we may use access specifiers for instance variables. If we do
not specify any access specifier, then the default access specifier will be used.
• Initialization of an instance variable is not mandatory. Its default value is 0.
• Instance variables can be accessed only by creating objects.

Class Variables: A variable which is declared inside a class, outside all the blocks and is
marked static is known as a class variable. The general scope of a class variable is throughout
the class and the lifetime of a class variable is until the end of the program or as long as the
class is loaded in memory. Static variables are also known as class variables.
• These variables are declared similarly as instance variables. The difference is that
static variables are declared using the static keyword within a class outside of any
method, constructor or block.
• Unlike instance variables, we can only have one copy of a static variable per class,
irrespective of how many objects we create.

COMPILED BY: BAL KRISHNA NYAUPANE 4


• Static variables are created at the start of program execution and destroyed
automatically when execution ends.
• Initialization of a static variable is not mandatory. Its default value is 0.
• If we access a static variable like an instance variable (through an object), the
compiler will show a warning message, which won’t halt the program. The compiler
will replace the object name with the class name automatically.
• If we access a static variable without the class name, the compiler will automatically
append the class name.

Local Variables: All other variables which are not instance and class variables are treated as
local variables including the parameters in a method. Scope of a local variable is within the
block in which it is declared and the lifetime of a local variable is until the control leaves the
block in which it is declared.
• These variables are created when the block is entered, or the function is called and
destroyed after exiting from the block or when the call returns from the function.
• The scope of these variables exists only within the block in which the variables are
declared, i.e., we can access these variables only within that block.
• Initialization of the local variable is mandatory before using it in the defined scope.

Example-1: WAP java program to illustrate the concept of Variables.

COMPILED BY: BAL KRISHNA NYAUPANE 5


Java Operators

Example-2: WAP java program to add two numbers.

COMPILED BY: BAL KRISHNA NYAUPANE 6


Example-3: WAP java program to illustrate the concept of Assignment operators.

Example-4: WAP java program to illustrate the concept of Shift operators.

COMPILED BY: BAL KRISHNA NYAUPANE 7


Example-5: WAP java program to illustrate the concept of Relational operators.

Example-6: WAP java program to illustrate the concept of Logical operators.

COMPILED BY: BAL KRISHNA NYAUPANE 8


Type Casting

COMPILED BY: BAL KRISHNA NYAUPANE 9


Syntax

double d = 57.17;
int i = (int)d; // Explicit casting from long to int data type

Java - Strings Class


In Java programming language, strings are treated as objects. The Java platform provides the
String class to create and manipulate strings.
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";

How to create a string object?


There are two ways to create String object:
1. By string literal
2. By new keyword

String Literal: Java String literal is created by using double quotes. For Example:
String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new object.
After that it will find the string with the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant pool".

By new keyword
String s=new String("Welcome");
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).

COMPILED BY: BAL KRISHNA NYAUPANE 10


Example-7: WAP java program to illustrate the concept of Basic String.

Java Arrays

COMPILED BY: BAL KRISHNA NYAUPANE 11


COMPILED BY: BAL KRISHNA NYAUPANE 12
Example-7: WAP java program to find sum of array elements and also find the largest
element of Array.

Java Control Statements


Java supports two selection statements: if and switch. These statements allow you to control
the flow of your program’s execution based upon conditions known only during run time.

COMPILED BY: BAL KRISHNA NYAUPANE 13


Example-8: WAP java program to illustrate the concept of If-else statement.

COMPILED BY: BAL KRISHNA NYAUPANE 14


For versions of Java prior to JDK 7, expression must be of type byte, short, int, char, or an
enumeration. Beginning with JDK 7, expression can also be of type String. Each value
specified in the case statements must be a unique constant expression (such as a literal value).
Duplicate case values are not allowed. The type of each value must be compatible with the
type of expression.

The switch statement works like this: The value of the expression is compared with each of
the values in the case statements. If a match is found, the code sequence following that case
statement is executed. If none of the constants matches the value of the expression, then the
default statement is executed. However, the default statement is optional. If no case matches
and no default is present, then no further action is taken.

The break statement is used inside the switch to terminate a statement sequence. When a
break statement is encountered, execution branches to the first line of code that follows the
entire switch statement. This has the effect of “jumping out” of the switch.

COMPILED BY: BAL KRISHNA NYAUPANE 15


Example-9: WAP java program to illustrate the concept of Switch statement using Loop.

Example-10: WAP java program to illustrate the concept of Switch statement using String
control variables.

COMPILED BY: BAL KRISHNA NYAUPANE 16


Example-11: WAP java program to display the season name using Switch statement.

COMPILED BY: BAL KRISHNA NYAUPANE 17


Example-12: WAP java program to illustrate the concept of simple While Statement.

COMPILED BY: BAL KRISHNA NYAUPANE 18


Example-13: WAP java program to illustrate the concept of simple Do-while Statement.

Example-13: WAP java program to check whether a given number is prime or not.

COMPILED BY: BAL KRISHNA NYAUPANE 19


Example-14: WAP java program to illustrate the concept of part of loop can be empty.

Java for each loop

Example-15: WAP java program to illustrate the concept of for each loop.

COMPILED BY: BAL KRISHNA NYAUPANE 20


Example-16: WAP java program to search a value of array using for each loop.

Reading Input

COMPILED BY: BAL KRISHNA NYAUPANE 21


Example-17: WAP java program to take input from users and display the result.

COMPILED BY: BAL KRISHNA NYAUPANE 22


Chapter – 6
Java Input/Output
Streams
▪ Java programs perform I/O through streams. A stream is an abstraction that
either produces or consumes information.
▪ A stream is linked to a physical device by the Java I/O system. All streams behave
in the same manner, even if the actual physical devices to which they are linked
differ. Thus, the same I/O classes and methods can be applied to different types
of devices.
▪ This means that an input stream can abstract many different kinds of input: from a
disk file, a keyboard, or a network socket. Likewise, an output stream may refer
to the console, a disk file, or a network connection.
▪ Streams are a clean way to deal with input/output without having every part of
your code understand the difference between a keyboard and a network, for
example.
▪ Java implements streams within class hierarchies defined in the [Link] package.

Byte Streams and Character Streams


▪ Java defines two types of streams: byte and character.
▪ Byte streams provide a convenient means for handling input and output of bytes.
Byte streams are used, for example, when reading or writing binary data.
▪ Character streams provide a convenient means for handling input and output of
characters. They use Unicode and, therefore, can be internationalized. Also, in
some cases, character streams are more efficient than byte streams.

The Byte Stream Classes


▪ Byte streams are defined by using two class hierarchies. At the top are two abstract
classes: InputStream and OutputStream.
▪ Each of these abstract classes has several concrete subclasses that handle the
differences among various devices, such as disk files, network connections, and
even memory buffers.

The Character Stream Classes


▪ Character streams are defined by using two class hierarchies. At the top are two
abstract classes: Reader and Writer.
▪ These abstract classes handle Unicode character streams. Java has several concrete
subclasses of each of these.

COMPILED BY: BAL KRISHNA NYAUPANE 1


▪ BufferedInputStream: contains methods to read bytes from the buffer.
▪ ByteArrayInputStream: contains methods to read bytes from a byte array.
▪ DataInputStream: contains methods to read Java primitive data types.
▪ FileInputStream: contains methods to read bytes from a file.
▪ FilterInputStream: This class contains methods to read bytes from the other input
streams, which are used as the primary source of data.
▪ ObjectInputStream: contains methods to read objects.
▪ PipedInputStream: contains methods to read from a piped output stream. A piped
input stream must be connected to a piped output stream.
▪ SequenceInputStream: contains methods to concatenate multiple input streams
and then read from the combined stream.
▪ BufferedOutputStream: Contains methods to write bytes into the buffer.
▪ ByteArrayOutputStream: Contains methods to write bytes into a byte array.
▪ DataOutputStream: Contains methods to write Java primitive data types.
▪ FileOutputStream: Contains methods to write bytes to a file.
▪ FilterOutputStream: Contains methods to write to other output streams.
▪ ObjectOutputStream: Contains methods to write objects.
▪ PipedOutputStream: Contains methods to write to a piped output stream.
▪ PrintStream: Contains methods to print Java primitive data types.

COMPILED BY: BAL KRISHNA NYAUPANE 2


COMPILED BY: BAL KRISHNA NYAUPANE 3
COMPILED BY: BAL KRISHNA NYAUPANE 4
COMPILED BY: BAL KRISHNA NYAUPANE 5
COMPILED BY: BAL KRISHNA NYAUPANE 6
Example: Write a Java Program to read data from keyboard and write those data into
file “[Link]” until user say “no”.

COMPILED BY: BAL KRISHNA NYAUPANE 7


Example: Write a Java Program to read data from file “[Link]” and display the
content of file into the console.

COMPILED BY: BAL KRISHNA NYAUPANE 8


COMPILED BY: BAL KRISHNA NYAUPANE 9
Object handling with File

COMPILED BY: BAL KRISHNA NYAUPANE 10


COMPILED BY: BAL KRISHNA NYAUPANE 11
Chapter – 7
Java Collections and Java API Library
The Collection Interfaces
▪ A Java collection framework provides an architecture to store and manipulate a group of
objects. A Java collection framework includes the following:
1. Interfaces
2. Classes
3. Algorithm
▪ Interfaces: Interface in Java refers to the abstract data types. They allow Java collections
to be manipulated independently from the details of their representation. Also, they form
a hierarchy in object-oriented programming languages.
▪ Classes: Classes in Java are the implementation of the collection interface. It basically
refers to the data structures that are used again and again.
▪ Algorithm: Algorithm refers to the methods which are used to perform operations such as
searching and sorting, on objects that implement collection interfaces. Algorithms are
polymorphic in nature as the same method can be used to take many forms or you can say
perform different implementations of the Java collection interface.

Why use Java collection?


▪ There are several benefits of using Java collections such as:
• Reducing the effort required to write the code by providing useful data structures
and algorithms.
• Java collections provide high-performance and high-quality data structures and
algorithms thereby increasing the speed and quality.
• Unrelated APIs can pass collection interfaces back and forth.
• Decreases extra effort required to learn, use, and design new API’s.
• Supports reusability of standard data structures and algorithms.

COMPILED BY: BAL KRISHNA NYAUPANE 1


Java Collections: Interface
▪ Iterator interface: Iterator is an interface that iterates the elements. It is used to traverse
the list and modify the elements. Iterator interface has three methods which are mentioned
below:
• public boolean hasNext() – This method returns true if the iterator has more
elements.
• public object next () – It returns the element and moves the cursor pointer to the next
element.
• public void remove () – This method removes the last elements returned by the
iterator.
Java collections: List
▪ A List is an ordered Collection of elements which may contain duplicates. It is an
interface that extends the Collection interface. Lists are further classified into the
following:
1. ArrayList
2. LinkedList
3. Vectors

COMPILED BY: BAL KRISHNA NYAUPANE 2


List
▪ List in Java provides the facility to maintain the ordered collection. It contains the index-
based methods to insert, update, delete and search the elements. It can have the duplicate
elements also. We can also store the null elements in the list.
▪ The List interface is found in the [Link] package and inherits the Collection interface.
▪ It is a factory of ListIterator interface. Through the ListIterator, we can iterate the list in
forward and backward directions. The implementation classes of List interface are
ArrayList, LinkedList, Stack and Vector.
▪ The ArrayList and LinkedList are widely used in Java programming.
▪ The Vector class is deprecated since Java 5.

How to create List


The List interface is declared as:
public interface List<E> extends Collection<E>;

▪ Creating a List of type String using ArrayList


List<String> list=new ArrayList<String> ();
▪ Creating a List of type Integer using ArrayList
List<Integer> list=new ArrayList<Integer> ();
▪ Creating a List of type Book using ArrayList
List<Book> list=new ArrayList<Book> ();
▪ Creating a List of type String using LinkedList
List<String> list=new LinkedList<String> ();

Methods of List
▪ Some of the commonly used methods of the Collection interface that's also available in
the List interface are:
• add() - adds an element to a list
• addAll() - adds all elements of one list to another
• get() - helps to randomly access elements from lists
• iterator() - returns iterator object that can be used to sequentially access elements of
lists
• set() - changes elements of lists
• remove() - removes an element from the list
• removeAll() - removes all the elements from the list
• clear() - removes all the elements from the list (more efficient than removeAll())
• size() - returns the length of lists
• toArray() - converts a list into an array
• contains() - returns true if a list contains specified element

COMPILED BY: BAL KRISHNA NYAUPANE 3


Java ArrayList
▪ ArrayList is the implementation of List Interface where the elements can be dynamically
added or removed from the list. Also, the size of the list is increased dynamically if the
elements are added more than the initial size.
▪ The important points about the Java ArrayList class are:
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because the array works on an index basis.
• In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a
lot of shifting needs to occur if any element is removed from the array list.
• We cannot create an array list of the primitive types, such as int, float, char, etc. It is
required to use the required wrapper class in such cases. For example:
✓ ArrayList<int> al = ArrayList<int>(); // does not work
✓ ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
• Java ArrayList gets initialized by the size. The size is dynamic in the array list, which
varies according to the elements getting added or removed from the list.

COMPILED BY: BAL KRISHNA NYAUPANE 4


COMPILED BY: BAL KRISHNA NYAUPANE 5
▪ Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-
list data structure. It inherits the AbstractList class and implements List and Deque
interfaces.
▪ The important points about Java LinkedList are:
• Java LinkedList class can contain duplicate elements.
• Java LinkedList class maintains insertion order.
• Java LinkedList class is non synchronized.
• In Java LinkedList class, manipulation is fast because no shifting needs to occur.
• Java LinkedList class can be used as a list, stack or queue.
▪ Creating a Java LinkedList
LinkedList<Type> linkedList = new LinkedList<>();
▪ Create Integer type linked list
LinkedList<Integer> linkedList = new LinkedList<>();

COMPILED BY: BAL KRISHNA NYAUPANE 6


▪ Create String type linked list
LinkedList<String> linkedList = new LinkedList<>();

COMPILED BY: BAL KRISHNA NYAUPANE 7


Set in Java
▪ The set interface is present in [Link] package and extends the Collection interface.
▪ It is an unordered collection of objects in which duplicate values cannot be stored.
▪ It is an interface that implements the mathematical set.
▪ This interface contains the methods inherited from the Collection interface and adds a
feature that restricts the insertion of the duplicate elements.
▪ There are two interfaces that extend the set implementation namely SortedSet and
NavigableSet.
▪ Creating Set Objects
Set<Obj> set = new HashSet<Obj> ();
▪ Methods present in the Set interface
• add(element): This method is used to add a specific element to the set.
• addAll(collection): This method is used to append all of the elements from the
mentioned collection to the existing set. The elements are added randomly without
following any specific order.
• clear():This method is used to remove all the elements from the set but not delete the
set. The reference for the set still exists.
• contains(element): This method is used to check whether a specific element is
present in the Set or not.
• containsAll(collection): This method is used to check whether the set contains all the
elements present in the given collection or not.
• isEmpty():This method is used to check whether the set is empty or not.
• iterator(): This method is used to return the iterator of the set. The elements from the
set are returned in a random order.
• remove(element): This method is used to remove the given element from the set. This
method returns True if the specified element is present in the Set otherwise it returns
False.
• removeAll(collection): This method is used to remove all the elements from the
collection which are present in the set.
• size(): This method is used to get the size of the set.
• toArray():This method is used to form an array of the same elements as that of the
Set.
HashSet
▪ Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.
▪ The important points about Java HashSet class are:
• The underlying data structure for HashSet is Hashtable.
• HashSet stores the elements by using a mechanism called hashing.
• As it implements the Set Interface, duplicate values are not allowed.
• HashSet allows null value.
• Objects that you insert in HashSet are not guaranteed to be inserted in the same order.
Objects are inserted based on their hash code.
• HashSet also implements Serializable and Cloneable interfaces.
• HashSet is the best approach for search operations.

COMPILED BY: BAL KRISHNA NYAUPANE 8


• HashSet default initial capacity is 16 and the default load factor is 0.75.

COMPILED BY: BAL KRISHNA NYAUPANE 9


Java Map Interface
▪ The map interface is present in [Link] package represents a mapping between a
key and a value.
▪ A map contains values on the basis of key, i.e. key and value pair. Each key and
value pair is known as an entry. A Map contains unique keys.
▪ Maps are perfect to use for key-value association mapping such as dictionaries.
The maps are used to perform lookups by keys or when someone wants to retrieve
and update elements by keys. Some common scenarios are as follows:
• A map of error codes and their descriptions.
• A map of zip codes and cities.
• A map of managers and employees. Each manager (key) is associated with a
list of employees (value) he manages.
• A map of classes and students. Each class (key) is associated with a list of
students (value).
▪ Characteristics of a Map Interface
▪ A Map cannot contain duplicate keys and each key can map to at most one
value. Some implementations allow null key and null values like the HashMap
and LinkedHashMap, but some do not like the TreeMap.
▪ The order of a map depends on the specific implementations. For example,
TreeMap and LinkedHashMap have predictable orders, while HashMap does
not.

COMPILED BY: BAL KRISHNA NYAUPANE 10


▪ There are two interfaces for implementing Map in java. They are Map and
SortedMap, and three classes: HashMap, TreeMap, and LinkedHashMap.
▪ Java Map Hierarchy: There are two interfaces for implementing Map in java:
Map and SortedMap, and three classes: HashMap, LinkedHashMap, and
TreeMap. The hierarchy of Java Map is given below:

▪ Map implementation using HashMap


Map<Key, Value> numbers = new HashMap<>();

COMPILED BY: BAL KRISHNA NYAUPANE 11


String Handling
▪ String is an object that represents sequence of characters. In Java, String is represented by
String class which is located into [Link] package
▪ It is probably the most commonly used class in java library. In java, every string that we
create is actually an object of type String.
▪ One important thing to notice about string object is that string objects are immutable that
means once a string object is created it cannot be changed.
▪ The Java String class implements Serializable, Comparable and CharSequence interface
that we have represented using the below image.
▪ In Java, CharSequence Interface is used for representing a sequence of characters.
CharSequence interface is implemented by String, StringBuffer and StringBuilder
classes. This three classes can be used for creating strings in java.

How to create a string object?


• There are two ways to create String object:
1. By string literal
2. By new keyword
1. String Literal: Java String literal is created by using double quotes. For Example:
String s="Java String";
▪ Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If the
string doesn't exist in the pool, a new string instance is created and placed in the pool. For
example:
• String s1="Welcome";
• String s2="Welcome"; // It doesn't create a new instance
2. By new keyword: We can create a new string object by using new operator that allocates
memory for the object.
• String s=new String("Welcome");
▪ In such case, JVM will create a new string object in normal (non-pool) heap memory, and
the literal "Welcome" will be placed in the string constant pool. The variable s will refer
to the object in a heap (non-pool).

What is an Immutable object?


▪ An object whose state cannot be changed after it is created is known as an Immutable
object.
▪ The Java String is immutable which means it cannot be changed. Whenever we change
any string, a new instance is created. For mutable strings, you can use StringBuffer and
StringBuilder classes.

Why string objects are immutable in java?


▪ Because java uses the concept of string literal. Suppose there are 5 reference variables, all
refers to one object “String immutable”. If one reference variable changes the value of the
object, it will be affected to all the reference variables. That is why string objects are
immutable in java.

COMPILED BY: BAL KRISHNA NYAUPANE 12


COMPILED BY: BAL KRISHNA NYAUPANE 13
▪ The syntax of the substring () method is:
[Link](int startIndex, int endIndex)
▪ Here, string is an object of the String class.
▪ The substring () method returns a substring from the given string.
▪ The substring begins with the character at the startIndex and extends to the character at
index endIndex - 1.
▪ If the endIndex is not passed, the substring begins with the character at the specified
index and extends to the end of the string.

COMPILED BY: BAL KRISHNA NYAUPANE 14


▪ The syntax of the replace () method is either
[Link](char oldChar, char newChar)
or
[Link](CharSequence oldText, CharSequence newText)
▪ To replace a single character, the replace () method takes these two parameters:
• oldChar - the character to be replaced in the string
• newChar - matching characters are replaced with this character
▪ To replace a substring, the replace () method takes these two parameters:
• oldText - the substring to be replaced in the string
• newText - matching substrings are replaced with this string

Java String indexOf()


▪ The indexOf() method returns the index of the first occurrence of the specified
character/substring within the string.
▪ The syntax of the String indexOf() method either
[Link](int ch, int fromIndex)
or
[Link](String str, int fromIndex)

COMPILED BY: BAL KRISHNA NYAUPANE 15


COMPILED BY: BAL KRISHNA NYAUPANE 16
COMPILED BY: BAL KRISHNA NYAUPANE 17
COMPILED BY: BAL KRISHNA NYAUPANE 18
String buffer and String builder
▪ String buffer and StringBuilder both are mutable classes which can be used to do
operation on string objects such as reverse of string, concating string and etc.
▪ We can modify string without creating a new object of the string.

COMPILED BY: BAL KRISHNA NYAUPANE 19


COMPILED BY: BAL KRISHNA NYAUPANE 20
Calendar Class in Java
▪ Calendar class in Java is an abstract class that provides methods for converting
date between a specific instant in time and a set of calendar fields such as
MONTH, YEAR, HOUR, etc.
▪ It inherits Object class and implements the Comparable, Serializable, Cloneable
interfaces.
▪ The [Link] class is an abstract class that provides methods for
converting between a specific instant in time and a set of calendar fields such as
YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating
the calendar fields, such as getting the date of the next week.
▪ Following are the important points about Calendar –
• This class also provides additional fields and methods for implementing a
concrete calendar system outside the package.
• Calendar defines the range of values returned by certain calendar fields.

COMPILED BY: BAL KRISHNA NYAUPANE 21


COMPILED BY: BAL KRISHNA NYAUPANE 22
Java SimpleDateFormat
▪ Java SimpleDateFormat class is used for formatting date and time.
▪ A SimpleDateFormat is a concrete class for formatting and parsing dates in a
locale-sensitive manner. It allows for formatting (date -> text), parsing (text ->
date), and normalization.
▪ A SimpleDateFormat allows you to start by choosing any user-defined patterns
for date-time formatting.

Date Format in Java


▪ Date, original version, defined by Java 1.0. When Java 1.1 was released, many of
the functions carried out by the original Date class were moved into the Calendar
and DateFormat classes, and as a result, many of the original 1.0 Date methods
were deprecated. Since the deprecated 1.0 methods should not be used for new
code.

COMPILED BY: BAL KRISHNA NYAUPANE 23


▪ The DateFormat class in Java is used for formatting dates. A specified date can be
formatted into the Data/Time string. For example, a date can be formatted into:
mm/dd/yyyy.
▪ DateFormat is an abstract class for date/time formatting subclasses which formats
and parses dates or time in a language-independent manner.
▪ The date/time formatting subclass, such as SimpleDateFormat, allows for
formatting (i.e., date -> text), parsing (text -> date), and normalization.
▪ The date is represented as a Date object or as the milliseconds since January 1,
1970, [Link] GMT.
▪ The formatting styles include FULL, LONG, MEDIUM, and SHORT.

▪ Date Format classes are not synchronized.

COMPILED BY: BAL KRISHNA NYAUPANE 24


COMPILED BY: BAL KRISHNA NYAUPANE 25
COMPILED BY: BAL KRISHNA NYAUPANE 26
COMPILED BY: BAL KRISHNA NYAUPANE 27
Chapter 1 and 2
AWT, AWT Controls, Layout Managers, Menus

1. An Overview of the AWT


▪ AWT: Abstract Window Toolkit.
▪ It is a part of JFC (Java Foundation Classes) developed by Sun Microsystems in 1995.
▪ It is a platform-dependent API to develop GUI (Graphical User Interface) or window-based
applications in Java.
▪ It is heavy-weight in use because it is generated by the system’s host operating system.
▪ One of the important features of AWT is that it is platform dependent. This means that
the AWT tools use the native toolkits of the platforms they are being implemented. This
approach helps in preserving the look and feel of each platform.
▪ But as said everything comes with a price, there is a major drawback of this approach.
When executed on various platforms because of platform dependency it will look different
on each platform. This hampers the consistency and aesthetics of an application.
▪ The AWT API in Java primarily consists of a comprehensive set of classes and methods
that are required for creating and managing the Graphical User Interface (GUI) in a
simplified manner.
▪ The AWT defines a basic set of controls, windows, and dialog boxes that support a usable,
but limited graphical interface. One reason for the limited nature of the AWT is that it
translates its various visual components into their corresponding, platform-specific
equivalents, or peers. This means that the look and feel of a component is defined by the
platform, not by Java. Because the AWT components use native code resources, they are
referred to as heavyweight.

Features of AWT
▪ AWT has a set of native user interface components.
▪ It provides various classes for graphical representation of components like font, shape,
color.
▪ It provides a robust event-handling model.
▪ It has Layout managers which is helpful for changing window size or screen resolution.
▪ It provides a large range of libraries that can be used for designing graphics for gaming
applications or educational applications.
▪ It has data transfer classes through which cut and paste operation can be performed using
the local clipboard.

Advantages of GUI over CUI (Character User Interface)


▪ GUI provides graphical icons to interact while the CUI offers the simple text-based
interfaces. GUI makes the application more entertaining and interesting.
▪ GUI offers click and execute environment while in CUI every time we have to enter the
command for a task.
▪ New user can easily interact with GUI by the visual indicators but it is difficult in CUI.
▪ GUI offers a lot of controls of file system and the operating system while in CUI you have
to use commands which is difficult to remember.
▪ Windows concept in GUI allow the user to view, manipulate and control the multiple
applications at once while in CUI user can control one task at a time.

COMPILED BY: BAL KRISHNA NYAUPANE 1


▪ GUI provides multitasking environment so as the CUI also does but CUI does not provide
same ease as the GUI do.
▪ Using GUI, it is easier to control and navigate the operating system which becomes very
slow in command user interface. GUI can be easily customized.

Java AWT vs. Java Swing

Java AWT Hierarchy

Component class: In the AWT class hierarchy, the Component class is derived from the Object
class. Component class is at the top of AWT hierarchy. Component class is an abstract class.
It is the superclass of all the GUI element classes like Container, Button, Label, Checkbox,
Choice, and List. Therefore, Component class is responsible for an overall graphical interface.
A component object is responsible for remembering the current foreground and background
colors and the currently selected text font.

Container: Container in Java AWT is a component that is used to hold other components such
as text fields, buttons, etc. It is a subclass of [Link] and is responsible for keeping

COMPILED BY: BAL KRISHNA NYAUPANE 2


a track of components being added. There are four types of containers provided by AWT in
Java.
1. Window: It is an instance of the Window class having neither border nor title. It is used
for creating a top-level window.
2. Frame: Frame is a subclass of Window and contains title, border and menu bars. It
comes with a resizing canvas and is the most widely used container for developing
AWT applications. It is capable of holding various components such as buttons, text
fields, scrollbars, etc. You can create a Java AWT Frame in two ways:
a. By Instantiating Frame class
b. By extending Frame class
3. Dialog: Dialog class is also a subclass of Window and comes with the border as well
as the title. Dialog class’s instance always needs an associated Frame class instance to
exist.
4. Panel: Panel is the concrete subclass of Container and doesn’t contain any title bar,
menu bar or border. Panel class is a generic container for holding the GUI components.
You need the instance of the Panel class in order to add the components.

COMPILED BY: BAL KRISHNA NYAUPANE 3


Working with Frame Windows
▪ Typically, the type of AWT-based application window you will most often create is
derived from Frame. As mentioned, it creates a standard-style, top level window that has
all of the features normally associated with an application window, such as a close box
and title.
▪ Here are two of Frame’s constructors:
• Frame () throws HeadlessException
• Frame (String title) throws HeadlessException
▪ The first form creates a standard window that does not contain a title.
▪ The second form creates a window with the title specified by title.
▪ Notice that you cannot specify the dimensions of the window. Instead, you must set the
size of the window after it has been created.
▪ A HeadlessException is thrown if an attempt is made to create a Frame instance in an
environment that does not support user interaction.

Setting the Window’s Dimensions


▪ The setSize() method is used to set the dimensions of the window. It is shown here:
• void setSize (int newWidth, int newHeight)
• void setSize (Dimension newSize)
▪ The new size of the window is specified by newWidth and newHeight, or by the width
and height fields of the Dimension object passed in newSize. The dimensions are
specified in terms of pixels.
▪ The getSize() method is used to obtain the current size of a window. One of its forms is
shown here:
• Dimension getSize()
▪ This method returns the current size of the window contained within the width and height
fields of a Dimension object.

COMPILED BY: BAL KRISHNA NYAUPANE 4


Hiding and Showing a Window
▪ After a frame window has been created, it will not be visible until you call setVisible(). Its
signature is shown here:
• void setVisible(boolean visibleFlag)
▪ The component is visible if the argument to this method is true. Otherwise, it is hidden.

Setting a Window’s Title


▪ You can change the title in a frame window using setTitle(), which has this general form:
• void setTitle(String newTitle)
▪ Here, newTitle is the new title for the window.

Closing a Frame Window


▪ When using a frame window, your program must remove that window from the screen
when it is closed. If it is not the top-level window of your application, this is done by
calling setVisible(false).
▪ For the main application window, you can simply terminate the program by calling
[Link]().

COMPILED BY: BAL KRISHNA NYAUPANE 5


2. AWT Control Fundamentals
▪ The AWT supports the following types of controls:
• Labels
• Push buttons
• Check boxes
• Choice lists
• Lists
• Scroll bars
• Text Editing

▪ All AWT controls are subclasses of Component. Although the set of controls
provided by the AWT is not particularly rich, it is sufficient for simple
applications, such as short utility programs intended for your own use.
▪ It is important to point out, however, that Swing provides a substantially larger,
more sophisticated set of controls better suited for creating commercial
applications.

Adding and Removing Controls


▪ To include a control in a window, you must add it to the window. To do this, you
must first create an instance of the desired control and then add it to a window by
calling add (), which is defined by Container.
▪ The add () method has several forms.
Component add (Component compRef)
▪ Here, compRef is a reference to an instance of the control that you want to add. A
reference to the object is returned. Once a control has been added, it will
automatically be visible whenever its parent window is displayed.
▪ To remove a control from a window when the control is no longer needed, call
remove (). This method is also defined by Container. Here is one of its forms
void remove (Component compRef)
▪ Here, compRef is a reference to the control you want to remove. You can remove
all controls by calling removeAll().

The HeadlessException
▪ Most of the AWT controls constructors can throw a HeadlessException when an
attempt is made to instantiate a GUI component in a non-interactive
environment (such as one in which no display, mouse, or keyboard is present).
▪ You can use this exception to write code that can adapt to non-interactive
environments.

Labels
▪ The easiest control to use is a label. A label is an object of type Label, and it
contains a string, which it displays.
▪ Labels are passive controls that do not support any interaction with the user.
▪ Label defines the following constructors:

COMPILED BY: BAL KRISHNA NYAUPANE 6


1. Label (): It constructs an empty label.
2. Label (String text): It constructs a label with the given string (left justified by
default).
3. Label (String text, int alignement): It constructs a label with the specified
string and the specified alignment. The value of alignement must be one of
these three constants: [Link], [Link], or [Link].

▪ You can set the alignment of the string within the label by calling setAlignment().
▪ To obtain the current alignment, call getAlignment().
▪ The methods are as follows:
void setAlignment (int alignment)
int getAlignment()

Buttons
▪ The most widely used control is the push button. A push button is a component
that contains a label and generates an event when it is pressed.
▪ Push buttons are objects of type Button. Button defines these two constructors:
1. Button (): Constructs a button with an empty string for its label.
2. Button (String text): Constructs a new button with specified label.

COMPILED BY: BAL KRISHNA NYAUPANE 7


Checkbox Group
▪ It is possible to create a set of mutually exclusive check boxes in which one and
only one check box in the group can be checked at any one time. These check
boxes are often called radio buttons.
▪ To create a set of mutually exclusive check boxes, you must first define the group
to which they will belong and then specify that group when you construct the
check boxes. Check box groups are objects of type CheckboxGroup.
▪ Only the default constructor is defined, which creates an empty group
CheckboxGroup (): Creates a new instance of CheckboxGroup.
▪ You can determine which check box in a group is currently selected by calling
getSelectedCheckbox ().
▪ You can set a check box by calling setSelectedCheckbox().

COMPILED BY: BAL KRISHNA NYAUPANE 8


▪ These methods are as follows:
Checkbox getSelectedCheckbox ()
void setSelectedCheckbox (Checkbox which)
▪ Here, which is the check box that you want to be selected. The previously selected
check box will be turned off.

Checkbox
▪ Checkbox control is used to turn an option on(true) or off(false). There is label for
each checkbox representing what the checkbox does. The state of a checkbox can
be changed by clicking on it.
▪ Constructors for CheckBox
1. Checkbox (): Creates a check box with an empty string for its label.
2. Checkbox (String label): Creates a check box with the specified label.
3. Checkbox (String label, boolean state): Creates a check box with the specified
label and sets the specified state.
4. Checkbox (String label, boolean state, CheckboxGroup group): Constructs a
Checkbox with the specified label, set to the specified state, and in the
specified check box group.
5. Checkbox (String label, CheckboxGroup group, boolean state): Creates a
check box with the specified label, in the specified check box group, and set to
the specified state.

COMPILED BY: BAL KRISHNA NYAUPANE 9


COMPILED BY: BAL KRISHNA NYAUPANE 10
AWT Choice
▪ In Java, AWT contains a Choice Class. It is used for creating a drop-down menu of
choices. When a user selects a particular item from the drop-down then it is shown on the
top of the menu.
▪ Choice Class constructor
Choice (): It constructs a new choice menu.

AWT List
▪ The List class provides a compact, multiple-choice, scrolling selection list.
▪ Unlike the Choice object, which shows only the single selected item in the menu, a List
object can be constructed to show any number of choices in the visible window.
▪ AWT List Class Constructors
1. List (): It constructs a new scrolling list.
2. List (int row_num): It constructs a new scrolling list initialized with the given
number of rows visible.
3. List (int row_num, Boolean multipleMode): It constructs a new scrolling list
initialized which displays the given number of rows.
▪ For lists that allow only single selection, you can determine which item is currently
selected by calling either getSelectedItem( ) or getSelectedIndex( ).
▪ These methods are shown here:
String getSelectedItem( )
int getSelectedIndex( )
▪ The getSelectedItem() method returns a string containing the name of the item. If more
than one item is selected, or if no selection has yet been made, null is returned.
▪ The getSelectedIndex() returns the index of the item. The first item is at index 0. If more
than one item is selected, or if no selection has yet been made, –1 is returned.

COMPILED BY: BAL KRISHNA NYAUPANE 11


TextField
▪ The TextField class implements a single-line text-entry area, usually called an edit
control. Text fields allow the user to enter strings and to edit the text using the
arrow keys, cut and paste keys, and mouse selections.
▪ TextField is a subclass of TextComponent. TextField Class constructors
1. TextField(): It constructs a new text field component.
2. TextField(String text): It constructs a new text field initialized with the given
string text to be displayed.
3. TextField(int numChars): It constructs a new textfield (empty) with given
numChars characters.
4. TextField(String text, int numChars): It constructs a new text field with the
given text and given numChars characters wide.
▪ To obtain the string currently contained in the text field, call getText( ). To set the
text, call setText( ). These methods are as follows:
String getText()
void setText(String str)
▪ We can obtain the currently selected text by calling getSelectedText( ). These
methods are shown here:
String getSelectedText()
void select (int startIndex, int endIndex)

COMPILED BY: BAL KRISHNA NYAUPANE 12


▪ getSelectedText() returns the selected text. The select() method selects the
characters beginning at startIndex and ending at endIndex –1.
▪ You can control whether the contents of a text field may be modified by the user
by calling setEditable( ).
void setEditable(boolean canEdit)
▪ In setEditable(), if canEdit is true, the text may be changed. If it is false, the text
cannot be altered.

TextArea
▪ The AWT includes a simple multiline editor called TextArea.
▪ Constructors of TextArea are:
1. TextArea(): It constructs a new and empty text area with no text in it.
2. TextArea (int row, int column): It constructs a new text area with specified
number of rows and columns and empty string as text.
3. TextArea (String text): It constructs a new text area and displays the specified
text in it.
4. TextArea (String text, int row, int column): It constructs a new text area with
the specified text in the text area and specified number of rows and columns.
5. TextArea (String text, int row, int column, int scrollbars): It construcst a new
text area with specified text in text area and specified number of rows and
columns and visibility.
▪ Fields of TextArea Class: The fields of [Link] class are as follows:
• static int SCROLLBARS_BOTH: It creates and displays both horizontal and
vertical scrollbars.
• static int SCROLLBARS_HORIZONTAL_ONLY: It creates and displays only
the horizontal scrollbar.
• static int SCROLLBARS_VERTICAL_ONLY: It creates and displays only the
vertical scrollbar.
• static int SCROLLBARS_NONE: It doesn't create or display any scrollbar in
the text area.
▪ It supports the getText(), setText(), getSelectedText(), select(), isEditable(), and
setEditable() methods.

COMPILED BY: BAL KRISHNA NYAUPANE 13


COMPILED BY: BAL KRISHNA NYAUPANE 14
Understanding Layout Managers

FlowLayout
▪ FlowLayout implements a simple layout style, which is similar to how words flow
in a text editor.
▪ The direction of the layout is governed by the container’s component orientation
property, which, by default, is left to right, top to bottom. Therefore, by default,
components are laid out line-by-line beginning at the upper-left corner.
▪ In all cases, when a line is filled, layout advances to the next line. A small space is
left between each component, above and below, as well as left and right.
▪ The constructors for FlowLayout:
• FlowLayout()
• FlowLayout(int how)
• FlowLayout(int how, int horz, int vert)
▪ The first form creates the default layout, which centers components and leaves five
pixels of space between each component.
▪ The second form lets you specify how each line is aligned. Valid values for how
are as follows:
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
▪ These values specify left, center, right, leading edge, and trailing edge alignment,
respectively.
▪ The third constructor allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.

COMPILED BY: BAL KRISHNA NYAUPANE 15


BorderLayout
▪ The BorderLayout class implements a layout style that has four narrows, fixed
width components at the edges and one large area in the center.
▪ The four sides are referred to as north, south, east, and west. The middle area is
called the center.
▪ BorderLayout is the default layout manager for Frame.
▪ Here are the constructors defined by BorderLayout:
• BorderLayout()
• BorderLayout (int horz, int vert)
▪ The first form creates a default border layout. The second allows you to specify
the horizontal and vertical space left between components in horz and vert,
respectively.
▪ BorderLayout defines the following commonly used constants that specify the
regions:
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
▪ When adding components, you will use these constants with the following form of
add(), which is defined by Container:
void add(Component compRef, Object region)
▪ Here, compRef is a reference to the component to be added, and region specifies
where the component will be added.

COMPILED BY: BAL KRISHNA NYAUPANE 16


GridLayout
▪ GridLayout lays out components in a two-dimensional grid.
▪ When you instantiate a GridLayout, you define the number of rows and columns.
▪ The constructors supported by GridLayout are shown here:
• GridLayout ()
• GridLayout (int numRows, int numColumns)
• GridLayout (int numRows, int numColumns, int horz, int vert)
▪ The first form creates a single-column grid layout.
▪ The second form creates a grid layout with the specified number of rows and
columns.

COMPILED BY: BAL KRISHNA NYAUPANE 17


▪ The third form allows you to specify the horizontal and vertical space left
between components in horz and vert, respectively.
▪ Either numRows or numColumns can be zero. Specifying numRows as zero
allows for unlimited-length columns. Specifying numColumns as zero allows for
unlimited-length rows.

COMPILED BY: BAL KRISHNA NYAUPANE 18


GridBagLayout
▪ The key to the grid bag is that each component can be a different size, and each
row in the grid can have a different number of columns. This is why the layout is
called a grid bag. It’s a collection of small grids joined together.
▪ The location and size of each component in a grid bag are determined by a set of
constraints linked to it. The constraints are contained in an object of type
GridBagConstraints. Constraints include the height and width of a cell, and the
placement of a component, its alignment, and its anchor point within the cell.
▪ The general procedure for using a grid bag is to first create a new GridBagLayout
object and to make it the current layout manager. Then, set the constraints that
apply to each component that will be added to the grid bag. Finally, add the
components to the layout manager.
▪ GridBagLayout defines only one constructor, which is shown here:
GridBagLayout()
▪ The key to successfully using GridBagLayout is the proper setting of the
constraints, which are stored in a GridBagConstraints object. GridBagConstraints
defines several fields that you can set to govern the size, placement, and spacing
of a component.
▪ weightx and weighty: Controls how additional space in the row or column is
allotted to the component

COMPILED BY: BAL KRISHNA NYAUPANE 19


COMPILED BY: BAL KRISHNA NYAUPANE 20
COMPILED BY: BAL KRISHNA NYAUPANE 21
COMPILED BY: BAL KRISHNA NYAUPANE 22
CardLayout
▪ The CardLayout class is unique among the other layout managers in that it stores
several different layouts. Each layout can be thought of as being on a separate
index card in a deck that can be shuffled so that any card is on top at a given time.
▪ This can be useful for user interfaces with optional components that can be
dynamically enabled and disabled upon user input.
▪ You can prepare the other layouts and have them hidden, ready to be activated
when needed.
▪ CardLayout provides these two constructors:
• CardLayout()
• CardLayout (int horz, int vert)
▪ The first form creates a default card layout. The second form allows you to specify
the horizontal and vertical space left between components in horz and vert,
respectively.

COMPILED BY: BAL KRISHNA NYAUPANE 23


COMPILED BY: BAL KRISHNA NYAUPANE 24
Menu Bars and Menus
▪ A menu bar displays a list of top-level menu choices. Each choice is associated
with a dropdown menu. This concept is implemented in the AWT by the following
classes: MenuBar, Menu, and MenuItem.
▪ In general, a menu bar contains one or more Menu objects. Each Menu object
contains a list of MenuItem objects. Each MenuItem object represents something
that can be selected by the user.
▪ Since Menu is a subclass of MenuItem, a hierarchy of nested submenus can be
created. It is also possible to include checkable menu items. These are menu
options of type CheckboxMenuItem and will have a check mark next to them
when they are selected.
▪ To create a menu bar, first create an instance of MenuBar. This class defines only
the default constructor.
• MenuBar()

COMPILED BY: BAL KRISHNA NYAUPANE 25


▪ The constructors for Menu:
• Menu ()
• Menu (String optionName)
• Menu (String optionName, boolean removable)
▪ Here, optionName specifies the name of the menu selection. If removable is true,
the menu can be removed and allowed to float free. Otherwise, it will remain
attached to the menu bar.
▪ Individual menu items are of type MenuItem. It defines these constructors:
• MenuItem ()
• MenuItem (String itemName)
• MenuItem (String itemName, MenuShortcut keyAccel)
▪ Here, itemName is the name shown in the menu, and keyAccel is the menu
shortcut for this item.
▪ You can disable or enable a menu item by using the setEnabled() method.
void setEnabled(boolean enabledFlag)
▪ If the argument enabledFlag is true, the menu item is enabled. If false, the menu
item is disabled.
▪ You can determine an item’s status by calling isEnabled().
boolean isEnabled()
▪ isEnabled() returns true if the menu item on which it is called is enabled.
Otherwise, it returns false.
▪ You can change the name of a menu item by calling setLabel(). You can retrieve
the current name by using getLabel().
void setLabel (String newName)
String getLabel ()
▪ You can create a checkable menu item by using a subclass of MenuItem called
CheckboxMenuItem. It has these constructors:
• CheckboxMenuItem()
• CheckboxMenuItem (String itemName)
• CheckboxMenuItem (String itemName, boolean on)
▪ Here, itemName is the name shown in the menu. Checkable items operate as
toggles. Each time one is selected, its state changes. If on is true, the checkable
entry is initially checked. Otherwise, it is cleared.
▪ Once you have created a menu item, you must add the item to a Menu object by
using add (), which has the following general form:
MenuItem add (MenuItem item)
▪ Here, item is the item being added. Items are added to a menu in the order in
which the calls to add () take place. The item is returned.

▪ Once you have added all items to a Menu object, you can add that object to the
menu bar by using this version of add () defined by MenuBar:
Menu add (Menu menu)
▪ Here, menu is the menu being added. The menu is returned. Menus generate
events only when an item of type MenuItem or CheckboxMenuItem is selected.

COMPILED BY: BAL KRISHNA NYAUPANE 26


▪ They do not generate events when a menu bar is accessed to display a drop-down
menu, for example. Each time a menu item is selected, an ActionEvent object is
generated. By default, the action command string is the name of the menu item.
▪ Each time a check box menu item is checked or unchecked, an ItemEvent object is
generated. Thus, you must implement the ActionListener and/or ItemListener
interfaces in order to handle these menu events.

Dialog Box
▪ Dialog boxes are primarily used to obtain user input and are often child windows
of a top-level window. Dialog boxes don’t have menu bars, but in other respects,
they function like frame windows.
▪ The Dialog control represents a top-level window with a border and a title used to
take some form of input from the user. It inherits the Window class.
▪ Frame and Dialog both inherits Window class. Frame has maximized and
minimize buttons but Dialog doesn't have.
▪ In the AWT, dialog boxes are of type Dialog. Two commonly used constructors
are shown here:
• Dialog (Frame parentWindow, boolean mode)
• Dialog (Frame parentWindow, String title, boolean mode)
▪ Here, parentWindow is the owner of the dialog box. If mode is true, the dialog
box uses the default modality. Otherwise, it is modeless. The title of the dialog box
can be passed in title. Generally, you will subclass Dialog, adding the functionality
required by your application.

FileDialog
▪ The FileDialog class displays a dialog window from which the user can select a
file. Since it is a modal dialog, when the application calls its show method to
display the dialog, it blocks the rest of the application until the user has chosen a
file.
▪ Constructor Summary
• FileDialog (Frame parent, String title, int mode): Creates a file dialog
window with the specified title for loading or saving a file.
• FileDialog (Frame parent, String title): Creates a file dialog window with the
specified title for loading a file.
• FileDialog (Frame parent): Creates a file dialog for loading a file.
• FileDialog (Dialog parent): Creates a file dialog for loading a file.
• FileDialog (Dialog parent, String title): Creates a file dialog window with the
specified title for loading a file.
• FileDialog (Dialog parent, String title, int mode): Creates a file dialog
window with the specified title for loading or saving a file.
▪ If mode is [Link], then the box is selecting a file for reading.
▪ If mode is [Link], the box is selecting a file for writing.
▪ If mode is omitted, the box is selecting a file for reading.
▪ Common methods
• String getDirectory (): Gets the directory of this file dialog.

COMPILED BY: BAL KRISHNA NYAUPANE 27


• String getFile (): Gets the selected file of this file dialog.
• FilenameFilter getFilenameFilter(): Determines this file dialog's filename
filter.
• Int getMode (): Indicates whether this file dialog box is for loading from a file
or for saving to a file.
• String paramString (): Returns a string representing the state of this FileDialog
window.
• Void setDirectory (String dir): Sets the directory of this file dialog window to
be the specified directory.
• Void setFile(String file): Sets the selected file for this file dialog window to
be the specified file.
• Void setFilenameFilter (FilenameFilter filter): Sets the filename filter for
this file dialog window to the specified filter.
• Void setMode (int mode): Sets the mode of the file dialog.

COMPILED BY: BAL KRISHNA NYAUPANE 28


COMPILED BY: BAL KRISHNA NYAUPANE 29
Chapter 3
Event Handling

Two Event Handling Mechanisms


▪ The way in which events are handled changed significantly between the original
version of Java (1.0) and all subsequent versions of Java, beginning with version
1.1.
▪ Although the 1.0 method of event handling is still supported, it is not
recommended for new programs. Also, many of the methods that support the old
1.0 event model have been deprecated.
▪ The modern approach is the way that events should be handled by all new
programs.

The Delegation Event Model


▪ The modern approach to handling events is based on the delegation event model,
which defines standard and consistent mechanisms to generate and process events.
▪ Its concept is quite simple: a source generates an event and sends it to one or
more listeners. In this scheme, the listener simply waits until it receives an event.
Once an event is received, the listener processes the event and then returns.
▪ The advantage of this design is that the application logic that processes events is
cleanly separated from the user interface logic that generates those events.
▪ A user interface element is able to “delegate” the processing of an event to a
separate piece of code.
▪ In the delegation event model, listeners must register with a source in order to
receive an event notification. This provides an important benefit: notifications are
sent only to listeners that want to receive them.

Events
▪ In the delegation model, an event is an object that describes a state change in a
source. An event can be generated as a consequence of a person interacting with
the elements in a graphical user interface.
▪ Some of the activities that cause events to be generated are pressing a button,
entering a character via the keyboard, selecting an item in a list, and clicking the
mouse. Events may also occur that are not directly caused by interactions with a
user interface.
▪ For example, an event may be generated when a timer expires, a counter exceeds
a value, software or hardware failure occurs, or an operation is completed.

COMPILED BY: BAL KRISHNA NYAUPANE 1


Event Sources
▪ A source is an object that generates an event. This occurs when the internal state
of that object changes in some way. Sources may generate more than one type of
event.
▪ A source must register listeners in order for the listeners to receive notifications
about a specific type of event.
▪ Each type of event has its own registration method. Here is the general form:

COMPILED BY: BAL KRISHNA NYAUPANE 2


Event Listeners
▪ A listener is an object that is notified when an event occurs. It has two major
requirements.
• First, it must have been registered with one or more sources to receive
notifications about specific types of events.
• Second, it must implement methods to receive and process these
notifications. In other words, the listener must supply the event handlers.
▪ The methods that receive and process events are defined in a set of interfaces,
such as those found in [Link].
▪ For example, the MouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved. Any object may handle one or
both of these events if it provides an implementation of this interface.

Event Classes
▪ The classes that represent events are at the core of Java’s event handling
mechanism. Thus, a discussion of event handling must begin with the event
classes.
▪ Arguably, the most widely used events at the time of this writing are those defined
by the AWT and those defined by Swing.
▪ This chapter focuses on the AWT events. Most of these events also apply to
Swing.
▪ The package [Link] defines many types of events that are generated by
various user interface elements. The below table shows several commonly used
event classes and provides a brief description of when they are generated.

COMPILED BY: BAL KRISHNA NYAUPANE 3


COMPILED BY: BAL KRISHNA NYAUPANE 4
COMPILED BY: BAL KRISHNA NYAUPANE 5
COMPILED BY: BAL KRISHNA NYAUPANE 6
COMPILED BY: BAL KRISHNA NYAUPANE 7
COMPILED BY: BAL KRISHNA NYAUPANE 8
COMPILED BY: BAL KRISHNA NYAUPANE 9
COMPILED BY: BAL KRISHNA NYAUPANE 10
▪ The delegation event model has two parts: sources and listeners. Listeners are
created by implementing one or more of the interfaces defined by the
[Link] package.
▪ When an event occurs, the event source invokes the appropriate method defined by
the listener and provides an event object as its argument.

COMPILED BY: BAL KRISHNA NYAUPANE 11


COMPILED BY: BAL KRISHNA NYAUPANE 12
COMPILED BY: BAL KRISHNA NYAUPANE 13
▪ Using the delegation event model is actually quite easy. Just follow these two
steps:
1. Implement the appropriate interface in the listener so that it can receive the
type of event desired.
2. Implement code to register and unregister (if necessary) the listener as a
recipient for the event notifications.
▪ Remember that a source may generate several types of events. Each event must be
registered separately. Also, an object may register to receive several types of
events, but it must implement all of the interfaces that are required to receive these
events.
▪ To see how the delegation model works in practice, we will look at examples that
handle two commonly used event generators: the mouse and keyboard.

COMPILED BY: BAL KRISHNA NYAUPANE 14


COMPILED BY: BAL KRISHNA NYAUPANE 15
COMPILED BY: BAL KRISHNA NYAUPANE 16
Flow of Event Handling
1. User Interaction with a component is required to generate an event.
2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.
3. The newly created object is passed to the methods of the registered listener.
4. The method executes and returns the result.

Code-Approaches
The three approaches for performing event handling are by placing the event handling
code in one of the below-specified places.
1. Within Class
2. Other Class
3. Anonymous Class

COMPILED BY: BAL KRISHNA NYAUPANE 17


COMPILED BY: BAL KRISHNA NYAUPANE 18
COMPILED BY: BAL KRISHNA NYAUPANE 19
COMPILED BY: BAL KRISHNA NYAUPANE 20
COMPILED BY: BAL KRISHNA NYAUPANE 21
COMPILED BY: BAL KRISHNA NYAUPANE 22
COMPILED BY: BAL KRISHNA NYAUPANE 23
COMPILED BY: BAL KRISHNA NYAUPANE 24
COMPILED BY: BAL KRISHNA NYAUPANE 25
COMPILED BY: BAL KRISHNA NYAUPANE 26
Adapter Class
▪ Java provides a special feature, called an adapter class, that can simplify the
creation of event handlers in certain situations.
▪ An adapter class provides an empty implementation of all methods in an event
listener interface. Adapter classes are useful when you want to receive and process
only some of the events that are handled by a particular event listener interface. You
can define a new class to act as an event listener by extending one of the adapter
classes and implementing only those events in which you are interested.

COMPILED BY: BAL KRISHNA NYAUPANE 27


▪ For example, the MouseMotionAdapter class has two methods, mouseDragged()
and mouseMoved(), which are the methods defined by the MouseMotionListener
interface. If you were interested in only mouse drag events, then you could simply
extend MouseMotionAdapter and override mouseDragged(). The empty
implementation of mouseMoved() would handle the mouse motion events for you.

COMPILED BY: BAL KRISHNA NYAUPANE 28


COMPILED BY: BAL KRISHNA NYAUPANE 29
COMPILED BY: BAL KRISHNA NYAUPANE 30
COMPILED BY: BAL KRISHNA NYAUPANE 31
Chapter – 4 and 5
Java Swing
Java AWT problems
1. First, because of variations between operating systems, a component might
look, or even act, differently on different platforms. This potential variability
threatened the overarching philosophy of Java: write once, run anywhere.
2. Second, the look and feel of each component was fixed (because it is defined
by the platform) and could not be (easily) changed.
3. Third, the use of heavyweight components caused some frustrating restrictions.
For example, a heavyweight component was always opaque.
▪ The solution was Swing. Introduced in 1997, Swing was included as part of the Java
Foundation Classes (JFC). Swing was initially available for use with Java 1.1 as a
separate library.
▪ Swing is built on the foundation of the AWT. This is why the AWT is still a crucial
part of Java. Swing also uses the same event handling mechanism as the AWT.
Therefore, a basic understanding of the AWT and of event handling is required to
use Swing.

Two Key Swing Features


1. Swing Components Are Lightweight: This means that they are written entirely
in Java and do not map directly to platform-specific peers. Thus, lightweight
components are more efficient and more flexible. Furthermore, because
lightweight components do not translate into native peers, the look and feel of
each component is determined by Swing, not by the underlying operating
system. As a result, each component will work in a consistent manner across all
platforms.

2. Swing Supports a Pluggable Look and Feel: Each Swing component is


rendered by Java code rather than by native peers, the look and feel of a
component is under the control of Swing. Advantages of Pluggable look-and-
feels
• Possible to define a look and feel that is consistent across all platforms.
• It is also possible to design a custom look and feel.
• The look and feel can be changed dynamically at run time.
Java provides look-and-feels, such as metal and Nimbus. The metal look and
feel is also called the Java look and feel. Default Java look and feel is metal
because it is platform independent.

COMPILED BY: BAL KRISHNA NYAUPANE 1


The MVC Connection
In general, a visual component is a composite of three distinct aspects:
• The way that the component looks when rendered on the screen.
• The way that the component reacts to the user.
• The state information associated with the component.
Over the years, one component architecture has proven itself to be exceptionally
effective: Model-View-Controller, or MVC for short. In MVC terminology,
• Model: The model corresponds to the state information associated with the
component. For example, in the case of a check box, the model contains a field
that indicates if the box is checked or unchecked.
• View: The view determines how the component is displayed on the screen,
including any aspects of the view that are affected by the current state of the
model.
• Controller: The controller determines how the component reacts to the user. For
example, when the user clicks a check box, the controller reacts by changing the
model to reflect the user’s choice (checked or unchecked).
Swing uses a modified version of MVC that combines the view and the controller into
a single logical entity called the UI delegate.
Swing’s approach is called either the Model-Delegate architecture or the Separable
Model architecture. Swing’s pluggable look and feel is made possible by its Model-
Delegate architecture.
To support the Model-Delegate architecture, most Swing components contain two
objects. The first represents the model. The second represents the UI delegate. Models
are defined by interfaces.

Components and Containers


A Swing GUI consists of two key items: components and containers.
• The difference between the two is found in their intended purpose: As the term
is commonly used, a component is an independent visual control, such as a
push button or slider.
• A container holds a group of components. Thus, a container is a special type
of component that is designed to hold other components.
• Furthermore, in order for a component to be displayed, it must be held within a
container. Thus, all Swing GUIs will have at least one container.
• Because containers are components, a container can also hold other
containers. This enables Swing to define what is called a containment
hierarchy, at the top of which must be a top-level container.

COMPILED BY: BAL KRISHNA NYAUPANE 2


Components
• In general, Swing components are derived from the JComponent class.
• JComponent provides the functionality that is common to all components. For
example, JComponent supports the pluggable look and feel.
• JComponent inherits the AWT classes Container and Component. Thus, a
Swing component is built on and compatible with an AWT component.
• All of Swing’s components are represented by classes defined within the
package [Link].
• The following table shows the class names for Swing components (including
those used as containers).

Containers: Swing defines two types of containers.


1. The first are top-level containers: JFrame, JApplet, JWindow, and JDialog.
These containers do not inherit JComponent. They do, however, inherit the
AWT classes Component and Container. Unlike Swing’s other components,
which are lightweight, the top-level containers are heavyweight. This makes
the top-level containers a special case in the Swing component library.
2. The second type of containers supported by Swing are lightweight containers.
Lightweight containers do inherit JComponent. An example of a lightweight
container is JPanel, which is a general-purpose container.
▪ Lightweight containers are often used to organize and manage groups of related
components because a lightweight container can be contained within another
container. Thus, you can use lightweight containers such as JPanel to create
subgroups of related controls that are contained within an outer container.
▪ Each top-level container defines a set of panes. At the top of the hierarchy is an
instance of JRootPane. JRootPane is a lightweight container whose purpose is to

COMPILED BY: BAL KRISHNA NYAUPANE 3


manage the other panes. It also helps manage the optional menu bar. The panes
that comprise the root pane are called the glass pane, the content pane, and the
layered pane.

COMPILED BY: BAL KRISHNA NYAUPANE 4


Java Swing Examples

COMPILED BY: BAL KRISHNA NYAUPANE 5


COMPILED BY: BAL KRISHNA NYAUPANE 6
JComboBox
▪ JComboBox inherits JComponent class. 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.
▪ JComboBox shows a popup menu that shows a list and the user can select an option
from that specified list.
▪ JComboBox can be editable or read- only depending on the choice of the
programmer.

COMPILED BY: BAL KRISHNA NYAUPANE 7


▪ Constructors of the JComboBox are:
1. JComboBox() : creates a new empty JComboBox .
2. JComboBox(ComboBoxModel M) : creates a new JComboBox with items
from specified ComboBoxModel
3. JComboBox(E [] items) : creates a new JComboBox with items. Here items
is an array that initializes the combo box.
4. JComboBox(Vector items) : creates a new JComboBox with items from the
specified vector
▪ Some commonly used Methods are:
1. addItem(E item): adds the item to the JComboBox
2. addItemListener(ItemListener l) : adds a ItemListener to JComboBox
3. getItemAt(int i): returns the item at index i.
4. getItemCount(): returns the number of items from the list
5. getSelectedItem(): returns the item which is selected
6. removeItemAt(int i): removes the element at index i
7. setEditable(boolean b): the boolean b determines whether the combo box is
editable or not .If true is passed then the combo box is editable or vice versa.
8. setSelectedIndex(int i): selects the element of JComboBox at index i.
9. showPopup(): causes the combo box to display its popup window.
10. setEnabled(boolean b): enables the combo box so that items can be selected.
11. removeItem(Object anObject): removes an item from the item list.
12. getItemCount(): returns the number of items in the list.

COMPILED BY: BAL KRISHNA NYAUPANE 8


COMPILED BY: BAL KRISHNA NYAUPANE 9
JList
▪ A JComboBox is a component that displays a drop-down list and gives users
options that we can select one and only one item at a time whereas a JList shows
multiple items (rows) to the user and also gives an option to let the user select
multiple items.
▪ A JList is a component that allows the user to choose either a single selection or
multiple selections.
▪ A JList class itself does not support scrollbar. In order to add scrollbar, we have to
use JScrollPane class together with the JList class. The JScrollPane then manages a
scrollbar automatically.
▪ A getSelectedIndex() method returns the index of the first selected item or –1 if no
items are selected and getSelectedIndexes() method returns an array with the index
of each selected item. The array is empty if no items are selected.
▪ A getSelectedValue() returns the first selected item or null if no items are selected.
▪ A DefaultListModel class provides a simple implementation of a list model, which
can be used to manage items displayed by a JList control.
▪ JList inherits JComponent class. JList was made generic and is now declared like
this:
class JList<E>
Here, E represents the type of the items in the list.

COMPILED BY: BAL KRISHNA NYAUPANE 10


COMPILED BY: BAL KRISHNA NYAUPANE 11
ImageIcon
▪ Icon is small fixed size picture, typically used to decorate components. ImageIcon
is an implementation of the Icon interface that paints icons from images. Images
can be created from a URL, filename, or byte array.
▪ 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.

COMPILED BY: BAL KRISHNA NYAUPANE 12


▪ ImageIcon constructors: ImageIcon has several constructors, including:
• ImageIcon(byte[] imageData): creates an ImageIcon from an array of
bytes.
• ImageIcon(Image image): creates an ImageIcon from an image object.
• ImageIcon(String filename): creates an ImageIcon the specified file.
• ImageIcon(URL location): creates an ImageIcon from the specified URL.
▪ ImageIcon can work with PNG, JPEG, and GIF images. If we want to work with
BMP or ICO images, we can use the image4j library.

COMPILED BY: BAL KRISHNA NYAUPANE 13


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 which are
JCheckBox and JRadioButton.
▪ Constructors in JToggleButton:
1. JToggleButton(): Creates an initially unselected toggle button without setting
the text or image.
2. JToggleButton(Action a): Creates a toggle button where properties are taken
from the Action supplied.
3. JToggleButton(Icon icon): Creates an initially unselected toggle button with
the specified image but no text.
4. JToggleButton(Icon icon, boolean selected): Creates a toggle button with the
specified image and selection state, but no text.
5. JToggleButton(String text): Creates an unselected toggle button with the
specified text.
6. JToggleButton(String text, boolean selected): Creates a toggle button with the
specified text and selection state.
7. JToggleButton(String text, Icon icon): Creates a toggle button that has the
specified text and image, and that is initially unselected.
8. JToggleButton(String text, Icon icon, boolean selected): Creates a toggle
button with the specified text, image, and selection state.

JCheckBox
▪ The JCheckBox class provides the functionality of a check box. Its immediate
superclass is JToggleButton, which provides support for two-state buttons.
▪ 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.
▪ Constructor of the class are:
1. JCheckBox(): creates a new checkbox with no text or icon
2. JCheckBox(Icon i): creates a new checkbox with the icon specified

COMPILED BY: BAL KRISHNA NYAUPANE 14


3. JCheckBox(Icon icon, boolean s): creates a new checkbox with the icon
specified and the boolean value specifies whether it is selected or not.
4. JCheckBox(String t): creates a new checkbox with the string specified
5. JCheckBox(String text, boolean selected): creates a new checkbox with the
string specified and the boolean value specifies whether it is selected or not.
6. JCheckBox(String text, Icon icon): creates a new checkbox with the string and
the icon specified.
7. JCheckBox(String text, Icon icon, boolean selected): creates a new checkbox
with the string and the icon specified and the boolean value specifies whether it
is selected or not.

JRadioButton
▪ 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.
▪ 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.
▪ 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.

COMPILED BY: BAL KRISHNA NYAUPANE 15


COMPILED BY: BAL KRISHNA NYAUPANE 16
COMPILED BY: BAL KRISHNA NYAUPANE 17
Java JOptionPane
▪ JOptionPane is a subclass of JComponent which includes static methods for
creating and customizing modal dialog boxes using a simple code.
▪ JOptionPane displays the dialog boxes with one of the four standard icons
(question, information, warning, and error) or the custom icons specified by the
user. The JOptionPane class is used to provide standard dialog boxes such as
message dialog box, confirm dialog box and input dialog box. These dialog boxes
are used to display information or get input from the user.
▪ Some of the constructors defined by the JOptionPane class are as follows.
• JOptionPane ()
• JOptionPane (Object message)
• JOptionPane (Object message, int messageType)
• JOptionPane (Object message, int messageType, int optionType)
• JOPtionPane (Object message, int messageType, int optionType, Icon icon)
• JOPtionPane (Object message, int messageType, int optionType, Icon icon,
Object [] options)
• JOPtionPane (Object message, int messageType, int optionType, Icon icon,
Object [] options, Object initialValue)

COMPILED BY: BAL KRISHNA NYAUPANE 18


▪ Where,
• message is the message to be displayed in the dialog box
• messageType specifies the type of the message to be displayed. It has various
values which are represented as: ERROR_MESSAGE,
INFORMATION_MESSAGE, WARNING_MESSAGE,
QUESTION_MESSAGE or PLAIN_MESSAGE.
▪ optionType is used to specify the options. It can have various values which are
represented as: DEFAULT_OPTION, YES_NO_OPTION,
YES_NO_CANCEL_OPTION or OK_CANCEL_OPTION icon specifies the icon
to be displayed.
▪ options are an array of options to be displayed in the dialog box with none of them
selected initial Value specifies the default option selected from the list provided in
options.
▪ JOptionPane class is used to display four types of dialog boxes namely,
1. MessageDialog: dialog box that displays a message making it possible to add
icons to alert the user.
2. ConfirmDialog: dialog box that besides sending a message, enables the user to
answer a question.
3. InputDialog: dialog box that besides sending a message, allows entry of a text.
4. OptionDialog: dialog box that covers the three previous types.

COMPILED BY: BAL KRISHNA NYAUPANE 19


COMPILED BY: BAL KRISHNA NYAUPANE 20
JPanel
▪ The JPanel is a simplest container class. It provides space in which an application
can attach any other component. It inherits the JComponents class.
▪ A panel is a lightweight container that is designed to group a set of components,
including other panels. It is visually represented as window that does not contain a
title bar, menu bar or border. It is simplest of all the containers. Its default layout
manager is FlowLayout.
▪ After the panel has been created, other components can be added to JPanel object
by calling it add (component) method inherited from the Container class.
▪ Commonly used Constructors:
1. JPanel(): It is used to create a new JPanel with a double buffer and a flow
layout.
2. JPanel(boolean isDoubleBuffered): It is used to create a new JPanel with
FlowLayout and the specified buffering strategy.
3. JPanel(LayoutManager layout): It is used to create a new JPanel with the
specified layout manager.
▪ Normally we create new JPanel object as simple as follows:
JPanel newPanel = new JPanel();

COMPILED BY: BAL KRISHNA NYAUPANE 21


COMPILED BY: BAL KRISHNA NYAUPANE 22
JTabbedPane
▪ JTabbedPane in Swing enables you to group several swing components groups on
the same container. To view a particular component group, you need to select the
tab corresponding to the component group in the tabbed pane.
▪ 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.
▪ To create a tabbed pane, create an instance of JTabbedPane class and add various
tabs to it using the addTab() method of JTabbedPane class.
▪ JTabbedPane defines three constructors. We will use its default constructor,
which creates an empty control with the tabs positioned across the top of the pane.
The other two constructors let you specify the location of the tabs, which can be
along any of the four sides.
▪ JTabbedPane uses the SingleSelectionModel model.
▪ JTabbedPane Constructor
1. JTabbedPane(): Creates an empty TabbedPane with a default tab placement of
[Link].
2. JTabbedPane(int tabPlacement): Creates an empty TabbedPane with a
specified tab placement. Creates an empty TabbedPane with the specified tab
placement of either: [Link], [Link],
[Link], or [Link].
3. JTabbedPane(int tabPlacement, int tabLayoutPolicy): Creates an empty
TabbedPane with a specified tab placement and tab layout policy.

COMPILED BY: BAL KRISHNA NYAUPANE 23


COMPILED BY: BAL KRISHNA NYAUPANE 24
COMPILED BY: BAL KRISHNA NYAUPANE 25
COMPILED BY: BAL KRISHNA NYAUPANE 26
JTable
▪ JTable is a component that displays rows and columns of data. You can drag the
cursor on column boundaries to resize columns. You can also drag a column to a
new position.
▪ Depending on its configuration, it is also possible to select a row, column, or cell
within the table, and to change the data within a cell.
▪ It is a component that consists of one or more columns of information. At the top
of each column is a heading. In addition to describing the data in a column, the

COMPILED BY: BAL KRISHNA NYAUPANE 27


heading also provides the mechanism by which the user can change the size of a
column or change the location of a column within the table.
▪ JTable does not provide any scrolling capabilities of its own. Instead, you will
normally wrap a JTable inside a JScrollPane.
▪ Constructors in JTable:
1. JTable(): A table is created with empty cells.
2. JTable(int rows, int cols): Creates a table of size rows * cols.
3. JTable(Object[][] data, Object []Column): A table is created with the specified
name where []Column defines the column names.
▪ Functions in JTable:
1. addColumn(TableColumn []column): adds a column at the end of the JTable.
2. clearSelection(): Selects all the selected rows and columns.
3. editCellAt(int row, int col): edits the intersecting cell of the column number col
and row number row programmatically, if the given indices are valid and the
corresponding cell is editable.
4. setValueAt(Object value, int row, int col): Sets the cell value as ‘value’ for the
position row, col in the JTable.

COMPILED BY: BAL KRISHNA NYAUPANE 28


COMPILED BY: BAL KRISHNA NYAUPANE 29
COMPILED BY: BAL KRISHNA NYAUPANE 30
COMPILED BY: BAL KRISHNA NYAUPANE 31
COMPILED BY: BAL KRISHNA NYAUPANE 32
COMPILED BY: BAL KRISHNA NYAUPANE 33
COMPILED BY: BAL KRISHNA NYAUPANE 34
COMPILED BY: BAL KRISHNA NYAUPANE 35
COMPILED BY: BAL KRISHNA NYAUPANE 36
Chapter 6
Java Applet
▪ An applet is a Java program that can be embedded into a web page. It runs inside
the web browser and works at client side.
▪ An applet is embedded in an HTML page using the APPLET or OBJECT tag and
hosted on a web server.
▪ Applets are used to make the website more dynamic and entertaining.
▪ To create an applet, a class must class extends [Link] class.
▪ An Applet class does not have any main () method. It is viewed using JVM. The
JVM can use either a plug-in of the Web browser or a separate runtime
environment to run an applet application. JVM creates an instance of the applet
class and invokes init() method to initialize an Applet.
▪ Note: Java Applet is deprecated since Java 9. It means Applet API is no longer
considered important.
▪ Important points:
• All applets are sub-classes (either directly or indirectly) of [Link]
class.
• Applets are not stand-alone programs. Instead, they run within either a web
browser or an applet viewer. JDK provides a standard applet viewer tool called
applet viewer.
• In general, execution of an applet does not begin at main () method.
• Output of an applet window is not performed by [Link](). Rather it
is handled with various AWT methods, such as drawString().
▪ There are some important differences between an applet and a standalone Java
application, including the following –
• An applet is a Java class that extends the [Link] class.
• A main () method is not invoked on an applet, and an applet class will
not define main ().
• Applets are designed to be embedded within an HTML page.
• When a user views an HTML page that contains an applet, the code for
the applet is downloaded to the user's machine.
• A JVM is required to view an applet. The JVM can be either a plug-in of
the Web browser or a separate runtime environment.
• The JVM on the user's machine creates an instance of the applet class
and invokes various methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser.
The security of an applet is often referred to as sandbox security,
comparing the applet to a child playing in a sandbox with various rules
that must be followed.
• Other classes that the applet needs can be downloaded in a single Java
Archive (JAR) file.
COMPILED BY: BAL KRISHNA NYAUPANE 1
Life cycle of an Applet
▪ When an applet begins, the following methods are called, in this sequence:
1. init ()
2. start ()
3. paint ()
▪ When an applet is terminated, the following sequence of method calls takes place:
1. stop ()
2. destroy ()

1. init(): This method is intended for whatever initialization is needed for your applet.
It is called after the param tags inside the applet tag have been processed. This
method is called only once during the run time of your applet.

2. start (): This method is automatically called after the browser calls the init method.
It is also called to restart an applet after it has been stopped. Note that init () is called
once i.e., when the first time an applet is loaded whereas start () is called each time
an applet’s HTML document is displayed onscreen. It is also called whenever the
user returns to the page containing the applet after having gone off to other pages.

3. paint (): Invoked immediately after the start () method, and also any time the applet
needs to repaint itself in the browser. For example, the window in which the applet
is running may be overwritten by another window and then uncovered. Or the applet
window may be minimized and then restored. Whatever the cause, whenever the
applet must redraw its output, paint () is called. The paint () method has one
parameter of type Graphics. This parameter will contain the graphics context,
which describes the graphics environment in which the applet is running. This

COMPILED BY: BAL KRISHNA NYAUPANE 2


context is used whenever output to the applet is required. Its prototype is
public void paint (Graphics g); where g is an object reference of class Graphic.

4. stop (): The stop () method is called when a web browser leaves the HTML
document containing the applet—when it goes to another page, for example. When
stop () is called, the applet is probably running. You should use stop () to suspend
threads that don’t need to run when the applet is not visible. You can restart them
when start () is called if the user returns to the page.

5. destroy (): This method is only called when the browser shuts down normally.
destroy () method is called when your applet needs to be removed completely from
memory.
Advantage of Applet
▪ There are many advantages of applet. They are as follows:
• It is simple to make it work on Linux, Windows and Mac OS i.e., to make it
cross platform.
• It is supported by most web browsers.
• It will cache in most web browsers, so will be quick to load when returning
to a web page but may get stuck in the cache and have issues when new
versions come out.
• It can have full access to the machine it is running on if the user agrees.
• It can improve with use: after a first applet is run, the JVM is already
running and starts quickly, benefitting regular users of Java but the JVM
will need to restart each time the browser starts fresh.
• It can run at a comparable (but generally slower) speed to other compiled
languages such as C++, but many times faster than JavaScript.
• It can move the work from the server to the client, making a web solution
more scalable with the number of users/clients.
Drawback of Applet
• It requires the Java plug-in, which isn't available by default on all web
browsers.
• Some browsers, notably mobile browsers running Apple iOS or Android do
not run Java applets at all.
• It cannot start until the Java Virtual Machine is running, and this may have
significant startup time the first time it is used.
• If untrusted, it has severely limited access to the user's system - in particular
having no direct access to the client's disk or clipboard.
• Some organizations only allow software installed by the administrators. As
a result, many users cannot view applets by default.
• Applets may require a specific JRE.

COMPILED BY: BAL KRISHNA NYAUPANE 3


Two Types of Applets
▪ It is important to state at the outset that there are two varieties of applets based on
Applet.
• The first are those based directly on the Applet class. These applets use the
Abstract Window Toolkit (AWT) to provide the graphical user interface (or
use no GUI at all). This style of applet has been available since Java was
first created.
• The second type of applets are those based on the Swing class JApplet,
which inherits Applet. Swing applets use the Swing classes to provide the
GUI. Swing offers a richer and often easier-to-use user interface than does
the AWT.
▪ Thus, both AWT- and Swing-based applets are valid.

Applet Skeleton

COMPILED BY: BAL KRISHNA NYAUPANE 4


HTML Applet Tags
▪ The <applet> tag in HTML was used to embed Java applets into any HTML
document. The <applet> tag was deprecated in HTML 4.01, and its support has
been completely discontinued starting from HTML 5. Alternatives available in
HTML 5 are the <embed> and the <object> tags.

Specifying Applet Parameters


▪ User-define Parameter can be applied in applet using <PARAM…> tags. Each
<PARAM…> tag has a name and value attribute.
Syntax: <PARAM name = ……… Value = “………” >

COMPILED BY: BAL KRISHNA NYAUPANE 5


▪ In an applet code, applet can refer to a parameter by its name and then find its
value. The two most important thing to handle and set up the parameter is the
<PARAM> tag in the HTML document and an applet code to parse this parameter.
▪ init () method is used to get hold of the parameters which is defined in the
<PARAM> tags. And getParameter () method is used for getting the parameters.
▪ In Applet, Parameters are passed on applet when it is loaded.

COMPILED BY: BAL KRISHNA NYAUPANE 6


COMPILED BY: BAL KRISHNA NYAUPANE 7
COMPILED BY: BAL KRISHNA NYAUPANE 8
Chapter 7
JDBC

Introduction to SQL
▪ Structured Query Language (SQL)
▪ SQL is an ANSI (American National Standards Institute) standard computer
language for accessing and manipulating database systems.
▪ SQL works with database programs like MS Access, DB2, Informix, MySQL,
SQL Server, Oracle, Sybase, etc.
▪ Most of the SQL database programs also have their own proprietary extensions
in addition to the SQL standard.

SQL: Syntax for Creating Table

COMPILED BY: BAL KRISHNA NYAUPANE 1


COMPILED BY: BAL KRISHNA NYAUPANE 2
COMPILED BY: BAL KRISHNA NYAUPANE 3
Modification of the Database

COMPILED BY: BAL KRISHNA NYAUPANE 4


Introduction to JDBC
▪ JDBC stands for Java Database Connectivity.
▪ JDBC is a Java API to connect and execute the query with the database. It is a
part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect
with the database.
▪ JDBC is a Java database connectivity technology from Oracle Corporation. This
technology is an API for the Java programming language that defines how a client
may access a database. It provides methods for querying and updating data in a
database.
▪ JDBC is oriented towards relational databases. A JDBC-to-ODBC bridge enables
connections to any ODBC-accessible data source in the JVM host environment.

COMPILED BY: BAL KRISHNA NYAUPANE 5


Why JDBC?

Architecture of JDBC

▪ Application: It is a java applet or a servlet that communicates with a data source.


▪ The JDBC API: The JDBC API allows Java programs to execute SQL statements
and retrieve results. Some of the important classes and interfaces defined in JDBC
API are as follows:
• Driver Manager
• Driver

COMPILED BY: BAL KRISHNA NYAUPANE 6


• Connection
• Statement
• PreparedStatement
• CallableStatement
• ResultSet
• SQL data
▪ Driver Manager: It plays an important role in the JDBC architecture. It uses some
database-specific drivers to effectively connect enterprise applications to databases.
▪ JDBC drivers: To communicate with a data source through JDBC, you need a JDBC
driver that intelligently communicates with the respective data source.

Type of JDBC drivers


▪ JDBC drivers are client-side adapters (installed on the client machine, not on the
server) that convert requests from Java programs to a protocol that the DBMS can
understand.
▪ There are commercial and free drivers available for most relational database
servers. JDBC technology drivers fit into one of four categories.
1. JDBC-ODBC bridge driver
2. Native-API Driver (Partially Java Driver)
3. Network-Protocol Driver (Fully Java Driver)
4. Thin Driver (Fully Java Driver)

▪ Advantages
1. Easy to use.
2. Can be easily connected to any database.

COMPILED BY: BAL KRISHNA NYAUPANE 7


▪ Disadvantages
1. Performance degraded because JDBC method call is converted into the
ODBC function.
2. The ODBC driver needs to be installed on the client machine.

Advantages:
• As there is no implementation of JDBC-ODBC bridge, its considerably faster
than a type 1 driver.
Disadvantages:
• The native driver needs to be installed on each client machine.
• The vendor client library needs to be installed on the client machine.

COMPILED BY: BAL KRISHNA NYAUPANE 8


Advantage
1. No client-side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.
Disadvantage
1. Network support is required on client machine.
2. Requires database-specific coding to be done in the middle tire.
3. Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tire.

Advantage
1. Completely implemented in Java to achieve platform independence.
2. These drivers don’t translate the requests into an intermediary format (such as
ODBC).
3. Better performance than all other drivers.
4. No software is required at client side or server side.
Disadvantage
1. Drivers are database dependent, as different database vendors use widely
different (and usually proprietary) network protocols.

COMPILED BY: BAL KRISHNA NYAUPANE 9


JDBC Architecture: Two-Tier Architecture
▪ A Java applet or application communicates directly with the data source in the
two-tier paradigm. This necessitates the use of a JDBC driver that can interface
with the data source in question.
▪ The user’s commands are transmitted to the database or other data source, and the
statements’ results are returned to the user. The data source could be on another
machine to which the user has a network connection.
▪ A client/server configuration is one in which the user’s machine acts as the client
and the system that houses the data source acts as the server. An intranet, for
example, can connect people within a company, or the Internet can be used as the
network.

JDBC Architecture: Three-Tier Architecture


▪ Commands are sent to a “middle tier” of services in the three-tier paradigm, which
subsequently transmits the commands to the data source.
▪ The data source interprets the commands and provides the results to the middle
tier, which ultimately passes them on to the user.
▪ The three-tier architecture appeals to MIS directors because the intermediate tier
allows them to maintain control over access and the types of changes that can be
made to company data.
▪ Another benefit is that it makes application deployment easier. Finally, the three-
tier architecture can bring performance benefits in many circumstances.

COMPILED BY: BAL KRISHNA NYAUPANE 10


Common JDBC Components

COMPILED BY: BAL KRISHNA NYAUPANE 11


Steps to connect Java program and database

COMPILED BY: BAL KRISHNA NYAUPANE 12


1. Loading the Driver
▪ We first need to load the driver or register it before using it in the program.
There should be registration once in your program.
▪ [Link](): In this, we load the driver’s class file into memory during
runtime. There is no need to use a new operator for the creation of an object.
▪ To load the Oracle driver:
[Link](“[Link]”);
▪ To load the MySQL driver:
[Link](“[Link].”);

2. Create the connections


▪ After loading the driver, we need to establish connections using the following
code:
Connection con = [Link](url, user, password)
▪ user: username from which sql command prompt can be accessed.
▪ password: password from which sql command prompt can be accessed.
▪ url: Uniform Resource Locator. We can create it as follows:
• String url = “jdbc:oracle:thin:@localhost:1521:xe”
• Where oracle is the database, thin is the driver, @localhost is the IP
Address where the database is stored, 1521 is the port number, and xe is
the service provider

COMPILED BY: BAL KRISHNA NYAUPANE 13


3. Create a statement
▪ Once you establish a connection, you can interact with the database.
▪ Three types of Statements

PreparedStatement: this represents precompiled sql/my sql statement which allows


improved performance. It allows to execute the query multiple times and we can set
the values according to our need.

COMPILED BY: BAL KRISHNA NYAUPANE 14


4. Execute the query
▪ The most crucial part is executing the query. Here, Query is an SQL Query.
• The query for updating or inserting tables in a database.
• The query for retrieving data from the database.

COMPILED BY: BAL KRISHNA NYAUPANE 15


COMPILED BY: BAL KRISHNA NYAUPANE 16
Useful ResultSet Methods

COMPILED BY: BAL KRISHNA NYAUPANE 17


5. Close the connection
▪ Release all the resources that the connection is holding.
• [Link]();
• [Link]();
• [Link]();

Example: Database CRUD operations Frame

COMPILED BY: BAL KRISHNA NYAUPANE 18


COMPILED BY: BAL KRISHNA NYAUPANE 19
COMPILED BY: BAL KRISHNA NYAUPANE 20
COMPILED BY: BAL KRISHNA NYAUPANE 21
Chapter 8
Introduction to J2EE
1
Java: Broadest Industry Adoption
2

9,000,000
JAVA DEVELOPERS
DEPLOYING TO 18 COMPLIANT APPLICATION SERVERS
3 Java SE
 Java SE: It stands Java Standard Edition which means all concepts
related to core java such as I/O, Collections, Threading, Concurrency,
etc.
 Java SE's API provides the core functionality of the Java programming
language.
 It defines everything from the basic types and objects of the Java
programming language to high-level classes that are used for
networking, security, database access, graphical user interface (GUI)
development, and XML parsing.
 In addition to the core API, the Java SE platform consists of a virtual
machine, development tools, deployment technologies, and other
class libraries and toolkits commonly used in Java technology
applications.
4 Java EE
The Java EE platform is built on top of the Java SE platform.
Java Platform Enterprise Edition.
It is a platform-independent, Java-centric environment
from Sun/Oracle for developing, building and deploying
Web-based enterprise applications online for business
solutions.
The J2EE platform consists of a set of services, APIs, and
protocols that provide the functionality for developing
multi-tiered, Web-based applications.
The Java EE platform provides an API and runtime
environment for developing and running large-scale, multi-
tiered, scalable, reliable, secure network applications.
5 J2EE Features
6 Differences between Java EE and Java SE
Java technology is both a programming language and a
platform.
The Java programming language is a high-level object-
oriented language that has a particular syntax and style.
A Java platform is a particular environment in which Java
programming language applications run.
There are several Java platforms.
Many developers, even long-time Java programming
language developers, do not understand how the
different platforms relate to each other.
7 What is Enterprise Application?
 An enterprise or e-commerce application is an application that an
enterprise or an organization uses to do business using Internet.
 The advent of internet has completely changed the world of
communication. With the widespread usage of internet, businesses
quickly realized a whole new market had opened up to exploit and
started taking advantage through e-commerce.
 With almost all the businesses going online, the information assets of a
company became more and more valuable.
 In order to sustain the competition, adoption of sophisticated
technologies has become the key factor in exploiting the information
assets of a business.
 J2EE is one such technology that helps businesses to build better and
flexible e-commerce applications by securing the critical business data.
8 Key challenges of enterprise application
 Performance: Since the application is now exposed to millions of
users, its very important that it responds faster enough to user
requests. This is one of the most important aspects that play a key
role in the success of a business.
 Reliability: The application must be reliable in terms of processing
the business transactions successfully and accurately.
 Availability: It’s very important that the application be up and
running all the times with almost zero downtime. Few seconds of
downtime can result in losing thousands of $$.
 Security: The application must be able to provide a secure
environment during the exchange of information between
customers and businesses.
9 Core J2EE Technologies
 J2EE technologies are standard helper technologies that we use
to build enterprise applications.
 Here is list of important technologies that every J2EE application
server supports:
10 Software Architecture
 Software Architecture can be of One Tier, Two Tier, Three Tier and N-
Tier. A “tier” can also be referred to as a “layer”.
 Generally three layers are involved in the application namely
Presentation Layer, Business Layer and Data Layer.
 Presentation Layer
It is also known as Client layer. Top most layer of an application. By
using this layer we can access the webpages.
The main functionality of this layer is to communicate with
Application layer.
This layer passes the information which is given by the user in terms of
keyboard actions, mouse clicks to the Application Layer.
For example, login page of Gmail where an end user could see text
boxes and buttons to enter user id, password and to click on sign-in.
11 Software Architecture
 Application Layer
 It is also known as Business Logic Layer which is also known as logical layer.
 Complete business logic will be written in this layer.
 As per the Gmail login page example, once user clicks on the login button,
Application layer interacts with Database layer and sends required
information to the Presentation layer.
 It controls an application’s functionality by performing detailed processing.
 This layer acts as a mediator between the Presentation and the Database
layer.
 Data Layer: The data is stored in this layer. Application layer
communicates with Database layer to retrieve the data. It contains
methods that connects the database and performs required action e.g.
insert, update, delete etc.
12 2-Tier Architecture
 In this architecture, all the business
logic and presentation logic of the
application is embedded in the
clients computer itself.
 Therefore if my application has 100
clients, I need to install the
application on all the 100 client
computers.
 However the database will still
reside on a separate computer
that will be shared by all the
clients.
13 2-Tier Architecture
 Advantages
 Simple and easy to build, Low cost
 Disadvantages
 Even a small change to the application requires a reinstall of the application on all
the client computers.
 If some clients are not ready to take the changes, then multiple versions of the
application will prevail, thereby causing maintenance nightmares.
 The performance of the application is dependent on the performance of client
computer.
 Heavy network traffic due to multiple requests to the database from all the client
computers.
 Scalability, and Low Security
 The disadvantages of this architecture outweigh the few advantages making it less
useful.
14 3-Tier Architecture
 In this architecture, the presentation logic, business logic and data are
logically distributed in three tiers.
 Client system handles Presentation layer, Application server handles
Application layer and Server system handles Database layer.
 The main difference is that the business logic is permanently isolated
from all the client systems and moved to centralized middle tier.
 The presentation logic on the client systems will query the business logic
in the middle tier which in turn accesses the data from the database.
 This architecture overcomes all the cons of 2-tier system.
15 3-Tier Architecture
► The decoupling of application logic
from either presentation or data
increases the flexibility of the
application design.
► Multiple views or a GUI can be
added without changing the existing
application logic.
► Similarly, multiple applications can be
created using the same data model.
► Changing the components of one
tier should not impact the other two
tiers. For example, any change to the
data or GUI will not affect the
application logic.
16 3-Tier Architecture
 Advantages
 Centralized business logic will offer more flexibility. Business logic is
only required to be changed at one place there by eliminating the
installation process of the application on client systems.
 Less network traffic, thereby improving the performance of the
application.
 Application performance is no longer dependent on client computer
due to the business logic isolation.
 No more maintenance nightmares.
 Disadvantages
 Any update to the business logic must be accepted by all the clients
even if they are not ready for updates.
17 N-Tier Architecture
 In this type of architecture, the application logic is divided based on
the functionality rather than physically like in 2-tier and 3-tier
architectures.
 A typical n-tier architecture contains the following elements:
User Interface: This is something like a web browser that handles the
client interactions.
Presentation Logic: This defines format using which the information
will be displayed.
Business Logic: Encapsulates all the business rules by interacting with
data sources.
Infrastructure Services: These are utility services that the presentation
and business logic makes use of.
Data tier: This contains all the enterprise data
18 N-Tier Architecture
▪ Breaking the application logic based on functionality offers several
benefits like flexibility, better maintenance, improved performance,
reusability of code and may more.
▪ This architecture is also referred to as Model-View-Controller (MVC)
architecture.
19 Enterprise Architecture
Simply stating, enterprise architecture is a combination of
several n-tier architectures.
An N-tier architecture is applicable to a single application in
an enterprise.
 The client/server application architecture, which was a two-tier
architecture, evolved over time to a multitier architecture. This
natural progression occurred as additional tiers were introduced
between the end-user clients and back-end systems.
 Although a multitier architecture brings greater flexibility of
design. It also increases the complexity of building, testing,
deploying, administering, and maintaining application
components.
20 Enterprise Architecture

 However, an enterprise
application is a collection
of several applications
within the enterprise with
all the applications
working in tandem and
interacting with each other
through well defined
interfaces a shown in the
following figure.
21 Enterprise Architecture
 An Enterprise JavaBeans (EJB) container manages the execution of all
enterprise beans for one J2EE application. Enterprise beans and their
container run on the J2EE server.
 EJB is specification for making server side components that enable and
simplifies the task of creating distributed objects. EJB is a server-side
software component that encapsulates business logic of an application
 A web container manages the execution of all JSP page and servlet
components for one J2EE application. Web components and their
container run on the J2EE server.
 An application client container manages the execution of all
application client components for one J2EE application. Application
clients and their container run on the client machine.
22 J2EE Application Servers
 An application server is a software framework that provides both
facilities to create web applications and a server environment to run
them
 A J2EE application server is a readymade sophisticated application
that will host and run all the J2EE applications.
 Once you have a J2EE application server, you can start building and
running enterprise applications.
 A J2EE application server runs enterprise internet applications that are
built using standard J2EE technologies.
 There are several free and commercial application servers available
in the market today that are developed by noted companies like Sun
Microsystems Inc, IBM, BEA and many more.
23 J2EE Application Servers
24 J2EE Application Servers
 A J2EE application server comprises of a Web Container and an EJB
Container. A container is nothing but a runtime environment to manage
the application components.
 In J2EE, there are two mainstream technologies like Servlets/JSP/Struts
and EJB.
 Application components built using Servlet/JSP/Struts technologies run within
Web container, and application components built using EJB technology are
run within EJB container.
 You cannot run EJB components in Web container and Servlets/JSP
components in an EJB container.
 All the remaining technologies (JDBC, JMS, JNDI(Java Naming and Directory
Interface), Spring, Hibernate etc.) are like helper technologies that are used
by the above two mainstream technologies in both the containers.
25 J2EE Application Servers
 An application server has both Web container and EJB
container.
 If our application doesn’t use EJB technology, do we need an
EJB container? You are right. We don’t need an EJB container.
 In such cases, having just a web container is good enough.
(Example: Apache Tomcat, Jetty )
 Some examples of fully compliant J2EE application servers are:
GlassFish Server , IBM WebSphere Application Server , Wildfly,
JBoss Application Server, Apache TomEE etc.
26 J2EE Application Servers
27

Thank You
???

You might also like