OOP in Java Notes
OOP in Java Notes
Definition, History of Java, The internet and Java‘s Place in IT, Applications and Applets,
Java Virtual Machine, Byte Code – not an executable code, Procedure-oriented vs. Object
Oriented programming, Compiling and Running a Simple Program, Setting up your
Computer for Java Environment, Writing a Program, Compiling, Interpreting and
Running the Program, Handling common errors.
Inheritance: Using ‗extends‘ keyword, Sub classes and Superclasses, super keyword
usage, Overriding methods, Dynamic Method Dispatch; The object class, Abstract and
final classes.
Java.io package, Files and directories, streams: Byte streams and character
streams:Reading/Writing console Input/Output, Reading and Writing Files, The
serialization Interface, Serialization and Deserialization.
Collection Classes: Array List, Linked List, Hash Set and Tree set; Accessing
Collections/Use of an Iterator, Comparator.
Unit 11: Java Applications [8 hours]
About AWT and Swing, About JFrame (a top level window in swing), swing components
(JLabel, About text components like JTextField, JButton, Event Handling in Swing
Applications, Layout Management using FlowLayout, Border Layout, Grid Layout,
Using JPanel, Choice Components like JCheckBox, JRadioButton, Borders Components,
JComboBox and its events, JList and its events with MVC patterns, Key and Mouse
Event Handling, Menus in Swing, JTextArea, Dialog boxes in Swing, JTable for
Displaying data in tabular form, MDI using JDesktopPane and JInternalFrame, Using
IDE like netbeans: JBuilder for building java applications using Drag and Drop), Adapter
classes.
Definition, applet lifecycle methods, build a simple applet, using applet viewer, adding
controls: animation concepts.
Using Connection, Statement and ResultSet interfaces for manipulating data with the
database.
Text Books:
The major objective of OOP is to eliminate some of the flaws encountered in the
procedural approach (in C- programming). OOP treat data as a critical element in the
program development. It ties data more closely to the functions that operate on it and
protects it from unintentional modification by other functions. OOP allows us to
decompose a problem into a number of entities called objects and build data and
functions/methods. The combination of data and functions/methods make up an object as
seen in figure;
Definition:
Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems'
Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of
Java and its widespread popularity, multiple configurations were built to suit various
types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile
Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java
is guaranteed to be Write Once, Run Anywhere.
Java is:
Object Oriented: In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
Platform Independent: Unlike many other programming languages including C and
C++, when Java is compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP
Java, it would be easy to master.
Secure: With Java's secure feature it enables to develop virus-free, tamper-free
(unauthorized access) systems. Authentication techniques are based on public-key
encryption.
Architecture-neutral: Java compiler generates an architecture-neutral object file format,
which makes the compiled code executable on many processors, with the presence of
Java runtime system.
Portable: Being architecture-neutral and having no implementation dependent aspects of
the specification makes Java portable.
Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
Multithreaded: With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.
Interpreted: Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.
High Performance: With the use of Just-In-Time compilers, Java enables high
performance.
Distributed: Java is designed for the distributed environment of the internet.
Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
History of Java:
James Gosling initiated Java language project in June 1991 for use in one of his many set-
top box projects. The language, initially called ‗Oak‘ after an oak tree that stood outside
Gosling's office, also went by the name ‗Green‘ and ended up later being renamed as
Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It promised Write
Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source software
under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-
source, aside from a small portion of code to which Sun did not hold the copyright.
A Java program can be classified into two types, one is an Application and another is an
Applet.
Application:
1. An application is a stand-alone java program that runs with the support of a virtual
machine in a client or server-side.
2. A java application is designed to perform a specific function to run on any Java-
compatible virtual machine regardless of the computer architecture.
3. An application is either executed for the user or for some other application program.
4. Examples of java applications include database programs, development tools, word
processors, text and image editing programs, spreadsheets, web browsers, etc.
Example:
import java.awt.*;
import java.applet.*;
public class AppletDemo extends Applet{
public void paint(Graphics g) {
g.drawString("Welcome to TutorialsPoint", 50, 50);
}
}
/* <applet code="AppletDemo.class" width="300" height="300">
<applet>*/
Java Technology:
JDK
JRE, Jar, Debugging tools, etc.
JRE
Java, libraries, etc
JVM
class Test
System.out.print(―Hello!‖);
The 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.
Note: Installation of recent JDK for the full execution of Java Programs.
Select Start -> Computer -> System Properties -> Advanced system settings ->
Environment Variables -> System variables -> PATH. ...
Prepend C:\Program Files\Java\jdk1.6.0_27\bin; to the beginning of the PATH
variable.
Click OK three times.
OR
In Command Mode:
Go to the directory where the java programs are located.
Then, set path=%path%;C:\Program Files\Java\ jdk1.6.0_27\bin.
C:\Workspace> javac yourfilename.java(compilation)
C:\Workspace> java yourfilename(Execution/Run)
ByteCode:
The key that allows Java to solve both the security and the portability problems is
that the output of a Java Compiler is not an executable code, rather it is a
bytecode.
In the Java programming language, all source code is first written in plain text
files ending with the .java extension. Those source files are then compiled into
.class files by the javac compiler. A .class file does not contain code that is native
to your processor; it instead contains bytecode—the language of the JVM.
The Java VM is available on many different operating systems, therefore the same
.class files are capable of running on Microsoft Windows, the Solaris™ Operating
System (Solaris OS), Linux, or Mac OS.
Java Architecture:
Source Code
Java Compiler
Bytecode
Errors in the very beginning of programming in java can be at compiling time such as;
1. If environment is not set up properly.
2. If the name of a source file during compilation is provided incorrect.
3. If the name of a class file during execution provided wrong (This may happen
when we give the name of a class different from a file name).
2 Approach In OOPs concept of objects and On other hand in case of POP the
classes is introduced and hence the the main program is divided into
program is divided into small small parts based on the functions
chunks called objects which are and is treated as separate program
instances of classes. for individual smaller program.
4 Security Due to abstraction in OOPs data On other hand POP is less secure
hiding is possible and hence it is as compare to OOPs.
more secure than POP.
5 Complexity In OOPs new data objects can be On other hand there is no simple
created easily from existing objects process to add data in POP at least
making object-oriented programs not without revising the whole
easy to modify program.
Unit 2: Tokens, Expressions and Control Structures [5 hours]
Primitive Data Types: Integers, Floating-Point types, Characters, Booleans, User-Defined
Data Types, Declarations, Constants, Identifiers, Literals, Type Conversion and Casting,
Variables: Variable Definition and Assignment, Default Variable Initializations:
Command Line Arguments, Arrays of Primitive Data Types, Comment Syntax, Garbage
Collection, Expressions.
Using control statements (Branching: if, switch; Looping: while, do-while, for; Jumping
statements: break, continue and return).
A primitive data type specifies the size and type of variable values, and it has no
additional methods.
Output:
User defined data types related variables allows us to store multiple values either of same
type or different type or both. This is a data type whose variable can hold more than one
value of dissimilar type, in java it is achieved using class concept.
Note: In java both derived and user defined data type combined name as reference data
type.
In C language, user defined data types can be developed by using struct, union, enum etc.
In java programming user defined datatype can be developed by using the features of
classes and interfaces.
Example: interface
interface StudentInterface{ //user defined data type
void DisplayName();
}
class Student implements StudentInterface{
void DisplayName(){
System.out.println(―My name is XYZ‖);
}
public static void main(String[] args){
Student st=new Student();
st. DisplayName();
}
}
Constants:
A constant is a variable whose value cannot change once it has been assigned. Java
doesn't have built-in support for constants.
A constant can make our program more easily read and understood by others. In addition,
a constant is cached by the JVM as well as our application, so using a constant can
improve performance.
To define a variable as a constant, we just need to add the keyword ―final‖ in front of the
variable declaration.
Syntax
final float pi = 3.14f;
Literals:
A literal is a source code representation of a fixed value. They are represented directly in
the code without any computation.
Literals can be assigned to any primitive type variable.
Example
byte a = 68;
char a = 'A'
Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behavior such as wagging their tail, barking, eating. An object is an
instance of a class.
Class - A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type supports.
Methods - A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are
executed.
Instance Variables - Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
Let us look at a simple code that will print the words Hello World.
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}
Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps:
Java Identifiers
All Java components require names. Names used for classes, variables, and methods are
called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
1. All identifiers should begin with a letter (A to Z or a to z), currency character ($)
or an underscore (_).
2. After the first character, identifiers can have any combination of characters.
3. A key word cannot be used as an identifier.
4. Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using modifiers.
There are two categories of modifiers:
Access Modifiers: default, public , protected, private
Non-access Modifiers: final, abstract, strictfp
We will be looking into more details about modifiers in the next section.
Java Variables
Java Arrays
Arrays are objects that store multiple variables of the same type. However, an array itself
is an object on the heap. We will look into how to declare, construct, and initialize in the
upcoming chapters.
- args is declared as an array of strings known as string objects. Any arguments provided
in the command line at the time of execution are passed to the array args as its elements.
E.g.
class CommandLine{
public static void main(String args[ ]){
int count, i=0;
String str;
count=args.length;
System.out.println(“Number of arguments=“+count);
while(i<count){
str=args[i];
i=i+1;
System.out.println(i+”:”+”Java is”+str+”!\n”);
}
}
}
Input is called command line argument
Java Keywords
The following list shows the reserved words in Java. These reserved words may not be
used as constant or variable or any other identifier names.
Comments in Java
Java supports single-line and multi-line comments very similar to C and C++. All
characters available inside any comment are ignored by Java compiler.
public class MyFirstJavaProgram{
public static void main(String[] args){
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}
Java Type Conversion and Casting
Type casting is when you assign a value of one primitive data type to another type.
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size
type:
Example
public class casting {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of
the value:
Example
class Main {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
String - stores text, such as "Hello". String values are surrounded by double
quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
boolean - stores values with two states: true or false
To create a variable, you must specify the type and assign it a value:
Syntax
data_type variable = value;
Where type is one of Java's types (such as int or String), and variable is the name of the
variable (such as x or name). The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
Example
String name=”harendra”;
int num=56;
System.out.println(name);
System.out.println(num);
System.out.println(num);
The general rules for constructing names for variables (unique identifiers) are:
An array is a collection of similar data types. Array is a container object that hold values
of homogenous type. It is also known as static data structure because size of an array
must be specified at the time of its declaration.
An array can be either primitive or reference type. It gets memory in heap area. Index of
array starts from zero to size-1.
Array Declaration
Syntax :
datatype[] identifier;
or
datatype identifier[];
Both are valid syntax for array declaration. But the former is more readable.
Example :
int[] arr;
char[] arr;
short[] arr;
long[] arr;
int[][] arr; //two dimensional array.
Initialization of Array
Example :
As mention ealier array index starts from 0. To access nth element of an array. Syntax;
arrayname[n-1];
int[] arr={10,20,30,40};
System.out.println("Element at 4th place"+arr[3]);
The above code will print the 4th element of array arr on console.
J2SE 5 introduces special type of for loop called enhanced for loop to access elements of
array. Using enhanced for loop you can access complete array sequentially without using
index of array. Let us see an example of enhanced for loop.
class Arraydemo
{
public static void main(String[] args)
{
int[] arr={10,20,30,40};
for(int x:arr)
{
System.out.println(x);
}
}
}
To do so, we were using free() function in C language and delete() in C++. But, in java it
is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
o It is automatically done by the garbage collector (a part of JVM) so we don't
need to make extra efforts.
Expressions
Expressions are constructed from operands and operators. The operators of an
expression indicate which operations to apply to the operands. The order of
evaluation of operators in an expression is determined by
the precedence and associativity of the operators.
Operators in Java
Operator in Java is a symbol which is used to perform operations. For example: +, -, *, /
etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:
Output:
10
12
12
10
Output:
-11
9
false
true
Java arithmatic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Output:
15
5
50
2
0
Output:
21
The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
Output:
40
80
80
240
The Java right shift operator >> is used to move left operands value to right by the
number of bits specified by the right operand.
Output:
2
5
2
Output:
5
5
-5
1073741819
The logical && operator doesn't check second condition if first condition is false. It
checks second condition only if first one is true.
The bitwise & operator always checks both conditions whether first condition is true or
false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Output:
false
false
Output:
false
10
false
11
The logical || operator doesn't check second condition if first condition is true. It checks
second condition only if first one is false.
The bitwise | operator always checks both conditions whether first condition is true or
false.
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}
Output:
true
true
true
10
true
11
Java Ternary operator is used as one liner replacement for if-then-else statement and used
a lot in Java programming. it is the only conditional operator which takes three operands.
Output:
Another Example:
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}
Output:
Java assignment operator is one of the most common operator. It is used to assign the
value on its right to the operand on its left.
Output:
14
16
Output:
13
9
18
9
Output:
class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is becomes int converted to short
System.out.println(a);
}}
Output:
20
Control Statements:
Decision making and branching.
If statement
Syntax:
if(test expression){statement-block}
If statement implemented in different forms:
Simple if statement
if(test expression){statement-block}
If…….else statement
if(test expression){statement-block}
else{statement-block}
Nested if statement
if(test expression){
if(condition){statement-block}
statement-block}
Else if ladder
if(test expression){statement-block 1}
else if(test expression){statement-block 2}
else if(test expression){statement-block 3}
else{default-statement-block}
Switch statement
Syntax:
Switch(expression){
Case value-1:
Block-1
Break;
Case value-2:
Block-2
Break;
…………………..
…………………..
Default:
Default-block
Break;
}
Implementation:
import java.util.Scanner;
class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11){
System.out.println("Count is: " + count);
count++;
}
}
}
o Do while statements
Syntax:
do { statement(s) }
while (expression);
Example:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
o For statement
class ForDemo {
public static void main(String[] args){
int i;
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
int length=numbers.length;
for (i=0;i< : numbers<length;i++) {
System.out.println("Count is: " + numbers[i]);
}
}
}
Java Break
You have already seen the break statement used in an earlier chapter of this tutorial. It
was used to "jump out" of a switch statement.
Example
break;
System.out.println(i);
Java Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs,
and continues with the next iteration in the loop.
This example skips the value of 4:
Example
continue;
System.out.println(i);
Java return:
Fundamental of classes:
A class is a template for an object, and an object is an instance of a class. Because an
object is an instance of a class, the two words object and instance used interchangeably.
A class is declared by use of the class keyword. The classes that have been used up to
this point are actually very limited examples of its complete form. Classes can (and
usually do) get much more complex. A simplified general form of a class definition is
shown here:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
} // ...
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class
are called members of the class. In most classes, the instance variables are acted upon
and accessed by the methods defined for that class. Thus, as a general rule, it is the
methods that determine how a class‘ data can be used.
Variables defined within a class are called instance variables because each instance of
the class (that is, each object of the class) contains its own copy of these variables.
Thus, the data for one object is separate and unique from the data for another. All
methods have the same general form as main( ), which we have been using thus far.
However, most methods will not be specified as static or public. Notice that the general
form of a class does not specify a main( ) method. Java classes do not need to have a
main( ) method.
Defining a class:
Class classname [extends superclassname]{
[fields declarations;]
[method declarations;]
}
Field declarations:
Class Rectangle{
int length;
int width;
}
Method Declarations:
type methodname(parameter-list){
method-body;
}
void getData(int x, int y){
length=x;
width=y;
}
Creating objects:
Rectangle rect;
rect=new Rectangle();
Accessing class members:
rect.length=12;
rect.width=23;
int rectArea()
{
int area = length*width;
return area;
}
}
Descriptions:
In the above example, we can see two different classes Rectangle and RectArea.
Rectangle has member variables (length and breadth of integer type) declared and
member functions getData() i.e. void type and rectArea() i.e. return type defined inside
Rectangle class.
Another class RectArea has a main method and inside main method the instances
(objects) of class Rectangle are created i.e. rect1 and rect2. Using these objects the
members are accessed from different class RectArea using dot operator. (e.g.
rect1.length). This is how the member variables and member methods are accessed by
using the objects of a particular class in different class.
Abstraction:
As per dictionary, abstraction is the quality of dealing with ideas rather than events. For
example, when you consider the case of e-mail, complex details such as what happens as
soon as you send an e-mail, the protocol your e-mail server uses are hidden from the
user. Therefore, to send an e-mail you just need to type the content, mention the address
of the receiver, and click send.
Likewise in Object-oriented programming, abstraction is a process of hiding the
implementation details from the user, only the functionality will be provided to the user.
In other words, the user will have the information on what the object does instead of how
it does it.
In Java, abstraction is achieved using Abstract classes and interfaces.
Abstract Class
A class which contains the abstract keyword in its declaration is known as abstract
class.
Abstract classes may or may not contain abstract methods, i.e., methods without
body ( public void get(); )
But, if a class has at least one abstract method, then the class must be declared
abstract.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the
abstract methods in it.
Example:
public abstract class Room //abstract is used to restrict object creation
{
int length, breadth;
Room(int length, int breadth)
{
this.length=length;
this.breadth=breadth;
}
int getArea(){
return length*breadth;
}
}
int getVolume(){
return length*breadth*height;
}
}
If you want a class to contain a particular method but you want the actual
implementation of that method to be determined by child classes, you can declare the
method in the parent class as an abstract.
abstract keyword is used to declare the method as abstract.
You have to place the abstract keyword before the method name in the method
declaration.
An abstract method contains a method signature, but no method body.
Instead of curly braces, an abstract method will have a semi colon (;) at the end.
Following is an example of the abstract method.
Example
public abstract class Employee {
private String name;
private String address;
private int number;
Encapsulation:
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting
on the data (methods) together as a single unit. In encapsulation, the variables of a class
will be hidden from other classes, and can be accessed only through the methods of their
current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables values.
Example
Following is an example that demonstrates how to achieve Encapsulation in Java −
/* File name : EncapTest.java */
public class EncapTest {
private String name;
private String idNum;
private int age;
Output
Name : James Age : 20
Benefits of Encapsulation
The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.
class Student{
int rn;
String name;
float fees;
Student(int rn,String name,float fees){
this.rn=rn;
this.name=name;
this.fees=fees;
}
void display(){ System.out.println(rn+" "+name+" "+fees); }
}
class TestMain{
public static void main(String args[]){
Student s1=new Student(111,"harendra",5000f);
Student s2=new Student(112,"mahesh",6000f);
s1.display();
s2.display();
}}
You may invoke the method of the current class by using the this keyword. If you don't
use the this keyword, compiler automatically adds this keyword while invoking the
method. Let's see the example
class ThisMethod{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestMain{
public static void main(String args[]){
ThisMethod a=new ThisMethod ();
a.n();
}}
The this() constructor call can be used to invoke the current class constructor. It is used to
reuse the constructor. In other words, it is used for constructor chaining.
class ThisConstructor{
ThisConstructor (){System.out.println("hello a");}
ThisConstructor (int x){
this(); //it calls the ThisConstructor() constructor
System.out.println(x);
}
}
class TestMain{
public static void main(String args[]){
ThisConstructor a=new ThisConstructor (10);
}}
OR
Class ThisParamCons{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestMain{
public static void main(String args[]){
ThisParamCons a=new ThisParamCons ();
}}
OR
The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's
see the example given below that displays the actual use of this keyword.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestMain{
public static void main(String args[]){
Student s1=new Student(111,"ram","java");
Student s2=new Student(112,"shyam","java",6000f);
s1.display();
s2.display();
}}
4) this: to pass as an argument in the method
The this keyword can also be passed as an argument in the method. It is mainly used in
the event handling(studied later). Let's see the example:
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this); //this refers to the current class
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
We can pass the ‗this‘ keyword in the constructor also. It is useful if we have to use one
object in multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
class A{
A getA(){//not a constructor
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
A a=new A().getA();//a contains the class variable
a.msg();
//new A().getA().msg();
}
}
Constructors
A constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of constructor call, memory for the object is allocated in
the memory.
Every time an object is created using the new() keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default if not provided by the user.
There are two types of constructors in Java: no-arg constructor (default constructor),
and parameterized constructor.
Default constructors
A constructor is called "Default Constructor" when it doesn't have any parameter.
Parameterized constructors
A constructor which has a specific number of parameters is called a parameterized
constructor.
In this example, we have created the constructor of Student class that has two parameters.
We can have any number of parameters in the constructor. We can have more than one
constructors as well.
Private Constructor:
Private constructor restricts the object creation outside the class but we can create objects
of a class inside the same class.
Example:
class Main {
More on Methods: passing by value, by reference, access control, methods that return
values, polymorphism and method overloading, recursion; Nested and inner classes.
There is only call by value in java, not call by reference. If we call a method passing a
value, it is known as call by value. The changes being done in the called method, is not
affected in the calling method.
class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
}
}
Output:before change 50
after change 50
Another Example of call by value in java
In case of call by reference original value is changed if we made changes in the called
method. If we pass object in place of any primitive value, original value will be changed.
In this example we are passing object as a value. Let's take a simple example:
class Operation2{
int data=50;
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.
return min;
}
}
Method Overloading
Method overloading is the process of defining more methods of same names with
different number of parameters or different data type.
Example:
public class ClassRoom {
int length;
int breadth;
int area()
{
return length*breadth;
}
}
Recursion
Recursion in java is a process in which a method calls itself continuously. A method in
java that calls itself is called recursive method.
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}
Output:
hello
hello
...
java.lang.StackOverflowError
Output:
hello 1
hello 2
hello 3
hello 4
hello 5
Output:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
Output:
We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.
Additionally, it can access all the members of outer class including private data members
and methods.
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
Inner class is a part of nested class. Non-static nested classes are known as inner classes.
There are two types of nested class non-static and static nested classes. The non-static
nested classes are also known as inner classes.
A non-static class that is created inside a class but outside a method is called member
inner class.
Syntax:
class Outer{
//code
class Inner{
//code
}
}
In this example, we are creating msg() method in member inner class that is accessing the
private data member of outer class.
class TestMemberOuter{
private int data=30;
class Inner{ //defined outside the main method
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
An inner class declared without a class name is known as an anonymous inner class.
In case of anonymous inner classes, we declare and instantiate them at the same time.
Generally, they are used whenever you need to override the method of a class or an
interface. The syntax of an anonymous inner class is as follows −
Syntax
AnonymousInner an_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};
The following program shows how to override the method of a class using
anonymous inner class.
Example
abstract class AnonymousInner {
public abstract void mymethod();
}
A static inner class is a nested class which is a static member of the outer class. It can be
accessed without instantiating the outer class, using other static members. Just like static
members, a static nested class does not have access to the instance variables and methods
of the outer class. The syntax of static nested class is as follows −
Syntax
class MyOuter {
static class Nested_Demo {
}
}
Instantiating a static nested class is a bit different from instantiating an inner class. The
following program shows how to use a static nested class.
Example
public class Outer {
static class Nested_Demo { //static nested class
public void my_method() {
System.out.println("This is my nested class");
}
}
Inheritance:
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of the parent class. Moreover, you can add new methods and fields in your current
class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
//Super class
class Employee{
float salary=40000;
}
//Sub class
class Programmer extends Employee{ //salary is already inherited to this class
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
METHOD OVERRIDING
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.
//.....Base Class.......
public class OverrideSuper{
int x;
public OverrideSuper(int x) //Constructor
{
this.x=x;
}
void display()
{
System.out.println("Super x= "+x);
}
}
//----Derived class--------------
public class OverrideSub extends OverrideSuper
{
int y;
public OverrideSub(int x, int y)
{
super(x); //This value of x is for base class‟s variable
this.y=y;
}
void display()//overriding the method display of base class
{
System.out.println("Super x= " +x);
System.out.println("Sub y = " +y);
}
}
Types of Inheritance:
Inheritance is the process of deriving all the properties of base class or parent class or
super class to a derived class or child class or sub class. Properties may include variables
and methods. There are three types of inheritances in java and the most important thing is
multiple inheritances is not compatible in java, we generally use interfaces to achieve
multiple inheritance. The types of inheritances are given as follows;
SINGLE INHERITANCE
When a class inherits another class, it is known as a single inheritance. In the example
given below, BedRoom class inherits the Room class, so there is the single inheritance.
Super keyword is used to initialize the variables of base class in derived class.
Example:
//... this is a base class ......
public class Room
{
int length, breadth;
Room(int length, int breadth)
{
this.length=length;
this.breadth=breadth;
}
int roomArea(){
return length*breadth;
}
}
int roomVolume(){
return length*breadth*height;
}
}
public class RoomMain
{
public static void main(String[] args)
{
Bedroom room = new Bedroom(24,12,35);
int area=room.roomArea();
int volume=room.roomVolume();
System.out.println("The area is"+area);
System.out.println("The volume of a room is"+volume);
}
}
MULTILEVEL INHERITANCE
Example:
//... this is a base class ......
public class Car
{
Car()
{
System.out.println(("This is a Class Car");
}
Public void vehicleType(){
System.out.println(("Vehicle Type: Car");
}
}
HIERARCHICAL INHERITANCE
When two or more classes inherits a single class, it is known as hierarchical inheritance.
In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
Example:
class Animal{
int legs=4;
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
System.out.println("I have”+c.legs+” legs.");
//c.bark(); //Compile Time Error
Dog d=new Dog();
d.bark();
d.eat();
System.out.println("I have”+d.legs+” legs.");
}
}
Java uses the principle of „a superclass reference variable can refer to a subclass
object‟ to resolve calls to overridden methods at run time. When a superclass reference is
used to call an overridden method, Java determines which version of the method to
execute based on the type of the object being referred to at the time call.
In other words, it is the type of object being referred to that determines which version of
an overridden method will be executed.
Example:
class Apple
{
void display()
{
System.out.println("Inside Apple's display method");
}
}
class Fruits_Dispatch
{
public static void main(String args[])
{
Apple a = new Apple(); // object of Apple
Banana b = new Banana(); // object of Banana
Cherry c = new Cherry(); // object of Cherry
//Dynamic dispatches
ref = a; // ref refers to a object in Apple
ref.display(); // calling Apple's version of display()
Note: Upcasting: When Parent class reference variable refers to Child class object, it is
known as Upcasting.
Example:
A method which is declared as abstract and does not have implementation is known as an
abstract method.
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Final classes:
The final modifier for finalizing the implementations of classes, methods, and variables.
The main purpose of using a class being declared as final is to prevent the class from
being subclassed. If a class is marked as final then no class can inherit any feature from
the final class.
You cannot extend a final class. If you try it gives you a compile time error.
Example
final class Super {
private int data = 30;
}
public class Sub extends Super{
public static void main(String args[]){
}
}
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at newJavaExamples.Sub.main(Sub.java:9)
Final variable:
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; //compile time error
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Final methods:
If you make any method as final, you cannot override it.
Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...");} //final method
}
class Honda extends Bike{
public static void main(String args[]){
new Honda2().run(); //run method is inherited
}
}
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
Student(){
PAN_CARD_NUMBER=‖10023N‖;
}
public static void main(String[] args){
System.out.println(―The pan card number is‖+ PAN_CARD_NUMBER);
}
}
OR
Initialize inside static block as;
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
static{PAN_CARD_NUMBER=‖10023N‖;}
Types of packages
• User defined package: The package we create is called user-defined package.
• Built-in package: The already defined package like java.io.*, java.lang.* etc are known as
built-in packages.
• Note: a package hierarchy must be reflected through the file system.
– E.g. package java.awt.image-> needs to be stored in java\awt\image.
public ProtectionLevel(){
System.out.println("Protection level in same class");
System.out.println("number="+number);
System.out.println("Public number="+numberPublic);
System.out.println("Private number="+numberPrivate);
System.out.println("Protected number="+numberProtected);
}
}
Note: Access modifiers (public, private, protected and no modifier) in same class are
accessible.
package PackageOne;
public class DerivedP extends ProtectionLevel{
DerivedP(){
System.out.println("Constructer derived from Protectionlevel: private does not work");
System.out.println("number="+number);
System.out.println("Public number="+numberPublic);
//System.out.println("Private number="+numberPrivate);
System.out.println("Protected number="+numberProtected);
}
}
Note: Access modifiers (public, protected and no modifier) in derived class are
accessible but private data are not accessible.
package PackageOne;
public class PackageSameAccess {
public PackageSameAccess() {
ProtectionLevel pl = new ProtectionLevel();
System.out.println("Protection level at the same package: private does not
work");
System.out.println("number="+pl.number);
System.out.println("Public number="+pl.numberPublic);
//System.out.println("Private number="+pl.numberPrivate);
System.out.println("Protected number="+pl.numberProtected);
}
}
Note: Access modifiers (public, protected and no modifier) in same package class are
accessible but private data are not accessible.
package PackageOne;
public class DemoPackage {
public static void main(String[] args) {
ProtectionLevel pl= new ProtectionLevel();
DerivedP dp= new DerivedP();
PackageSameAccess psa=new PackageSameAccess();
}
}
Note: We can run above class for the output.
package PackageTwo;
public class ProtectionLevel2 extends PackageOne.ProtectionLevel{
public ProtectionLevel2() {
System.out.println("Derived from other package constructor");
//System.out.println("number="+number);//no modifier
System.out.println("Public number="+numberPublic);
//System.out.println("Private number="+numberPrivate);
System.out.println("Protected number="+numberProtected);
}
}
Note: Access modifiers (public, protected) in different package derived class are
accessible but private and no modifier data are not accessible.
package PackageTwo;
public class PackageOtherProtection {
public PackageOtherProtection() {
PackageOne.ProtectionLevel p1pl=new PackageOne.ProtectionLevel();
System.out.println("Protection level from other package class instantiation");
//System.out.println("number="+p1pl.number);
System.out.println("Public number="+p1pl.numberPublic);
//System.out.println("Private number="+p1pl.numberPrivate);
//System.out.println("Protected number="+p1pl.numberProtected);
}
}
Note: Access modifiers (public) in different package class (instantiation) are accessible
but private, protected and no modifier data are not accessible.
package PackageTwo;
public class DemoPackage2 {
public static void main(String[] args) {
ProtectionLevel2 p2 = new ProtectionLevel2();
PackageOtherProtection pop = new PackageOtherProtection();
}
}
8.Interface variables must be initialized at the time of declaration otherwise compiler will
through an error.
9.Inside any implementation class, you cannot change the variables declared in interface
because by default, they are public, static and final.
10. Any interface can extend any interface but cannot implement it. Class implements
interface and interface extends interface.
Exception:
With exception handling the program continue executing after dealing with a
problem.
Overview:
Perform Task
If the preceding task did not execute correctly
Perform error processing
Perform next task
If the preceding task did not execute correctly
Perform error processing
…………….
This pseudo code begins by performing a task; then tests whether it executed correctly. If
not, we perform error processing. Otherwise, we continue with the next task. Although
this types of error handling works but difficult to read, modify, maintain and debug-
especially in large applications.
Exception Handling:
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
Checked Exception
Checked exceptions are checked at compile-time.
e.g. IOException, SQLException etc
Unchecked Exception
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc
Blocks used for handling exceptions:
try{
Block of codes
}
catch(type of exception)
{
exception handler for try block of codes
}
Here, the exception occurred in the ‗try‘ block is caught by ‗catch‘ block.
Throw:
The "throw" keyword is used to throw an exception.
Throws:
• The "throws" keyword is used to declare exceptions.
• It doesn't throw an exception.
• It specifies that there may appear an exception in the method.
• It is always used with method signature.
class DivideByZeroNoExceptionHandling
{
public static int quotient(int numerator, int denominator)
{
return numerator/denominator;
}
public static void main(Strings args[])
{
Scanner input= new Scanner(System.in);
System.out.println(“Please enter an integer numerator:”);
int numerator=input.nextInt();
System.out.println(“Please enter an integer denominator:”);
int denominator=input.nextInt();
int result = quotient(numerator, denominator);
System.out.println(“Result is :”+result);
}
}
Output:
Please enter an integer numerator: 20
Please enter an integer numerator:hello
It gives InputMismatchException
Output:
Please enter an integer numerator: 20
Please enter an integer numerator:0
It gives ArithmeticException
Handling mismatch and divide by zero exceptions:
import java.util.InputMismatchException;
import java.util.Scanner;
class ExceptionHandling
{
public static int quotient(int numerator, int denominator)
{
return numerator/denominator;
}
public static void main(String args[]){
Scanner input= new Scanner(System.in);
boolean continueloop=true; //determines if more input is needed
do{
try{
System.out.println("Please enter an integer numerator:");
int numerator=input.nextInt();
System.out.println("Please enter an integer denominator:");
int denominator=input.nextInt();
int result = quotient(numerator, denominator);
System.out.println("Result is :"+result);
continueloop=false;
} //end try
catch(InputMismatchException ex){
System.err.println("Exception is:" + ex);
input.nextLine();
System.out.println("You must enter integer.Please try again:");
}
catch(ArithmeticException arEx) {
System.err.println("Exception is:" + arEx);
System.out.println("Zero is an invalid denominator.Please try again:");
}
}while(continueloop); //end do……while
}
}
Output:
Please enter an integer numerator:
30
Please enter an integer denominator:
hello
Exception is:java.util.InputMismatchException
You must enter integer.Please try again:
Please enter an integer numerator:
23
Please enter an integer denominator:
0
Exception is:java.lang.ArithmeticException: /
by zero
Zero is an invalid denominator.Please try again:
Please enter an integer numerator:
Note: Exception handling does not stop the execution of a program, means the whole
program is executed. In above example, we can easily see the program is not stopped
however the exceptions arisen. It continues till we supply the correct values i.e. both
numerator and denominator must be integer values.
Finally Block:
Java guarantees that the final block will execute whether or not an exception is thrown in
the corresponding try block.
Java also guarantees that the finally block executes if a try block exits by using a
return, break or continue statement.
But, the finally block will not execute if the application exits early from a try
block by calling method System.exit.
try
{
Main block of code to check the exception
resource used statements
}
catch(AKindofException e)
{
exception handling statements
}
catch(AotherKindofException e)
{
exception handling statements
}
finally
{
statements
resource released statements
always executes
}
Description:
Since, finally block always executes, it typically contains resource-release code. Suppose
a resource is allocated in a try block. If no exception occurs, the catch blocks are skipped
and control proceeds to the finally block, which frees the resource.
Whether there is exception occurs or not, finally block is responsible to release the
resource.
Throwing exceptions using throw statement:
―throw‖ statement is used to send exceptions to the next block. E.g. in the
example before; the method throwException throws a new exception generated
using Exception class.
throw new Exception() ;=> indicates that an exception is occurred.
Re-throwing statements:
Exceptions are re-thrown from catch blocks, if these types of exceptions can not
be processed or can be partially processed.
―throw‖ keyword is used to pass the exceptions from the current block to the next
block.
E.g. throw ex; => in the previous program.
Stack Unwinding:
When an exception is thrown but not caught in a particular scope, the method called stack
unwind.
Example:
import java.util.Scanner;
public class StackUnwinding {
public static void main(String[] args) {
try{
throwException();
}
catch(Exception ex){
System.err.println("Exception handled in main");
}
}
//Demonstrate try...catch...finally blocks
public static void throwException() throws Exception //throws used to inherit
{
try{
//System.out.println("Method throw exception");
Scanner input= new Scanner(System.in);
System.out.println("Enter the value of number1");
int number1=input.nextInt();
System.out.println("Enter the value of number2");
int number2=input.nextInt();
int result=number1/number2;
System.out.println("The value after dividing is"+result);
throw new Exception(); //generate system exception
}
catch(RuntimeException e){
System.err.println("Exception handled in method
throwException");
}
finally{
System.err.println("Finally is always executed.");
}
}
}
Note:
Exception thrown from try block does not match the RuntimeException, so catch block is
not executed. The condition is called Stack Unwinding.
A user can create custom exceptions by extending the class from Exception class.
Exception is a super class for all kinds of exceptions, so whenever a class extends
Exception class it becomes the exception.
The ‗finally‘ block is generally used to free the resources such as closing files in file
handling, closing connections in database, closing sockets in network programming, etc.
We will learn in the respective sections how finally block is used to free the resources.
Unit 6: Handling Strings [2 hours]
Creation, Concatenation and Conversion of a string, Changing Case, Character
Extraction, String Comparison, Searching Strings, Modifying Strings, String buffer.
Strings Manipulation
String manipulation is the most common part in many java programs. String
represents the sequence of characters. The easiest way to represent the sequence of
characters in java is by using character array;
char charArray[ ] = new char[4];
char[0]=‗j‘;
char[1]=‗a‘;
char[2]=‗v‘;
char[3]=‗a‘;
Using String class;
String stringname = new String(―Java‖);
1. s.length() Method
public class Example{
public static void main(String args[]{
String s1="hello";
String s2="whatsup";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}
2. s.toLowerCase() Method
public class StringLowerExample{
public static void main(String args[]){
String s1="HELLO HOW Are You?”;
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}
}
3. s.toUpperCase() Method
public class StringUpperExample{
public static void main(String args[]){
String s1="hello how are you";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}
}
4. s. replace () Method
public class ReplaceExample1{
public static void main(String args[]){
String s1="hello how are you";
String replaceString=s1.replace('h','t');
System.out.println(replaceString);
}
}
5. s.trim() Method
public class StringTrimExample{
public static void main(String args[]){
String s1=" hello ";
System.out.println(s1+"how are you"); // without trim()
System.out.println(s1.trim()+"how are you"); // with trim()
}
}
6. s1.equals(s2);
public class Equals{
public static void main(String args[]){
String s1="hello";
String s2="HELLO";
System.out.println(s1.equals(s2)); // returns true
System.out.println(s1.equals(s2)); // returns false
}
}
7. s1.equalsIgnoreCase(s2);
public class EqualsExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="hi";
System.out.println(s1.equalsIgnoreCase(s2)); // returns true
System.out.println(s1.equalsIgnoreCase(s3)); // returns false
}
}
8. s1.CharAt(n);
public class CharAtExample {
public static void main(String args[]) {
String str = "Welcome to string handling tutorial";
char ch1 = str.charAt(0);
char ch2 = str.charAt(5);
System.out.println("Character at 0 index is: "+ch1);
System.out.println("Character at 5th index is: "+ch2);
}
}
9. s1.compareTo(s2);
public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="hemlo";
String s4="flag";
System.out.println(s1.compareTo(s2)); // 0 because both are equal
System.out.println(s1.compareTo(s3)); //-1 because "l" is only one time lower
than "m"
System.out.println(s1.compareTo(s4)); // 2 because "h" is 2 times greater than "f"
}
}
10. s1.concat(s2);
public class ConcatExample{
public static void main(String args[]){
String s1="hello";
String s2=" how are you?";
s1=s1.concat(s2);
System.out.println(s1);
}
}
12. s.ToString();
public class JavaCharacterToStringExample1 {
public static void main(String[] args) {
Character c1, c2;
c1 = new Character('r');
c2 = new Character('9');
String s1, s2;
s1 = c1.toString();
s2 = c2.toString();
System.out.println( s1 );
System.out.println( s2 );
}
}
13. s1.isEmpty()
public class IsEmptyExample{
public static void main(String args[]){
String s1="";
String s2="hello";
System.out.println(s1.isEmpty()); // true
System.out.println(s2.isEmpty()); // false
}
}
14. s1.getChars()
Syntax:
void getChars(int stringStart, int stringEnd, char arr[], int arrStart)
Here stringStart and stringEnd is the starting and ending index of the substring. arr is the
character array that will contain the substring. It will contain the characters starting
from stringStart to stringEnd-1. arrStart is the index inside arr at which substring will be
copied. The arr array should be large enough to store the substring.
15. getBytes()
getBytes() extract characters from String object and then convert the characters in a
byte array. It has following syntax.
Example:
String str="Hello";
byte b[]=str.getBytes();
16. toCharArray()
It is an alternative of getChars() method. toCharArray() convert all the characters in a
String object into an array of characters. It is the best and easiest way to convert string
to character array.
Example:
class temp
{
public static void main(String[] args)
{
String str="Hello World";
char ch[]=str.toCharArray();
System.out.println(ch);
}
}
Unit 7: Threads [3 hours]
Create/Instantiate/Start New Threads: Extending java.lang.Thread, Implementing
java.lang.Runnable interface; Understand Thread Execution, Thread Priorities,
Synchronization, Inter-Thread Communication, Deadlock.
Concurrency / Multithreading:
The human body can perform a great variety of operations concurrently
Blood circulation, digestion, thinking, walking
Likely, computers too can perform operations concurrently
Java supports multithreaded programming.
Multithreading in java is a process of executing multiple threads simultaneously.
A multi-threaded program contains two or more parts that can run concurrently.
Each part of such program is called a thread, and each thread defines a separate
path of execution.
A thread is a lightweight sub-process, the smallest unit of processing.
we use multithreading than multiprocessing because threads use a shared memory
area.
They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
Java Multithreading is mostly used in games, animation, etc.
Advantages of Java Multithreading
o It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
o You can perform many operations together, so it saves time.
o Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.
1.New
2.Runnable
3.Running
4.Non-Runnable
(Blocked)
5.Terminated (Dead)
Thread States:
Blocked states(Non-Runnable):
A runnable thread transitions to the blocked state when it attempts to perform a task that
cannot be completed immediately and it must temporarily wait until that task completes.
The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
A new thread starts.
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.
Sleep Method of a Thread Class: It is used to wait some threads for certain time.
t1.start();
t2.start();
}
}
t1.start();
//Thread.yield(); //if we want to stop main thread and give chance to
execute other threads
In java 5, yield method uses sleep method internally. But, in java 6, yield method works
by providing the request for yielding to ThreadScheduler whether to accept or reject the
request. For example in above program there are two threads, Thread-0 and Main thread.
Thread-0 and Main thread executes concurrently. Yield is used to request the
ThreadScheduler to stop the current thread and give chance to another threads. E.g. If
Thread.yield() method is used inside the Thread-0, then Main thread executes fully (if
ThreadScheduler accepts the request otherwise the threads executes concurrently). The
output may vary in different execution of a program, which is due to the
ThreadScheduler. Similarly, if Thread.yield() method is used insidethe Main thread then
Thread-0 executes completely.
// stop t3 thread
t3.stop();
System.out.println("Thread t3 is stopped");
}
}
class Morning{
void display()
{
for (int i = 0; i < 5; i++) {
System.out.println("Morning");
try{Thread.sleep(1000);}catch(Exception ex) {}
//5 second to print this for loop
}
}
}
public class NoThread {
public static void main(String[] args) {
Good gd=new Good();
Morning mrg= new Morning();
gd.display();
mrg.display();
}
}
}
}
}
public class UseThreadClass {
public static void main(String[] args) {
GoodHi gd=new GoodHi();
MorningHello mrg= new MorningHello();
gd.start();
try{Thread.sleep(10);}catch(Exception ex) {}
mrg.start();
//Parallel execution of two different threads
}
}
Description:
In program 1, there is no multithreading used, so the program executes sequentially, the
time to execute the program is more because single thread (single processor) is used.
In program 2, there is a use of Thread class. In which, the start() method executes the
run() method of the thread class. Two different classes are extended from thread class and
objects of these classes are two different threads which executes parallel.
In program 2, there is a use of Runnable interface which contains only method i.e. run().
But we cannot call object using start() method directly, for this we have to pass the
objects(i.e runnable type) in the Thread class‘s constructor.
Thread Priorities:
Thread priority is used to schedule the running sequence of threads. The thread with the
same priority is given the same treatment by the Thread Scheduler or Java Scheduler.
Java permits us to set the priority of a Thread using setPriority() method as follows;
ThreadName.setPriority(intnumber);
The intNumber is an integer value to which the Thread‘s priority is set. The Thread class
defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants of any value between 1 and 10.
Default setting is NORM_PRIORITY.
Example:
package ThreadClass;
Output:
running thread name is:Thread-1
running thread priority is:10
running thread name is:Thread-0
running thread priority is:1
Synchronization:
Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
Java Synchronization is better option where we want to allow only one thread to access
the shared resource.
Synchronization can be used in ticketing systems or any booking systems, banking
transactions, etc. Without synchronization we can face the problems like data
inconsistency, Thread interference(one thread interfere other may cause deadlock).
class CSITBookSeat {
Output:
30 seats books successfully
30 seats books successfully
18 seats are available
-12 seats are available
Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent access
to an object's fields has to acquire the object's lock before accessing them, and then
release the lock when it's done with them.
package ThreadClass;
class CSITBookSeat {
Output:
30 seats books successfully
18 seats are available
Seats are not vailable
18 seats are available
Or
28 seats books successfully
20 seats are available
Seats are not vailable
20 seats are available
Example:
package ThreadClass;
class CSITBookSeat {
int csit_seats = 48;
Note: Synchronized block is used in that area of a program where there is a data
inconsistency problem occurred.
3. Static synchronization:
So far we have worked for only one object, what if we create more objects and execute
different object‘s thread, there seems the same inconcistence problem.
Example:
package ThreadClass;
class CSITSeatBook {
In above example, both objects have 48 plus 48 seats each to access but the total seats
must be 48 for both objects. There occurs inconsistence, so to resolve this problem static
synchronization is used. Following example uses static synchronization;
package ThreadClass;
class CSITSeatBook {
}
}
Inter-Thread Communication
Inter thread communication is a mechanism in which a thread releases the lock and enter
into paused state and another thread acquires the lock and continue to execute. It is
implemented by following methods;
1. wait():- If any thread calls the wait() method, it causes the current thread to
release the lock and wait until another thread invokes the notify() or notifyAll()
method for this object, or specifies amount of time has elapsed.
Syntax:
public final void wait() throws InterruptedException {}- wait until object is
notified
public final void wait(long timeout) throws InterruptedException {}- waits for
the specified amount of time.
2. notify():- This method is used to wake up a single thread and releases the object
lock.
Syntax:
public final void notify(){}
3. notifyAll():- This method is used to wake up all threads that are in waiting state.
Syntax:
public final void notifyAll(){}
Note: to call wait(), notify() or notifyAll() method on any object, thread should
own the lock of that object. i.e. the thread should be inside synchronized area.
Example:
class TotalEarnings extends Thread {
int total = 0;
Note:
it gives inaccurate total value because run method takes some times to execute, so at that
time main thread executes and the value will be total=0. Main thread executes before
thread-0.
Description:
In above program we can see there are two synchronized blocks, one inside main thread
and another inside thread-0 thread. This is the main reason to get the correct calculation
of the program.
There are basically two areas inside any object of a class, which are non-synchronized
and synchronized areas as shown in figure.
Deadlock:
Deadlock is a situation where two or more threads are blocked forever, waiting for each
other. It occurs in java when synchronized keyword causes the executing thread to block
waiting to get the lock, associated with the specified object.
Example:
class DeadlockOne extends Thread {
private Object object1;
private Object object2;
Description:
The above program has a deadlock. There are two threads thread-0 and thread-1 and both
are acquiring the lock needed by both.
So to remove the deadlock condition, objects are provided in the same order in which
order they are required.
So, modify the partial code as follows;
After executing modified code, there will be no any deadlocks. Clear the console
terminal and execute fresh one.
Unit 8: I/O and Streams [2 hours]
Java.io package, Files and directories, streams: Byte streams and character
streams:Reading/Writing console Input/Output, Reading and Writing Files, The
serialization Interface, Serialization and Deserialization.
java.io package
This package provides for system input and output through data streams, serialization and
the file system. Unless otherwise noted, passing a null argument to a constructor or method
in any class or interface in this package will cause a NullPointerException to be thrown.
Some of the classes are as follows;
BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
DataInputStream
DataOutputStream
FileInputStream
FileOutputStream
FileReader
FileWriter
PrintStream
PrintWriter
InputStream
OutputStream
File
And so on…
Data stored in variables and arrays is temporary-it lost when a local variable goes
out of scope or when the program terminates. For long term retention of data, even
after the programs that create the data terminate, computers use files.
So we use hard drive to save files, documents , etc. to use the data in future.
Data hierarchy
Bits: The smallest data item in a computer can assume the value 0 or the value 1.
Characters: characters are composed of bits. Digits, letters and special symbols are
known as characters.
Fields: Fields are composed of characters or bytes. E.g. The uppercase and
lowercase letters can be used to represent a person‘s name(Harendra Raj Bist).
Records and Files: Typically, several fields are composed of a record. E.g. record
for an employee might consist of the following fields;
Employee identification number(int)
Name(String)
Address(String), etc.
Stream Classes
The java.io package contains a large number of stream classes that provide
capabilities for processing all types of data. These classes may be categorised into
two groups based on the data type on which they operate;
Byte Stream classes that provide support for handling I/O operations on
bytes.
Character Stream classes that provide support for managing I/O operations
on characters.
This package includes definitions for stream classes, such as FileInputStream,
FileOutputStream, FileReader and FileWriter.
Byte Character
Stream Stream
Classes Classes
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
try {
inputStream = new FileReader("C:\\Users\\haren\\Desktop\\test.txt");
outputStream = new FileWriter("C:\\Users\\haren\\Desktop\\test1.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
BufferedWriter outputStream = null;
try {
inputStream = new BufferedReader(new
FileReader("C:\\Users\\haren\\Desktop\\test.txt"));
outputStream = new BufferedWriter(new
FileWriter("C:\\Users\\haren\\Desktop\\test1.txt"));
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}
try{
RandomAccessFile file = new
RandomAccessFile("C:\\Users\\haren\\Desktop\\test.txt","rw");
//Writing to the file
file.writeChars("X");
file.writeInt(100);
file.writeDouble(3.1424);
file.seek(0);
Before reading and writing an object to any file, first we need to understand about the
Serialization. It is a process of converting objects into writable byte stream. Once converted into a
byte stream, these objects can be written to a file. A java object is a serializable if its class or any
superclasses implement the java.io.Serializable interface.
Example:
import java.io.Serializable;
// Read objects
Student st1 = (Student) oi.readObject();
Student st2 = (Student) oi.readObject();
class deseriazable {
public static void main(String args[]) {
try {
// Creating stream to read the object
ObjectInputStream in = new ObjectInputStream(new FileInputStream("harendra.t
xt"));
Student s = (Student) in.readObject();//deserialization
// printing the data of the serialized object
System.out.println(s.name + " " + s.age + " " + s.gender);
// closing the stream
in.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Unit 9: Understanding Core Packages [3 hours]
Using java.lang Package: java.lang.Math, Wrapper classes and associated methods
(Number, Double, Float; Integer, Byte; Short, Long; Character, Boolean); Using
java.util package: Core classes (Vector, Stack, Dictionary, Hashtable, Enumerations,
Random Number Generation).
java.lang.Math:
The java.lang.Math class contains methods for performing basic numeric operations
such as the elementary exponential, logarithm, square root, and trigonometric functions.
Java Math class provides several methods to work on math calculations like min(),
max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
Example:
public class MathPackageDemo{
public static void main(String[] args){
double x = 28;
double y = 4;
System.out.println("Maximum number of x and y is: " +Math.max(x, y));
System.out.println("Square root of y is: " + Math.sqrt(y));
System.out.println("Power of x and y is: " + Math.pow(x, y));
System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));
System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("log10 of y is: " + Math.log10(y));
int a=30;
// converting values to radian
double b = Math.toRadians(a);
// return the trigonometric sine of a
System.out.println("Sine value of a is: " +Math.sin(a));
// return the trigonometric cosine value of a
System.out.println("Cosine value of a is: " +Math.cos(a));
// return the trigonometric tangent value of a
System.out.println("Tangent value of a is: " +Math.tan(a));
// return the trigonometric arc sine of a
System.out.println("Sine value of a is: " +Math.asin(a));
// return the trigonometric arc cosine value of a
System.out.println("Cosine value of a is: " +Math.acos(a));
// return the trigonometric arc tangent value of a
System.out.println("Tangent value of a is: " +Math.atan(a));
// return the hyperbolic sine of a
System.out.println("Sine value of a is: " +Math.sinh(a));
// return the hyperbolic cosine value of a
System.out.println("Cosine value of a is: " +Math.cosh(a));
// return the hyperbolic tangent value of a
System.out.println("Tangent value of a is: " +Math.tanh(a));
}
}
Wrapper classes and associated methods (Number, Double, Float; Integer, Byte; Short,
Long; Character, Boolean);
The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert
the primitive into objects.
//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);
//Printing primitives
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}}
Vector:
Vector is used to generic dynamic array that can hold objects of any type and any
number. Unlike array, the objects do not have to be homogenous. Vectors are created like
arrays as follows;
Vector intvect = new Vector();//declaring vector array without size
Vector intvect = new Vector(5);//declaring vector array with size
Output:
Intial Vector Array is: [Harendra, Narendra, Ram, Shyam]
The capacity of a vector is: 30
The size of a vector array or list is: 4
Is Harendra contained in current list?: true
All elements of coll present in list? false
The element at 3rd position is :Shyam
Modified Vector Array is: [Harendra, Narendra, Ram, Shyam, Suresh, Ramesh]
The size of a modified vector array or list is: 6
The sixth item is Ramesh
Modified Vector Array after removing is: [Harendra, Narendra, Shyam, Suresh,
Ramesh]
The size of a modified vector array or list is: 5
Modified Vector Array after removeElementAt(2) is: [Harendra, Narendra, Suresh,
Ramesh]
The size of a modified vector array or list is: 4
Modified Vector Array after insertElementAt() is: [Harendra, Narendra, Gita, Suresh,
Ghanshyam, Sita, Ramesh]
The size of a modified vector array or list is: 7
The array items are:
Harendra Narendra Gita Suresh Ghanshyam Sita Ramesh
The final vector list is empty: []
Stack:
The Stack class inherits or extends Vector class. Additionally, stack class contain some
methods to perform operations such as pop, push, peek and search.
Methods used in stack class implementation;
Methods Descriptions
st.empty() Returns true if stack is empty
st.peek() Returns the element at the top of stack
st.pop() Removes the element from top of stack and
return the removed element
st.push() Adds an item to the top of the stack
Implementation:
import java.util.Stack;
Output:
The element in the stack are: [Java, is, an, object, oriented, programming, language]
Element at Top of Stack: language
The element popped out of the Stack(Top of Stack) is: language
The element in the stack after pop operation are: [Java, is, an, object, oriented,
programming]
The result of searching object: 3
Implementation:
import java.util.*;
// put method
dictionary.put("Apple", "A fruit");
dictionary.put("Ball", "A round shaped toy");
dictionary.put("Car", "A four wheeler vehicle designed to accomodate usually four p
eople");
dictionary.put("Dog", "An animal with four legs and one tail");
// get method
System.out.println("\nApple: " + dictionary.get("Apple"));
System.out.println("Dog: " + dictionary.get("Dog"));
System.out.println("Elephant: " + dictionary.get("Elephant"));
System.out.println();
// elements method
for (Enumeration<String> i = dictionary.elements(); i.hasMoreElements();) {
System.out.println("Values contained in Dictionary : " + i.nextElement());
}
System.out.println();
// keys method :
for (Enumeration<String> k = dictionary.keys(); k.hasMoreElements();) {
System.out.println("Keys contianed in Dictionary : " + k.nextElement());
}
// isEmpty method
System.out.println("\nThe dictionary is empty? " + dictionary.isEmpty());
// remove method :
dictionary.remove("Dog");
// size method
System.out.println("\nSize of Dictionary : " + dictionary.size());
}
}
Output:
Apple: A fruit
Dog: An animal with four legs and one tail
Elephant: null
Values contained in Dictionary : An animal with four legs and one tail
Values contained in Dictionary : A round shaped toy
Values contained in Dictionary : A fruit
Values contained in Dictionary : A four wheeler vehicle designed to accomodate usually
four people
Dog: null
Size of Dictionary : 3
Random Number Generation:
Random numbers within a specific range of type integer, float, double, long, and boolean
can be generated in Java.
Implementation:
import java.util.Random;
}
}
Output:
Default Random integer 1458303222
Random integer value from 0 to24
Random float value between 0.0 and 1.0 : 0.5172497
Random double value between 0.0 and 1.0 : 0.10373183149200027
Unit 10: Holding Collection of Data [3 hours]
Arrays and Collection Classes/Interface, Map/List/Set implementation: Map Interface,
List Interface, Set Interface.
The collection framework which is contained in the java.util package is one of Java‘s most
powerful sub-systems. The collection framework contains many interfaces such as Collection,
Map, and Iterator. Other interfaces of the framework extend these interfaces. The interfaces List
and Set are the sub-interfaces of the Collection interface. The SortedMap interface is the sub-
interface of the Map interface.
Map , List and Set can be cleary shown in picture below;
Iterator
Collection
ListIterator
List
Queue
Set
SortedSet
Map
SortedMap
Methods Description
add(Object o) Returns true if object is added to the specified collection
addAll(Collection c) Return true if entire object in the collection is added to the
specified collection.
clear() Removes all elements from the collection
contains(Object o) Returns true if the collection contains specified element
containsAll(Collection c) Returns true if the collection contains all the elements in the
specified collection
equals(Object o) Returns true if the specified object matches to the object in the
collection
hashCode() Return the hash code for the collection
isEmpty() Returns if the collection is empty
iterator() Returns iterator over the elements in the collection
remove(Object o) Removes an object from the collection.
removeAll(Collection c) Returns true if all the elements in collection c is removed from the
specified collectiomn.
retainAll(Collection c) Returns true if all the elements in collection c is retained from the
specified collectiomn
size() Returns the number of elements in the collection
toArray() Returns an array containing all of the elements in the collection
toArray (Object[] a) Returns an array of object if the array contains all the elements in
the specified collection
The set interface extends the Collection interface and it contains all the methods that are inherited
from the collection interface. The set interface does not allow the duplicate entry in a collection
so, add() method returns false if we are going to add duplicate element in a collection.
ArrayList:
The ArrayList class extends the AbstractList class and implements Interfaces such as
List, Cloneable and Serializable. Using the ArrayList class, we can use dynamic array in
java applications. The dynamic array is an array in which the array size is not fixed in
advance. Therefore, we can change the size of an array at run time using ArrayList class.
Every instance of arrayList class is allowed to store a set of elements in the List. The
capacity increases automatically if we add elements to the list.
Constructors used in ArrayList are;
ArrayList(): default constructor
ArrayList(Collection c): Creates a list to which the elements of the specified collection
are added.
ArrayList(int capacity): Creates empty list. The capacity of the list is initialized to the
specified value.
The ArrayList class inherits the methods from the List interface. Te elements of an array
can be accessed directly using get() and set() methods. The add() method is used to add
elements to the array list and remove() method is used to remove the elements from the
array list.
Example:
import java.util.ArrayList;
Output:
Initial size of an array: 0
Size of an array after elements are added: 4
Elements of list are: [Ram, shyam, harendra, hitesh]
Elements of modified list are: [Manish, Ram, shyam, harendra, Rajendra, hitesh]
The item at index 3 is: shyam
List after removing some elements are: [Ram, shyam, harendra, hitesh]
LinkedList:
The LinkedList class extends the AbstractSequentialList class and implements the List
interface. This class supports the methods shown below;
These methods allow us to insert and remove elements in a list. We can use the list as a
stack, queue and doubly linked list. The constructor of LinkedList are;
LinkedList()
LinkedList(Collection c)
Example:
import java.util.LinkedList;
HashSet:
The HashSet class extends the AbstractSet class and implements the Set interface. The
HashSet class is used to create a collection and store it in a hash table. Each collection
refers to a unique value called hash code. The hash code is used as an index to associate
with the object, which is stored in the hash table. This type of storing in a hash table is
called hashing. Constructors for HashSet are as follows;
HashSet()
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillratio): Initializes capacity and fill ratio of the HashSet. The
value of fill ratio ranges from 0.0 to 1.0. This value is used to set the initial size of the
hash set. If the number of elements is greater than the capacity of the hash set, the size of
the hash set is expanded automically by multiplying the capacity with the fill ratio. The
default value of fill ratio is 0.75.
Example:
import java.util.HashSet;
Output:
The elements in the HashSet are: [Earth, Mars, Neptune, Saturn, Venus, Uranus, Jupitor,
Pluto]
true
List after removing Pluto: [Earth, Mars, Neptune, Saturn, Venus, Uranus, Jupitor]
TreeSet:
The TreeSet class implements the Set interface. The sorted elements are stored in a Tree
structure. This class allows us to retrieve or access the elements in less time. Constructors
are shown below;
TreeSet()
TreeSet(Collection c)
TreeSet(Comparator co): Build the TreeSet based on the comparator.
TreeSet(SortedSet s): Builds a TreeSet which contains elements in the specified order.
Example:
import java.util.TreeSet;
Output:
The elements in the TreeSet are: [Earth, Jupitor, Mars, Neptune, Pluto, Saturn, Uranus,
Venus]
true
List after removing Pluto: [Earth, Jupitor, Mars, Neptune, Saturn, Uranus, Venus]
List after adding Sun: [Earth, Jupitor, Mars, Neptune,
Saturn, Sun, Uranus, Venus]
TreeSet after clearing : []
Java Iterator
Example:
import java.util.ArrayList;
import java.util.Iterator;
Java Comparator:
Java Comparator interface is used to order the objects of a user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object
obj1,Object obj2) and equals(Object element).
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any
data member, for example, rollno, name, age or anything else.
public void sort(List list, Comparator c): is used to sort the elements of List by the
given Comparator.
Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Student {
int rollno;
String name;
int age;
System.out.println("Sorting by Name");
Output:
Sorting by Name
105 Birendra 35
104 Dipendra 25
101 Harendra 32
104 Harendra 30
106 Narendra 40
Sorting by age
104 Dipendra 25
104 Harendra 30
101 Harendra 32
105 Birendra 35
106 Narendra 40
Unit 11: Java Applications [8 hours]
About AWT and Swing, About JFrame (a top level window in swing), swing components
(JLabel, About text components like JTextField, JButton, Event Handling in Swing
Applications, Layout Management using FlowLayout, Border Layout, Grid Layout, Using
JPanel, Choice Components like JCheckBox, JRadioButton, Borders Components,
JComboBox and its events, JList and its events with MVC patterns, Key and Mouse Event
Handling, Menus in Swing, JTextArea, Dialog boxes in Swing, JTable for Displaying data
in tabular form, MDI using JDesktopPane and JInternalFrame, Using IDE like netbeans:
JBuilder for building java applications using Drag and Drop), Adapter classes.
GUI provides a user friendly mechanism for interacting with an application. The
components used in any applications, Such as Jframe, TextFields, TextAreas,
Radiobuttons, Checkboxes, ComboBoxes, etc. are the examples of GUI components.
Concept of AWT:
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Example:
Several Swing GUI components from package javax.swing are used to build java
GUIs. Swing is known as lightweight UI because it uses its own look and feel in
every OS unlike AWT.
Some basic GUI components are as follows;
JLabel: displays ineditable text or icons.
JTextField: enables user to enter data.
JButton: triggers an event when clicked.
JCheckBox: specifies an option that can be selected.
JComboBox: provides dropdown list.
JList: Multiple items can be selected from the JList.
JPanel: provides an area in which components can be placed and organized.
Object Jlabel
Component JList
JTable
Container JComponent
JTextArea
JComboBox
Window Panel
JSlider
Applet
JButton
There are actually two sets of GUI components in java. Before swing was
introduced Java GUIs are built with components from Abstract Window
Toolkit(awt) in package java.awt.
When a Java application with awt GUI executes on different Java platforms, the
application‘s GUI components display differently on each platform.
E.g. But using Swing the component button in windows OS will have the same
appearance as the buttons in other windows applications and the component
button in macintosh os will have the same appearance of button as in other
macintosh applications.
Using swing GUI components there is a uniform look and feel of components all
across the platforms.
Layout Management
Layout Manager:
Layout Managers arrange the GUI component in a container for presentation
purposes.
All layout managers implement the interface LayoutManager(in package
java.awt). Class Container‘s setLayout method takes an object that implements the
LayoutManager interface as an argument.
FlowLayout:
◦ Default for javax.swing.JPanel. Places the components sequentially (from
left to right) in the order they were added. It‘s also possible to specify the
order of the components by using the container method add, which takes a
component and an integer index position as argument.
BorderLayout:
◦ Default for JFrames. Arranges the components into five areas: NORTH,
SOUTH, EAST, WEST and CENTER.
GridLayout:
◦ Arranges the components into single row and column.
FlowLayout:
FlowLayout is the simplest layout manager. GUI components are arranged on a
container from left to right in the order in which they are added to the container. It
is the default layout manager.
When the edge of the container is reached, components continue to display on the
next line.
Class FlowLayout allows GUI components to be left aligned, centered(default
one) and right aligned.
FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.
Simple Example:
import java.awt.*;
import javax.swing.*;
FlowLayoutDemo() {
setLayout(new FlowLayout());
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
BorderLayout :
BorderLayout manager is the default layout manager for the JFrame.
It arranges the components into five regions: NORTH, SOUTH, EAST, WEST
AND CENTER.
NORTH corresponds to the top of the container, SOUTH corresponds to the
bottom, EAST corresponds to the right, WEST corresponds to the left.
BorderLayout(): creates a border layout but with no gaps between the
components.
JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
Simple Example:
import java.awt.*;
import javax.swing.*;
BorderLayoutDemo() {
setLayout(new BorderLayout(5, 5));// vgap and hgap 5
JButton b1 = new JButton("NORTH");
JButton b2 = new JButton("SOUTH");
JButton b3 = new JButton("EAST");
JButton b4 = new JButton("WEST");
JButton b5 = new JButton("CENTER");
add(b1, BorderLayout.NORTH);
add(b2, BorderLayout.SOUTH);
add(b3, BorderLayout.EAST);
add(b4, BorderLayout.WEST);
add(b5, BorderLayout.CENTER);
setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
GridLayout
GridLayout manager divides the container into a grid so that the components can
be placed in rows and columns.
Every component in a GridLayout has the same width and height.
Components are added to a GridLayout starting at the top-left cell of the grid and
proceeding left to right untill the row is full.
And, the process continues left to right on the next row and so on.
GridLayout(): creates a grid layout with one column per component in a row.
GridLayout(int rows, int columns): creates a grid layout with the given rows
and columns but no gaps between the components.
GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout
with the given rows and columns alongwith given horizontal and vertical gaps.
Example:
import java.awt.*;
import javax.swing.*;
MyGridLayout() {
layout = new GridLayout(3, 3, 5, 5);// 3 by 3 grids and 5 hgap and vgap
setLayout(layout);
setTitle("Grid Layout");
setSize(300, 300);
JButton b1 = new JButton("1");
JButton b2 = new JButton("2");
JButton b3 = new JButton("3");
JButton b4 = new JButton("4");
JButton b5 = new JButton("5");
JButton b6 = new JButton("6");
JButton b7 = new JButton("7");
JButton b8 = new JButton("8");
JButton b9 = new JButton("9");
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Text Input
Text Fields, Password Fields, Text Areas, Scroll Pane, Label and Labeling
Components.
We are finally ready to start introducing the Swing user interface components. We
start with components that let a user input and edit text. You can use the
JTextField and JText-area components for gathering text input.
A text field can accept only one line of text; a text area can accept multiple lines of
text.
A JPasswordField accepts one line of text without showing the contents.
Note: All three of these classes inherit from a class called JTextComponent. You
will not be able to construct a JTextComponent yourself because it is an abstract
class.
The usual way to add a text field to a window is to add it to a panel or other
container:
JPanel panel = new JPanel();
JTextField textField = new JTextField("Default input", 20);
panel.add(textField);
This code adds a text field and initializes the text field by placing the string
"Default input‖ inside it. The second parameter of this constructor sets the
width. In this case, the width is 20 ―columns.‖
One column is the expected width of one character in the font you are using for
the text.
If you need to reset the number of columns at runtime, you can do that with the
setColumns method.
TIP: After changing the size of a text box with the setColumns method, call the
revalidate method of the surrounding container.
textField.setColumns(10);
panel.revalidate();
The revalidate method recomputes the size and layout of all components in a
container.
After you use the revalidate method, the layout manager resizes the container, and the
changed size of the text field will be visible.
JTextField textField = new JTextField(20);
You can change the content of the text field at any time by using the setText
method from the JTextComponent parent class mentioned in the previous section.
For example:
◦ textField.setText("Hello!");
◦ String text = textField.getText().trim();
◦ This method returns the exact text that the user typed. To trim any
extraneous leading and trailing spaces from the data in a text field, apply
the trim method to the return value of getText.
To change the font in which the user text appears, use the setFont method.
void setFont(Font f)
Labels are components that hold text. They have no decorations (for example, no
boundaries). They also do not react to user input. You can use a label to identify
components.
1. Construct a JLabel component with the correct text.
2. Place it close enough to the component you want to identify so that the user can
see that the label identifies the correct component.
The constructor for a JLabel lets you specify the initial text or icon, and
optionally, the alignment of the content. You use constants from the
SwingConstants interface to specify alignment. That interface defines a number of
useful constants such as LEFT, RIGHT, CENTER, NORTH, EAST, and so on.
The JLabel class is one of several Swing classes that implement this interface.
Therefore, you can specify a right-aligned label either as
◦ JLabel label = new JLabel("User name: ", SwingConstants.RIGHT);
or
◦ JLabel label = new JLabel("User name: ", JLabel.RIGHT);
The setText and setIcon methods let you set the text and icon of the label at runtime.
javax.swing.Jlabel contains
JLabel(String text)
JLabel(Icon icon)
JLabel(String text, int align)
JLabel(String text, Icon icon, int align) constructs a label.
String getText()
void setText(String text)
gets or sets the text of this label.
Icon getIcon()
void setIcon(Icon icon) gets or sets the icon of this label.
Parameters: text The text in the label
icon The icon in the label
align One of the swingConstants constants
LEFT (default), CENTER,
or RIGHT.
Password Fields
Password fields are a special kind of text field. The characters that the user
entered are not actually displayed.
Instead, each typed character is represented by an echo character, typically an
asterisk (*).
Swing supplies a JPasswordField class that implements such a text field.
javax.swing.JPasswordField contains
JPasswordField(String text, int columns) constructs a new password field.
void setEchoChar(char echo) sets the echo character for this password field. This
is advisory; a particular look and feel may insist on its own choice of echo
character. A value of 0 resets the echo character to the default.
char[] getPassword() returns the text contained in this password field. For stronger
security, you should overwrite the content of the returned array after use. (The
password is not returned as a String because a string would stay in the virtual
machine until it is garbage-collected.)
Text Areas
Sometimes, we need to collect user input that is more than one line long. As
mentioned earlier, we use the JTextArea component for this collection. When we
place a text area component in our program, we can enter any number of lines of
text, using the ENTER key to separate them.
In the constructor for the JTextArea component, you specify the number of rows
and columns for the text area. For example,
textArea = new JTextArea(8, 40); // 8 rows 40 columns each.
◦ textArea.setRows(10); textArea.setColumns(50); to change the number of
rows and columns respectively.
If there is more text than the text area can display, then the remaining text is
simply wrapped.
textArea.setLineWrap(true); // long lines are wrapped
Implementation:
package TextInput;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
add(northPanel, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
insertButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
textArea.append("User name: " + textField.getText() + " Password: "
+ new String(passwordField.getPassword()) + "\n");
}
});
add(southPanel, BorderLayout.SOUTH);
Components providing the choice chosen from set of items, or choosing any one of the item or
choosing many items.
CheckBoxes:
If you want to collect just a ―yes‖ or ―no‖ input, use a checkbox component.
Checkboxes automatically come with labels that identify them.
The user usually checks the box by clicking inside it and turns off the check mark
by clicking inside the box again.
To toggle the check mark, the user can also press the space bar when the focus is in the
checkbox.
Checkboxes need a label next to them to identify their purpose. You give the label
text in the constructor.
o bold = new JCheckBox("Bold");
You use the setSelected method to turn a checkbox on or off. For example:
o bold.setSelected(true);
The isSelected method then retrieves the current state of each checkbox. It is false
if unchecked; true if checked.
When the user clicks on a checkbox, this triggers an action event. As always, you
attach an action listener to the checkbox. In our program, the two checkboxes
share the same action listener.
o ActionListener listener = . . .
o bold.addActionListener(listener);
o italic.addActionListener(listener);
The actionPerformed method queries the state of the bold and italic
checkboxes and sets the font of the panel to plain, bold, italic, or both
bold and italic.
Implementation:
package ChoiceComponents;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public CheckBoxFrame()
{
setTitle("CheckBoxTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
label = new JLabel("The quick brown fox jumps over the lazy dog.");
label.setFont(new Font("Serif", Font.PLAIN, FONTSIZE));
add(label, BorderLayout.CENTER);
package ChoiceComponents;
import javax.swing.JFrame;
Radio Buttons:
In many cases, we want to require the user to check only one of several boxes.
When another box is checked, the previous box is automatically unchecked. Such a group of
boxes is often called a radio button group because the buttons work like the station selector
buttons on a radio. When you push in one button, the previously depressed button pops out.
Implementing radio button groups is easy in Swing. We can construct one object of type
ButtonGroup for every group of buttons. Then, we can add objects of type JRadioButton
to the button group. The button group object is responsible for turning off the previously
set button when a new button is clicked.
◦ ButtonGroup group = new ButtonGroup();
◦ JRadioButton smallButton = new JRadioButton("Small", false);
◦ group.add(smallButton);
◦ JRadioButton mediumButton = new JRadioButton("Medium", true);
◦ group.add(mediumButton);
Example:
package ChoiceComponents;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public RadioButtonFrame()
{
setTitle("RadioButtonTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
label = new JLabel("The quick brown fox jumps over the lazy dog.");
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
add(label, BorderLayout.CENTER);
addRadioButton("Small", 8);
addRadioButton("Medium", 12);
addRadioButton("Large", 18);
addRadioButton("Extra large", 36);
add(buttonPanel, BorderLayout.SOUTH);
}
button.addActionListener(listener);
}
}
package ChoiceComponents;
import javax.swing.JFrame;
Borders:
If you have multiple groups of radio buttons in a window, you will want to
visually indicate which buttons are grouped. Swing provides a set of useful
borders for this purpose.
Border can be applied to any component that extends JComponent. The most
common usage is to place a border around a panel and fill that panel with other
user interface elements such as radio buttons.
Types of Borders:
We can choose from quite a few borders, but you follow the same steps for all of them.
1. Call a static method of the BorderFactory to create a border. You can choose
among the following styles:
Lowered bevel(tilt)
Raised bevel
Etched
Line
Matte
Empty (just to create some blank space around the component)
2. add a title to our border by passing border to BorderFactory.createTitledBorder.
3. combining several borders with a call to BorderFactory.createCompoundBorder.
4. Add the resulting border to your component by calling the setBorder method of
the JComponent class.
For example, here is how we can add an etched border with a title to a panel:
◦ Border etched = BorderFactory.createEtchedBorder()
◦ Border titled = BorderFactory.createTitledBorder(etched, "A Title");
panel.setBorder(titled);
Example:
package ChoiceComponents;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
public BorderFrame() {
setTitle("BorderTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
addRadioButton("Lowered bevel",
BorderFactory.createLoweredBevelBorder());
addRadioButton("Raised bevel",
BorderFactory.createRaisedBevelBorder());
addRadioButton("Etched", BorderFactory.createEtchedBorder());
addRadioButton("Line", BorderFactory.createLineBorder(Color.BLUE));
addRadioButton("Matte", BorderFactory.createMatteBorder(10, 10, 10,
10, Color.BLUE));
addRadioButton("Empty", BorderFactory.createEmptyBorder());
group.add(button);
buttonPanel.add(button);
}
}
package ChoiceComponents;
Combo Boxes:
radio buttons are not a good choice because they take up too much screen space.
The alternative is combobox. When the user clicks on the component, a list of
choices drops down, and the user can then select one of them.
The JComboBox class provides a combo box component.
Implementation:
package ChoiceComponents;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public ComboBoxFrame()
{
setTitle("ComboBoxTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// the combo box listener changes the label font to the selected face name
faceCombo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
label.setFont(new Font((String)
faceCombo.getSelectedItem(), Font.PLAIN,
DEFAULT_SIZE));
}
});
// add combo box to a panel at the frame's southern border
JPanel comboPanel = new JPanel();
comboPanel.add(faceCombo);
add(comboPanel, BorderLayout.SOUTH);
}
}
package ChoiceComponents;
Example:
Model – CourseModel.java
package mvcPackage;
View – CourseView.java
package mvcPackage;
Controller – CourseController.java
package mvcPackage;
package mvcPackage;
JList:
The JList Component:
– The JList component is similar to a set of check boxes or radio buttons,
except that the items are placed inside a single box and are selected by
clicking on the items themselves, not on buttons. If you permit multiple
selection for a list box, the user can select any combination of the items in
the box.
• To construct this list component, you first start out with an array of strings, then
pass the array to the JList constructor:
– String[] words= { "quick", "brown", "hungry", "wild", ... };
– JList wordList = new JList(words);
• Alternatively, we can use an anonymous array:
– JList wordList = new JList(new String[] {"quick", "brown", "hungry",
"wild", ... });
• List boxes do not scroll automatically. To make a list box scroll, you must insert it
into a scroll Pane:
– JScrollPane scrollPane = new JScrollPane(wordList);
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
JList(ListModel<ary> Creates a JList that displays elements from the specified,
dataModel) non-null, model.
Methods Description
Void It is used to add a listener to the list,
addListSelectionListener(ListSelectionListener to be notified each time a change to
listener) the selection occurs.
int getSelectedIndex() It is used to return the smallest
selected cell index.
ListModel getModel() It is used to return the data model
that holds a list of items displayed
by the JList component.
void setListData(Object[] listData) It is used to create a read-only
ListModel from an array of objects.
Example:
package mvcPackage;
import javax.swing.JFrame;
import javax.swing.JList;
public JListDemo() {
String week[] = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
list = new JList<String>(week);
list.setSelectedIndex(3);
add(list);
setSize(200, 300);
setVisible(true);
}
public static void main(String[] args) {
new JListDemo();
}
}
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public JListDemo() {
setTitle("JList Event Handler");
layout = new FlowLayout();
setLayout(layout);
String week[] = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
list = new JList<String>(week);
list.setSelectedIndex(3);
list.addListSelectionListener(this);
add(list);
lbl = new JLabel("Select Day and Displayed here..");
add(lbl);
setSize(400, 300);
setVisible(true);
}
@Override
public void valueChanged(ListSelectionEvent e) {
lbl.setText(list.getSelectedValue());
}
}
JMenuBar:
Menu Bar
A menu bar on top of the window contains the names of the pull-down menus.
Clicking on a name opens the menu containing menu items and submenus.
When the user clicks on a menu item, all menus are closed and a message is sent to the
program.
Menu Building
Building menus is straightforward. Creation of menu-bar:
◦ JMenuBar menuBar = new JMenuBar();
A menu bar is just a component that we can add anywhere we like. Normally, menu-bar
appear at the top of a frame. We can add it there with the setJMenuBar method:
◦ frame.setJMenuBar(menuBar);
For each menu, we can create a menu object:
◦ JMenu editMenu = new JMenu("Edit");
Adding top level menus
◦ menuBar.add(editMenu);
menu items, separators, and submenus to the menu object:
◦ JMenuItem pasteItem = new JMenuItem("Paste");
◦ editMenu.add(pasteItem);
◦ editMenu.addSeparator();
◦ JMenu optionsMenu = . . .; // a submenu
◦ editMenu.add(optionsMenu);
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
public MenuDemo() {
super("Menu Demo File Frame");
setSize(400, 300);
setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mb = new JMenuBar();
fm = new JMenu("File");
vm = new JMenu("View");
em = new JMenu("Edit");
zm = new JMenu("Zoom");
mb.add(fm);
mb.add(vm);
mb.add(em);
fm.setMnemonic('F');//alt+f
vm.setMnemonic('V');//alt+v
em.setMnemonic('E');//alt+e
miopen = new JMenuItem("Open", 'o');
misave = new JMenuItem("Save", 's');
misb = new JCheckBoxMenuItem("Status Bar", true);
fm.add(miopen);
fm.add(misave);
vm.add(misb);
vm.add(zm);
JMenuItem exit = new JMenuItem("Exit", KeyEvent.VK_N);
exit.setAccelerator(KeyStroke.getKeyStroke("ctrl X"));//press ctrl+x
fm.add(exit);
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
setJMenuBar(mb);
setVisible(true);
}
public static void main(String[] args) {
MenuDemo frame = new MenuDemo();
}
}
JTable:
The JTable class is used to display data in tabular form. It is composed of rows and
columns.
• A table 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. Tables are implemented by the JTable class, which extends
JComponent.
• One of its constructors is shown here:
– JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and
colHeads is an onedimensional array with the column headings.
Example:
package mvcPackage;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
JTableDemo() {
f = new JFrame();
String data[][] = { { "101", "Harendra", "100000" }, { "102", "Mahendra",
"200000" },
{ "101", "Narendra", "300000" } };
String column[] = { "ID", "NAME", "SALARY" };
JTable jt = new JTable(data, column);
jt.setBounds(30, 40, 200, 300);
JScrollPane sp = new JScrollPane(jt);
jt.setValueAt("Surendra", 0, 1);//modify the value at [0,1] cell
jt.addColumn(new TableColumn(2));//add the copy of the column at index
2
f.add(sp);
f.setSize(300, 400);
f.setVisible(true);
}
Event: An event is an object that describes a state change in a source. It can be generated
as a consequence of a program interacting with the elements in a graphical user interface.
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. Some of the event sources are JButtons, JTextFields, JComboBoxs,
Jsliders, Window, etc.
Event Listeners: To react to an event, there is a need to implement correct event listener.
A listener is an object that is notified when an event occurs. Some of the commonly used
listeners are ActionListener, KeyListener, FocusListener, WindowListener,
ChangeListener, etc.
Basically, event handling is the process of controlling the events created by the
components(such as: Jbutton, JCheckBox, JRadioButton, JList, etc.).
Different event sources can produce different kinds of events. For example, a button can
send ActionEvent objects, whereas a window can send WindowEvent objects.
Event Delegation Model: Modern versions of java use the Delegation Event Model to
handle the events. This model defines the standard mechanism to generate and handle the
events. In this model, source generates an event and sends it to one or more listeners. All
classes used in event handling process are known as delegated classes.
• When an event is triggered the JAVA runtime first determines its source and type.
• If a listener for this type of event is registered with the source an event object is
created.
• For each listener to this type of event, the java runtime invokes the appropriate
event handling method to the listener and passes the event object as the parameter.
Figure: Event Handling
Action Event:
• In Java, most components have a special event called an ActionEvent. This is one
of the most common event for that component. A good example is a click for a
button. To have any component listen for an ActionEvent, we must register the
component with an ActionListener as;
• Component.addActionListener(new ActionListener());
• And then write the
• Public void actionPerformed(ActionEvent event){
– Method for the component to react to the event
}
Example:
class EventHandling implements ActionListener{ //Step 1(ActionListener interface is
implemented)
public DelegationModelDemo() {
super("Handling Action Events");
l1= new JLabel("First Value");
t1=new JTextField(10);
l2= new JLabel("Second Value");
t2=new JTextField(10);
l3= new JLabel("Result");
t3=new JTextField(10);
b1=new JButton("+");
b2=new JButton("-");
b1.addActionListener(this); //’this’ represent a class that implements
ActionListener
b2.addActionListener(this); //’this’ represent a class that implements
ActionListener
The class KeyEvent is defined in java.awt.event package. Key events occur when
a key is pressed on the keyboard. Any component can generate these events, and a
class must implement KeyListener interface to support them. An object that
implements the KeyListener interface gets this KeyEvent when the event occurs
and hence must handle the event by overriding keyTyped(), keyPressed(), and
keyreleased() methods of KeyListener Interface. Presseing and releasing a key on
the keyboard results in generating the following key events(in order);
- KEY_PRESSED
- KEY_TYPED
- KEY_RELEASED
Implementation:
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
}
@Override
public void keyPressed(KeyEvent ke) {
int x,y,z;
x=Integer.parseInt(t1.getText());
y=Integer.parseInt(t2.getText());
if(ke.getKeyChar()=='a'){
z=x+y;
}
else if(ke.getKeyChar()=='s'){
z=x-y;
}
else{
t3.setText("Press A or S");
return;
}
t3.setText(String.valueOf(z));
}
@Override
public void keyReleased(KeyEvent arg0) {
keyLabel.setText("Key is released");
}
@Override
public void keyTyped(KeyEvent arg0) {
keyLabel.setText("Key typed");
}
public static void main(String[] args) {
new KeyListenerDemo();
}
}
Output:
Figures: Key Event Demonstration.
Note: The above programs used KeyEvent and KeyListener and all methods
implemented from KeyListener interface as keyPressed(), keyReleased(),
keyTyped(). KeyListener is active only when the calculate button is clicked.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.*;
JFrame frame;
public WindowListenerDemo() {
frame=new JFrame();
frame.setVisible(true);
frame.addWindowListener(this);
frame.setSize(300, 400);
}
}
@Override
public void windowActivated(WindowEvent e) {
JOptionPane.showMessageDialog(frame, "Window Activated");
}
@Override
public void windowDeactivated(WindowEvent e) {
JOptionPane.showMessageDialog(frame, "Window Deactivated");
}
}
Note: But in case of using window listener classes we have to declare all the
methods of WindowListener interface. There is same output of WindowListener
interface and WindowAdapter class.
Implementation:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
mouselistenerdemo() {
addMouseListener(this);
l = new Label();
l.setBounds(20, 50, 100, 20);
add(l);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
Note: In above program, we are forced to implement all the methods that are declared in
MouseListener interface and are overridden in the program. We can not skip any of the
methods while implementing MouseListener interface in any class to handle the mouse
events.
import javax.swing.JFrame;
l = new Label();
l.setBounds(20, 50, 100, 20);
frame.add(l);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
Note: In a program above we have only overridden the methods from MouseAdapter
class that are needed.
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you
inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.
Implementation:
import java.awt.FlowLayout;
import javax.swing.*;
DeskTopPane(){
setSize(600,600);
setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
dp= new JDesktopPane();
iframe= new JInternalFrame("Internal frame", true, true, true, true);
iframe.setSize(100, 100);
iframe.setLocation(50, 50);
dp.add(iframe);
add(dp);
lb=new JLabel("Email");
tf=new JTextField(10);
iframe.setLayout(new FlowLayout(FlowLayout.CENTER));
iframe.add(tf);
iframe.add(lb);
iframe.setVisible(true);
Java Applets:
An applet is a special kind of Java program that runs in a Java enabled browser. This is
the first Java program that can run over the network using the browser. Applet is typically
embedded inside a web page and runs in the browser.
Applets are designed to be embedded within an HTML page. Applets interact with the
user through the AWT.
In other words, we can say that Applets are small Java applications that can be accessed
on an Internet server, transported over Internet, and can be automatically installed and run
as apart of a web document.
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. Applet support ended in March 2019. Oracle announced in January
2016 that Applets would be deprecated in Java SE 9, and the technology was removed
in Java SE 11. Components required to run Applets on non-Windows platforms
are being removed starting July 2020.
1. Applet is initialized.
2. Applet is started
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Write a html file in same directory for displaying the contents of Applet in a web view as
follows;
<html>
<head>
<TITLE> A Simple Program </TITLE>
</head>
<body>
Here is the output of my program:
<applet code="appletdemo.class" width="150" height="25"></applet>
</body>
</html>
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
public void init(): is used to initialized the Applet. It is invoked only once.
public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
By html file.
By appletViewer tool (for testing purpose).
Note: class must be public because its object is created by Java Plugin software that
resides on the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
Unit 13: Database Programming using JDBC [2 hours]
Using Connection, Statement and ResultSet interfaces for manipulating data with the
database.
Likely as, Open your Eclipse and create a new java project of you can use
any old project to add the jdbc libraries. For this, right click on your
project -> build path->configure build path->libraries->module->add
external jar/add libraries.
For database, you have to install the microsoft sql server and sql management
studio. Then follow the following methods;
Open SQL Server Configuration Manager and under SQL Server
Network Configuration go to Protocols for SQLEXPRESS. Right-click
on TCP/IP and choose Properties. Set Enabled = true.
While you are there, click on IP Addresses tab and find the section IP
All. Set TCP Port to 1433.
Add sqljdbc_auth.dll file to your PATH Environment Variable. In my
case:
D:\HarendraFolder\sqljdbc_6.0.7130.100_enu\sqljdbc_6.0\enu\auth\x6
4.
Copy the sqljdbc_auth.dll to your JDK directory. In my case:
C:\Program Files\Java\jdk-13.0.2\bin.
The sqljdbc.jar is a file that is used to connect the java application with database.
In this jar file, we have a package ―com.microsoft.sqlserver.jdbc” which contains
many different classes used for the interaction with the database.
Database URLs: These are the connection strings used to connect with database.
jdbcUrl="jdbc:sqlserver:"+server+":"+port+";databaseName="+database+";i
ntegratedSecurity=true";
Making the Connection: You need to find out the names of the JDBC driver
classes used by your vendor. Typical driver names are;
- com.microsoft.sqlserver.jdbc.SQLServerDriver(WE USE THIS)
- COM.ibm.db2.jdbc.app.DB2Driver
- COM.cloudscape.core.JDBCDriver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String server=‖//DESKTOP-L7LVCJU\\SQLEXPRESS";
This is a name of a server that can be copied from Sql Management Studio. Open Sql
server Management Studio and create a database after authenticating the server with
Windows Authentication.
int port=1433;
if you have not set port yet follow the instructions below;
It is a network port that is set by: SQL Server Configuration Manager and under
SQL Server Network Configuration go to Protocols for SQLEXPRESS. Right-click
on TCP/IP and choose Properties. Set Enabled = true.
While you are there, click on IP Addresses tab and find the section IP All. Set TCP
Port to 1433.
Also restart Sql Server Services – SQL Server (SQLExpress)=Right Click and
Restart.
String
jdbcUrl="jdbc:sqlserver:"+server+":"+port+";databaseName="+database+";integrated
Security=true";
This is the connectionstring that is used to connect to the sql server. It contains server
type(i.e.jdbc:sqlserver), server name(i.e. //Desktop-L7LVCJU\\SQLEXPRESS),
Database name(i.e. CollegeDb) and integratedSecurity = true for windows
authentication and false for username and password if we are using the database
server of certain organization.
Connection is a java class that is used to connect the java program to the sql server.
And DriverManager .getConnection(“ConnectionString”) method takes
connectionstring as an argument.
java.sql.Statement statement=con.createStatement();
Statement is a java class used to support all kinds of statements that are necessary for
database. createStatement() method in inbuilt method used to create the statements
that are listed below;
a. Insertion
› String insertdata="INSERT INTO StdTbl VALUES('Ram',‘Vedas‘…………)";
statement.executeUpdate(insertdata);
b. Updation
› String updateString="UPDATE tblStudent "+" SET Rollno=75 "+" WHERE
StudentName='Harendra'";
statement.executeUpdate(updateString);
c. Deletion
› String deleteString="DELETE FROM StdTbl "+" "+ "WHERE StudentName='Ram'";
statement.executeUpdate(deleteString);
d. Selection
ResultSet rsltset = statement.executeQuery("SELECT Name, Address from
Info_tbl;");
ResultSet is a java class used used to keep the data selected from the database table
according to queries. executeQuery() method invokes the queries.
while(rsltset.next()) {
System.out.println("The person is " + rsltset.getNString("Name") + " from ―
+ rsltset.getInt("Address"));
}
Note: executeQuery() method is for retrieving data from database table and
executeUpdate() method is for Insertion, Updation and Deletion of data from database
table.
Creating Table
Creating Table:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver loaded");
con = DriverManager.getConnection(jdbcUrl);
System.out.println("Connection obtained");
statement = con.createStatement();
System.out.println("Statement is created");
}
}
con = DriverManager.getConnection(jdbcUrl);
System.out.println("Connection obtained");
statement = con.createStatement();
System.out.println("Statement is created");
while (rsltset.next()) {
System.out.println("The name of the Student is " +
rsltset.getNString("StudentName")+ " whose College Name
is " + rsltset.getNString("CollegeName"));
}
con = DriverManager.getConnection(jdbcUrl);
System.out.println("Connection obtained");
statement = con.createStatement();
System.out.println("Statement is created");
while (rsltset.next()) {
System.out.println("The name of the Student is " +
rsltset.getNString("StudentName")+ " whose College Name
is " + rsltset.getNString("CollegeName"));
}
con = DriverManager.getConnection(jdbcUrl);
System.out.println("Connection obtained");
statement = con.createStatement();
System.out.println("Statement is created");
while (rsltset.next()) {
System.out.println("The name of the Student is " +
rsltset.getNString("StudentName")+ " whose Address is " +
rsltset.getNString("Address"));
}
con = DriverManager.getConnection(jdbcUrl);
System.out.println("Connection obtained");
statement = con.createStatement();
System.out.println("Statement is created");
}
}
ResultSet Concurrency
A ResultSet can have one of two concurrency levels:
1. ResultSet.CONCUR_READ_ONLY:
CONCUR_READ_ONLY means that the ResultSet can only be read.
statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
2. ResultSet.CONCUR_UPDATABLE
CONCUR_UPDATABLE means that the ResultSet can be both read and updated.
statement = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
If a ResultSet is updatable, you can update the columns of each row in the ResultSet. You
do so using the many updateXXX() methods. For instance:
statement = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet result = statement.executeQuery("SELECT * FROM tblStudent");
result.absolute(2);
result.updateString("StudentName", "Mahesh Bist");
result.updateRow();
We can also update a column using column index instead of column name. Here is an
example:
result.updateString (1, "Ram");
result.updateInt (2, 55);
result.updateRow();
Implementation:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
public class RowSetsCachedRowSetsDemo