Core Java
Core Java
Programs Offered
n e
i
Post Graduate Programmes (PG)
l
• Master of Business Administration
• Master of Computer Applications
n
• Master of Commerce (Financial Management / Financial
Technology)
Core Java O
• Master of Arts (Journalism and Mass Communication)
• Master of Arts (Economics)
• Master of Arts (Public Policy and Governance)
•
•
•
•
Master of Social Work
Master of Arts (English)
Master of Science (Information Technology) (ODL)
Master of Science (Environmental Science) (ODL)
i ty
Diploma Programmes
• Post Graduate Diploma (Management)
r s
e
• Post Graduate Diploma (Logistics)
• Post Graduate Diploma (Machine Learning and Artificial
•
Intelligence)
Post Graduate Diploma (Data Science)
i v
Undergraduate Programmes (UG)
•
•
•
•
Bachelor of Business Administration
Bachelor of Computer Applications
Bachelor of Commerce
Bachelor of Arts (Journalism and Mass Communication)
U n
•
•
•
English / Sociology)
Bachelor of Social Work y
Bachelor of Arts (General / Political Science / Economics /
it
Bachelor of Science (Information Technology) (ODL)
A m
c )DIRECTORATE OF Product code
(
DISTANCE & ONLINE EDUCATION
AMITY
r si
ty
O
nl
in
e
e
in
© Amity University Press
nl
No parts of this publication may be reproduced, stored in a retrieval system or transmitted
in any form or by any means, electronic, mechanical, photocopying, recording or otherwise
without the prior permission of the publisher.
O
SLM & Learning Resources Committee
ty
Chairman : Prof. Abhinash Kumar
si
Members : Dr. Divya Bansal
Dr. Coral J Barboza
r
Dr. Apurva Chauhan
ve
Dr. Monica Rose
Dr. Winnie Sharma
Published by Amity University Press for exclusive use of Amity Directorate of Distance and Online Education,
Amity University, Noida-201313
Contents
e
Page No.
in
Module I: Introduction to Java 01
1.1 Contract
nl
Module II: Java with Object Orientated Features 36
2.1 Introduction to OOP
O
Module III: Exception Handling Interface and Thread in Java 67
ty
3.1 Throwable Class and Its Subclasses
si
4.1 Defining Package
r
Module V: Event Driven Programming and Database Programming using JDBC 120
ve
5.1 Introduction to AWT
ni
U
ity
m
)A
(c
(c
)A
m
ity
U
ni
ve
r si
ty
O
nl
in
e
Core Java 1
Module - I: Introduction to Java
Notes
e
Course Contents:
in
●● Object
●● Object Oriented Programming
nl
●● Java Development Kit
●● Byte code
O
●● Class, Method, Variable
●● Data types
●● Operators
ty
●● Control Statements
●● Loops
si
●● Arrays
●● Inheritance
●● Method Overriding
●● Abstract Classes
r
ve
●● Final classes
●● Command line arguments
ni
e
Unit Outcome:
in
At the end of this unit, you will be able to:
nl
●● Categories different kinds of data types, variables, control statements, loops.
●● Define class, method, variables
O
●● Summarize basic features of Java.
●● Define method overloading
●● Categories inheritance
ty
●● Differentiate abstract class and final class
si
Java is a object oriented programming language created by James Gosling in
1991. As, it is mentioned object oriented so we need to know what is object.
r
Object is nothing but real-world entity that we can touch like pen, pencil, chair,
computer, dog etc. Object has state (which represents data) and behavior (which
ve
represents functionality or method). For example dog has state like its name, color,
breed etc and behavior like eating, barking etc.
Now, the question will come now what is platform. Here, platform means the operating
system on which you will run your Java program such as Windows, Mac OS, UNIX
etc. Java programming is little bit matured now, near about 23 years old. The target of
Java language was to write a program once and run this program on multiple operating
U
systems. The first publicly available version of Java (Java 1.0) was released in 1995.
So, let us know about object first.
The developer claimed that the Java programming language is very simple,
ity
●● Simple: Java is easy to learn if you understand the concepts of OOP (Object
Oriented Programming).
●● Object Oriented: In Java, everything is considered as an Object.
)A
●● Platform Independent: This term means Java is not compiled into platform
specific machine. You can write the code once in one platform and can run it in
other platforms without writing it several times for different platforms.
●● Secure: Java enables to develop virus-free systems as all the pointers work
(c
e
makes the compiled code executable on many processors, with the presence of
Java runtime system.
in
●● Portable: Java is portable as it gives us opportunity to carry the Java bytecode to
any platform. It doesn’t require any implementation.
●● Robust: It uses strong memory management and has automatic garbage
nl
collection methods etc. That’s why Java is called Robust which means strong.
●● Multi threaded: Multi threaded because it can perform many tasks at the same
time.
O
●● 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.
ty
●● High Performance: Java enables high performance.
●● Distributed: Java is distributed as it helps users to create distributed applications
in Java. RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are
si
used for creating distributed applications.
●● Dynamic: Java is considered to be more dynamic as Java programs can carry
extensive amount of run-time information which can be used to verify and resolve
accesses to objects on run-time. r
ve
1.1.2 History of Java
First time Java was introduced the 1991, there was a team named as the Green
Team from the sun micro system lab, Sun system lab was very famous for developing
ni
hardware and software. The pioneer of this Green Team was James Gosling and his
colleagues Mike Sheridan and Patrick Naughton.
U
They first time introduce the concept of object oriented programming. They give
the name of the programming has Greentalk as it is from the green team. Later, they
developed a more improved version of the concept and they gave the name as Oak.
In 1995, Gosling introduced the name Java. Java is an island of Indonesia, where
ity
best coffee of the world is produced and Gosling was very fond of coffee and use to
consume coffee while working on this project, that is why he chose the name Java for
this programming language.
Then gradually Java became very popular and with this popularity in 1996, the
m
Sun Micro system introduced a full set of programming environment, and they named it
as JDK (Java Development Kit). So, this gives you a brief history of the Java and why
the name of the programming language is Java.
)A
e
appletview-er Run and debug applets without a web browser.
Apt Annotation processing tool.
in
extcheck Utility to detect Jar conflicts.
Jar Create and manage Java Archive (JAR) files.
nl
The launcher for Java applications. In this release, a single
Java launch-er is used both for development and deployment.
The old deployment launcher, jre, is no longer provided.
O
javac The compiler for the Java programming language.
javadoc API documentation generator.
javah C header and stub generator. Used to write native methods.
ty
javap Class file disassembler
Jdb The Java Debugger.
si
●● Security Tools: keytool, jarsigner, policytool, kinit, klist, ktab
These security tools help you obtain, list, and manage Kerberos tickets.
e
Tool Name Brief Description
in
Rmic Generate stubs and skeletons for remote objects.
rmiregistry Remote object registry service.
Rmid RMI activation system daemon.
nl
serialver Return class serialVersionUID.
O
Tool Name Brief Description
tnameserv Provides access to the naming service.
Generates .java files that map an OMG IDL interface and
ty
Idlj enable an application writ-ten in the Java programming
language to use CORBA functionality.
Provides support for clients to transparently locate and invoke
si
persistent objects on servers in the CORBA environment.
ORBD is used instead of the Transient Nam-ing Service,
tnameserv. ORBD includes both a Transient Naming Service
Orbd
r
and a Per-sistent Naming Service. The orbd tool incorporates
ve
the functionality of a Server Manager, an Interoperable
Naming Service, and a Bootstrap Name Server. When
used in conjunction with the servertool, the Server Manager
locates, registers, and activates a server when a client wants
ni
Command line tool for launching Java Web Start and setting
javaws
various options.
e
jconsole, jmc, jvisualvm
in
JVM Diagnostic Commands tool - sends diagnostic command
Jcmd
requests to a running Java Virtual Machine.
nl
A JMX-compliant graphical tool for monitoring a Java virtual
jconsole machine. It can moni-tor both local and remote JVMs. It can
also monitor and manage an application.
O
The Java Mission Control (JMC) client includes tools
to monitor and manage your Java application without
Jmc
introducing the performance overhead normally associat-ed
with these types of tools.
ty
A graphical tool that provides detailed information about the
Java technology-based applications (Java applications) while
they are running in a Java Virtual Ma-chine. Java VisualVM
jvisualvm
si
provides memory and CPU profiling, heap dump analysis,
memory leak detection, access to MBeans, and garbage
collection
●● r
Java Web Services Tools: schemagen, wsgen, wsimport, xjc
ve
Tool Name Brief Description
schemagen Schema generator for Java Architecture for XML Binding.
wsgen Tool to generate JAX-WS portable artifacts.
ni
FirstProgram.java
m
}
(c
Output:
e
after that we compile the .java file which will produce .class file. We must remember
that a Java source file can have only one public class and it name must match with
name of file. For example, if our file name is FirstProgram.java then in that file a public
in
class should be there whose name should be FirstProgram and after compilation First
Program. class file will be produced.
nl
Steps of compilation
In the above program, we can see we have one public class First Program and we
will save this program by writing FirstProgram.java and we can compile our file either
O
in command prompt or in IDE. If we compile the program in command prompt then we
have to write javac FirstProgram.java (javac followed by your program name with
.java extension) and if there is no error in your program then no message will come and
after compilation FirstProgram.class will be produced. Now you can run your program
ty
by writing java FirstProgram (java followed by program name without extension) in
command prompt. On successful running you will get your desired output.
si
1.1.5 Java Bytecode
Java bytecode is the result of the compilation of a Java program which the Java
Virtual Machine (JVM) understands and which is machine independent. On compilation
r
of a Java program, a byte code has to be produced only once and after that it can run
ve
on any platform wherever a Java Virtual Machine exists. Bytecode files have a .class
extension.
In above example, you can see we have used javac which is the compiler. In
command prompt, we have to write javac then file name with extension to compile your
ni
Java program. So, we have to give the name of the file in the same way as the name
of the class you have given and it is a case sensitive so, be careful about that. Now, let
us compile it. So, as there is no error, no message in the command prompt, this means
U
Once on the successful compilation, you can see in the same directory one file
is created, the name of the file is the same as the name of the Java file except the
ity
extension is .class. So, here you can see the byte code file which has been created
is FirstProgram.class. So, once this program is successful on compilation now we
are ready to run it, to run this program the command that we said to use it java. So,
Java first program FirstProgram and then .class you can use the .class or even if you
use the class also no issue so it will run. So, here, for example, the class file name
m
is FirstProgram. Simply type java and the name of the class file, namely FirstProgram
here. So, this is the program that has been executed and as you see this program is
basically used only one statement namely System.out.println() and within this println() is
)A
1.1.6 JVM
JVM (Java Virtual Machine) is an machine which does not exist physically, we
(c
platform independent but JVM is platform dependent. JVM calls the main method
Notes
e
present in a java code. JVM is a part of Java Runtime Environment (JRE).
in
nl
O
ty
The JVM has different tasks. It loads code, verifies code, executing code and it
provides runtime environment. As you can see in the picture JVM lies inside JRE (Java
Runtime Environment) which provides runtime environment and is the implementation
of JVM. It physically exists. It contains a set of libraries and other files that JVM uses at
si
runtime.
We can see in the picture that JRE lies inside JDK (Java Development Kit). JDK
r
is a software package and you need to download it to develop Java applications and
applets. It contains JRE and other development tools. The JDK includes the JRE,
ve
an archiver (jar), a compiler (javac), an interpreter (java), a documentation generator
(javadoc), and few more development tools.
1.1.7 Identifiers
ni
name, interface name or a label. Identifiers are names of variables, methods, classes,
packages and interfaces. In the FirstProgram.java program, FirstProgram, String, args,
main and println are all examples of identifiers.
ity
Example:
class IdentifierExample{
void myMethod(){
m
System.out.println(“Hello Java”);
}
)A
int a = 95;
}
(c
e
●● myMethod, main : method name.
●● System, String : predefined class name.
in
●● args, a : variable name.
nl
To define a valid java identifier you need to follow few rules. If rules are not
followed then you will get compile time error.
O
●● Alphanumeric characters are only allowed characters which includes ([A-Z], [a-z],
[0-9]), ‘$‘(dollar sign) and ‘_’ (underscore).
●● Example: “abc@” is not a valid java identifier as it contain ‘@’ which is a special
character.
ty
●● Identifiers should not start with digits ([0-9]). Example: “12abc” is not a valid java
identifier.
si
●● Java identifiers are case-sensitive i.e. myVariable, MyVariable and Myvariable are
different from each other.
●● Though no limit is there to specify the length of the identifier but it is always better
r
if you use an optimum length of 4 to 15 letters only.
ve
●● You cannot use Reserved Words as an identifier.
●● Example: “int while = 20;” is an invalid statement as “while” is a reserved word.
There are 53 reserved words in Java.
ni
MyVariable
MYVARIABLE
myvariable
ity
x
m
p1
i1
)A
_myvariable
$myvariable
total_salary
(c
salary123
e
My Variable: as it contains space between My and Variable
in
var-5: as hyphen is not an alphanumeric character
nl
a&b: as ampersand is not an alphanumeric character
O
Any programming language reserves some words to represent functionalities
defined by that language. These words are called reserved words.
ty
abstract do if
private
assert double implements
protected
boolean else import
si
public
break enum instanceof
return
byte extends int
short
case r
false interface
static
ve
catch final long
strictfp
char finally native
super
class float new
switch
ni
type means the data types which are predefined and provided to us by the Java
programming language.
The primitive are the numeric types, boolean type and character type.
m
The numeric types contain integral types and floating-point types. Integral types
contain byte, short, int, long and the floating-point types contain float and double.
The non-primitive or reference types are class, interface, array etc. which user
)A
creates as their own. String literals are represented by String objects. Picture 2 depicts
the data types available in Java.
(c
Notes
e
in
nl
O
1.1.8.1 Integral Types and Values
Integral types have values in the below ranges:
ty
●● The byte data type has values ranging from -128 (-27)to 127 (27– 1), inclusive.
Default value is 0. For example, byte a = 10 or byte b = -20
●● For short data type, range from -32768 (216 ) to 32767(216 – 1), inclusive. Default
si
value is 0. For example; short s = 20000, short r = -6500
●● For int data type, range from -2147483648 (-231) to 2147483647 to (231– 1),
inclusive. Default value is 0. int a = 100000, int b = -200000
●● r
For long data type, range from -9223372036854775808 (-263 ) to
ve
9223372036854775807 (263 – 1), inclusive. Default value is 0L. long a =
100000L, long b = -150000L
Example:
ni
e
Wrapper Class: Long
in
●● Minimum value: (-2^63)
●● Maximum value: (2^63 -1)
●● Default value: 0L.
nl
●● Example: long a = 100000L, long b = -600000L;
O
There are two floating-point data types which are double and float. The float
data type is characterized by single-precision 32-bit and double data type is double-
precision 64-bit IEEE 754 floating point values. Precision means how many digits the
ty
value can have after the decimal point. It is recommended to use a float if you want to
save memory area in large arrays of floating point numbers. The float data type stores
fractional numbers which is capable to store 6 to 7 decimal digits whereas the double
data type stores fractional numbers which is capable to store 15 decimal digits. Default
si
value of float data type is 0.0f and for double it is 0.0d. The float data type can store
fractional numbers ranging from 3.4e−038 to 3.4e+038 and double data type can store
fractional numbers ranging from 1.7e−308 to 1.7e+308.
r
ve
Example of float and double:
float f1 = 234.5f
double d1 = 12.3
ni
e
The boolean data type is used to store two possible values: true and false. This
data type specifies one bit of information, but its “size” can’t be defined precisely.
in
Example: boolean a = false
nl
●● This data type is used for simple flags that track true/false conditions.
●● Default value is false.
O
1.1.8.5 Reference Types and Values
There are few reference types and those are class, interface, type variables, array
etc.
ty
Class: Class is the blue print of what your object is representing. Hence, we can
say object is instance of class. Also, we can say class is a group of objects which have
common properties i.e. in a single class we can put many similar type objects and
si
objects are created from this class. It is a logical entity. It can’t be physical but object is
physical entity.
r
A class or interface consists of a type declaration specifier, optionally followed by
type arguments. A type declaration specifier may be either a type name, or a class or
ve
interface type followed by “.” and an identifier. In the latter case, the specifier has the
form obj.id, where id should be the name of an accessible member type of obj, or a
compile-time error occurs. The specifier denotes that member type. Let us make it more
clear with an example.
ni
Example: Dog.java
class Dog {
U
}
)A
In the above example, you can see the first line is written as class class_name,
here our class name is Dog. When we will create object we have to write
(c
Here in our example, class_name is Dog, object_name you can write as per your
Notes
e
wish. In this example object_name is obj and with the help of “new” keyword we always
create object in Java and then constructor calling (We will later know about constructor).
in
1.1.9 Operators
In Java language, operators perform some operations and which are nothing but
nl
symbols. +, -, *, / etc. are all examples of operators. Arithmetic operation, magnitude
and tests for equality are common examples of expressions as after operation they
return a value and you can assign that result to a variable or you can put the value to
O
test in other Java statements. Arithmetic operator, assignment operator, increment and
decrement operator and logical operator are commonly used operators in Java.
ty
Java has five operators for basic arithmetic as described in below table.
si
+ Addition 10+12
- Subtraction 20-4
*
/
r Multiplication
Division
8*7
14/2
ve
% Modulus 100%8
Each operator takes two operands and one operator. To negate a single operand
you can use the subtraction (-) operator. If you are performing integer division, it will
ni
return an integer value as integers don’t have decimal fractions, thus is any remainder
is coming that will be ignored. For example the expression 52/ 7 gives results as 7.
The role of the modulus (%) operator is to return the remainder of two numbers. For
U
example, 31% 9 gives results as 4 because modulus gives the result which is the
remainder of your division operation.
Note that, the result of most operations involving integer values will produce an
ity
int or long values, regardless of the original type of the operands. If large values are
coming as result then it is of type long; rest are int. Arithmetic operation involving one
operand as integer and another as floating point will return a floating-point result.
Example: ArithmeticProgram.java
m
class ArithmeticProgram {
short x = 6;
int y = 4;
float a = 12.5f;
(c
float b = 7f;
System.out.println(“x is “ + x + “, y is “ + y);
e
System.out.println(“x - y = “ + (x - y));
System.out.println(“x / y = “ + (x / y));
in
System.out.println(“x % y = “ + (x % y));
nl
System.out.println(“a is “ + a + “, b is “ + b;
System.out.println(“a / b = “ + (a / b));
O
}
ty
Output:
x is 6, y is 4
x + y = 10
si
x-y=2
x/y=1
x%y=2
r
ve
a is 12.5, b is 7
a / b = 1.78571
ni
to the value of x, and then that new value is reassigned to x. This kind of operation
is very common hence Java has several operators to do a shorthand version which is
borrowed from C and C++. Below table shows these shorthand assignment operators.
m
x += y x=x+y
x –= y x+x–y
x *= y x=x*y
x ¸= y x=x¸y
(c
e
To increase or decrease a value by 1, we use + + and – – operators. For example,
x++ increments the value of x by 1 which actually equivalent to x = x + 1 expression.
in
Similarly, x– – decrements the value of x by 1. These increment and decrement
operators can be prefixed i.e. ++ or -- can appear before the value or postfixed i.e. ++
or – – can appear after the value it increments or decrements.
nl
For simple increment or decrement expressions, which form you use is not overly
important but in case of complex assignments which form you use makes a difference
because you are assigning the result of an increment or decrement expression.
O
Let us consider the following two expressions:
y = x++;
ty
y = ++x;
These two expressions will produce different results because of the difference
between prefix and postfix. The postfix operators (x++ or x--) first return the variable
si
value, then increment or reduce the value of the variable. The prefix operators (++x
or –x) first increment or decrease the value of a variable and then returns value of the
variable.
r
Example of prefix and postfix increment operators:
ve
class PrePostFixProgram {
int x = 0;
int y = 0;
U
x++;
++x;
m
x = 0;
)A
System.out.println(“——————”);
y = x++;
System.out.println(“x is “ + x);
System.out.println(“y is “ + y);
Amity Directorate of Distance & Online Education
Core Java 17
System.out.println(“——————”);
Notes
e
y = ++x;
in
System.out.println(“x is “ + x);
System.out.println(“y is “ + y);
nl
System.out.println(“——————”);
O
}
ty
}
si
x++ results in 1
++x results in 2
Resetting x back to 0.
r
ve
——————
The postfix operator ++ adds one to its operand / variable and returns the value
only after it is assigned to the variable. In other words, the assignment takes place first
U
x is 1
ity
y is 0
——————
The prefix operator ++ adds one to its operand / variable and returns the value
)A
before it is assigned to the variable. In other words, the increment takes place first and
the assignment next.
x is 2
y is 2
(c
——————
Java has several expressions for testing equality and magnitude. All of these
Notes
e
expressions return a boolean value (that is, true or false). Below table shows the
comparison operators:
in
1.1.9.4 Comparison operators
nl
= Equal x == 3
!= Not equal x != 3
< Less than x<3
O
> Greater than x>3
≤ Less than or equal x ≤3
ty
≥ Greater than or equal x≥3
si
If there is a chance to get result in boolean values of Expressions (for example,
the comparison operators) then it can be combined by using logical operators that
represent the logical combinations AND, OR, XOR, and logical NOT.
r
1.1.9.5.1 AND expression
ve
We use either & or && for AND combination. && is known as logical AND operator.
In an expression it will return true if both the statements are true. If first condition is
false then second condition will not be checked. Second condition will only be checked
if the first condition is true.
ni
& is known as bitwise operator and this operator always checks both conditions
whether first condition is true or false.
U
Example:
int a=15;
ity
int b=5;
int c=30;
The expression will produce true result only if both operands true; if either
expression is false, the entire expression will produce false result as you can see in
the above example. You can find the difference between these two operators during
expression evaluation.
(c
e
For OR expressions, we use either | or ||. In an expression, if first condition is true
then the logical || operator does not check second condition and if the first condition is
in
false then only it checks second condition.
The bitwise | operator always checks both conditions regardless first condition is
true or false.
nl
In addition, there is the XOR operator (^), which returns true value only if its
operands are different i.e. if there is one true value and one false value (or vice versa)
and returns false if both are true or both are false. In general, only the && and || are
O
commonly used as actual logical combinations. &, |, and ^ are more commonly used for
bitwise logical operations.
ty
Example:
int a=40;
int b=25;
si
int c=50;
System.out.println(a>b||a<c);
r
//(a>b) is true here and (a<c) is also true so, true || true = true
ve
System.out.println(a>b|a<c);
//(a>b) is true here and (a<c) is also true so, true | true = true
For NOT, use the ! operator with a single expression argument. The value of the
NOT expression is the negation of the expression; if x is true, !x is false.
Example:
m
!1 = 0
!0 = 1
)A
bitwise operators.
Bitwise operators
Notes
e
Operator Meaning
& Bitwise AND
in
| Bitwise OR
^ Bitwise XOR
nl
<< Left shift
>> Right shift
>>> Zero fill right shift
O
~ Bitwise complement
<<= Left shift assignment (x = x << y)
ty
>>= Right shift assignment (x = x >> y)
>>>= Zero fill right shift assignment (x = x >>> y)
x&=y AND assignment (x = x & y)
si
x|=y OR assignment (x + x | y)
x^=y NOT assignment (x = x ^ y)
has a higher precedence than subtraction or addition. In the expression 5+2*3, the
multiplication will be done before the addition which in turn will produce a result of 14.
When operators of equal precedence appear in the same expression, binary operators
U
except for the assignment operators are evaluated from left to right and assignment
operators are evaluated right to left. In general, increment and decrement are evaluated
before arithmetic expressions are evaluated, arithmetic expressions are evaluated
before comparisons, and comparisons are evaluated before logical expressions.
ity
[], () Parentheses group expressions; dot (.) is used for access to methods and
variables within objects and classes. [] is used for arrays. ++ –– ! ~ instance of Returns
true or false based on whether the object is an instance of the named class or any of
m
One special expression in Java is the use of the addition operator (+) which we will
use to create and concatenate strings.
Example:
(c
e
System.out.println(name + “ is “ + color + “ in color whose age is “+ age +”years”);
in
Output:
Tojo is white in color whose age is 10 years
nl
In this example you can see the output of this line has come in a single line as
a string, with the values of the variables (name and color) embedded on it. The
concatenation (+) operator, when used with strings and other objects, creates a single
string that contains the concatenation of all its operands. If any of the operands in string
O
concatenation is not a string (age here is not String), it is automatically converted to a
string, making it easy to create these sorts of output lines.
ty
The statements inside your source files are generally executed from top to bottom.
Control flow statements break up the flow of execution for decision making, looping,
si
and branching and enable your program to conditionally execute particular blocks of
code. This section describes the decision-making statements (if, if-else, switch),
the looping statements (for, while, do-while), and the branching statements (break,
continue) supported by the Java programming language.
r
ve
1.1.10.1 The if and if-else Statements
block of code to execute only if a condition checking produces true result. A car can
allow the brakes to decrease its speed only when the car is in motion. One possible
implementation of the apply Brake method can be written as:
U
void applyBrake() {
speed--;
m
If this test evaluates to true then only we can change the value of speed variable
)A
by 1 but if result is false that means that the car is not in motion then the control jumps
to the end of the if statement.
The if-else statement provides a secondary path of execution when an “if” clause
evaluates to false. You could use an if-else statement in the apply Brake method to take
some action if the brakes are applied when the car is not in motion. In this case, the
Notes
e
action is to simply print an error message stating that the car has already stopped.
void applyBrake() {
in
if (isMoving) {
speed--;
nl
} else {
O
}
}
ty
The Java switch statement executes one statement from multiple conditions. It is
like if-else-if kind of statement. The switch statement works with primitive data types like
byte, short, int, long. It can work with wrapper class types like Byte, Short, Integer and
si
Long, it also works with enumerated types. It can also work with String class. In other
words, the switch statement tests the equality of a variable against multiple values.
Example: SwitchTest.java r
ve
public class SwitchTest {
int n=35;
ni
switch(n){
break;
break;
ity
break;
}
)A
In the above example we have used break statement. When a break statement is
encountered, flow is immediately terminated and the program control resumes at the
next statement. The Java break statement is used to break switch or loop statement. It
(c
e
In any programming language, we use loops to execute a set of instructions
repeatedly when some conditions become true. The control flow goes out of the loop
in
only when the condition will become false. Here, we are going to discuss three types of
loops used in Java.
●● for loop
nl
●● while loop
●● do-while loop
O
1.1.11.1 The for loop
The for loop is a control flow statement that iterates a part of the programs multiple
times.
ty
Example:
for(int a =0; a<=10; a++){
si
System.out.println(a);
}
r
ve
1.1.11.1.1 Nested for loop
When we have a for loop inside another for loop the we will call it a nested for loop.
Example:
ni
{
U
notation. It works on elements basis and not index basis. It returns element one by one
in the defined variable.
Example: LoopExample.java
e
//Printing the values of the array using for-each loop
for(int a : myArray){
in
System.out.println(a);
nl
}
O
1.1.11.2 The while and do-while loop
The while statement continually executes a block of statements while a particular
ty
condition is true. Its syntax can be expressed as:
si
int a =0; //initialisation
{
r
ve
System.out.println(a);
a++; //increment
}
ni
Note: The last line before the ending of brace, we have to increment the value of
the variable
U
do{
ity
System.out.println(a);
a++; //increment
Note: In do-while loop, you must end while statement with a semicolon.
boolean value. If the expression evaluates to true, the while statement executes the
statement(s) in the while block. The while statement continues testing the expression
and executing its block until the expression evaluates to false but when you are working
with do-while loop then first time the loop will get executed without checking the
condition and condition checking will be done afterwards.
(c
e
A collection of similar type of elements when put in contiguous memory location is
known as array. In Java, array is an object which contains elements of a similar data
in
type. Array is a kind of data structure where we store similar elements. Array follows
index-based structure, the first element of the array is stored at 0th index, and 2nd
element is stored at 1st index and so on. In Java programming language, array is an
nl
object of a dynamically generated class. We can store primitive values or objects in an
array in Java. You can also create one dimensional or multidimensional array in Java.
In other words, we can say that array is a container object that holds a fixed number of
values of same type.
O
ty
si
Element is accessed by its numerical index. As shown in Fig 1.3, indexing begins
with 0. The 9th element, for example, would therefore be accessed at index 8.
r
When we want to store multiple values in a single variable then we will use array,
ve
rather than declaring separate variables for each value. To declare an array we need
to define the variable type with square brackets. For example, String[] car; or you can
write as String car[] (though it will work but not preferred ). Here, car is the name of the
variable that holds an array of strings.
ni
In the above case you are only creating an empty array with specified size.
)A
In the above case you are creating an array as well as putting values to it.
(c
The array elements are accessed through the index value. Array index starts from
0 to myArray.length-1.
e
An array declaration has two parts: First is type of array and the second is name of
array. The way to write data type of array is written as type[]. The brackets are special
in
symbols differentiating from other variable and indicating it as array variable. An array’s
name can be given as per user’s choice maintaining the rules and conventions.
nl
Example:
Below example allocates an array with memory for 10 integer elements and
assigns the array to the myArray variable.
O
// create an array of integers
ty
Following statement declares an array variable, myArray and creates an array of
10 elements of double type and assigns its reference to myArray variable.
si
double[] myArray = new double[10];
Example: ArrayExample.java
class ArrayExample { r
ve
public static void main(String[] args){
//printing array
ni
System.out.println(arr[i]);
U
}
ity
Note: length is the property of array. So, we can access length of array by
mentioning it as arr.length.
The way we inherit properties from our parents, like the same way a class can
acquire properties from another class. This mechanism of inheriting properties of one
object from a parent object is called inheritance. A class that is inheriting properties
)A
from another class is called a subclass or a child class or a derived class. The class
from which the subclass is derived is called a superclass, or a parent class or a base
class. Inheritance represents IS-A relationship which is also known as a parent-child
relationship.
(c
e
facilitates us to reuse the properties (fields and methods). You can use the same fields
and methods already defined in the previous class.
in
We have to use extends keyword to acquire the property of parent class to child
class. The meaning of “extends” is to increase the functionality.
Example:
nl
class Employee{
int salary=35000;
O
}
ty
System.out.println(“Tester’s salary is:”+ salary);
si
int bonus=15000;
In the above example, we have written three classes, Employee class, Tester
U
class and Programmer class. We have defined salary (variable) inside the Employee
class (parent class) but we are accessing the same salary variable from Tester class
(child class of Employee class) and Programmer class (child class of Employee
ity
class). Hence, here we are using the inheritance property of Java. Also, note that we
have mentioned about IS-A relationship and for this example we can say Tester IS-A
Employee or Programmer IS-A Employee.
In java programming, there are three types of inheritance in java: single, multilevel
and hierarchical. There are also multiple and hybrid inheritance is supported through
)A
In java programming, there are three types of inheritance in java: single, multilevel and hierarchical.
There are also multiple and hybrid inheritance is supported through interface only. In Java, multiple
28 inheritance is not supported through class.
Core Java
Notes
e
in
nl
O
Fig 1.4: Inheritance in Java
ty
1.1.13.1.1 Single Inheritance
When a class inherits properties from another class, it is known as a single
inheritance. In Single
1.13.1.1 the example
Inheritance given below, Dog class inherits the Animal class, so there is
the single inheritance.
si
When a class inherits properties from another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.
Example: InheritanceExample.java
Example:
class InheritanceExample.java
Animal{
class Animal{ r
ve
voidvoid
eat(){
eat(){
System.out.println(" Animals eat."); }
System.out.println(“
} Animals eat.”); }
class Horse extends Animal{
}
void run(){
ni
System.out.println("Horse
class Horse extends Animal{ gallops."); }
void run(){ 34
U
System.out.println(“Horse gallops.”); }
void roar(){
System.out.println(“Lions roar.”); }
}
m
obj1.run();
obj1.eat();
e
obj2.roar();
in
}
nl
1.1.13.1.2 Multilevel Inheritance
When there is a chain of inheritance, it is known as multilevel inheritance. In the
given example we can see BabyDog class inherits from the Dog class and Dog class
O
inherits from the Animal class, so there is a multilevel inheritance.
Example: InheritanceTest.java
class Animal{
ty
void eat(){
System.out.println(“Animals eat.”);}
si
}
void bark(){ r
ve
System.out.println(“Dog barks.”);}
void wag(){
obj.wag();
m
obj.bark();
obj.eat();
}
)A
inheritance. In the example given below, Dog and Cat classes inherits the Animal class,
so there is hierarchical inheritance.
Example: InheritanceExample.java
Notes
e
class Flower{
void petal(){
in
System.out.println(“Flowers have petals.”);}
nl
class Rose extends Flower{
void smell(){
O
System.out.println(“Rose has beautiful smell.”);}
ty
class Tulip extends Flower{
void color(){
si
}
obj1.petal();
ni
obj1.smell();
obj2.petal();
obj2.color();
}
ity
method with more specific way. Method overriding performs only if two classes have
parent-child relationship (IS-A relationship) which means classes must have inheritance
relationship. If a child class has a method same as declared in the parent class then
method overriding takes place in Java. Java programming language does not allow
method overriding if child class has more restricted access modifier than parent class.
(c
e
●● In method overriding, name of method of both classes must have same and equal
number of parameters.
in
●● Method overriding is referred to as runtime polymorphism because during runtime
which method is being called is decided by JVM.
●● Access modifier of child class’s method must not be more restrictive than parent
nl
class’s method.
●● Private, final and static methods cannot be overridden.
O
●● There must be an IS-A relationship between classes (inheritance).
Example: SamsungNote10.java
Below we have simple code example with one parent class and one child class
ty
wherein the child class will override the method provided by the parent class.
class Samsung {
si
void camera(){
}
r
ve
public class SamsungNote10 extends Samsung{
void camera(){
ni
obj.camera();
ity
In the above example you can see that both Samsung class (parent class) and
m
SamsungNote10 class (child class) has the same method name camera() with
same number of parameter. Here, you can see, SamsungNote10 class gives its own
implementation of camera() method.
)A
any class has even a single abstract method then it must be declared as abstract class.
We cannot create object of abstract class. We use abstract class to achieve abstraction
but it may not provide 100% abstraction because it can have concrete methods too.
Rather we can say abstract class has 0 to 100% abstraction. Abstract classes cannot
Notes
e
be instantiated, but abstract classes can have subclass. When an abstract class has
a subclass then that subclass usually provides implementations for all of the abstract
methods of parent class. However, if it does not, then the subclass must also be
in
declared abstract.
nl
●● Abstract keyword should be used before a class if you want to have abstract class
in your program.
O
●● Abstract class can have abstract and concrete methods.
●● Abstract class can have constructors and static methods also.
●● It can have final methods which will force the subclass not to change the body of
ty
the method.
●● It cannot be instantiated.
●● It is used for abstraction.
si
Example: AbstractionTest.java
void draw(){
System.out.println(“Drawing a rectangle”);}
U
void draw(){
System.out.println(“Drawing a circle”);}
}
m
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g.,
getShape() method
s.draw();
}
(c
e
provided by the Rectangle class and Circle class. Generally, we don’t know about the
implementation class and is hidden to the end user. In this example, if you create the
instance of Rectangle class, draw() method of Rectangle class will be invoked and if
in
you create Circle class then draw() method of Circle class will be invoked.
nl
A class can be declared as final. If we declare a class as final then it prevents from
being inherited. If you make any class as final, you cannot extend it i.e. inheritance is
O
not possible.
Example: Honda.java
ty
int a =10;
void myMethod(){
si
System.out.println (“I am inside a final class”);
} r
ve
public class TVS extends Bike{
void run(){
obj.run();
}
ity
The above example will give compile time error because inheritance is not possible
for final class and here we made Bike class as final class so whenever you will try to
m
can be used as an input. So, it provides a convenient way to check the behaviour of
the program for the different values. You can pass any numbers of arguments from the
Notes
e
command prompt.
Example: CmdExample.java
in
class CmdExample{
nl
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
O
}
ty
run by > java CmdExample Tea Coffee Pepsi Fruti
Output:
si
Tea
Coffee
Pepsi r
ve
Fruti
In the above example, Tea will be stores in args[0], Coffee will be stores in args[1],
Pepsi will be stores in args[2], Fruti will be stores in args[3]
ni
Note: This program will give output as Tea, Coffee, Pepsi, Fruti on a line by itself.
This is because the space character separates command-line arguments. To have Tea
Coffee Pepsi Fruti as a single argument, the user would join them by enclosing them
U
Summary
ity
Java is a simple language because its syntax is simple and easy to understand.
Complex and ambiguous concepts of C++ are either eliminated or re-implemented
in Java. Like pointer and operator overloading are not used in Java. Java is Object
Oriented language and everything is in the form of the object here. It means it has data
(state) and method (behaviour). Java contains a security manager that defines the
m
Activity:
1. What is byte code?
(c
e
4. Differentiate between Bitwise AND operator and Logical And Operator.
5. Write a program to check whether a number is even number of not.
in
6. Print the below pattern
*
nl
* *
* * *
O
****
7. Write a program to form a 1D array and put five integer values into it and print the
array.
ty
8. What do you understand by inheritance in Java?
9. How to find duplicate elements in an array?
si
10. How to find sum of all digits of a number in java?
11. How to find second largest number in an integer array?
12. How to check whether user input is number or not in java?
r
13. Can a class extend more than one classes or does java support multiple inheritance?
ve
If not, why?
14. What are the rules to be followed while overriding a method?
15. Can we override static methods?
ni
U
ity
m
)A
(c
e
Course Contents:
in
●● Class
●● Encapsulation
nl
●● Abstraction
●● Polymorphism
O
●● Different types of Inheritance
●● Types of methods
●● Constructors
ty
●● Method Overloading
●● Abstract class
si
●● Final method
●● Static keyword
●● Super Keyword
●● Garbage Collection
r
ve
Key Learning Objective :
1. Better understanding of class
ni
2. Concept of Encapsulation
3. Types of polymorphism
U
4. Types of methods
5. Types of constructors
6. Concept of method overloading
ity
e
Unit Outcome:
in
At the end of this unit, you will be able to:
●● Differentiate class and object
nl
●● Define Encapsulation
●● State types of polymorphism
O
●● Define various types of Inheritance
●● Define constructor and its types
●● Differentiate between method overloading and method overriding
ty
●● Define final method, final variable, final class
●● Use “static” and “super” keywords
si
●● How garbage collection runs in Java
2.1.1 Introduction
r
Object-Oriented Programming (OOP) define a programming concept based on
ve
objects and classes. OOP allows us to establish software as a collection of objects that
consist of state and behavior of object.
with that object helps to access the data. The functions of one object can access the
functions of an alternative object. OOP does not permit data to flow spontaneously
around the system rather ties data more closely to the function that operate on it, and
U
●● Objects
●● Classes
(c
●● Polymorphism
Notes
e
●● Dynamic binding
●● Message passing
in
2.1.2 Classes and Objects:
nl
An object is a software bundle of related state and behavior. Software objects are
often used to model the real-world objects that you find in everyday life. This lesson
explains how state and behavior are represented within an object, introduces the
concept of data encapsulation, and explains the benefits of designing your software in
O
this manner.
2.1.2.1 Class:
ty
A class is a design or pattern from which objects are created. In the real world,
many individual objects of the same kind can be found. There are many kind of cars
exists and each one is built from the same set of blueprints (i.e. four wheels, gear,
break, engine etc) and contains the same components. In object-oriented terms, we say
si
that Swift is an instance of the class Car. A class is the outline from which individual
objects are created. In programming standpoint, we can pronounce class is a group of
objects of having common properties. Class is logical entity whereas object is physical
one. r
ve
Example: Car.java
class Car {
int wheel = 4;
ni
int speed = 0;
int gear = 5;
U
gear = value;
ity
void printState() {
e
2.1.2.2 Objects:
in
Objects are the run time entities in object oriented system. Objects are real
life entity like person, table, pen, pencil, car etc. Objects take up space in the
memory. When a program is executed, the objects interact with each other by
sending messages to one another. For example, if “customer” and “account” are two
nl
objects present in a program, then the customer object can send message to the
account object requesting for the bank balance. Each object contains data and code
to manipulate data. We already know that object has state that represents data and
O
behavior that represents functionality. Pencil is an example of object. Pencil has name
(eg. Doms) and color (eg. yellow) so these are the state of pencil. The functionality of
Pencil is writing, drawing, sketching etc. So these are behaviors of Object.
ty
r si
ve
Fig 2.1. Creation of object
The above picture is depicting how to create object in Java programming language.
ni
The above picture is depicting how to create object in Java programming language.
Example: Box.java
Example: Box.java
class Box{
class Box{
U
void display(){
int depth = 30;
ity
System.out.println("Width is: " + width+ "Height is: "+ height + "Depth is: " + depth);
void display(){
}
obj.display();
public static
} void main(String args[]){
}
Box obj = new Box();
)A
obj.display(); 49
}
(c
In above example we have used “new” keyword which is used to allocate memory.
2.1.3 Encapsulation
Notes
e
One of the most important object oriented concept is Encapsulation. As we know
class is a base of any object oriented programming , so writing program in Java
in
means to have a set of classes. All created classes can be used to create objects
which basically can be achieved with the concept of object oriented principle called
encapsulation, and the different elements that is possible in a class. As discussed ,
nl
that class is a basic building blocks in any Java program that mean using it is feasible
to write the entire Java program. So, a class in fact, is a template ,basically gives a
framework of an object. So, in order to describe an object many elements for that object
are required.
O
The elements which are very important in any objects are called fields, the
methods, constructor and sometimes special items called blocks and also class within
a class called the nested class. One More important concept in an object is called the
ty
interface. So, mainly there are 6 different items to be incorporated in a class. Now fields
and methods little bit we have familiarity in our last few programs, but other 3 things
like constructors and then interface and everything is not known to us at the moment.
si
So, we shall on all this thing slowly. We will basically discuss or emphasized on field
methods and constructors these 3 things.
So, any class can be defined with its own unique name. So, it is called the class
r
name usually it is given by the user, so user defined name. So here so this is the
ve
name of the class that you have you are going to build, so these are name. And then
it consists of 2 things which is mentioned here as you see a set of it is called the fields
or member elements. All are member elements method also a member elements the
particularly it is called fields and other is called the methods. So, fields and methods are
ni
A class can consist of 1 or 0 or more methods and 0 or more fields. There is quite
possible that a class does not have any fields also possible that a class does not have
U
any methods, but which is really not useful is a useless thing without any fields are
any methods anyway. So, logically a class have 0 or more member elements fields
and methods. So, fields is basically simplest of his form is basically reference variables
or some primitive variables that means objects and other name of the other variables
ity
that can be define and then methods are basically the operations which are possible
to manipulate all the fields variables are there. So, these are basically called data in a
class and these are basically called operations in a class. So, these are the 2 things
data and operations when they are punched together it is call encapsulation which you
have a little bit learn in our previous lectures. So, here encapsulation means data and
m
2.4 Abstraction:
)A
Abstraction is a process of hiding the implementation details from the user. Only
the functionality will be provided to the user. In Java, abstraction is achieved using
abstract classes and interfaces.
(c
e
full-time employees – the time they work for the company. Full-time employees work
constantly 8 hours per day and the working time of contractors may vary.
in
nl
O
Which should you use, abstract classes or interfaces?
ty
●● Consider using abstract classes if any of these statements apply to the situation:
◌◌ share code among several closely related classes.
si
◌◌ Anticipate that classes that extend your abstract class have many common
methods or fields, or require access modifiers other than public (such as
protected and private).
r
◌◌ Affirm non-static or non-final fields. This empowers to define methods that can
ve
access and modify the state of the object to which they belong.
●● Consider using interfaces if any of these statements apply to the situation:
◌◌ Presume that unrelated classes would implement your interface. For example,
the interfaces Comparable and Cloneable are implemented by many unrelated
ni
classes.
◌◌ Specify the behavior of a particular data type, but not concerned about who
implements its behavior.
U
2.1.5 Polymorphism:
ity
Polymorphism is the ability of an object to take on many forms. The most common
use of polymorphism in OOP occurs when a parent class reference is used to refer to
a child class object. Polymorphism in Java is a concept by which we can perform a
single action in different ways. Polymorphism is derived from 2 Greek words: poly and
m
morphs. The word “poly” means many and “morphs” means forms. So polymorphism
means many forms. There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism. We can perform polymorphism in java by
)A
determination of the method to be called is based on the object being referred to by the
reference variable.
e
Method Overriding is known as runtime polymorphism. During runtime it is decided
which method has to call that’s why it is called runtime polymorphism.
in
Example:
1. Animal.java
nl
public class Animal{
O
System.out.println(“Animal is making a sound”);
ty
Horse.java
si
public void sound(){ // Override
System.out.println(“Neigh”);
} r
ve
public static void main(String args[]){
obj.sound();
ni
}
U
Output:
Neigh
ity
2. Cat.java
public class Cat extends Animal{
System.out.println(“Meow”);
m
obj.sound();
}
(c
e
Meow
in
2.1.5.2 Compile time Polymorphism Example
Method Overloading on the other hand is known as compile time polymorphism.
During compile time it is decided which method has to call that’s why it is called
nl
compiler time polymorphism.
Example.
O
class Overload
ty
{
si
}
{ r
ve
System.out.println (“a and b: “ + a + “,” + b);
double demo(double a) {
ni
System.out.println(“double a: “ + a);
return a*a;
U
}
ity
class MethodOverloading
double result;
)A
Obj .demo(10);
System.out.println(“O/P : “ + result);
}
Amity Directorate of Distance & Online Education
44 Core Java
}
Notes
e
2.1.6 Inheritance:
in
Why use inheritance in java
nl
●● For Code Reusability.
We are now going to learn a very important feature of object oriented paradigm
which is called the Inheritance. Inheritance is very common biological term and you
O
know inheritance means basically taking properties from ancestor. Previously we
discussed about this concept where we came to know about Single Inheritance,
Multilevel Inheritance, Hierarchical Inheritance, Multiple Inheritance and Hybrid
Inheritance.
ty
In OOP, the concept of inheritance provides the idea of reusability. This means that
we can add additional features to an existing class without modifying it. This is possible
by deriving a new class from the existing one. The new class will have the combined
si
feature of both the classes.
Single inheritance:
Single If a child
inheritance: If a ischild
inheriting properties
is inheriting from a parent
properties from athen it is then
parent knownit as single
is known
inheritance. Here, in Java language single inheritance implies that when a class inherits properties
r
as single inheritance. Here, in Java language single inheritance implies that when a
from another class then it is called as Single Inheritance.
class inherits properties from another class then it is called as Single Inheritance.
ve
ni
U
ity
voidvoid
display(){
display(){
System.out.println("I am inside parent class.");
} System.out.println(“I am inside parent class.”);
)A
}
}
public class B extends A{
}
void myMethod(){
public class B extends
System.out.println("I am insideA{
child class.");
(c
}
void myMethod(){
public static void main(String args[]){
B obj = new B();
Amity Directorate of Distance & Online Education
obj.myMethod();
obj.display();
}
}
Core Java 45
System.out.println(“I am inside child class.”);
Notes
e
}
in
B obj = new B();
obj.myMethod();
nl
obj.display();
O
}
Output:
ty
I am inside child class.
From the above example, you can easily understand that A class in parent class
si
and B is child class and as B class is inheriting properties of A class that is why B class
From the above example, you can easily understand that A class in parent class and B is child class
can access A class’s data and method. In this example, we have created B class’s
and as B class is inheriting properties of A class that is why B class can access A class's data and
object (obj)Inand we are weaccessing display() method (obj)by
andBwe
class’s object. Hence, we can
method. this example,
writebyobj.display().
have created B class's object
B class's object. Hence, we can write obj.display(). r are accessing display() method
ve
2.1.7
2.7 Multilevel Inheritance:
Multilevel Inheritance:
Multilevelinheritance
Multilevel inheritance
refersrefers to a technique
to a technique in Object
in Object Oriented Oriented
technology wheretechnology where
one class can
one inherit
class from
can ainherit
derived class, thereby making that derived class the base class for the new class. Anbase
from a derived class, thereby making that derived class the
ni
classeasy
forreal
thelifenew class.
example Anbeeasy
would realinherits
children life example wouldgrandchildren
from the parent, be childreninherits
inherits
fromfrom
the the
parent, grandchildren inherits from the children.
children.
U
ity
m
)A
class A{C.java
Example:
(c
voidA{draw(){
class
System.out.println(“I
void draw(){ am inside parent class A.”);
System.out.println("I am inside parent class A.");
} Amity Directorate of Distance & Online Education
}
class B extends A{
46 Core Java
}
Notes
e
}
class B extends A{
in
void display(){
nl
}
O
public class C extends B{
void myMethod(){
ty
System.out.println(“I am inside child class C.”);
si
B obj = new B();
obj.draw();
r
ve
obj.display();
obj1.myMethod();
ni
obj1.display();
obj1.draw();
U
Output:
ity
I am inside class B.
I am inside class B.
From the above example, you can easily understand that A class in parent class of
B and C. Class B is parent class of class C. So, class B is inheriting properties of class
A and class C is inheriting the properties of class B. Hence, class C is actually inheriting
properties of class B as well as class A. In this example, we have created B class’s
object (obj) and C class’s object (obj1) and we are accessing draw() and display()
(c
method by B class’s object and by C class’s object, we can access draw(), display and
myMethod().
e
In Hierarchical Inheritance, one class is inherited by many sub classes. Suppose,
class A represents
In Hierarchical Animal one
Inheritance, class
classand class byB many
is inherited represents Dos
sub classes. and class
Suppose, class C represents
A represents
in
Cat class.
AnimalSo,classDog andB Cat
and class classes
represents inherits
Dos and class Cthe Animal
represents Catclass, soDog
class. So, there is hierarchical
and Cat classes
inherits
inheritance. the Animal class, so there is hierarchical inheritance.
nl
O
ty
Fig 2.5: Hierarchical Inheritance
Example: HiechicalInheritanceExample.java
si
class Animal{
Example: HiechicalInheritanceExample.java
void
classrun(){
Animal{
void run(){
System.out.println(“Animals are running.”);
System.out.println("Animals are running."); r
ve
}}
}
} class Dog extends Animal{
void bark(){
class Dog extends Animal{
System.out.println("Dog barks.");
ni
}
void
} bark(){
class Cat extends Animal{
System.out.println(“Dog barks.”);
void sound(){
U
class
publicCat
classextends Animal{
ity
HiechicalInheritanceExample{
public static void main(String args[]){
void sound(){
Cat obj=new Cat();
obj.eat();
System.out.println(“Cat sounds like meow.”);
obj.sound();
}
m
58
}
obj.eat();
(c
obj.sound();
}
Notes
e
}
}
Output:
in
}
Animals are running.
Output:
Cat sounds
Animals like meow.
are running.
nl
Cat sounds like meow.
From the above example, you can easily understand that Animal class in parent
class
Fromofthe
Dog class
above andyou
example, Catcanclass. So, classthat
easily understand Dog is class
Animal inheriting properties
in parent class of Dogfrom class
class and
Animal andSo,class Catisis also inheriting fromclass
class Animal. In Cat
thisis example, wefrom
have
O
Cat class. class Dog inheriting properties from Animal and class also inheriting
created Cat class’s
class Animal. object we
In this example, (obj)
havewith that
created Catobject we accessed
class's object Animal
(obj) with that class’s
object we accessedrun()
Animal class's run() method.
method.
ty
2.1.9 Multiple
2.9 Multiple Inheritance
Inheritance:
InIn Multiple
Multiple Inheritance,
Inheritance, a classacan
class cantheinherit
inherit the properties
properties from more thanfrom more
one than
parent one
class. Weparent
can
class. We caninheritance
say multiple say multiple
meansinheritance means
a class extending more a class
than extending
one class. more than one
In Java programming class.
language
si
In Java
multipleprogramming language
inheritance is not supportedmultiple inheritance
in class level is not
rather it can supported
be achieved in class
indirectly level
through
interfaces which we will learn later.
rather it can be achieved indirectly through interfaces which we will learn later.
r
ve
ni
U
Hybrid inheritance is mixture of Single and Multiple inheritance and as Multiple inheritance is not
inheritance is not supported in class level in Java hence, Hybrid inheritance is also
supported in class level in Java hence, Hybrid inheritance is also not supported in class level and by
notusing
supported inyou
interfaces class
can level and by
have hybrid using interfaces
inheritance in Java. you can have hybrid inheritance in
Java.
m
)A
59
(c
In the above diagram you can see Class A is the Parent for both class B and class C which is Single
Inheritance and both class B and class C are Parent for class C which is Multiple Inheritance and is not
supported in class level in Java.
Core Java 49
In the above diagram you can see Class A is the Parent for both class B and class
C which is Single Inheritance and both class B and class C are Parent for class C which Notes
e
is Multiple Inheritance and is not supported in class level in Java.
in
Example:
class A
nl
{
O
{
ty
}
class B extends A
si
{
{ r
ve
System.out.println(“I am in class B “);
}
ni
{
U
{
ity
}
m
}
(c
{
Notes
e
D obj = new D();
obj.displayD();
in
obj.show();
nl
}
Output :
O
Error..
In the above example you can see when we are calling show() method by class D’s
object then confusion happens, compiler does not understand which shoe() method has
ty
to call. This the reason why multiple inheritance is not supported in class level in Java.
Hence, Hybrid Inheritance is also not supported in class level.
si
2.1.11 Methods
We have discussed that object has state and behavior. The behavior of object is
represented by method in Java. The method is collection of instructions or you can say
r
block of code that can do a specific task. We use method to achieve reusability of code.
ve
We write a method once and can use it many times. We do not require to write code
again and again. The most important method in Java is the main() method. Execution of
Java program starts from main() method. We write public static void main(String[] args)
access modifier. It specifies the visibility of the method. Four types of access specifier:
method declaration, Java uses default access specifier. It is visible only from the
same package.
Return Type: Every method returns some value which is known as Return type. It
)A
may return a primitive data type, object etc. If the method does not return anything, we
use void keyword.
Method Name: In your Java program you have to provide a unique name which
will define the name of method. Name of method must be well connected to the
(c
functionality of the method. Suppose, you are creating a method for addition of two
numbers, the method name can be add() or sum() or addition(). A method is invoked by
e
Parameter List: It means list of parameters separated by a comma and
enclosed in the pair of parentheses like void myMethod (int a, int b). Here, a and b
in
are parameters which are of int type. It contains the data type (int here) and variable
name( a and b here). If the method has no parameter, left the parentheses blank like
void myMethod().
nl
Method Body: It is a part of the method declaration which contains all the tasks to
be performed. It is enclosed within the pair of curly braces.
Naming a Method: While defining a method we need to keep it in mind that the
O
method name must be a verb and as per convention it should start with a lowercase
letter. In the multi-word method name, the first letter of each word must be in uppercase
except the first word.
ty
Example:
Single-word method name: sum(), add(), area() etc.
si
Multi-word method name: areaOfTriangle(), perimeterOfCircle, stringComparision()
etc.
These are also known as the standard library method or built-in method. In
Java, predefined methods are those methods which are already defined in the Java
libraries. You can directly use these built-in methods by calling them in the program.
U
Some pre-defined methods are equals(), length(), sqrt(), compareTo() etc. When we
call any predefined methods in our program, a block of codes related to the particular
method runs in the background. These built-in methods are also defined inside class.
Like, print() method is defined in the java.io.PrintStream class. This method prints the
ity
Example: Test.java
class Test
m
}
(c
Output:
e
In this example, three built-in methods namely main(), print(), and sqrt() have been
used. You can see these methods have been used directly without declaration because
in
they are predefined. The sqrt() method is a method of the Math class which returns the
square root of a number.
nl
2.1.11.3 User-defined Method
These types of methods are written by the user or programmer. You can modify
these methods according to the requirement.
O
Example:
Let’s create a user defined method that checks the number is even or odd. First,
we will define the method.
ty
class Addition{
si
int c = a+b;
} r
ve
}
We have defined the above method named add(). It has a parameter a and b of
type int. The method does not return any value that’s why we have used void.
ni
called. The program control will be transferred to the called method when you will call or
invoke a user-defined method,
obj.add(5,7);
}
)A
Output :
e
Constructor is a special kind of method. It is called to create an instance of class
and memory for the object is allocated. Whenever an object is created using the new
in
keyword, a constructor must be called. Constructor can use any access specifier. You
can write a constructor private but there scope of that constructor would be within the
class only.
nl
2.1.12.1 Types of constructors:
There are two types of constructors in Java:
O
1. Default constructor or no-argument constructor: If programmer does not write
constructor then Java compiler provides a default constructor. The default constructor
is used to provide the default values to the object like 0, null etc.
ty
2. Parameterized constructor: When a constructor is accepting a specific number of
parameters then it is called a parameterized constructor. This type of constructor is
used to provide values to objects.
si
2.1.12. 2 Function of constructor:
1. To instantiate object.
2. To initialize the instance variable. r
ve
2.1.12.3 Rules for creating Java constructor
Few rules are there which a programmer must follow.
Example: Car.java
class Car{
String name;
m
name = n;
)A
void display(){
e
Car obj1 = new Car(“Zen Estilo”);
in
obj1.display();
obj2.display();
nl
}
O
Output:
Zen Estilo
ty
Swift VDI
si
Constructor Method
The name of constructor must be same The name of method may or may not
as the class name. be same as the class name.
r
A constructor is used to initialize the A method is used to perform a specific
ve
state of an object. task.
A constructor do not have a return type. A method have a return type.
If a programmer does not write a A programmer must write method to
ni
constructor then Java compiler provides perform specific task. Java compiler
a default constructor. never provides any method by default.
The constructor is invoked implicitly. The method is invoked explicitly.
U
variables and methods from its parent class but it cannot inherit constructor of parent
class or super class because constructors are special kind of method and have same
name as class name. Hence, if constructors are inherited in child class then child class
)A
would contain a parent class constructor which is not possible as constructor must have
same name as class name.
If we define constructor of parent class inside constructor of child class it will give
compile time error. If constructors could be inherited then it would be impossible to
(c
e
When more than one method having same name but different parameter list
reside in a same class, it is known as method overloading. The advantage of method
in
overloading is it increases the readability of the program.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two parameters,
nl
and b(int,int,int) for three parameters then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
O
There are two ways to overload the method in java
ty
2. By changing the data type
Example of by changing number of arguments: OverloadingExample.java
si
class OverloadingExample{
r
System.out.println(“Result is: “ + (a+b));
ve
}
obj.add(4,7,8); \
obj.add(5,7); }
}
ity
Output:
Result is: 19
Result is: 12
m
In the above example, we have created two method of having same name
(add()) but in first method we have passed two parameters and in case of second we
have passed three parameters and both the methods are in same class. Compiler
)A
understands by counting the number of argument that which method is being called.
In this example, we have created two methods that differs in data type. The first
add method receives two integer arguments and second add method receives two
(c
double arguments.
class OverloadingExample1{
Notes
e
void add(int a, int b){
in
}
nl
System.out.println(“Result is: “ + (p+q));
O
public static void main(String[] args){
ty
obj.add(4,8);
obj.add(1.2, 4.5);
si
}
Output: r
ve
12
5.7
In the above example, we have created two method of having same name (add())
ni
but in first method we have passed two integer type parameters and in case of second
we have passed two double type parameters and both the methods are in same class.
Compiler understands by data type which method is being called.
U
et us say we have a class Animal that has a method sound() and the subclasses
of it like Dog, Lion, Horse, Cat etc. Since the animal sound differs from one animal to
another, there is no point to implement this method in parent class. This is because
)A
every child class must override this method to give its own implementation details, like
Lion class will say “Roar” in this method and Dog class will say “Woof”.
So when we know that all the animal child classes will and should override this
method, then there is no point to implement this method in parent class. Thus, making
this method abstract would be the good choice as by making this method abstract we
(c
e
error), also we need not to give any implementation to this method in parent class.
2.1.15 Final
in
The final keyword in java is used to restrict the user. The java final keyword can be
used in many context. Class, method and variable can be final.
nl
2.1.15.1 Java Final Method:
If we use final keyword with variables then we cannot change the value of that
O
variable. A final variable which is not initialised that means which does not have any
value then it is called blank final variable. It can be initialized in the constructor only. The
blank final variable can be static also which can be initialized in the static block only.
ty
Example of final variable: Car.Java
There is a final variable speed, 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
si
changed.
class Car{
}
ni
obj.run();
}
ity
In the above program you will get compile time error as you want to change the
value of final variable.
class Car1{
Car(){
speedlimit=70;
System.out.println(speedlimit);
(c
e
}
in
Output:
70
nl
2.1.15.2 Java final method:
We can make any method as final, but whenever we are making one method
O
as final then we will not be able to override it. Method which is final can be inherited
but cannot be overridden. Remember that we cannot make a constructor final as
constructor is never inherited.
ty
Example of final method: Car3.java
class Car3{
si
final void run(){
}
r
ve
class Swift extends Car{
obj.run();
}
ity
In the above program you will get compile time error again as you want to override
a final method which is not possible.
m
}
(c
class ZenEstilo extends Car{ //We are trying to inherit from a final class
void run(){
e
}
in
ZenEstilo obj= new ZenEstilo();
obj.run();
nl
}
O
In the above program you will get compile time error because you want to inherit
from a final class which is not possible.
ty
2.1.16 Static
As long as memory management in Java is concerned, static keyword is used.
With variables, methods, blocks and nested classes you can use static keyword. The
si
static keyword belongs to the class than an instance of the class. When the class is
loaded at that time the static variable gets memory only once. Advantage of using static
variable is it saves memory and make program memory efficient.
class Student{ r
ve
String name;
int roll;
String section;
ni
String school=”DPS”;
}
U
Let us think of a school where there are 3000 students. Instance variables get
memory every time whenever the object is created. All students have its unique name
and roll and here “school” refers to the common property of all objects. If we make it
ity
static variable then this field will get the memory only once. Thus saves the memory.
class Student{
m
String name;
String section;
name = n;
(c
roll = r;
section = s;
Notes
e
}
in
System.out.println(name + “is having roll number “+ roll+”and in
section”+section+”is studying in “+school);
nl
}
O
public class StaticExample{
public static void main(String args[]){
ty
Student s2 = new Student(“Binay Sinha”, 2 , “A”);
s1.display();
si
s2.display();
r
ve
Output:
In above example if you have learned the use of static and if you want to change
the name of school the it can be easily done by writing Student.school=”St.Xaviers”;
U
without the need for creating an instance of a class. When a program starts executing
that point of time there is no object resides in the memory and we need a point to start
execution. As static method can be invoked without creation of object hence main() is
static always. A static method can access static variable and can change the value of
it but cannot access non static data member or call non-static method directly. “this”
m
class Calculate{
e
System.out.println(result);
in
}
Output:
nl
400
Java static block: It is used to initialize the static variable and is executed before
O
the main method during the loading of class.
class StaticBlockExample{
ty
static{
si
}
Output:
ni
I am inside main
U
create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable. You can use super keyword to access the data
member of parent class if parent class and child class have same data member.
class Car{
(c
e
}
in
String color=”red”;
void display(){
nl
System.out.println(color); //prints color of Zen class
O
}
ty
public class TestSuper1{
si
d.display();
}
r
ve
Output:
red
ni
purple
In the above example, color is the common property of Car class and Zen class. If
you want to print color property of Car class then you have to write super.color as super
U
keyword refers to parent class’s property. Without mentioning super will give output of
child class’s member.
The super keyword can also be used to invoke parent class method. When parent
class and child class have same method (i.e. when the method is overridden) then
super key.
m
Example: SuperExample.java
class Animal{
void eat(){
)A
void eat(){
e
super.eat(); }
void display(){
in
System.out.println(“Cats are running.”);}
nl
}
O
public static void main(String args[]){
ty
obj.eat();
obj.display();
si
}
Output:
In the above example Animal class and Cat class have eat() method and if we
call eat() method from Cat class, it will call the eat() method of Dog class by default
because priority of local member is high. To call the parent class’s method, we have to
write super keyword.
U
Example: SuperTest.java
class Bird{
Bird(){
m
}
)A
Hen(){
(c
super();
System.out.println(“Hen is running.”);
}
Notes
e
}
in
public static void main(String args[]){
nl
}
O
Output:
ty
Hen is running.
si
When an object is unused then by the process of garbage collection Java
language releases fallow memory occupied by unused objects. This process is
inevitably done by the JVM and this garbage collection is essential for memory
r
management. When Java programs run, objects are generated and memory is
allocated to the program. When there is no reference to an object is there that object is
ve
assumed to be no longer needed and the memory occupied by the object are released.
This technique is called Garbage Collection. Java gc() method is applied to call garbage
collector unequivocally. However gc() method does not guarantee that JVM will perform
the garbage collection. It only request the JVM for garbage collection. This method is
ni
Java. We can request JVM for garbage collection by calling System.gc() method. But
our request does not guarantee that JVM will perform the garbage collection.
)A
2.1.18.1.1 Set Null to object Reference Which Makes it Able for Garbage
Collection
(c
For example:
e
2.1.18.1.2 By Setting New Reference Which Makes it Able for Garbage
Collection
in
For example
nl
A obj2 = new A();
obj2 = obj1;
O
2.1.18.1.3 By Making Anonymous Which Makes it Able for Garbage
Collection.
ty
2.1.18.3 Finalize() Method
In some cases, there may be some specific task to be performed before it is
destroyed such as releasing any resources or closing an connection etc. We use
si
finalize() to handle such situation.________________________________________
Example: GCTest.java
class GCTest{
ni
obj = null;
System.gc();
ity
System.out.println(“Garbage collected”);
m
}
)A
Output:
Garbage Collected
Summary
(c
All the code you will write have to put inside class. Method shows the behavior
of object. Java makes an effort to check error at run time and compile time. It uses
a strong memory management system, called garbage collector. Encapsulation means
Amity Directorate of Distance & Online Education
66 Core Java
putting together data and method into a single unit called class. Abstraction features
Notes
e
is a concept or idea not associated with any specific instance and does not have a
concrete existence. Inheritance describes the parent child relationship between two
classes. Constructor helps to instantiate object.
in
Activity:
nl
1. Is final method inherited?
2. Can we initialize blank final variable?
3. What is blank or uninitialized final variable?
O
4. What would happen if constructors can be inherited?
5. What is constructor and how many types of constructors are there?
ty
6. Abstraction provides 100% abstraction. Is this statement true or false? Give reason.
7. Java program to demonstrate working of method overloading in Java.
8. Write a Java program to illustrate the concept of Abstraction.
si
9. Write advantages of abstraction.
10. What does super() do in Java?
r
11. What is the use of final keyword?
ve
12. What is blank final variable?
13. What is the difference between abstract method and final method.?
14. Differentiate between method and constructor?
ni
e
in Java
in
Course Content:
●● Throwable class
nl
●● Exceptions
●● Error
O
●● Keywords use in exception
●● Exception handling
●● “Throw” and “throws” keywords
ty
●● Interface
●● Abstract method
●● Thread
si
●● Multithreading
●● Synchronization of threads
r
ve
Key Learning Objective:
1. Understanding of Throwable class
2. Concept of Exception and Error
ni
5. Concept of interface
6. Ability to do program with interface
7. Concept of multiple interface
ity
e
Unit Outcome:
in
At the end of this unit, you will be able to:
nl
●● Define exceptions and its types
●● Differentiate between Exception and Error
O
●● Handling exceptions with try, catch, throw, throws, finally
●● Discuss about interfaces and how to implement multiple inheritance through
interface
ty
●● Discuss about uncaught exception
●● Define threads
●● Draw thread life cycle
si
●● Discuss about thread priorities
●● Define Synchronization
r
3.1.1 Throwable Class and Its Subclasses
ve
Throwable class is child class of Object class which is the parent class of all
classes in Java Programming Language. Throwable has two direct child classes and
they are Error class and Exception class. A throwable contains a snapshot of the
ni
execution stack of its thread at the time it was created. It can also contain a message
string that gives more information about the error. Over time, a throwable can suppress
other throwables from being propagated. Finally, the throwable can also contain a
U
cause: another throwable that caused this throwable to be constructed. The recording
of this causal information is referred to as the chained exception facility, as the cause
can, itself, have a cause, and so on, leading to a “chain” of exceptions, each caused by
another. One reason that a throwable may have a cause is that the class that throws it
ity
is built atop a lower layered abstraction, and an operation on the upper layer fails due
to a failure in the lower layer. It would be bad design to let the throwable thrown by the
lower layer propagate outward, as it is generally unrelated to the abstraction provided
by the upper layer.
m
The figure below illustrates the class hierarchy of the Throwable class and its most
significant subclasses.
)A
(c
Notes
e
in
nl
O
Fig 3.1. Throwable class and its subclasses
3.1.2 Exceptions
3.2 Exceptions:
A problem thatA problem
arises during the execution of a program is known as exception. In
ty
that arises during the execution of a program is known as exception. In this situation, the
this situation, the normal flow of the program is disrupted and the program terminates
normal flow of the program is disrupted and the program terminates abnormally. An exception is an
event that occurs during the execution of a program which disturb the normal flow of instructions.
abnormally. An exception is an event
Creating an exception object that
and handing it occurs
at the runtime is calledduring the execution of a program
throwing an exception.
si
methods that had been called to get to the method where the error occurred. The list of methods is
it at the runtime is known
called as thethrowing
call stack. Thereanare exception.
two types of exception. Checked exception and Unchecked
exception.
Example:
int a=50/0; //ArithmeticException
int a=50/0;
String s=null; //ArithmeticException
String s=null;
System.out.println(s.length()); //NullPointerException
m
System.out.println(s.length());
String s=”abc”; //NullPointerException
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
)A
int
inti=Integer.parseInt(s); //NumberFormatException
num = Integer.parseInt(“abhay”); //NumberFormatException
int num
int = Integer.parseInt("abhay");
a[]=new int[5]; //NumberFormatException
The classes which directly inherit Throwable class except RuntimeException and ErrorAmity Directorate
(which are of Distance & Online Education
marked in Blue color in Fig. 3) are known as checked exceptions e.g. IOException, SQLException etc.
Checked exceptions are checked at compile-time.
70 Core Java
e
The classes which directly inherit Throwable class except RuntimeException and
Error (which are marked in Blue color in Fig. 3) are known as checked exceptions e.g.
in
IOException, SQLException etc. Checked exceptions are checked at compile-time.
nl
O
ty
3.1.4 Unchecked Exception
The classes which inherit Runtime Exception are known as unchecked exceptions
si
e.g. NullPointer Exception, Arithmetic Exception, Array Index Out Of Bounds Exception
etc are unchecked exception.
r
An unchecked exception is an exception that occurs at the time of execution.
These are also called as Runtime Exceptions.
ve
3.1.5 Checked Vs Unchecked Exception
Checked Exception Unchecked Exception
ni
3.1.6 Error
Error class is child class of the built-in class “Throwable”. Due to the lack of the
)A
system resources errors occur and cannot be handled by the programmer. Errors
cannot be created, thrown or caught, hence errors cannot be recovered by any means
because they. Errors are caused due to the catastrophic failure which usually cannot be
handled by your program.
(c
Errors are always of unchecked type, as compiler do not have any knowledge
about its occurrence. Errors always occur in the run-time environment. The error can be
Errors are always of unchecked type, as compiler do not have any knowledge about its occurrence.
CoreErrors
Java always occur in the run-time environment. The error can be explained with the help of an 71
example, the program has an error of stack overflow, out of memory error, or a system crash error,
explained with the help of an example, the program has an error of stack overflow, out
this kind of error are due to the system.
Notes
e
of memory error, or a system crash error, this kind of error are due to the system.
in
nl
O
Fig 3.4 Exception class and Error class.
3.6.1 Difference Between Exception and Error:
Exception Error
3.6.1 Difference
Exception between exception
is classified and error:
as checked and
ty
Error is classified as an unchecked type.
unchecked. Exception Error
Exception toisjava.lang.Exception
It belongs classified as checked class.and Error is classified as an unchecked type.
It belongs to java.lang.Errors class.
unchecked.
The use oftotry-catch blocks class.
can handle
si
It belongs java.lang.Exception It belongs to java.lang.Errors class.
The use of
exceptions andtry-catch
recoverblocks can handle
the application ItIt is
is not
notpossible
possibleto recover from from
to recover an error.
an error.
exceptions and recover the application from
from them.
them.
It canoccur
It can occur at
at run
run time
timecompile time
compile both.
time both.
r
ItIt can't
can'tbebeoccur at compile
occur time. time.
at compile
Errors happen at run time. They will not be
ve
Checked exceptions
Checked exceptions are known to compiler
are known to known to compiler.
compiler where as unchecked exceptions
where as unchecked exceptions are not known Errors happen at run time. They will not
are not known to compiler because they
to compiler because they occur at run time.
be known to compiler.
occur at run“ArrayIndexOutOfBounds”
Example: time. is an
Example: “OutOfMemory” and
example of an unchecked exception, while “StackOverflow” are examples of errors.
ni
Example: “ArrayIndexOutOfBounds” is
“ClassNotFound” is an example of a checked
anexception.
example of an unchecked exception, E x a m p l e : “ O u t O f M e m o r y ” a n d
while “ClassNotFound” is an example of “StackOverflow” are examples of errors.
U
a checked exception.
3.1.7 Keywords 87
ity
Keywords which are used in Exception Handling are try, catch, throw, throws and
finally.
The most important process or mechanism of handling runtime errors (so that the
normal flow can be maintained) in Java is known as 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. The use of exceptions to manage
)A
errors has some advantages over traditional error-management techniques. Below are
the methods discussed by which one can catch and handle exception.
In “try” block you have to place those code that you think can generate exception.
The try block must be followed by either catch block or finally block. You cannot use try
block alone. In “catch” block you have to place code that will handle exception.
Amity Directorate of Distance & Online Education
72 Core Java
Syntax:
Notes
e
try {
in
catch(Exception e) {
nl
A method catches an exception using a combination of try and catch keyword. A
try block is placed around the code that might generate or throw an exception. A catch
block is used to handle the exception.
O
A try block can be followed by multiple catch blocks. But at a time only one catch
block is executed.
ty
Example:
class ExceptionDemo {
si
try{
}
U
Output:
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 5
ity
Out of block
A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks at the
occurrence of different exceptions, use java multi-catch block.
)A
●● At a time only one exception occurs and at a time only one catch block is
executed.
●● All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
(c
e
int b=5, c=0;
int a = b/c;
in
System.out.println(a);
nl
catch (ArithmeticExceptione)
O
}
catch(ArrayIndexOutOfBoundsExceptione)
ty
{ System.out.println(“ArrayIndexOutOfBounds Exception occurs”);
catch(Exception e) {
si
System.out.println(“Parent Exception occurs”);
}
ni
FileNotFoundException etc.
The Java throw keyword is used to explicitly throw an exception. We can throw
either checked or uncheked exception in java by throw keyword. The throw keyword is
mainly used to throw custom exception. We will see custom exceptions later.
m
If a method does not handle a checked exception, the method must declare it using
the throws keyword.
)A
Syntax:
throw Instance
Example:
(c
void method(){
}
Notes
e
But this exception i.e., Instance must be of type Throwable or a subclass of
Throwable. For example Exception is a sub-class of Throwable and user defined
in
exceptions typically extend Exception class.
nl
static void validate(int age) {
if(age<18)
O
else
System.out.println(“welcome to vote”);
ty
}
public static void main(String args[]){
si
validate(10);
}
}
r
ve
Output
java.lang.ArithmeticException: not valid
at TestThrowDemo.validate(TestThrowDemo.java:4)
ni
at TestThrowDemo.main(TestThrowDemo.java:9)
....
U
The throws keyword appears at the end of method’s signature throws is a keyword
in Java which is used in the signature of method to indicate that this method might
throw one of the listed type exceptions. The caller to these methods has to handle the
exception using a try-catch block.
m
Throws keyword is required only for checked exception and usage of throws
keyword for unchecked exception is meaningless.
)A
By the help of throws keyword we can provide information to the caller of the
method about the exception.
Syntax:
return_type method_name() throws exception_class_name{
(c
//method code
e
Example
in
public class ThrowsDemo {
nl
if (age < 18) {
else {
O
System.out.println(“Access granted - You are old enough!”);} }
ty
checkAge(15); // Set age to 15 (which is below 18...)
si
}
Output
run TestThrowDemo r
ve
java.lang.ArithmeticException: not valid
at TestThrowDemo.validate(TestThrowDemo.java:4)
at TestThrowDemo.main(TestThrowDemo.java:9)
ni
...
Java finally block is a block that is used to execute important code such as closing
connection, stream etc. Java finally block is always executed whether exception
is handled or not. Java finally block follows try or catch block. If you don’t handle
ity
exception, before terminating the program, JVM executes finally block(if any exist).
Example:
public class TestFinallyBlock2{
m
try{
)A
int data=25/0;
System.out.println(data);
} catch(ArithmeticException e){System.out.println(e);}
(c
}
Notes
e
Output
in
java.lang.ArithmeticException: / by zero
nl
or each try block there can be zero or more catch blocks, but only one finally block.
Note: The finally block will not be executed if program exits (either by calling
System.exit() or by causing a fatal error that causes the process to abort).
O
3.1.9 Difference Between Throw and Throws
Throw Throws
ty
Throw keyword is used to throw an Throws keyword is used to declare an
exception explicitly. exception.
Throw is followed by an instance. Throws is followed by a class.
si
Throw is used within method. Throws is followed by class.
Throw is used inside method. Throws is used with method signature.
r Multiple exception can be declared
ve
Multiple exception cannot be thrown by by throws keyword. You can write
throw keyword. void myMethod() throws IOExcepton,
SQLException
ni
occur. When an uncaught exception occurs in a particular thread, Java looks for what
is called an uncaught exception handler, actually an implementation of the interface
Uncaught Exception Handler.
ity
The specific procedure is as follows. When an uncaught exception occurs, the JVM
does the following:
use. Normally, this will actually be the thread’s parent Thread Group, whose handle
Exception() method by default will print the stack trace.
e
main thread is about to terminate due to an uncaught exception the JVM will invoke the
thread’s Uncaught Exception Handler for a chance to perform some error handling like
logging the exception to a file or uploading the log to the server before it gets killed.
in
We can set a Default Exception Handler which will be called for the all unhandled
exceptions. It is introduced in Java 5 Version.
nl
This Handler can be set by using the below static method of java.lang. Thread
class.
O
exception handler. The uncaught exception handler always force the program to exit but
before shut down it may perform some task. The default uncaught exception handler
puts a message to the console before it exits the program. You can set a custom
function as the uncaught exception handler using the NSSet Uncaught Exception
ty
Handler function. You can obtain the current uncaught exception handler with the
NSGet Uncaught Exception Handler function. We have to provide an implementation of
the interface Thread. Uncaught Exception Handler and it has only one method.
si
Example
public class UncaughtExTest{
r
public static void main(String args[]) throws Exception{
ve
Thread.setDefaultUncaughtExceptionHandler(new MyHandler());
}
ni
}
ity
Output
m
Java has several exception classes inside the package java.lang. Below Mentioned
exceptions are Checked Exceptions Defined in java.lang.
e
4. InstantiationException (Attempt to create an object of an abstract class or interface.)
5. InterruptedException (One thread has been interrupted by another thread.)
in
6. NoSuchFieldException (A requested field does not exist.)
7. NoSuchMethodException (A requested method does not exist.)
nl
Java has several other types of exceptions. Below mentioned exceptions are
Unchecked RuntimeException.
O
2. ArrayIndexOutOfBoundsException (Array index is out-of-bounds.)
3. ArrayStoreException (Assigning an array element which has incompatible type.)
ty
4. ClassCastException (Invalid cast.)
5. IllegalArgumentException (Illegal argument used to invoke a method.)
6. IllegalMonitorStateException (Illegal monitor operation, such as waiting on an
si
unlocked thread.)
7. IllegalStateException (Application is in incorrect state.)
8. r
IllegalThreadStateException (Asked operation is not compatible with the current
ve
thread state.)
9. IndexOutOfBoundsException (Some type of index is out-of-bounds.)
10. NegativeArraySizeException (Array created with a negative size.)
ni
3.1.12 Interface
To achieve abstraction there are two ways in Java. First one by abstract class
and the other one by interface. So, we can tell an interface in Java is a mechanism to
achieve abstraction. The way we write class like the same way we write interface in
m
Java. Hence, you can say interface is a blueprint of a class. In interface variables must
be public, static and final and all the methods must be public and abstract (the methods
which does not have any body). Because all the methods are abstract hence interface
)A
e
While writing an interface, you must use interface keyword. and all the variables
will by default be public, static and final.
in
Syntax:
interface interface_name {
nl
// public static final variable
O
} While writing an interface, you must use interface keyword. and all the variables will by default be
public, static and final.
3.1.12.2 Abstract
Syntax: Methods in Interfaces
ty
All methods inside
interface interface
interface_name { must be abstract hence no codes will be there inside
methods. Abstract methods
// public static will have a semicolon (;) at the end of closing bracket. Also
final variable
si
3.12.2 Abstract Methods in Interfaces:
Syxtax: All methods inside interface must be abstract hence no codes will be there inside methods. Abstract
methods will have a semicolon (;) at the end of closing bracket. Also remember that even if you do
void show(); //abstract methods
r
not explicitly write public and abstract keyword , compiler will add those keywords on behalf of you.
ve
Syxtax:
3.1.12.3 Implementing Interfaces and Extending Interfaces
void show(); //abstract methods
To inherit properties from class we have used “extends” keyword and to inherit
3.12.3 Implementing Interfaces and extending interfaces:
properties from an interface we will use “extends” keyword if parent and child both are
To inherit properties from class we have used "extends" keyword and to inherit properties from an
interface but interface
we will we use “implements”
"extends" keywordkeyword
if parent andifchild
parent is interface
interface type and child is
ni
Example : InterfaceExample.java
Fig 3.5 Class and interface inheritance
ity
interface Drawable{
Example : InterfaceExample.java
public abstract void draw();
interface Drawable{
public abstract void draw();
}
m
interfaceinterface
Showable extends
Showable Drawable{
extends Drawable{
1void show();
1void show();
)A
97
}
}
Notes
e
public void draw(){
in
}
nl
InterfaceExample obj = new InterfaceExample ();
obj.show();
O
obj.draw();
ty
}
Output:
si
Implementing show() of Showable Interface
If variables are declared as interface type, it can reference any object of any class
ni
that implements the interface. We cannot create objects of interface but we can get and
Java permits reference variables creation with interfaces but not objects.
U
Example: InterfaceReferenceExample.java
interface Car {
}
)A
Car obj1;
e
obj1.run();
in
}
Output:
nl
Zen is a type of Car.
O
3.1.12.5 Default Methods in Interfaces
Default methods add new functionality to existing interfaces and ensure binary
compatibility with code written for older versions of those interfaces. In particular,
default methods enable you to add methods that accept lambda expressions as
ty
parameters to existing interfaces.
Example:
si
interface TestInterface
}
ni
}
public class DefaultExample implements TestInterface
U
{
System.out.println(a*a);
}
m
{
)A
d.square(4);
d.show();
}
Notes
e
3.1.12.6 Static Methods in Interfaces
in
Static methods in case of interface are those which are
Static Methods in Interface are those methods, which are defined in the interface
with the keyword static. Unlike other methods in Interface, these static methods
nl
contain the complete definition of the function and since the definition is complete and
the method is static, therefore these methods cannot be overridden or changed in the
implementation class.
O
Similar to Default Method in Interface, the static method in an interface can be
defined in the interface, but these methods cannot be overridden in Implementation
Classes. To use a static method, Interface name should be instantiated with it, as it is a
part of the Interface only.
ty
In this program, a simple static method is defined and declared in an interface
which is being called in the main() method of the Implementation Class InterfaceDemo.
si
Unlike the default method, the static method defines in Interface hello(), cannot be
overridden in implementing the class.
Example:
interface NewInterface {
r
ve
// static method
// Implementation Class
NewInterface.hello();
e
public void overrideMethod(String str)
in
System.out.println(str);
nl
}
Output:
O
Hello, New Static Method Here
ty
3.1.12.7 Constants in Interfaces
Placing constants in an interface was a popular technique in the early days of Java,
but now many consider it a distasteful use of interfaces, since interfaces should deal
si
with the services provided by an object, not its data. As well, the constants used by a
class are typically an implementation detail, but placing them in an interface promotes
them to the public API of the class.
r
ve
Example
interface OlympicMedal {
//..elided
//..elided
m
medal = GOLD;
)A
}
(c
e
A Java class can only extend one parent class. Multiple inheritance is not allowed.
Interfaces are not classes, however, and an interface can extend more than one parent
in
interface.
The extends keyword is used once, and the parent interfaces are declared in a
comma-separated list.
nl
For example, if the Hockey interface extended both Sports and Event, it would be
declared as − public interface Hockey extends Sports, Event.
O
Example
Starting with Java 8, interfaces could choose to define default implementations for
its methods
ty
public interface Floatable {
si
System.out.println(“Repairing Floatable object”);
} r
ve
public interface Flyable {
}
U
}
ity
If the interfaces in the preceding examples define variables with the same name,
m
say duration, we can’t access them without preceding the variable name with the
interface name:
}
Amity Directorate of Distance & Online Education
Core Java 85
public class ArmoredCar extends Car implements Floatable, Flyable {
Notes
e
public void aMethod() {
in
System.out.println(Floatable.duration); // outputs 10
System.out.println(Flyable.duration); // outputs 20
nl
}
O
An interface can extend multiple interfaces.
Example:
ty
public interface Floatable {
void floatOnWater();
si
}
void fly();
r
ve
}
void remoteControl();
ni
An interface inherits other interfaces by using the keyword extends. Classes use
the keyword implements to inherit an interface.
U
When a class inherits another class or interfaces, apart from inheriting their
members, it also inherits their type. This also applies to an interface that inherits other
interfaces.
ity
3.1.13 Thread
Thread is nothing but a process and we must remember thread is a light weight
process. We all know process is a program in execution. If we are considering a gaming
m
app then if one car is running at a time then you can say single thread is running in
the system but if multiple cars are running at the same time then you can say multiple
threads are running in the system. Execution of threads start from main() method.
)A
thread.
86 1) New: The thread is in new state if you create an instance of Thread class but before
Core Java
e
the invocation of start()
2) Runnable: The threadmethod.
is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.
2. Runnable: The thread is in runnable state after invocation of start() method, but the
in
thread scheduler
3) Running:has notis selected
The thread in running stateit tothread
if the be the running
scheduler thread.
has selected it.
3. Running: The thread is in running state if the thread scheduler has selected it.
4) Blocked :This is the state when the thread is still alive, but is currently not eligible to run.
4. Blocked : This is the state when the thread is still alive, but is currently not eligible
nl
to run. 5) Terminated:A thread is in terminated or dead state when its run() method exits.
5. Terminated: A thread is in terminated or dead state when its run() method exits.
O
ty
Fig 3.6 Thread life cycle
si
3.1.13.2 Creating and Implementing Thread
There are two approaches by which we can create thread.
3.13.2 Creating and implementing thread:
1. By extending Thread class:
r
There are two approaches by which we can create thread.
ve
Thread class provides
1. By extending Threadconstructors
class: and methods to create thread and to perform
different operations. Executions starts from main() method as we already 105
know and also
to start user thread we must depend on main thread.
class. public void start(), public void run(), public void sleep(long milliseconds), public
int getPriority(), public int setPriority(int priority), public String getName(),public
String setName(String name), public void yield(), public void suspend(),public void
U
resume(),public void stop(), public boolean isAlive(), public Thread currentThread() etc.
are few commonly used methods of Thread class.
Example:
class MyThread extends Thread {
)A
e
public static void main(String args[]) // main thread
in
MyThread t = new MyThread();
t.start(); // user thread has started, so now two threads are there
nl
//logic of main thread
O
System.out.println(“This is main thread”); } } }
Output:
ty
This is main thread
si
This is main thread
In the above example, you can see there is no start() method is explicitly
(c
mentioned in MyThread class but we can start() method (t.start()) in our program
because start() method is available in Thread class as we discussed earlier. When we
call t.start() then JVM searches in MyThread class but as it is not there so JVM will
Notes
e
search in Thread class and Thread class’s start() automatically will call run(). So, run()
method will run when we call t.start().
in
If your application contains three threads and execution starts from main method,
so now the question is which thread will run next? Thread execution will be decided by
Thread scheduler which is having algorithms like preemptive, time slicing etc. Thread
nl
schedular is part of JVM.
2. By implementing Runnable interface.
You can create thread by implementing Runnable interface.
O
Example:
class RunnableExample implements Runnable{
ty
public void run(){
si
System.out.println(“User Thread”);
}
r
ve
public static void main(String args[]) {
t.start();
System.out.println(“Main Thread”);
}
ity
Output:
m
Main Thread
Main Thread
Main Thread
)A
Main Thread
Main Thread
Main Thread
(c
e
Main Thread
Main Thread
in
Main Thread
User Thread
nl
User Thread
User Thread
O
User Thread
User Thread
ty
User Thread
User Thread
User Thread
si
User Thread
User Thread
r
In the above example you can see we have not written m.start() because neither
ve
RunnableExample class nor Runnable class have start() method in them. So, here we
need to take Thread class’s help and have to create object of Thread class and passing
object of RunnableExample class. Then with the help of Thread class’s object, we are
calling start() method.
ni
are we using multithreading and not multiprocessing because threads use shared
memory area. When child thread is created it shares the memory area of parent thread.
So saves memory, and context-switching between the threads takes less time than
process.
ity
Advantage of multithreading:
1. Multiple operations can be done at the same time. Hence, saves time.
m
System.out.println(“Thread 1”);
(c
}
Notes
e
class Thread2 extends Thread{
in
System.out.println(“Thread 2”);
nl
}
O
public void run(){
System.out.println(“Thread 3”);
ty
}
si
public static void main(String args[]){
t1.start();
r
ve
Thread2 t2 = new Thread2();
t2.start();
ni
t3.start();
U
}
}
Output:
ity
Thread 1
Thread 3
Thread 2
m
priority then thread scheduler decides which thread will run and when. Priorities are
number ranging from 1 to 10. In Thread class there are 3 types of constants.
e
is known as NORM_PRIORITY. The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.
in
Example: PriorityExample.java
nl
public void run(){
O
getPriority());
}
public static void main(String args[]){
ty
PriorityExample m1=new PriorityExample();
m1.setPriority(Thread.MAX_PRIORITY);
si
m1.start();
}
} r
ve
Output:
The running thread is:Thread-3
ni
to allow only one thread to access the shared resource then Java Synchronization is
better option.
Let us take an real life example in order to make the clear concept about
synchronization and non-synchronization. Think of railway ticket reservation system
m
where people are waiting in a queue to buy ticket. Here data is consistent synchronized
(only one thread at a time able to access). But in this case waiting time increases and
performance decreases. Now think of reservation system in application level where all
)A
passengers can buy ticket online, here data inconsistency occurred because multiple
threads are running at a time. But in this case waiting time decreases and performance
increases.
Example: NonSyncTest.java
(c
class Table{
e
for(int i=1;i<=5;i++){
System.out.println(n*i);
in
try{
Thread.sleep(400);
nl
}catch(Exception e){System.out.println(e);}
O
}
}
class MyThread1 extends Thread{
ty
Table t;
MyThread1(Table t){
si
this.t=t;
}
public void run(){ r
ve
t.printTable(5);
}
}
ni
Table t;
U
MyThread2(Table t){
this.t=t;
ity
t.printTable(100);
m
}
)A
e
t2.start();
in
}
nl
Output:
5
100
O
200
10
ty
300
15
si
400
20
500
r
ve
25
synchronized method. This method lock an object for shared resource. A thread
automatically acquires the lock for an object when a thread invokes a synchronized
method and releases it when the thread completes its task.
U
Example: SyncTest.java
class Table{
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
m
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
)A
}
(c
Table t;
Notes
e
MyThread1(Table t){
this.t=t;
in
}
nl
t.printTable(5);
O
}
ty
Table t;
MyThread2(Table t){
this.t=t;
si
}
t.printTable(100);
r
ve
}
}
ni
t1.start();
t2.start();
}
m
Output:
)A
10
15
(c
20
e
100
200
in
300
400
nl
500
O
system without queue is non synchronized.
ty
state. This method is used if you want to stop the thread execution and start it again
when a certain event occurs. This method allows a thread to temporarily stop execution.
The suspended thread can be resumed using the resume() method.
si
The suspend(), resume() and stop() methods are deprecated because suspend()
sometimes causes serious system problem though resume() method did not create
r
any problem but it has also been deprecated because it cannot work without suspend()
method. The stop() method also caused system problem hence it has also been
ve
deprecated.
Summary
ni
The Thread class defines and implements Java threads. You can subclass the
Thread class to provide your own thread implementations or you can use the Runnable
interface. Java offers a mechanism to? avoid race conditions by synchronizing
thread access to shared data. A piece of logic marked with synchronized becomes a
m
Activity:
)A
1. What is exception?
2. What do you mean by checked and unchecked exception?
3. What is the difference between Exception and Error?
4. What is the difference between Throw and Throws keyword?
(c
e
7. Differentiate thread and process.
8. Draw and explain Thread life cycle.
in
9. What is multithreading?
10. Is it possible to start a thread twice?
nl
11. Write a Java program to show how to use setPriority() and getPriority() methods.
12. Handle any possible exceptions like divide by zero.
O
13. Write a Java program that implements a multithreaded program has three threads.
14. What is the use of static method in interface?
15. Write a short note on resuming and stopping Threads.
ty
r si
ve
ni
U
ity
m
)A
(c
e
Course Content:
in
●● Package
●● Types of packages
nl
●● String creation
●● String handling methods
O
●● Predefine packages
●● Applet
●● Applet life cycle
ty
Key Learning Objective:
1. Understanding of packages
si
2. Advantages of using packages
3. Types of packages
4. Built-in packages r
ve
5. How to create a String in Java
6. Difference method to handle strings
7. Applet class
ni
e
Unit Outcome:
in
At the end of this unit, you will be able to:
●● Define package
nl
●● Discuss about the advantages of using packages
●● Define types of packages
O
●● Summarize built-in packages
●● Create user define packages
●● Create strings
ty
●● Handle strings
●● Define Applet class
●● Create your own applet
si
●● Discuss about graphics class
object contains state and behavior for character strings, various Graphical User Interface (GUI)
character strings,
objects likevarious Graphical
text box, buttons, checkboxesUser Interface
and many (GUI)
other things related objects
to graphical userlike text box, buttons,
interfaces.
These allows a programmer to design of particular application.
There are two types of packages as we already know. Predefine package and user define package.
Predefine packages are defined by Java programming language along with Java software. You already
Core Java 99
checkboxes and many other things related to graphical user interfaces. These allows a
Notes
e
programmer to design of particular application.
in
4.1.3.1 Types of packages:
nl
There are two types of packages as we already know. Predefine package and user
define package. Predefine packages are defined by Java programming language along
with Java software. You already know lang, IO, awt, net etc are examples of predefined
package
O
a. User define package: User defined packages are packages that are created by
developer as per their application requirement.
b. Creation of package:
ty
To create a package, you have to use package keyword.Package statement must
be the first statement in your program. It must have unique name.
si
Example: PackageExample.java
package mypackage;
class PackageExample {
r
ve
public static void main(String args[]) {
To compile java package below steps you have to follow if you are using command
U
prompt
The above command forces the compiler to create a package. The “.” operator
represents the current working directory. You can use any directory name like /home (in
case of Linux), d:/program (in case of windows) etc.
m
To run java package program, you need to use fully qualified name e.g.
mypackage.PackageExample to run the class.
When you execute the code, it creates a package mypackage. When you open the
(c
Java package mypackage inside that you will find PackageExample.class file. If you
e
mypackage then you have to write as mypackage.mysubpackage.
in
There are 3 ways by which you can access package from another program.
1. import mypackage.* ;
nl
2. import mypackage.PackageExample ;
3. by fully qualified name.
O
Example of package that import the packagename:
//save by Example1.java
package pack1;
ty
public class Example1{
si
}
r
// save byPackageExample.java
ve
import pack1.*; // * implies all classes of package pack1
class PackageExample{
obj.msg();
U
Output:
ity
I am in package 1
//save by Example1.java
package pack1;
)A
}
(c
//save by PackageExample.java
e
class PackageExample{
in
Example1 obj = new Example1();
obj.msg();
nl
}
O
Output:
I am in package 1
ty
Example of package using fully qualified name
//save by Example1.java
si
package pack1;
r
public void msg(){System.out.println(“I am in package 1”);
ve
}
//save by PackageExample.java
ni
class PackageExample{
obj.msg();
ity
Output:
m
I am in package 1
All the classes and interface of a package will be imported excluding the classes
and interfaces of the subpackages when you import a package. So, you need to import
)A
It is a default package and we do not need to import this package in our program.
All basic classes and interfaces which are required to prepare basic programs are
String, StringBuffer, System, Thread, Runnable, all wrapper classes, Exceptions and its
Notes
e
subclasses are residing inside lang package.
in
Java Input and Output (I/O) is used to process the input and produce the output.
To make I/O operation fast , Java uses the concept of a stream. The java.
nl
io package contains all the classes required for input and output operations. We can
perform file handling in Java by Java I/O API.
O
operations. InputStream, FileInputStream, OutputStream, FileOutputStream, Reader,
BufferedReader, InputStreamReader, Writer are residing inside IO package.
ty
A sequence of data is known as streams. A stream is composed of bytes. In Java,
3 streams are created for us automatically.
si
1. System.in refers to standard input stream
2. System.out refers to standard output stream
3. System.err refers to standard error stream
Input stream:
r
ve
An input stream is used to read data from source and source may be a device,
a file, an array or socket. InputStream class is an abstract class. Subclasses of
InputStream are FileInputStream, DataInputStream, ObjectInputStream etc.
ni
Example:
System.in:
U
Output stream:
An output stream is used to write data to destination and destination it may a
device, a file, an array or socket. OutputStream class is an abstract class. Subclasses
of OutputStream are PrintStream, FileOutputStream, DataOutputStream etc.
m
System.out
System.out.println(“simple message”);
)A
Standard Error:
This is used to output the error data produced by the user’s program and usually a
computer screen is used for standard error stream and represented as System.err.
(c
e
System.err.println(“error message”);
in
Sample programs on I/O files:
Below example shows how to read file content line by line. To get this, you have to
use BufferedReader object. By calling readLine() method you can get file content line
nl
by line. readLine() returns one line at each iteration, we have to iterate it till it returns
null.
Example: ReadLinesExample.java
O
import java.io.BufferedReader;
import java.io.FileNotFoundException;
ty
import java.io.FileReader;
import java.io.IOException;
si
public class ReadLinesExample {
BufferedReader br = null;
r
ve
String strLine = “”;
try {
System.out.println(strLine);
U
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
m
}
)A
Java programming languag. String objects are immutable which means unchangeable
once created.
Example:
Notes
e
char[] ch={‘o’,’b’,’j’,’e’,’c’,’t’,’o’,’r’,’i’,’e’,’n’,’t’,’e’,’d’};
in
is same as:
String s=”objectoriented”;
nl
Java String class provides many methods to perform operations on Strings
like compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
O
There are two ways by which you can create String object.
ty
Each time when we create a string literal, first the JVM checks the “constant string
pool”. If the string is there in the pool, a reference to the pool is returned. If the string
doesn’t exist in the pool, a new string instance is created and put in the pool.
si
Example:
String str = “Java is an object oriented programming”;
r
ve
4.1.5.2 By “New” Keyword
JVM will create a new string object in heap memory when you use “new” keyword.
Example:
ni
char ch[]={‘s’,’t’,’r’,’i’,’n’,’g’,’s’};
System.out.println(s1);
System.out.println(s2);
m
System.out.println(s3);
}
)A
Output:
java
(c
e
Java Programming
In the above program we have used String class, System class but we did not
in
import the lang package. Other than lang package, if you wish to use other classes
resides in other packages then you have to import those built-in package.
nl
4.1.6 String Handling Operations
O
If you want to combine two or more strings in java then you can do it by string
concatenation which adds two or more stings and forms a new string.
ty
1. By + operator
2. By concat() method
si
1) String Concatenation by + (string concatenation) operator
The + operator is used to add strings.
Example: StringConcat.java r
ve
class StringConcat{
System.out.println(str);
}
U
Output:
ity
Ratan Tata
The string concatenation operator can concat all primitive values. String
concatenation operator produces a new string by appending the second string at the
end of the first string.
m
string.
Example: StringConcat2.java
class StringConcat2{
(c
String s1=”Sri “;
Notes
e
String s2=”Ravishankar”;
String s3=s1.concat(s2);
in
System.out.println(s3);
nl
}
Output:
O
Sri Ravishankar
ty
We can compare string in java on the basis of content and reference.
si
1. By equals() method
2. By = = operator
3. By compareTo() method r
ve
1) String Compare By Equals() Method
The equals() method checks the values of strings for comparing the equality. String
class provides two methods: a) equals() and equalsIgnoreCase()
ni
class StringCompareExample{
U
String s1=”SubhasChandra”;
String s2=”SubhasChandra”;
ity
String s4=”Bose”;
System.out.println(s1.equals(s2));
m
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
)A
Output:
(c
true
e
false
In above example you can see that though we have created String s1 and s3
in
in different manner still when we are comparing s1 and s3, it is giving result as true
because the value of s1 and s3 are same.
nl
Example: StringComparison.java (Comparing strings with equalsIgnoreCase()
method)
class StringComparison {
O
public static void main(String args[]){
String s1=”SubhasChandra”;
ty
String s2=”SUBHASCHANDRA”;
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
si
}
}
r
ve
Output:
false
true
ni
In the above example you can see that both s1 and s2 are same name but case is
different, so when equals() method will compare then it will give false result as values
are different but when you are using equalsIgnoreCase() method will ignore the case of
U
two strings and compare it and it will give true result as both string are containing same
name if you ignore the case.
When we will use = = operator then it will not compare the value but it will compare
references.
Example: StrExample.java
m
class StrExample{
String s2=”Birendra”;
System.out.println(s1==s2);
System.out.println(s1==s3);
(c
}
Notes
e
Output:
in
true
false
nl
In the above example you can see s1==s2 is producing true result as both strings
are referring to the same instance but as the reference of s1 and s3 are different hence
s1==s3 is giving result as false.
O
3) String Compare By Compareto() Method
The compareTo() method compares values lexicographically and returns an integer
value which tells whether first string is less than or equal to or greater than second
ty
string.
si
If s1 == s2 then the method will produce 0
class StrCompare{
String s3=”Bachan”;
}
m
Output:
s1.compareTo(s2) resulting: 0
)A
s1.compareTo(s3) resulting: -1
s3.compareTo(s1) resulting: 1
In the above program you can notice that as s1 and s2 are same hence when
(c
e
class StrHandling1{
in
String str=”Rabindranath”;
System.out.println(str.startsWith(“Rabin”));
nl
System.out.println(str.endsWith(“th”));
O
}
Output:
ty
true
true
si
4.6.4 Charat() Method
The string charAt() method returns a character at specified index.
class StrHandling2{ r
ve
public static void main(String args[]){
String str=”Rabindranath”;
System.out.println(str.charAt(0));
ni
System.out.println(str.charAt(3));
}
U
Output:
ity
The java string toUpperCase() method converts this string into uppercase letter
and string toLowerCase() method into lowercase letter.
class StrHandling3{
)A
String str=”Rabindranath”;
System.out.println(str);
(c
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
Amity Directorate of Distance & Online Education
110 Core Java
}
Notes
e
}
in
Output:
Rabindranath
nl
RABINDRANATH
rabindranath
O
4.1.6.6 Length() Method
The string length() method returns length of the string.
class StrHandling4{
ty
public static void main(String args[]){
String str=”Rabindranath”;
si
System.out.println(str.length());
} r
ve
Output:
12
ni
class StrHandling5{
U
String str1=str.replace(“Ravishankar”,”Guruji”);
System.out.println(str1);
}
m
Output:
)A
class StrHandling6{
e
System.out.println(str);
System.out.println(str.trim());
in
}
nl
Output:
Ravishankar
O
Ravishankar
In above example you can see in first output has been printed with spaces before
ty
and after the string. When we are using trim() method then all the spaces before and
after are getting removed.
si
A subset of string is called substring. When working with substring you have to
remember that startIndex is inclusive and endIndex is exclusive. You can get substring
from the given string object by one of the two methods:
r
public String substring(int startIndex): This method returns new String object
ve
containing the substring of the given string from specified startIndex (inclusive).
public String substring(int startIndex, int endIndex): This method returns new String
object containing the substring of the given string from specified startIndex to endIndex.
ni
Example: SubstringExample.java
String s=”RabindranathTagore”;
System.out.println(s.substring(12));
ity
System.out.println(s.substring(0,12));
}
m
Output:
)A
Tagore
Rabindranath
e
on or return collections.Following are the important points about Collections
in
return a new collection backed by a specified collection.
●● The methods of this class all throw a NullPointerException if the collections or
class objects provided to them are null.
nl
The java.util.HashMap class is the Hash table based implementation of the Map
interface.Following are the important points about HashMap −
O
●● This class makes no guarantees as to the iteration order of the map; in particular,
it does not guarantee that the order will remain constant over time.
●● This class permits null values and the null key.
ty
The java.util.Date class contains a time, with millisecond precision.
Java.io package provides classes for system input and output through data
streams, serialization and the file system. This reference will take you through simple
si
and practical methods available in java.io package.
written.
●● Instances may or may not denote an actual file-system object such as a file or a
directory. If it does denote such an object then that object resides in a partition. A
partition is an operating system-specific portion of storage for a file system.
●● A file system may implement restrictions to certain operations on the actual file-
m
system object, such as reading, writing, and executing. These restrictions are
collectively known as access permissions.
●● Instances of the File class are immutable; that is, once created, the abstract
)A
e
all objects in the graph created from the stream match the classes present in the
Java Virtual Machine.
in
●● Classes are loaded as required using the standard mechanisms.
nl
A Java applet is a special kind of Java program that is embedded in webpage and
runs in web browser. You can download applet from the internet and run. An applet
must be a child class of the java.applet.Applet class. The Applet class provides the
O
standard interface between the applet and the browser environment.
There are some important differences between an applet and a standalone Java
application, including the following −
ty
●● An applet is a Java class that extends the java.applet.Applet class.
●● A main() method is not invoked on an applet, and an applet class will not define
main().
si
●● Applets are designed to be embedded within HTML page.
●● When a user views an HTML page that contains an applet, the code for the applet
is downloaded to the user’s machine. r
ve
●● A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
●● The JVM on the user’s machine creates an instance of the applet class and
invokes various methods during the applet’s lifetime.
ni
●● Applets have strict security rules that are enforced by the Web browser. The
security of an applet is often referred to as sandbox security, comparing the applet
to a child playing in a sandbox with various rules that must be followed.
U
●● Other classes that the applet needs can be downloaded in a single Java Archive
(JAR) file.
ity
Advantage of Applet
●● It is secured
●● It works at client side so less response time.
●● It can be executed by browsers running under many platforms, including Linux,
m
●● Applet itself cannot run or modify any application on the local system.
●● Applets has no access to client-side resources such as files , OS etc.
●● Applets can have special privileges. They have to be tagged as trusted applets
Notes
e
and they must be registered to APS (Applet Security Manager).
●● Applet has little restriction when it comes to communication. It can communicate
in
only with the machine from which it was loaded.
●● Applet cannot work with native methods.
●● Applet can only extract information about client-machine is its name, java version,
nl
OS, version etc.
●● Applets tend to be slow on execution because all the classes and resources which
it needs have to be transported over the network.
O
4.1.10 Life cycle of applet:
There are four main steps in applet’s lifecycle.
ty
1. Applet is started.
2. Applet is painted.
si
3. Applet is stopped.
4. Applet is destroyed.
r
ve
ni
U
1. public void init(): To initialize and Applet, init() method is invoked. This method is
invoked only once.
2. public void start(): To start an Applet, start() method is invoked.
m
3. public void stop(): To make an Applet stop you have to use stop() method.
4. public void destroy(): To destroy an Applet, use destroy().This method is also invoked
)A
only once.
1. public void paint(Graphics g): To paint an Applet, paint() method is used. It is used
to draw square, rectangle etc and provides Graphics class object which helps to
draw.
Amity Directorate of Distance & Online Education
Core Java 115
Steps to run an Applet
Notes
e
There are two ways to run an applet
1. By html file.
in
2. By appletViewer tool (for testing purpose).
nl
Steps:
1. First create child class of Applet class
O
2. Implement init() method and paint() method of Applet class
ty
We have to put applet tag in comment while creating an applet in order to execute
applet by appletviewer tool.
Example: Draw.java
si
import java.applet.*;
import java.awt.*;
}
ni
</applet>*/
Example: FirstApplet.java
import java.applet.*;
m
import java.awt.*;
g.setColor(Color.red);
g.drawString(“Welcome”, 100,100);
(c
g.drawLine(20,30,20,300);
g.setColor(Color.blue);
Notes
e
g.drawRect(70,100,30,30);
g.fillRect(70,30,30,30);
in
}
nl
/* <applet code =”FirstApplet.class” width = “300” height = “300”>
</applet> */
O
In the above example, we have imported applet class and awt class in order to run
the program. AWT (Abstract Windowing Toolkit) is an API to develop GUI or window
based application. It is to be noted that for applet programming, the upper left corner of
ty
screen has coordinate (0,0). X coordinate increases from left to right and y coordinator
increases from top to bottom of the screen.
si
To create an applet and execute by html file, you have to create an html file and
place the applet code in html file. After creation of HTML file you have to click the
r
html file. You must make class as public because its object is created by Java Plugin
software that resides on the browser.
ve
Example: MyApplet.java
import java.applet.Applet;
import java.awt.Graphics;
ni
}
ity
myapplet.html
<html>
m
<body>
</applet>
</body>
</html>
(c
e
Every applet is an extension of the java.applet.Applet class. The base Applet
class provides methods that a derived Applet class may call to obtain information and
in
services from the browser context.
nl
Get applet parameters
Get the network location of the HTML file that contains the applet
O
Print a status message in the browser
Fetch an image
ty
Fetch an audio clip
si
Resize the applet.
1. public abstract void drawString(String str, int x, int y): This method is used to
draw string.
ni
2. public void drawRect(int x, int y, int width, int height): This method is used to
draws rectangle with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): This method is used
U
to fill rectangle with the default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): This method is
used to draw oval with the specified width and height.
ity
5. public abstract void fillOval(int x, int y, int width, int height): This method is used
to fill oval with the default color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): This method is used
to draw line between the points(x1, y1) and (x2, y2).
m
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): This method is used to draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): This method is used to fill a circular or elliptical arc.
(c
10. public abstract void setColor(Color c): This method is used to set the graphics
current color to the specified color.
11. public abstract void setFont(Font font): This method is used to set the graphics
Notes
e
current font to the specified font.
Example: GraphicsExample.java
in
import java.applet.Applet;
import java.awt.*;
nl
public class GraphicsExample extends Applet{
O
g.setColor(Color.red);
g.drawLine(20,30,20,300);
ty
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
si
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);r
ve
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
ni
Summary:
U
Packages in java are used to organize related or similar classes, interfaces and
enumerations into one group. For example, java.sql package has all classes needed
for database operation. One more interesting thing about String objects in java is that
ity
they are immutable. That means once you create a string object, you can’t modify the
contents of that object. If you try to modify the contents of string object, a new string
object is created with modified content. The Applet class extends the AWT Panel class,
which extends the AWT Container class, which extends the AWT Component class.
m
From Component , an applet inherits the ability to draw and handle events.
Activity:
)A
a string?
e
6. Write a java program to count the total number of occurrences of a given character
in a string without using any loop?
in
7. Write a java program to reverse each word of a given string?
8. Write a Java program to create a package which has classes and methods to read
Student Admission details.
nl
9. Write a short note on built-in packages.
10. With an example describe user define packages.
O
12. 11. Draw and describe applet life cycle.
13. Write a program to show how to add applet to HTML ?
14. Write a program to show how to display graphics in applet?
ty
15. How to execute applet by appletviewer?
16. Write a short note on java.lang paclage.
r si
ve
ni
U
ity
m
)A
(c
e
Programming using JDBC
in
Course Content:
●● AWT
nl
●● AWT components
●● Event handling techniques
O
●● Event model
●● Event classes
●● Event listener
ty
●● AWT controls
●● Networking classes and interfaces
●● Socket programming
si
●● JDBC architecture
●● Database connectivity with Oracle
●● java.sql package
r
ve
●● SQL statements
1. Understanding of AWT
2. Different components of AWT
U
3. Concept of Event
4. Event handling mechanism
5. Event listener interface
ity
6. Swing
7. Java networking
8. java.net package
m
e
Unit Outcome:
in
At the end of this unit, you will be able to:
nl
●● Define AWT components
●● Discuss Event model
O
●● Define Event class
●● Define Event handling processes
●● Discuss about AWT controls
ty
●● Define different Layout Managers
●● Define Swing classes
●● Advantages of Swing over AWT
si
●● Use java.net package
●● Define TCP and UDP
●● Do TCP/IP and datagram programming
r
ve
●● Do Socket programming
●● Define JDBC architecture
●● Connect database with Oracle
ni
including shape, colour, and font classes. Components of AWT are platform-dependent
i.e. depending on the view of operating system. AWT is heavyweight i.e. its components
are using the resources of OS.
●● A general interface between Java and the native system, used for windowing,
events, and layout managers. This API is at the core of Java GUI programming
and is also used by Swing and Java 2D. It contains:
)A
●● The interface between the native windowing system and the Java application;
●● The core of the GUI event subsystem;
●● Several layout managers;
(c
AWT also makes some higher level functionality available to applications, such as:
●● The ability to launch some desktop applications such as web browsers and email
Notes
e
clients from a Java application.
in
nl
O
Fig 5.1: Hierarchy of AWT
As you can see in above diagram, Component is the parent class of all the GUI
As you can see in above diagram, Component is the parent class of all the GUI controls. It is an
controls. It isabstract
an abstract class.
class. For the look and feelFor the component
of interface, look and
class feel
instanceof interface, component class
is responsible.
ty
instance is responsible.
5.1.1 AWT Components
si
1. Container
1. Container: InAWT,
In Java Java AWT,
Container classContainer class
is a GUI component that is is atoGUI
used component
manage thatsuch
other GUI components is used to manage
other GUI components such as Frame, Window, Panel etc. For AWT, java.awt package
as Frame, Window, Panel etc. For AWT, java.awt package is there and Container is a subclass of
java.awt.Component and is responsible for components being added. There are four types of
is there and Container is inaJava.
subclass of java.awt.Component and is responsible for
containers
components
provided by AWT
r
being added. There are four types of containers provided by AWT in
ve
Types of Containers
Java.
a) Window: It is Window class's instance which does not have border or title. It is used for creating
a top-level window.
Types of Containers
b) Frame: Frame is a container and able to manage some other GUI components like label, text
field etc. It is the most widely used container for developing AWT applications. You can create a
a. Window: It is Window class’s instance which does not have border or title. It is
ni
c. Dialog: Dialog class is also a subclass of Window. It contains border, title etc.
d. Panel: Panel is the concrete subclass of Container. Panel doesn’t contain title
bar, birder or menu bar.
m
2. Button: To create a labeled button, you can use Button class. When user will click a
button , it will trigger a certain programmed action. Button class has two constructors.
3. Text Field: To create a single-line text box so that user can enter texts, you can use
)A
5. Canvas: To draw in an application or receive inputs created by the user, you can use
Canvas class. It is a rectangular area.
e
The selected choice is shown on the top of the given menu.
7. Scroll Bar: To add horizontal and vertical scrollbar in the GUI, Scrollbar class object
in
is used It enables user to see the more number of rows and columns.
8. List: To enable user to choose from a list of text items, List class is used.
9. CheckBox: To create a checkbox which can accept either of the two option, you can
nl
use Checkbox class. It has two state options; true and false. At any point in time, it
can have either of the two.
O
5.1.2 Event Handling Mechanism:
Components are displayed in frame which is a container, but these components
are static i.e. they can’t respond. Suppose you have created a login button and if
ty
you press it now, it will not act. To make it dynamic, we need to add event. So, we
can tell Buttons, Checkboxes are not able to perform any actions. If you click a
button, automatically an event will be raised. to handle events we require listener.
Responsibility of listener is to listen to the event generated by GUI components, handle
si
that event and sending results back to GUI program.
event handling. A number of listeners are available in Java and for each listener, a
number of listener methods are available.
Button ActionEvent
Checkbox ItemEvent
RadioButton ItemEvent
List ItemEvent
m
Choice ItemEvent
Menu ActionEvent
)A
ScrollBar AdjustmentEvent
Window WindowEvent
Mouse MouseEvent
Keyboard KeyEvent
(c
TextField TextEvent
TextArea TextEvent
For button, listener is ActionListener. Buttons will raise one event that is
Notes
e
ActionEvent. To handle this ActionEvent, we will implement ActionListener as it is an
interface. In ActionListener, actionPerformed() method is there which we have to use for
putting implementation.
in
Let us take an example, let us think in a form there are two Text fields which
will accept data from user and in 3rd field, it will produce the result once user click
nl
on Button. Once data is put in two fields and you click on button then automatically
an event will be raised (ActionEvent) and immediately flow of execution will go to
correspondint listener (here ActionListener) and inside the listener, event method will
be executed. Hence, in general we can tell that whenever we trigger a GUI component,
O
an event will be raised. the process of raising an event and the process of delegating
or bypassing event to the listener in order to handle. So, the total process of handling
event is called Event delegation model or event handling.
ty
5.1.4 Event Classes
Event is to change the state of an object. The java.awt.event package provides
si
many event classes and Listener interfaces for event handling. For example dragging
mouse of clicking a button etc are events. The java.awt.event package provides many
event classes and Listener interfaces for event handling.
r
Event classes Listener interfaces
ve
ActionEvent ActionListerner
MouseEvent MouseListener
MouseWheelEvent MouseWheelListener
ni
ItemEvent ItemListener
KeyEvent KeyListener
U
ComponentEvent ActionListerner
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ity
TextEvent TextListener
ContainerEvent ContainerListener
FocusEvent FocusListener
m
5.1.4.1 Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
)A
e
●● public void addTextListener (TextListener a){}
●● TextArea (Creates a multiline edit control)
in
●● public void addTextListener (TextListener a){}
●● Checkbox(Creates a check box control)
nl
●● public void addItemListener (ItemListener a){}
●● Choice (Creates a pop-up list)
●● public void addItemListener (ItemListener a){}
O
●● List ( creates a list from which a user can choose)
●● public void addActionListener (ActionListener a){}
●● public void addItemListener (ItemListener a){}
ty
5.1.4.2 Java Event Handling Code
We can put the event handling code into one of the following places:
si
1. Within class
2. Other class
3. Anonymous class
r
ve
5.1.5 Sources of Events
The Delegation Event Model has the following key participants namely:
for providing information of the occurred event to it’s handler. Java provide as with
classes for source object.
●● Listener - It is also known as event handler.Listener is responsible for generating
U
response to an event. From java implementation point of view the listener is also
an object. Listener waits until it receives an event. Once the event is received , the
listener process the event an then returns.
ity
The benefit of this approach is that the user interface logic is completely
separated from the logic that generates the event. The user interface element is able
to delegate the processing of an event to the separate piece of code. In this model,
Listener needs to be registered with the source object so that the listener can receive
m
the event notification. This is an efficient way of handling the event because the event
notifications are sent only to those listener that want to receive them.
1. Create container class and declare a 0-arg constructor, inside the constructor declare
a GUI component.
Example:
MyFrame(){
.......
Notes
e
}
in
2. Select a listener and provide Listener implementation class with the implementation
of Listener methods.
nl
class MyActionListener implements ActionListener {
......
O
}
ty
In general, in GUI applications, we will implement Listener interface in the same
container class.
si
.....
}
r
3. Attach Listener to GUI component like public void addxxxListener (xxxListener l)
ve
Note that, xxxListener may be ActionListener, ItemListener and so on.
e
In case of WindowEvent, component is Window, event is WindowEvent and listener
is WindowListener.
in
Working with Frame Windows
Most often the type of window we will create be derived from Frame. There are two
nl
constructors of Frame.
1. Frame ( )
2. Frame (String title)
O
The first one will create a standard window which does not contain a title. The
second form creates a window with the title specified by title. Here, we cannot specify
the dimensions of the window but we have to set the size of the window after it has
ty
been created.
si
The setSize( ) method is used to set the dimensions of the window.
Syntax:
Syntax:
Dimension getSize( )
U
This method returns the current size of the window mentioning the width and height
After a window has been created, it will not be visible. You have to make it visible
and in order to make it visible you have to call setVisible() method and you have to pass
“true” as parameter.
Syntax:
m
If you want to set title as per your choice, you can do that by calling setTitle() and
you have to pass the desired title as parameter.
Syntax:
(c
e
To implement window close event, you have to implement windowClosing() method
of WindowListener interface and inside windowClosing() you must remove the window
in
from screen.
nl
implementation of all the methods of listener interfaces.
Example:
O
import java.awt.*;
import java.awt.event.*;
ty
class MyFrame extends Frame{
MyFrame(){
si
this.setVisible(true);
this.setSize(500,500);
r
this.setTitle(“My frame with closing option enabled”);
ve
this.setBackground(Color.green);
System.exit(0);
U
});
ity
class WindowEventEx {
m
The below three aspects have been considered by every user interface:
●● UI elements: These are the visual elements the user eventually sees and
e
varying from basic to complex which we will cover in this tutorial.
●● Layouts: They define how UI elements should be organized on the screen and
in
provide a final look and feel to the GUI (Graphical User Interface). This part will be
covered in Layout chapter.
●● Behavior: These are events which occur when the user interacts with UI
nl
elements. This part will be covered in Event Handling chapter.
Every AWT controls inherits properties from Component class which is an abstract
class and parent class for GUI controls. Below are the list of control which you will
O
require during designing of GUI using AWT.
1. Label
2. Button
ty
3. Check box
4. CheckboxGroup
si
5. TextField
6. TextArea
7. List
r
ve
8. Choice
9. Image
10. Scrollbar
ni
the layout manager to arrange the components inside a container. Below are several
layout managers:
1. Flow layout
ity
2. Border layout
3. Grid layout
4. GridBag layout
m
5. Card layout
Flow Layout
)A
This layout is able to arrange all GUI component in row manner one after another.
To represent this Java has FlowLayout class. In order to use this you have to import
java.awt.FlowLayout.
Border Layout
(c
This layout is able to arrange all GUI component along with borders of the
container. Java has BorderLayout class. In order to use this you have to import java.
awt.BorderLayout. It places components in five places which is top, bottom, left, right
Notes
e
and center.
Grid Layout
in
This layout places the GUI components in the form of grids i.e. in row and column
manner. Predefine class java.awt.GridLayout is there.
nl
GridBag Layout
This layout is almost same as GridLayout. Predefine class java.awt.GridBagLayout
O
is there.
ty
2. Empty grids are allowed between components.
Card Layout:
si
This layout is able to arrange GUI components in the form of layers along with
borders of the container. Java has BorderLayout class. In order to use this you have to
import java.awt.BorderLayout.
r
ve
5.1.10 Introduction to Swing classes and Controls
Swing is a lightweight toolkit having huge variety of widgets for making optimized
window based applications. It is a part of the Java Foundation Classes (JFC) and is
ni
build on top of the AWT API. It is platform independent. To build applications in Swing is
easy as we already have GUI components like buttons, checkboxes etc and very much
helpful as you need not to start from the scratch.
U
Container Class
A container class is a class which has other components. For building GUI
applications at least one container class is necessary.
ity
3. Dialog : It is like a pop up window but not fully functional like the frame
JFrame : A frame is an instance of JFrame. Frame is a window that can have title,
border, menu, text fields , buttons etc. A Swing application must have a frame to have
)A
JPanel : A panel is an instance of JPanel. Frame can have more than one panels
and each panel can have several components. Those are parts of Frame. Panels are
useful for grouping components and placing them to appropriate locations in a frame.
(c
e
JTextField : This is used for taking user inputs from the text boxes where user
enters the data.
in
JPasswordField : Similar to text fields but the entered data gets hidden and
displayed as dots on GUI.
nl
5.1.11 Advantages of swings over AWT
AWT and Swing are both part of a group of Java class libraries called the Java
O
Foundation Classes (JFC). The Abstract Windowing Toolkit (AWT) is the original GUI
toolkit shipped with the Java Development Kit (JDK). The AWT provides a basic set of
graphical interface components similar to those available with HTML forms. Swing is the
latest GUI toolkit, and provides a richer set of interface components than the AWT. In
ty
addition, Swing components offer the following advantages over AWT components:
si
●● Swing components can change their appearance based on the current “look and
feel” library
●●
r
Swing uses a more efficient event model than AWT; therefore, Swing components
can run more quickly than their AWT counterparts
ve
●● Swing provides “extras” for components, such as: Icons on many components,
Decorative borders for components, Tooltips for components
●● Swing provides built-in double buffering
ni
The devices are all connected to each other using a network. The java.net package
contains a collection of classes and interfaces that provide the low-level communication
details. Below are listed few important classes and interfaces used is networking.
ity
CacheRequest CookieHandler
CookieManager Datagrampacket
InetAddress ServerCocket
)A
Socket DatagramSocket
Proxy URL
(c
e
CookiePolicy CookieStore
FileNameMap SocketOption
in
InetAddress ServerSocket
SocketImplFactory ProtocolFamily
nl
5.1.14 Using Java.net Package, Doing TCP/IP and Datagram
Programming
O
The java.net package provides support for the two common network protocols:
5.1.14.1 TCP
ty
Transmission Control Protocol (TCP) allows reliable communication between two
applications. TCP is typically used over the Internet Protocol(IP) and is referred to as
TCP/IP. TCP provides a point-to-point channel for applications that require reliable
si
communications. The Hypertext Transfer Protocol (HTTP), File Transfer Protocol
(FTP) and Telnet are all examples of applications that require a reliable communication
channel. When HTTP is used to read from a URL, the data must be received in the
order in which it was sent. Otherwise, you can have a jumbled HTML file or some other
r
invalid information or a corrupt zip file.
ve
5.1.14.2 UDP
User Datagram Protocol (UDP) is a connection-less protocol that allows for
packets of data to be transmitted between applications. The UDP protocol provides for
ni
communication that is not guaranteed between two applications on the network. UDP
is not connection oriented like TCP instead UDP sends independent packets of data
(datagrams) from one application to another. The order of delivery is not important and
U
communicate by writing to and reading from the socket. The java.net.Socket class
represents a socket, and the java.net.ServerSocket class provides a mechanism for the
server program to listen for clients and establish connections with them.
)A
When establishing a TCP connection between two computers using sockets the
below steps takes place:
●● The server invokes the accept() method of the ServerSocket class. This method
waits until a client connects to the server on the given port.
e
server name and the port number to connect to.
●● The constructor of the Socket class attempts to connect the client to the specified
in
server and the port number. If communication is established, the client now has a
Socket object capable of communicating with the server.
●● On the server side, the accept() method returns a reference to a new socket on
nl
the server that is connected to the client’s socket.
Communication can occur using I/O streams after the connections are established.
Each socket has an InputStream and an OutputStream. The client’s OutputStream is
O
connected to the server’s InputStream, and the client’s InputStream is connected to the
server’s OutputStream.
ty
streams at the same time.
si
The java.net.ServerSocket class is used by server applications to obtain a port and
listen for client requests.
execute the query with the database. JDBC drivers are used in JDBC API to connect
with the database. There are four types of JDBC drivers:
●● Native Driver
●● Network Protocol Driver
●● Thin Driver
m
To access tabular data stores in any relational database, we can use JDBC API.
With the help of JDBC API, we can save, update, fetch and delete from the database.
)A
(c
The java.sql package contains classes and interfaces for JDBC API. Below are a
Notes
e
list of popular interfaces of JDBC API:
Driver interface
in
Connection interface
Statement interface
nl
PreparedStatement interface
CallableStatement interface
O
ResultSet interface
ResultSetMetaData interface
DatabaseMetaData interface
ty
RowSet interface
si
DriverManager class
Blob class
Clob class r
ve
Types class
We can use JDBC API to handle database using Java program and can perform
the following activities:
ni
calls. Because of thin driver this is now does not have that importance. The Native API
driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java. The Network
Protocol driver uses middleware (application server) that converts JDBC calls directly
or indirectly into the vendor-specific database protocol. It is fully written in java. The thin
(c
driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
e
To connect java application with the oracle database, you must follow 5 steps. In
this example, we are using Oracle 10g as the database. So we need to know following
in
information for the oracle database:
1. Driver class: The driver class for the oracle database is oracle.jdbc.driver.
OracleDriver.
nl
2. Connection URL: The connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database,
thin is the driver, localhost is the server name on which oracle is running, we may
O
also use1521 is the port number and XE is the Oracle service name. You may get all these
IP address, 1521 is the port number and XE is the Oracle service name.
information from the tnsnames.ora file.
You may get all these information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
3. Username: The default username for the oracle database is system.
ty
4. 4. Password:
Password: It is theIt password
is the password given
given bybythe
theuser
user at
at the
thetime of of
time installing the oracle
installing the oracle
database.
database.
si
5.17 JDBC Architecture:
5.17 JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for
The JDBC
database API supports both two-tier and three-tier processing models for database access.
access.
r
ve
ni
a JDBC driver that can communicate with the particular data source which is being
A Java application talks directly to the data source in two-tier model. This requires a JDBC driver that
accessed. User’s commands are delivered to the database or other data source,
can communicate with the particular data source which is being accessed. User's commands are
and the results
delivered of database
to the those statements are sent
or other data source, back
and the resultstoof the
thoseuser. The are
statements data
sent source
back to may
be located onThe
the user. another machine
data source to which
may be located the user
on another machineis to
connected viais aconnected
which the user network. via aThis is
ity
referred to asThis
network. a client/server
is referred to as aarchitecture, with the with
client/server architecture, user’s machine
the user's asasthe
machine the client, and the
client, and
the machine housing the data source
machine housing the data source as the server. as the server.
InInthe
the three-tier
three-tier model, commands
model, are sent to
commands area "middle
sent totier"
a of services, tier”
“middle whichof
then sends the which
services,
commands to the data source. The data source processes the commands and sends the results back
then sends the commands to the data source. The data source processes the
m
advantage it simplifies the deployment of applications. Finally, in many cases, the three-tier
makesarchitecture
it possible to maintain
can provide control
performance over access and the kinds of updates that can
advantages.
be made to corporate data. Another advantage is that it simplifies the deployment of
applications. Finally, in many cases, the three-tier architecture can provide performance
advantages.
(c
167
Notes
e
in
nl
O
5.1.18 Connection Interface:
The Connection interface is a factory of Statement. A Connection is the session
ty
between java application and database.
si
Connection interface provide numerous methods for transaction management similar to
commit(), rollback() etc.
r
public Statement createStatement(): creates a statement object that can be applied
to execute SQL queries.
ve
5.1.19 Java Database Connectivity
JDBC stands for Java Database Connectivity, which is a standard Java API for
ni
The JDBC library includes APIs for each of the tasks stated below that are
U
There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
ity
●● Execute queries
●● Close connection
)A
e
interface is used to create statement. The object of statement is responsible
to execute queries with the database.
in
4. Execute the query: The executeQuery() method of Statement interface is
used to execute queries to the database. This method returns the object of
ResultSet that can be used to get all the records of a table
nl
5. Close the connection object: By closing connection object statement and
ResultSet will be closed automatically. The close() method of Connection
O
interface is used to close the connection.
ty
in the database especially relational database by using the java programming language.
It includes a framework where we different drivers can be installed dynamically to
access different databases especially relational databases
si
This java.sql package contains API for the following :
c. Driver interface: This interface is mainly used by the DriverManager class for
registering and connecting drivers based on JDBC technology.
d. DriverPropertyInfo class : This class is generally not used by the general
U
user.
procedures.
d. Connection interface : It provides methods for creating statements and
managing their connections and peoperties.
)A
of data. The cursor is initially positioned before the first row. The next method of
the resultset interface moves the cursor to the next row and it will return false if
there are no more rows in the ResultSet object. By default ResultSet object is
Notes
e
not updatable and has a cursor that moves forward only.
in
Java Programming Language.
a. Array interface: It provides the mapping for SQL Array.
nl
b. Blob interface : It provides the mapping for SQL Blob.
c. Clob interface: It provides the mapping for SQL Clob.
d. Date class: It provides the mapping for SQL Date.
O
e. Ref interface: It provides the mapping for SQL Ref.
f. Struct interface: It provides the mapping for SQL Struct.
ty
g. Time class: It provides the mapping for SQL Time.
h. Timestamp: It provides the mapping for SQL Timestamp.
i. Types: It provides the mapping for SQL types.
si
5) Metadata
a. Database Meta Data Interface: It keeps the data about the data. It provides
r
information about the database.
ve
b. Result Set Meta Data: It gives the information about the columns of a ResultSet
object.
c. Parameter Meta Data: It gives the information about the parameters to the
PreparedStatement commands.
ni
6) Exceptions
a. SQLException: It is thrown by the methods whenever there is a problem while
U
Programming Language.
a. SQLData interface: It gives the mapping of a UDT to an instance of this class.
)A
b. SQLInput interface: It gives the methods for reading UDT attributes from a
stream.
c. SQLOutput: It gives the methods for writing UDT attributes back to a stream.
e
In all of these examples I’ll access a database named “Demo”, and in these
SELECT query examples I’ll access a database table named “Customers” that’s
in
contained in the Demo database.
nl
Cnum Lname Salutation City Snum
1001 Simpson Mr. Springfield 2001
1002 MacBeal Ms. Boston 2004
O
1003 Flinstone Mr. Bedrock 2003
1004 Cramden Mr. New York 2001
ty
How to perform a JDBC SELECT query against a database
Querying a SQL database with JDBC is typically a three-step process:
si
Create a JDBC ResultSet object.
This statement returns each Lname (last name) record from the Customers
database, where Snum (salesperson id-number) equals 2001. In plain English, you
ity
might say “give me the last name of every customer where the salesperson id-number
is 2001”.
Now that we know the information we want to retrieve, how do we put this SQL
statement into a Java program? It’s actually very simple. Here’s the JDBC code
m
Snum = 2001”);
Reading the JDBC SELECT query results (i.e., a Java JDBC ResultSet)
After you execute the SQL query, how do you read the results? Well, JDBC
(c
makes this pretty easy also. In many cases, you can just use the next() method of the
ResultSet object. After the previous two lines, you might add a loop like this to read the
results:
Amity Directorate of Distance & Online Education
140 Core Java
while (rs.next()) {
Notes
e
String lastName = rs.getString(“Lname”);
System.out.println(lastName + “\n”);
in
}
nl
The full source code for our example JDBC program
import java.sql.*;
/**
O
* A JDBC SELECT (JDBC query) example program.
*/
ty
class Query1 {
try {
si
String url = “jdbc:msql://200.210.220.1:1114/Demo”;
ResultSet rs;
while ( rs.next() ) {
System.out.println(lastName);
}
ity
conn.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
)A
Summary
(c
AWT stands for Abstract Window Toolkit. It is a Java package that can be imported
as java. awt. * and that consists of platform-independent windowing, graphics, and user
interface tools for programmers to use when building up applets and/or stand-alone
Amity Directorate of Distance & Online Education
Core Java 141
Java applications. Event Handling is the mechanism that controls the event and decides
Notes
e
what should happen if an event occurs. This mechanism have the code which is known
as event handler that is executed when an event occurs.
in
Java Uses the Delegation Event Model to handle the events. A layout manager in
Java is responsible for placing the components such as buttons and text boxes on the
application. This lesson explains how layout manager object is used to determine size
nl
and position of components in a container. Package java.net provides the classes for
implementing networking applications. Addresses which are networking identifiers, like
IP addresses. Sockets, which are basic bidirectional data communication mechanisms.
Interfaces, which describe network interfaces.
O
Activity:
1. What is difference between Swing and AWT in Java?
ty
2. What is difference between paint and repaint in Java Swing?
3. How many types of layout is there?
si
4. What is difference between BorderLayout and GridLayout ?
5. Why Swing is called light weight ?
6. r
What is difference between Container and Component ?
ve
7. What is JDBC?
8. What is JDBC driver?
9. What are the steps to connect to the database in java?
ni
Project.
communications are via TCP/IP network protocol enabling the using of both intranet and
internet communications world wide.
The solution includes several standard items, which are combined to provide an
integrated solution with interfaces to other business systems. The system is based on
(c
The open nature of VRS allows the addition of new systems and features, ensuring
that the VRS system can be adapted to keep up with the changing requirements of the
Amity Directorate of Distance & Online Education
142 Core Java
e
1> Reservations
in
3> Fares
nl
All user/agents are allocated a SINE code, which is used during sine-on and then
appended to all transactions carried out by the agent for security purpose . Different
security levels may be assigned so that different agents can access different areas of
O
the system and also different records in the case where a travel agent is only allowed to
review PNR’s that have been created by that agency.
Flights may be entered as far ahead as required without limitation using the flight
ty
inventory GUI. Native transactions support reservations up to 1 year ahead. The flights
may be specified within a particular date range and may be used to display different
classes of service and different fare within a specific seating class. Sell from availability
si
when it has been displayed and a simple entry is used to sell seats. A direct sale may
be made using a long hand entry if the flight details are fully
known.
Sample Code :
r
ve
package test;
import java.io.Serializable;
ni
import java.util.*;
import java.sql.*;
import java.io.*;
U
{
ity
if(customerid != null)
)A
this.customerid = customerid;
return(this.customerid);
e
public Vector getResult()
in
{
nl
try
O
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
ty
PreparedStatement stat = con.prepareStatement(“SELECT * from customer where
cust_id= ? “);
stat.setString(1,customerid);
si
ResultSet rs = stat.executeQuery();
if(rs.next())
{
r
ve
v.addElement(rs.getString(“cust_name”));
v.addElement(rs.getString(“address”));
v.addElement(rs.getString(“city”));
ni
}
U
catch(Exception ex)
{
ity
ex.printStackTrace();
this.result = v;
m
return v;
}
)A
}
(c