Download CORE JAVA - WordPress.com

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Introduction to Java
In 1990, Sun Microsystems (US) has conceived a
project to develop software for consumer
electronic devices that could be controlled by a
remote. This project was called Stealth Project
but later its name was changed to
Green Project
In January of 1991, Bill Joy, James Gosling,
Mike Sheradin, Patrick Naughton, and several
others met in Aspen, Colorado to disuss this
project
Gosling thought C and C++ could be used to
develop the project.
But the problem he faced with them is that they
were system dependent languages and hence
could not be used on various processors, which
the electronic device might use.
So he started developing a new language, which
was completely system independent.
This language was initially called Oak.
Since this name is registered by some other
company, later it was changed to Java
Internal Structure of Java
Generally, Java is available in the form of
j2sdk (version)
J2sdk having the following components
JVM (Java Virtual Machine)
JRE (Java Runtime Environment)
JDK (Java Development Kit)
JIT (Just In time Compiler)
Java Virtual Machine (JVM) is an abstract
computing machine.
Java Runtime Environment (JRE) is an
implementation of the JVM.
Java Development Kit (JDK) contains JRE
along with various development tools like Java
libraries, Java source compilers, Java
debuggers, bundling and deployment tools.
JIT is the part of the Java Virtual Machine (JVM)
that is used to speed up the execution time.
Versions of Java
JDK 1.0 (January 23, 1996)
Codename Oak. Initial release The first stable
version was the JDK 1.0.2. is called Java 1
JDK 1.1 (February 19, 1997)
J2SE 1.2 (December 8, 1998)
Codename Playground
J2SE 1.3 (May 8, 2000)
Codename Kestrel.
J2SE 1.4 (February 6, 2002)
Codename Merlin.
J2SE 5.0 (September 30, 2004)
Codename Tiger.
Java SE 6 (December 11, 2006)
Codename Mustang.
Java SE 7 (July 28, 2011)
Java 7 codename Dolphin
Java SE 8(
Editions of Java
• Java Standard Edition (J2SE)
– J2SE can be used to develop client-side
standalone applications or applets.
• Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side
applications such as Java servlets and Java
ServerPages.
• Java Micro Edition (J2ME).
– J2ME can be used to develop applications for
mobile devices such as cell phones.
12
Features of Java
Features of Java
• Java is simple
• Java is object-oriented
• Java is distributed
• Java is interpreted
• Java is robust
• Java is secure
• Java is portable
• Java’s performance
• Java is multithreaded
• Java is dynamic
• System independence
14
Simple
The concepts of pointers which is very difficult
for both learners and programmers has been
completely eliminated from java
JavaSoft people maintained the same syntax of C
and C++
Object-Oriented
Java is object-oriented programming language.
This means Java programs use objects and
classes
Distributed
Using java, we can write programs, which
capture information and distribute it to the
clients
Interpreted
In Java, we use both compiler and interpreter for
the execution
Robust
Robust means strong. Java programs are strong
and they don’t crash easily like C or C++. The
reasons are in built exception handling
mechanism and memory management features
Secure
Security problems like tampering and virus
threats can be eliminated or minimized by
using Java on Internet
Portability
If a program yields the same result on every
machine, then that program is called portable.
Java programs are portable
Performance
The problem with interpreter inside the JVM is
that it is slow. Because of this, Java programs
used to run slow. To overcome this problem,
along with the interpreter, JavaSoft people
have introduced JIT (Just In Time) compiler,
which enhances the speed of execution
Multithreaded
A thread represents an individual process to
execute a group of statements. JVM uses
several threads to execute different blocks of
code. Creating multiple threads is called
‘multithreaded’
Dynamic
Before development of Java, only static text used
to be displayed in the browser. Java applet
program, which is dynamically interacting
programs on Internet
System Independence
Java’s byte code is not machine dependent. It can
be run on any machine with any processor and
any operating system
First Java Program
Hello World Program
import java.lang.System;
import java.lang.String;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println(“Hello World!”);
}
}
import java.lang.System;
import java.lang.String;
Whenever we want to import several classes of
the same package, we need not write several
import statements, as shown above; instead,
we can write a single statement as:
import java.lang.*;
Here, * means all the classes and interfaces of
that package
public class HelloWorld
After importing classes into the program, the
next step is to write a class. Since Java is
purely an object-oriented programming
language, we cannot write a Java program
without having at least one class. So, it is
mandatory that every Java program should
have at least one class in it
Writing a Class
We should use class keyword for this purpose
and then write the class name
A class code starts with a { and ends with a }
public static void main (String args[])
A method generally, performs two operations
1. It can accept some data from outside
2. It can also return some result
Example: sqrt()
Similarly the main() method also accept some
data from us
Example: it accepts a group of string, which is
called a string type array.
Here args[] is the array name and it is of String
type. The values passed to main() are called
arguments
If a method is not menat to return any value, then
we should write void before that method’s
name. main() method does not return any
value, so void should be written before that
method’s name
We should call the main() method without
creating an object. Such methods are called
static methods and should be declared as static
JVM is a program written by JavaSoft people
and main() is the method written by us. Since,
main() method should be available to the JAM,
it should be declared as public
System.out.println(“Hello World”);
System.out gives the PrintStream class object.
This object, by default, represents the standard
output device, i.e. the monitor. So, the string
“Hello World” will be sent to the monitor
Naming Conventions
Identifiers
Identifiers
• A name in the program is an identifier it may be class name or
method name, variable name or label name.
Example
Class Test
{
public static void main(String[] args)
{
int x=10
System.out.println(x);
}
Rules for defining Identifiers
• Identifiers must start with a letter, a currency character ($), or
a connecting character such as the underscore ( _ ).
• Identifiers cannot start with a number
• After the first character, identifiers can contain any
combination of letters, currency characters, connecting
characters, or numbers.
• In practice, there is no limit to the number of characters an
identifier can contain.
• You can't use a Java keyword as an identifier.
• Identifiers in Java are case-sensitive; foo and FOO are two
different identifiers.
Legal Identifiers
• int _a;
• int $c;
• int ______2_w;
• int _$;
• int this_is_a_very_detailed_name_for_an_identifier;
Illegal Identifiers
• int :b;
• int -d;
• int e#;
• int .f;
• int 7g;
Java coding Standards
Coding standards for classes
Usually class name should be noun. Should starts with upper case
letter and if it contain multiple words every inner words also
should start with capital letters.
Example:
• String
• StringBuffer
• NumberFormat
• CustomerInformation
Coding standards for Interfaces
Usually interface named should be adjective, starts with capital
letters and if it contains multiple words, every inner word also
should starts with capital letter.
Example:
• Runnable
• Serializable
• Clonable
• Movable
• Transferable
• Workable
Coding standards with methods
• Values should be either verbs or verb + noun combination.
• Starts with lower case and every inner words starts with upper case(this
convention is also called camel case convention).
Example:
• getName(), getMessage(), toString(), show(), display().
Coding standards for variables
• Usually the variable starts with noun and every inner word should start
with upper case i.e camel case convention.
Example:
• Name, rollno, bandwidth, totalNumber.
Coding standards for constants
• It should be noun, it should contain only upper case letters and works are
separated with underscores.
• Example:
• MAX_SIZE, MIN_PRIORITY, COLLEGE_NAME.
Data Types in Java
Primitive Data Types
Represent numbers, characters,
boolean values
• Integers: byte, short, int, and long
• Real numbers: float and double
• Characters: char
• Boolean :boolean
Except boolean and char all the remaining datatypes are signed
datatypes i.e we can represent both +ve and –ve numbers.
byte
• Size : 8-bits
• Range: -128 to 127
Example:
• byte b = 10;
• byte b = 127;
• byte b = 130; C.E: possible loss of precision
• byte b = true; C.E: Incompatible types found: boolean
required: byte
byte datatype is best suitable if we are handling data either from
file or form network.
short
• size = 2 bytes
• range = -215 to 215 -1 (-32768 to 32767)
Example:
• short s = 10;
• short s = 32767;
• short s = 65535; C.E: possible loss of precision.
• short s = true; C.E: Incompatible types
short is best suitable datatype for 16-bit process. But currently these are
completely out dated and hence the corresponding datatypes also no one is
using.
int
The most commonly used datatype is int.
• size = 4 bytes
• range = -231 to 231 – 1(-2147483648 to 2147483747)
The size of int is always fixed irrespective of platform hence the chance of
failing java program is very less if you are changing the platform hence the
java is considered as Robust.
long
if int is not enough to hold big values then we should go for longdatatype
• size = 8 bytes
• range = -263 to 263 – 1
Example:
• The amount of distance traveled by light in 1000days can be
represented by long datatype only and int is not enough.
floating-point
For representing real numbers(numbers with decimal points)
float
• size = 4 bytes
• range = -3.4e38 to 3.4e38
• If 6 to 7 decimal places of accuracy required
double
• size = 8 bytes
• range = -1.7e308 to 1.7e308
• If 14 to 15 decimal places of accuracy required
boolean datatye
• size = not applicable(virtual machine dependent).
• range = not applicable but allowed values are true/false.
Which of the following boolean declarations are valid
• boolean b1 = true;
• boolean b2 = 0; Incompatible types found:int required :
booleaan
• boolean b3 = TRUE; capital TRUE is not valid.
char Data Type
• One Unicode character (16 bits - 2 bytes)
Type
char
Size
Minimum Value
in Bytes
2
character
encoded as 0
Example declarations:
char finalGrade;
char newline, tab, doubleQuotes;
Maximum Value
character
encoded as FFFF
Literal Values for All Primitive Types
A primitive literal is merely a source code representation of the
primitive data types you type in while writing code.
The following are examples of primitive literals:
• 'b' // char literal
• 42 // int literal
• false // boolean literal
• 2546789.343 // double literal
Integer Literals
• There are three ways to represent integer numbers in the Java
language: decimal (base 10), octal (base 8), and hexadecimal
(base 16).
Decimal Literals
• Decimal integers need no explanation; you've been using
them since grade one or earlier.
• In the Java language, they are represented as is, with no prefix
of any kind, as follows:
int length = 343;
Octal Literals
• Octal integers use only the digits 0 to 7.
• In Java, you represent an integer in octal form by placing a zero in front of
the number, as follows:
class Octal {
public static void main(String [] args) {
int six = 06; // Equal to decimal 6
int seven = 07; // Equal to decimal 7
int eight = 010; // Equal to decimal 8
int nine = 011; // Equal to decimal 9
System.out.println("Octal 010 = " + eight);
}
}
• Notice that when we get past seven and are out of digits to use we revert
back to zero, and one is added to the beginning of the number.
Hexadecimal Literals
• Hexadecimal (hex for short) numbers are constructed using 16 distinct symbols.
• Because we never made-up single digit symbols for the numbers 10 through 15, we
use alphabetic characters to represent these digits.
• Counting from 0 through 15 in hex looks like this:
• 0123456789abcdef
• Java will accept capital or lowercase letters for the extra digits
• You are allowed up to 16 digits in a hexadecimal number, not including the prefix
0x
• All of the following hexadecimal assignments are legal:
class HexTest {
public static void main (String [] args) {
int x = 0X0001;
int y = 0x10
int z = 0x11
System.out.println("x = " + x + " y = " + y + " z = " + z);
}
}
Floating-Point Literals
•
Floating-point numbers are defined as a number, a decimal symbol, and more
numbers representing the fraction.
• double d = 11301874.9881024;
• In the preceding example, the number 11301874.9881024 is the literal value.
• Floating-point literals are defined as double (64 bits) by default, so if you want to
assign a floating-point literal to a variable of type float (32 bits), you must attach
the suffix F or f to the number.
• If you don't, the compiler will complain about a possible loss of precision, because
you're trying to fit a number into a (potentially) less precise "container."
float f = 23.467890; // Compiler error, possible loss of precision
float g = 49837849.029847F; // OK; has the suffix "F“
• You may also optionally attach a D or d to double literals, but it is not necessary
because this is the default behavior.
• double d = 110599.995011D; // Optional, not required
• double g = 987.897; // No 'D' suffix, but OK because the literal is a double by
default
• Look for numeric literals that include a comma, for example,
• int x = 25,343; // Won't compile because of the comma
Boolean Literals
• Boolean literals are the source code representation for
boolean values.
• A boolean value can only be defined as true or false.
boolean t = true; // Legal
boolean f = 0; // Compiler error!
• Be on the lookout for questions that use numbers where
booleans are required.
• You might see an if test that uses a number, as in the
following:
int x = 1;
if (x) { } // Compiler error!
Character Literals
• A char literal is represented by a single character in single quotes.
char a = 'a';
char b = '@';
• You can also type in the Unicode value of the character, using the Unicode
notation of prefixing the value with \u as follows:
char letterN = '\u004E'; // The letter 'N'
• Remember, characters are just 16-bit unsigned integers under the hood.
That means you can assign a number literal, assuming it will fit into the
unsigned 16-bit range (65535 or less).
• For example, the following are all legal:
char a = 0x892; // hexadecimal literal
char b = 982; // int literal
char c = (char)70000; // The cast is required; 70000 is out of char range
Literal Values for Strings
• A string literal is a source code representation of a value of a
String object.
• For example, the following is an example of two ways to
represent a string literal:
String s = "Bill Joy";
System.out.println("Bill" + " Joy");
• Although strings are not primitives, they're included in this
section because they can be represented as literals—in other
words, typed directly into code.
• The only other nonprimitive type that has a literal
representation is an array
Variables in Java
Variables
• A variable is a location in memory that can
hold values of a certain data type
• Each variable must be declared before it is
used
Variable Declarations
• The syntax of a variable declaration is
data-type variable-name;
• For example
int total;
• Multiple variables can be declared on the same line
long total, count, sum;
• Variables can be initialized (given an initial value) in the
declaration
int total = 0, count = 20;
unitPrice
= 57.25;(given an initial value) in the
•double
Variables
can be initialized
VariableExample Program
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}
VariableExample Program (2)
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}
x
VariableExample Program (3)
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}
3
x
VariableExample Program (4)
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}
3
x
VariableExample Program (5)
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}
4
x
VariableExample Program (6)
public class VariableExample {
public static void main(String[] args){
int x;
x = 3;
System.out.println(x);
x = 4;
System.out.println(x);
}
}
4
x
Variable Declaration Example
public class DeclarationExample {
public static void main (String[] args) {
int weeks = 14;
long numberOfStudents = 120;
double averageFinalGrade = 78.6;
System.out.println(weeks);
System.out.println(numberOfStudents);
System.out.println(averageFinalGrade);
}
}
More Variable Examples
double pi, conversionRate, temprature;
long salary;
boolean isOn;
char c;
pi = 3.14159;
isOn = false;
c = ‘A’;
salary = 34000;
isOn = true;
Constants
• We may declare that a variable is a constant
final double PI = 3.14159;
and
its
value
may
never
change.
final int CHINA_OLYMPICS_YEAR = 2008;
• Advantages:
– readability
– efficiency
– error detection
Operators in Java
An operator is a symbol that performs an
operation
An operator acts on some variables called
operands to get the desired result as shown
below
Example: a + b
If operator acts on single variable it is called
unary operator; if it acts on two variables, it is
called binary operator; and it is acts on three
variables, then it is called as ternary operator
Java supports the following types of operators
1. Arithmetic operators
2. Unary operataors
3. Assignment operator(=)
4. Relational operators
5. Logical operators
6. Boolean operators
7. Bitwise operators
8. Ternary Operator or Conditional Operator
11. Member Oerator
12. instanceof operator
13.new operator
14.Cast operator
Arithmetic Operators
Operator
Operation
+
addition
-
subtraction
*
multiplication
/
division
%
modulus
(remainder after
division)
Simple Arithmetic
public class Example {
public static void main(String[] args) {
int j, k, p, q, r, s, t;
j = 5;
k = 2;
p = j + k;
q = j - k;
r = j * k;
s = j / k;
t = j % k;
System.out.println("p = " + p);
System.out.println("q = " + q);
System.out.println("r = " + r);
System.out.println("s = " + s);
System.out.println("t = " + t);
}
> java Example
p = 7
}
q = 3
r = 10
s = 2
t = 1
>
Unary Operators
As the name indicates unary operators act on
only one operand. There are 3 kinds of unary
operators
1) Unary minus (-)
2) Increment operator (++)
3) Decrement operator(--)
Unary minus(-)
This operator is used to negate a given value.
Negation means converting a negative value
into positive and vice versa
Example:
int x=5;
System.out.println(-x); will display -5
System.out.println(-(-x)); will display 5
Increment Operator(++)
This operator increases the value of variable by 1
Example
int x=1;
++x will make x=2
X++ now x=3
Here, the value of the variable x is incremented
by 1 when ++ operator is used before or after
it. Both are valid in Java
Writing ++ before a variable is called pre
increment and writing ++ after a variable is
called post increment
In pre incrementation, incrementation is done
first and any other operation is done next
In post incrementation, all the other operations
are done first and incrementation is done only
at the end.
Example:
int x=1;
System.out.println(x);
System.out.println(++x);
System.out.println(x);
Output:1 2 2
int x=1;
System.out.println(x);
System.out.println(x++);
System.out.println(x);
Output:1 1 2
Increment and Decrement
public class Example {
public static void main(String[] args) {
int j, p, q, r, s;
j = 5;
p = ++j; // j = j + 1; p = j;
System.out.println("p = " + p);
q = j++; // q = j;
j = j + 1;
System.out.println("q = " + q);
System.out.println("j = " + j);
r = --j; // j = j -1;
r = j;
System.out.println("r = " + r);
s = j--; // s = j;
j = j - 1;
System.out.println("s = " + s);
}
}
> java example
p = 6
q = 6
j = 7
r = 6
s = 6
>
Assignment Operator
Syntax:
target = expression;
expression: operators and operands that
evaluate to a single value
--value is then assigned to target
--target must be a variable (or constant)
--value must be compatible with target's data
type
Examples:
int numPlayers = 10; // numPlayers holds 10
numPlayers = 8;
// numPlayers now holds 8
int legalAge = 18;
int voterAge = legalAge;
The next statement is illegal
int height = weight * 2; // weight is not defined
int weight = 20;
and generates the following compiler error:
illegal forward reference
Relational Operators
These operators are used for the purpose of
comparing
For example, to know which one bigger or
whether two quantities are equal or not.
Relational Operators
>
<
>=
<=
Primitives
• Greater Than
• Less Than
• Greater Than or Equal
• Less Than or Equal
==
!=
>
<
>=
<=
Primitives or Object References
• Equal (Equivalent)
==
• Not Equal
!=
The Result is Always true or false
Relational Operator Examples
public class Example {
public static void main(String[] args) {
int p =2; int q = 2; int r = 3;
Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println("p
System.out.println("p
System.out.println("p
System.out.println("p
< r " + (p < r));
> r " + (p > r));
== q " + (p == q));
!= q " + (p != q));
System.out.println("i == j " + (i == j));
System.out.println("i != j " + (i != j));
}
}
>
p
p
p
p
i
i
>
java Example
< r true
> r false
== q true
!= q false
== j false
!= j true
Logical Operators
Logical operators are used to construct
compound condition
A compound condition is a combination of
several simple conditions
Logical Operators (boolean)
&&
|| !
•
Logical AND
&&
•
Logical OR
||
•
Logical NOT
!
Logical (&&) Operator Examples
public class Example {
public static void main(String[] args) {
boolean t = true;
boolean f = false;
System.out.println("f
System.out.println("f
System.out.println("t
System.out.println("t
&&
&&
&&
&&
f
t
f
t
"
"
"
"
+
+
+
+
(f
(f
(t
(t
&&
&&
&&
&&
f));
t));
f));
t));
}
}
>
f
f
t
t
>
java
&& f
&& t
&& f
&& t
Example
false
false
false
true
Logical (||) Operator Examples
public class Example {
public static void main(String[] args) {
boolean t = true;
boolean f = false;
System.out.println("f
System.out.println("f
System.out.println("t
System.out.println("t
||
||
||
||
f
t
f
t
"
"
"
"
+
+
+
+
(f
(f
(t
(t
||
||
||
||
f));
t));
f));
t));
}
}
>
f
f
t
t
>
java
|| f
|| t
|| f
|| t
Example
false
true
true
true
Logical (!) Operator Examples
public class Example {
public static void main(String[] args) {
boolean t = true;
boolean f = false;
System.out.println("!f " + !f);
System.out.println("!t " + !t);
}
}
> java Example
!f true
!t false
>
• Boolean Operators
1) & boolean and operator
2) | boolean or operator
3) ! boolean not operator
Example:
a=true, b=false;
a&b // returns false
a|b // returns true
a&a //return true
b|b // return false
!a //gives false
!b //gives true
Priority of Operators
1) First the contents inside the braces ( ) and [] will be executed
2) Next ++ and –
3) Next * , / , and % will be executed
4) + and – will come next
5) Next relational operators
6) Boolean and bitwise operators
7) Next logical operators
8) Then ternary operator
9) Assignment operator are executed at the last
10)
Arrays
• Arrays are objects in Java that store multiple
variables of the same type.
• Arrays can hold either primitives or object
references, but the array itself will always be an
object on the heap, even if the array is declared to
hold primitive elements.
• For this arrays, you need to know three things:
■ How to make an array reference variable (declare)
■ How to make an array object (construct)
■ How to populate the array with elements (initialize)
Declaring an Array
• Arrays are declared by stating the type of element the array will
hold, which can be an object or a primitive, followed by square
brackets to the left or right of the identifier.
Example:
int[] key; // brackets before name (recommended)
int key []; // brackets after name (legal but less readable)
// spaces between the name and [] legal, but bad
It is never legal to include the size of the array in your declaration.
int[5] scores;
• Remember, the JVM doesn't allocate space until you actually
instantiate the array object.
Constructing an Array
• Constructing an array means creating the array object on the
heap.
• To create an array object, Java must know how much space to
allocate on the heap, so you must specify the size of the array
at creation time.
• The size of the array is the number of elements the array will
hold.
• The most straightforward way to construct an array is to use
the keyword new followed by the array type, with a bracket
specifying how many elements of that type the array will hold.
int[] testScores; // Declares the array of ints
testScores = new int[4];
int[] testScores;
testScores = new int[4];
----values-------
0
0
0
0
1
0
2
The Heap
3
• You can also declare and construct an array in one statement as follows:
int[] testScores = new int[4];
• The JVM needs the size to allocate the appropriate space on the heap for
the new array object.
int[] carList = new int[];
• You may see the words "construct", "create", and "instantiate" used
interchangeably. They all mean, “An object is built on the heap.”
Initializing an Array
• Initializing an array means putting things into it. The "things"
in the array are the array's elements, and they're either
primitive values (2, x, false, and so on), or objects referred to
by the reference variables in the array.
• Note
• if an array has three elements, trying to access the [3]
element will raise an ArrayIndexOutOfBoundsException,
because in an array of three elements, the legal index values
are 0, 1, and 2.
int[] x = new int[5];
x[4] = 2; // OK, the last element is at index 4
x[5] = 3;
int[] z = new int[2];
int y = -3;
z[y] = 4;
Declaring, Constructing, and Initializing on One Line
int[] dots = {6,9,8};
• Declares an int array reference variable named dots.
• Creates an int array with a length of three (three elements).
• Populates the array's elements with the values 6, 9, and 8.
• Assigns the new array object to the reference variable dots
The size (length of the array) is determined by the number of commaseparated items between the curly braces.
Constructing and Initializing an Anonymous Array
• The second shortcut is called "anonymous array creation" and can be used
to construct and initialize an array, and then assign the array to a
previously declared array reference variable:
int[] testScores;
testScores = new int[] {4,7,2};
• Remember that you do not specify a size when using anonymous
arraycreation syntax.
Two Dimensional Array
• A two dimensional array is a combination of two or more one dimensional
arrays
• A two dimensional array represents several rows and columns of data
Example
Group of students marks in five different subjects can be represented by a 2D
array
M1
M2
M3
M4
M5
S1
50
60
70
80
90
S2
55
65
75
85
95
S3
45
50
55
60
65
• Creating Two Dimensional Array
int[] [] marks ={ {50,60,70,80,90},
{55,65,75,85,95},
{50,55,60,65,70}};
In general int[i][j] marks where i represents rows j represents columns
int[][] marks;
marks=new int[3][5];
or
int[][] marks=new int[3][5];
• Given an array of integer as input ex:{1,100,100}
Return true if 2 100’s occur consecutively
• Three integers are given as arguments . find the
number of unique elements
Ex:input 24,30,21
Output:3
Ex2:input:1,1,2
Output:2
• Given 2 arrays of ints, a and b, return true if they have the same first
element or they have the same last element. Both arrays will be length 1
or more.
commonEnd({1, 2, 3}, {7, 3}) → true
commonEnd({1, 2, 3}, {7, 3, 2}) → false
commonEnd({1, 2, 3}, {1, 3}) → true
public booleancommonEnd(int[] a, int[] b) {
if(a[0]==b[0] || a[a.length-1]==b[b.length-1]){
return true;
}
else{
return false;
}
}
8)Given an array of ints length 3, figure out which is larger between the first
and last elements in the array, and set all the other elements to be that
value. Return the changed array.
maxEnd3({1, 2, 3}) → {3, 3, 3}
maxEnd3({11, 5, 9}) → {11, 11, 11}
maxEnd3({2, 11, 3}) → {3, 3, 3}
10)Given 2 int arrays, a and b, each length 3, return a new array length 2
containing their middle elements.
middleWay({1, 2, 3}, {4, 5, 6}) → {2, 5}
middleWay({7, 7, 7}, {3, 8, 0}) → {7, 8}
middleWay({5, 2, 9}, {1, 4, 5}) → {2, 4}
• 14)Given an int array, return a new array with double the length where its
last element is the same as the original array, and all the other elements
are 0. The original array will be length 1 or more. Note: by default, a new
int array contains all 0's.
makeLast({4, 5, 6}) → {0, 0, 0, 0, 0, 6}
makeLast({1, 2}) → {0, 0, 0, 2}
makeLast({3}) → {0, 3}
OCJP
Which three are legal array declarations? (Choose three.)
A. int [] myScores [];
B. char [] myChars;
C. int [6] myScores;
D. Dog myDogs [];
E. Dog myDogs [7];
Answer: A, B, and D.
Which two will declare an array and initialize it with five numbers?
(Choosetwo.)
A. Array a = new Array(5);
B. int [] a = {23,22,21,20,19};
C. int [] array;
D. int array [] = new int [5];
E. int a [] = new int(5);
F. int [5] array;
Answer : B and D.
Which will legally declare, construct, and initialize an array? (Choose one.)
A. int [] myList = {“1”, “2”, “3”};
B. int [] myList = (5, 8, 2);
C. int myList [] [] = {4,9,7,0};
D. int myList [] = {4, 3, 7};
E. int [] myList = [3, 5, 6];
F. int myList [] = {4; 6; 5};
Answer :D
Which four describe the correct default values for array elements of the
types indicated? (Choose four.)
A. int -> 0
B. String -> “null”
C. Dog -> null
D. char -> ‘\u0000’
E. float -> 0.0f
F. boolean -> true
Answer: A, C, D, and E.
Strings
• Most of the data that transmits on internet will be in the form
of group of characters. Such group of characters are called
‘strings’
• In java, a string is an object of String class
• Java soft people have created a class separately with the
name ‘String’ in java.lang package with all necessary methods
to work with strings
• In Java, each character in a string is a 16-bit Unicode
character. Because Unicode characters are 16 bits a rich,
international set of characters is easily represented in
Unicode.
• String class is declared as final, which means that String class
not subclassed
• String class is implemented from CharsSequence interface
Creation of Strings
1)We can create a string just by assigning a group of characters
to a string type variable
String s;// declare a string type variable
S=“Hello”;//assign a group of characters to it
Note: String s=“Hello”;
2) We can create an object to String class by allocating memory
using new operator
String s=new String(“Hello”);
3)Creating string by converting character array into strings
char[] arr={‘H’,’e’,’l’,’l’,’o’};
String s=new String(arr);
String s=new String(arr,1,3); //ell
• String s=“abc”;
• String s1=new String(“abc”);
Strings Are Immutable Objects
• Once you have assigned a String a value, that value can never
change— it's immutable
• Once a String object is created, it can never be changed
• The good news is that while the String object is immutable, its
reference variable is not.
String s=“abcdef”; //create a new String object, with value "abcdef",
refer s to it
String s2 = s; // create a 2nd reference variable referring to the same
String
s = s.concat(" more stuff"); //create a new String object, with value
"abcdef more stuff", refer s to it.
String objects and their reference variables
• String s=“abc”;
s
abc
• String s2=s;
s
abc
s2
• s = s.concat (”def”);
abc
s2
s
abcdef
s
String x = "Java";
x.concat(" Rules!");
System.out.println("x = " + x);
String x = "Java";
x = x.concat(" Rules!");
System.out.println("x = " + x);
String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ");
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);
Answer: spring winter spring summer.
• There are two reference variables, s1 and s2. There were
a total of eight String objects created as follows: "spring",
"summer " (lost), "spring summer", "fall" (lost), "spring
fall" (lost), "spring summer spring" (lost), "winter" (lost),
"spring winter" (at this point "spring" is lost). Only two of
the eight String objects are not lost in this process.
String class methods
Character Extraction
• charAt()
• getChars()
• getBytes()
• toCharArray()
charAt()
To extract a sigle character from a Sting
char charAt(int index)
Example:
String x = "airplane";
System.out.println( x.charAt(2) ); // output is 'r‘
getChars()
To extract more than one character at a time
void getChars(int start, int end,char target[], int targetStart)
Example:
String s=“This is a demo of the getChars method”;
int start=10;
int end=14;
char[] buf=new char[end-start];
s.getChars(start,end,buf,0);
System.out.println(buf); //demo
getBytes()
byte[] getBytes()
toCharArray()
Convert all the characters in a string object into
a character array
char[] toCharArray()
String Comparison
1)
2)
3)
4)
5)
6)
equals()
equalsIgnoreCase()
regionMatches()
startsWith()
endsWith()
compareTo()
equals()
1) To compare two strings for equality, use equals()
boolean equals(Object str)
1) It returns true if the strings contains same characters in the
same order, and false otherwise
2) The comparison is case-sensitive
String s1=“exit”;
String s2=“exit”;
Strrong s3=“Exit”;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
public boolean equalsIgnoreCase(String s)
This method returns a boolean value (true or false) depending
on whether the value of the String in the argument is the
same as the value of the String used to invoke the method.
This method will return true even when characters in the String
objects being compared have differing cases
For example,
String x = "Exit";
System.out.println( x.equalsIgnoreCase("EXIT")); // is "true"
System.out.println( x.equalsIgnoreCase("tixe")); // is "false"
regionMatches()
This method compares a specific region inside a string with
another specific region in other string
boolean regionMatches(int startindex, String s2, int s2Startindex,
int numChars)
Example:
String s1="helloworld";
String s2="world";
System.out.println(s1.regionMatches(5,s2,0,3));
boolean regionMatches(boolean ignoreCase,int startindex, String
s2, int s2Startindex, int numChars)
startsWith()
This method determines whether a given string begins with a
specified string
boolean startsWith(String str)
String s1=“hello world”;
System.out.println(s1.startsWith(“hello”);
boolean startsWith(String str, int startindex)
System.out.println(s1.startsWith("world",6));
endsWith()
This method determines the string ends with a specified string
boolean endsWith(String str)
String s1="hello world";
System.out.println(s1.endsWith("rld"));
compareTo()
This method is useful to compare two strings and to know which
string is bigger or smaller
This should be used as s1.compareTo(s2)
If s1 and s2 strings are equal, then this method gives 0
If s1 is greater than s2, then this method a +ve number
If s1 is less than s2, then it returns a –ve number
When we arrange the strings in dictionary order, which ever
string comes first is lesser than the string that comes next.
Example: “Box” is lesser than “Boy”
This method case sensitive. It means “BOX” and “box” are not
same for this method
int compareTo(String s)
int compareToIgnoreCase(String s)
Modifying a Strings
1) substring()
2) concat()
3) replace()
4) trim()
substring()
This method is useful to extract sub string from a main string
String substring(int x)
It return a new string consisting all characters starting from the
position ‘x’ until the end of the string
Example:
String x = "0123456789";
System.out.println( x.substring(5) ); // 56789
String substring(int stratindex, int endindex)
The string returned contains all the characters from the
beginning index, up to, but not including the ending index
System.out.println( x.substring(5, 8));
String concat()
This method concatenates or joins two strings (s1 and s2) and
return a third string (s3) as result.
public String concat(String s)
Example:
String x = "taxi";
System.out.println( x.concat(" cab") );
public String replace(char old, char new)
This method replaces all the occurrences of character by a new
character ;
For example,
String x = "oxoxoxox“
System.out.println( x.replace('x', 'X') ); // output is
"oXoXoXoX“
public String trim()
This method removes spaces from the beginning and ending of a string
For example,
String x = “ Ram Mohan ";
System.out.println( x.trim() );
Searching String
indexOf()
lastindexOf()
indexOf()
int indexOf(String s)
This method is called in the form s1.indexOf(s2), and it returns
an integer value.
If s1 contains s2 as sub string, then the first occurrence of s2 in
the string s1 will be returned by this method
String s1=“This is a book”
String s2=“is”
int n=s1.indexOf(s2);
lastIndexOf(String s)
This method returns the last occurrence of the sub string ‘s’ in
the main string. If ‘s’ is not found, then it returns negative
value
Example:
String s1=“This is a book”
String s2=“is”
int n=s1.lastIndexOf(s2);
public int length()
This method returns the length of the String used to invoke the
method
For example,
String x = "01234567";
System.out.println( x.length() ); // returns "8"
public String toLowerCase()
This method returns a String whose value is the String used to
invoke the method, but with any uppercase characters
converted to lowercase
For example,
String x = "A New Moon";
System.out.println( x.toLowerCase() );
public String toUpperCase()
This method returns a String whose value is the String used to
invoke the method, but with any lowercase characters
converted to uppercase
For example,
String x = "A New Moon";
System.out.println( x.toUpperCase() );
Method contains (String[] and integer parameter)
• If the input parameter size equals the length of the
particular string in String[], Then print the no of
times..
Example:
String appears
String[]=”cat”,”mat”,”monkey”,”dog”,”rat”;
Integer =3
Output=4
Given an array of string return a string which contains
only the last characters of the strings in the string
array
Eg:{arr,abc,cde}
o/p rce
Given an input string, check whether the first word and
the last word in the string match, if they match
return the number of characters in the word else
return sum of the characters in both
• Ex: hello world hello
• Output:5
• Ex hello this world op=10
input1:”Hello”
Input2:2(n)
Output=”lolo”
Print the last two(n) characters two(n) times
Two strings S1 and S2 are passed as arguments. Find the
number of times S2 is repeated in S1. Ignore the case of both
S1 and S2
• Ex1:input{catcowcatmat,cat}
• Output:2
• Ex2:input(makemymylow,abc}
• Output:0
String=COWARD
• If integer input is 3 or greater than three. .. print first three characters of
strings the no of times.
• And if input integer is less than 2 then print 1st two character of String,
the no of times
• If input integer is one then print only one character of String once.
String=COWARD
If integer input=4, o/p cow cow cow cow
If integer input=2, o/p coco
If integer input=1, o/p c
input1: hello world, world is wonderful
Input2:world
Output-count the number of occurrence of input2 in
the input1
Ex output:2
StringBuffer
• StringBuffer is a class which represents strings in
such a way that their data can be modified
• It means StringBuffer class objects are mutable
Creating StringBuffer class objects
StringBuffer sb=new StringBuffer(“Hello”);
StringBuffer sb=new StringBuffer();
Here, we are creating a StringBuffer object as an empty object.
In this case, a StringBuffer object will be created a default capacity of
16 characters
StringBuffer sb=new StringBuffer(50);
In this case, a StringBuffer object will be created a default capacity of
50 characters
Even if we declare the capacity as 50, it is possible to store more than
50 characters into this StringBuffer. The reason is StringBuffer is
mutable and can expand dynamically in memory
Methods of StringBuffer class
StringBuffer append(x)
‘x’ may be boolean, byte, int, long, float, double, char, character
array,String or other StringBuffer
It will be append to the StringBuffer object
Example:
StringBuffer sb=new StringBuffer(“uni”);
sb.append(“versity’);
System.out.println(sb);
sb.append(sb);
StringBuffer insert(int i , x)
It will be inserted into StringBuffer at the position represented by
i
Example:
StringBuffer sb=new StringBuffer(“intelligent person”);
sb.insert(11,”young”);
System.out.println(sb);
StringBuffer delete(int I, int j)
This method removes characters from ith position till j-1th
position in the StringBuffer
sb.delete(0,3);
StringBuffer reverse()
This method reverse the characters in the StringBuffer
StringBuffer sb=new StringBuffer(“abc”);
sb.reverse();
System.out.println(sb);
int length()
int indexOf(String str)
int lastIndexOf(String str)
StringBuffer replace(int I, int j,String str)
This replace characters from I to j-1, by the string ‘str’ in the StringBuffer
object
Example:
StringBuffer sb=new StringBuffer(“High Cost”);
sb.replace(0,4,”low”);
System.out.println(sb);
Create a class Problem1.java with a method
validateIP(String) which takes an ip address as a
string input. Write codento validate given ip address.
Return true if is valid IP Address else return false
• Note: An ip address has the format a.b.c.d where
a,b,c,d are numbers between 0 to 255
• Create a Problem2.java with a method
findTwoMiddledigits(….)
Example: 123456
Output: 34
OCJP
Which two are valid declarations of a String? (Choose two.)
A. String s1 = null;
B. String s2 = ‘null’;
C. String s3 = (String) ‘abc’;
D. String s4 = (String) ‘\ufeed’;
E. String s5 = “strings rule”;
Answer: A and E.
CORE JAVA (JAVA SE)
BASICS
Procedure oriented approach
 In this model, a programmer uses procedures or functions to
perform a task
 When the programmer wants to write a program, he will first
divide the task into separate sub tasks, each of which is
expressed as a function
 So a C-program generally contains several functions which are
called and controlled from a main() function
 This approach is called as Procedure oriented approach
method1
main()
method2
method3
Limitations of Procedure oriented approach
No Reusability
 The programmer concentrate on a specific task, and writes a
set of functions to achieve it
 When there is another task to be added to the software, he
would be writing another set of functions
 Thus, there will be no reusability of previous functions in most
of the cases
Losing control on the code
 Software developed following procedure oriented approach,
naturally code size will also be increased
 When the code size exceeds 10,000 lines and before reaching
100,000 lines, suddenly at a particular point, programmers
were losing control on the code
Procedure oriented approach is unnatural
Object Oriented approach
 In this model, classes and objects are used to achieve the task
 A class is a module which itself contains data and methods to
achieve the task
 The main task is divided into several modules, and these are
represented as classes
 Each class can perform some tasks for which several methods
are written in a class
Class with
main()
class1
Data
members
class2
Data
members
class3
Data
members
method
Features of Object Oriented Programming System (oops)
Class/Object
Encapsulation
Abstraction
Inheritance
Polymorphism
Class/Object
 An object is anything that really exist in the world and can be
distinguished from others
Example: a table, a ball, a car etc.,
 If something does not really exist, then it is not an object
Example: our thoughts, imagination, plans, ideas etc.,
 Every object has properties and can perform certain actions
Example:
• Let us take a person whose name is ‘Raju’.
• Raju is an object because he exist physically.
• He has properties like name, age, gender etc.
These properties can be represented by variables in our
programming
Example: String name, int age, char gender;
• Raju can perform some actions like talking, walking, eating
and sleeping. We may not write code for such actions in
programming
• But, we can consider calculations and processing of data as
actions
• These actions are performed by methods.
So an object contains variables and methods
It is possible that some objects may have similar properties and
actions. Such objects belongs to same category called a
‘class’
Example:
Not only Raju, Ravi, Sita, etc., personas have same properties and
actions. So they are all objects of same class ‘Person’
Note:
Observe that the ‘Person’ will not exist physically but only Raju,
Ravi exist physically this means class not exist physically and
object exist physically
Person class and Raju object
Name
Age
sex
Talking
Walking
Eating
class :Person
Raju
25
M
talk()
walk()
eat()
object:Raju
Creating classes and objects in Java
class Person
{
//properties of a person-variables
String name;
int age
//actions done by a person-methods
void talk()
{ }
void eat()
{ }
}
Person class has two variables and two methods.
This class code is stored in JVM’s method area
When we want use this class, we should create an object to the
class as,
Person Raju=new Person();
Here , Raju is an objects of Person class.
Object represents memory to store the actual data.
Sun's Java Code Conventions
• Sun has created a set of coding standards for Java, and
published those standards in a document smartly titled "Java
Code Conventions," which you can find at java.sun.com.
1) Classes and interfaces
• The first letter should be capitalized, and if several words are
linked together to form the name, the first letter of the inner
words should be uppercase (a format that's sometimes called
"camelCase").
For example:
• Dog
• Account
• PrintWriter
2) Methods
• The first letter should be lowercase, and then normal
camelCase rules should be used.
For example:
• getBalance
• doCalculation
• setCustomerName
3) Variables
Like methods, the camelCase format should be used, starting with
a lowercase letter.
Sun recommends short, meaningful names, which sounds good to
us.
Some examples:
• buttonWidth
• accountBalance
• myString
Source File Declaration Rules
 There can be only one public class per source code file.
 Comments can appear at the beginning or end of any line in
the source code file.
 If there is a public class in a file, the name of the file must
match the name of the public class.
For example, a class declared as public class Dog { } must be in
a source code file named Dog.java.
 If the class is part of a package, the package statement must
be the first line in the source code file, before any import
statements that may be present.
 If there are import statements, they must go between the
package statement and the class declaration.
 If there isn't a package statement, then the import statement(s)
must be the first line(s) in the source code file.
 If there are no package or import statements, the class
declaration must be the first line in the source code file.
 import and package statements apply to all classes within a
source code file.
 A file can have more than one nonpublic class.
Class Declarations and Modifiers
• The following code is a bare-bones class declaration:
class MyClass { }
• This code compiles just fine, but you can also add modifiers
before the class declaration.
Modifiers fall into two categories:
 Access modifiers: public, protected, private.
 Non-access modifiers (including strictfp, final, and abstract).
Using access modifiers you'll learn how to restrict or allow
access to a class you create.
Class Access
What does it mean to access a class? When we say code from one
class (class A) has access to another class (class B), it means
class A can do one of three things:
• Create an instance of class B.
• Extend class B (in other words, become a subclass of class B).
• Access certain methods and variables within class B,
depending on the access control of those methods and
variables.
Access Modifiers
• Access control in Java is a little tricky because there are four
access controls (levels of access) but only three access
modifiers.
• The fourth access control level (called default or package
access) is what you get when you don't use any of the three
access modifiers.
• In other words, every class, method, and instance variable you
declare has an access control, whether you explicitly type one
or not.
• A class can be declared with only public or default access; the
other two access control levels don't make sense for a class
Default Access
• A class with default access has no modifier preceding it in the
declaration!
• It's the access control you get when you don't type a modifier
in the class declaration.
• Default access is package-level access, because a class with
default access can be seen only by classes within the same
package.
package cert;
class Beverage { }
Now look at the second source file:
package exam;
import cert.Beverage;
class Tea extends Beverage { }
• As you can see, the superclass (Beverage) is in a different
package from the subclass (Tea).
• The import statement at the top of the Tea file is trying to
import the Beverage class.
• The Beverage file compiles fine, but when we try to compile
the Tea file we get compile-time error
You can do one of two things to make this work.
• You could put both classes in the same package, or you could
declare Beverage as public
Public Access
• A class declaration with the public keyword gives all classes
from all packages access to the public class.
• In other words, all classes in the Java Universe (JU) have
access to a public class.
package cert;
public class Beverage { }
Now look at the second source file:
package exam;
import cert.Beverage;
class Tea extends Beverage { }
Other (Nonaccess) Class Modifiers
• You can modify a class declaration using the keyword final,
abstract, or strictfp.
public final (acceptable)
strictfp final (acceptable)
abstract final (not acceptable)
Final Classes
• When used in a class declaration, the final keyword means the
class can't be subclassed.
public final class Beverage {
public void importantMethod() { }
}
Now, if we try to compile the Tea subclass:
import cert.Beverage;
class Tea extends Beverage { }
Abstract Classes
• An abstract class can never be instantiated.
abstract class Car {
private double price;
private String model;
private String year;
public abstract void goFast();
public abstract void goUpHill();
public abstract void impressNeighbors();
}
public class CarTest
{
public static void main(String args[])
{
Car c1=new Car();
}}
• strictfp is a keyword and can be used to modify a class or a
method, but never a variable.
• Marking a class as strictfp means that any method code in the
class will conform to the IEEE 754 standard rules for floating
points.
• Without that modifier, floating points used in the methods
might behave in a platform-dependent way.
• If you don't declare a class as strictfp, you can still get strictfp
behavior on a method-by-method basis, by declaring a method
as strictfp.
Declare Class Members
• Methods and instance (nonlocal) variables are collectively
known as members
• Whereas a class can use just two of the four access control
levels (default or public), members can use all four:
 public
 protected
 default
 private
• Default protection is what you get when you don't type an
access modifier in the member declaration.
• The default and protected access control types have almost
identical behavior, except for one difference that will be
mentioned later. (Inheritance)
Public Members
• When a method or variable member is declared public, it
means all other classes, regardless of the package they belong
to, can access the member
class Zoo {
public String coolMethod() {
return "Wow baby";
}
}
class Moo {
public void useAZoo() {
Zoo z = new Zoo();
System.out.println("A Zoo says, " + z.coolMethod());
}
}
Private Members
• Members marked private can't be accessed by code in any
class other than the class in which the private member was
declared.
class Roo {
private String doRooThings() {
return "fun";
}
}
class UseARoo {
public void testIt() {
Roo r = new Roo();
System.out.println(r.doRooThings());
}
}
Protected and Default Members
• The protected and default access control levels are almost
identical, but with one critical difference.
• A default member may be accessed only if the class accessing
the member belongs to the same package, whereas a protected
member can be accessed (through inheritance) by a subclass
even if the subclass is in a different package.
package certification;
public class OtherClass {
void testIt() {
System.out.println("OtherClass");
}
}
In another source code file you have the following:
package somethingElse;
import certification.OtherClass;
class AccessClass {
static public void main(String[] args) {
OtherClass o = new OtherClass();
o.testIt();
}
}
package certification;
public class Parent {
protected int x = 9;
}
package other;
import certification.Parent;
class Child extends Parent {
public void testIt() {
System.out.println("x is " + x);
}
}
package certification;
public class Parent{
int x = 9; // default access
}
And in the second class you have the following:
package certification;
class Child extends Parent{
static public void main(String[] args) {
Child sc = new Child();
sc.testIt();
}
public void testIt() {
System.out.println("Variable x is " + x); // No problem;
}
}
Instance Variables
• Instance variables are defined inside the class, but outside of
any method, and are only initialized when the class is
instantiated.
• Instance variables are the fields that belong to each unique
object
class Employee {
private String name;
private String title,
private String manager;
//code goes here including access methods
}
• Can use any of the four access levels (which means they can be
marked with any of the three access modifiers)
• Can be marked final
• Can be marked transient
• Cannot be marked abstract
• Cannot be marked synchronized
• Cannot be marked strictfp
• Cannot be marked native
• Cannot be marked static, because then they'd become class
variables.
Local (Automatic/Stack/Method) Variables
• Local variables are variables declared within a method.
• That means the variable is not just initialized within the
method, but also declared within the method
class TestServer {
public void logIn() {
int count = 10;
}
}
• The key is to remember that a local variable must be initialized
before you try to use it.
class TestServer {
public void logIn() {
int count = 10;
}
public void doSomething(int i) {
count = i;
// method logIn()
}
}
• It is possible to declare a local variable with the same name as
an instance variable. It's known as shadowing
class TestServer {
int count = 9; // Declare an instance variable named count
public void logIn() {
int count = 10; // Declare a local variable named count
System.out.println("local variable count is " + count);
}
public void count() {
System.out.println("instance variable count is " + count);
}
public static void main(String[] args) {
new TestServer().logIn();
new TestServer().count();
}
}
• The following (wrong) code is trying to set an instance
variable's value using a parameter:
class Foo {
int size = 27;
public void setSize(int size) {
size = size; // ??? which size equals which size???
}
}
• Use the keyword this.
• The keyword this always, always, always refers to the object
currently running.
class Foo {
int size = 27;
public void setSize(int size) {
this.size = size; // this.size means the current object's
// instance variable, size. The size
// on the right is the parameter
}
}
Initialization of Instance Variables
Encapsulation
Encapsulation is a mechanism where the data (variables) and the
code (methods) that act on the data will bind together.
Example: class
We write the variables and methods inside the class. Thus, class
is binding them together.
To achieve Encapsulation we need
• Keep instance variables protected (with an access modifier,
often private).
• Make public methods, and force calling code to use those
methods rather than directly accessing the instance variable
Final Variables
• Declaring a variable with the final keyword makes it
impossible to reinitialize that variable once it has been
initialized with an explicit value
class Roo
{
final int size=20;
void changeSize()
{
size=16;
}
}
Transient Variables
• If you mark an instance variable as transient, you're telling the
JVM to skip (ignore) this variable when you attempt to
serialize the object containing it.
• With serialization you can save an object to a file.
Volatile Variables
• The volatile modifier tells the JVM that a thread accessing the
variable must always settle its own private copy of the variable
with the master copy in memory.
• The volatile modifier may also be applied to project
managers
Static Variables and Methods
• The static modifier is used to create variables and methods that
will exist independently of any instances created for the class.
• All static members exist before you ever make a new instance
of a class, and there will be only one copy of a static member
regardless of the number of instances of that class.
• Static method does not act upon instance variables of a class
• Static methods are called using Classname.methodname()
• Static method can access static variables
class Test
{
int x=11;
static void access()
{
System.out.println(“x=“+x);
}
class TestDemo
{
public static void main(String[] args)
{
Test.access();
}
}
class Test
{
static int x=11;
static void access()
{
System.out.println(“x=“+x);
}
class TestDemo
{
public static void main(String[] args)
{
Test.access();
}
}
Things you can mark as static:
• Methods
• Variables
• A class nested within another class, but not within a method
• Initialization blocks
Things you can't mark as static:
• Constructors
• Classes (unless they are nested)
• Interfaces
• Method local inner classes
• Inner class methods and instance variables
• Local variables
Difference Between Static and Instance Variables
class Test{
int x=10;
void display(){
System.out.println(x);
}
class InstanceTest{
public static void main(String[] args){
Test t1=new Test();
Test t2=new Test();
++t1.x;
System.out.print(“x in t1”);
T1.display();
System.out.print(“x in t2”);
T2.display();
}}
class Test{
static int x=10;
static void display(){
System.out.println(x)l
}
class InstanceTest{
public static void main(String[] args){
Test t1=new Test();
Test t2=new Test();
++t1.x;
System.out.print(“x in t1”);
T1.display();
System.out.print(“x in t2”);
T2.display();
}}
Static Block
• A static block is a block of statements declared as ‘static’
static
{
statements;
}
JVM executes a static block on a higher priority basis. This means
JVM first goes to static block even before it looks the main()
method in the program
class StaticBlock
{
static
{
System.out.println("I Am In Static Block");
}
public static void main(String[] args)
{
System.out.println("I Am In Static method");
}
}
class StaticBlock
{
static
{
System.out.println("I Am In Static Block");
}
}
Solution: Program compiles but gives an error at run time
class StaticBlock
{
static
{
System.out.println("I Am In Static Block");
System.exit(0);
}
}
CONSTRUCTORS IN JAVA
• A constructor is a special member method which will be called
by JVM automatically(implicitly) whenever an object is
created for placing our own values without placing default
values
• The purpose of constructor is to initialize an object
• Every time you make a new object, at least one constructor is
invoked.
• Every class has a constructor, although if you don't create one
explicitly, the compiler will build one for you
Characteristics of Constructor
•
•
•
•
The name of the constructor must be similar to the class name
Constructor should not return any value even void also
The modifier of a constructor should not be static
Constructors of base class will not be inherited into derived
class
• A constructor of a class may or may not be private
– If constructor access specifier is private then an object of
corresponding class can be created with in the same class context but
not in some other class context
– If the constructor access specifier is not private then an object of
corresponding class can be created either in same class context or in
other class context
Types of Constructors
• Based on the object creation in java, constructors are classified
into two types. They are
1) Default/Parameter less/Zero argument Constructor
2) Parameterized Constructor
Default Constructor
• A constructor is said to be default constructor if and only if it
should not take any parameters
• Whenever we want to place same values in multiple objects of
same type of class then we must use the concept of default
constructor
Parameterized Constructor
• A constructor is said to be a parameterized constructor if and
only if it takes some parameters
• Parameterized constructor is useful to initialize each object
with different values
Rules
Rule-1
• Whenever we create an object only with default constructor,
defining the default constructor is optional
• If we are not defining any default constructor then JVM will
call its own default constructor known as system defined
default constructor and it places default values depends on the
data members of the class
• If we define our own default constructor known as
programmer defined default constructor then JVM will call
programmer defined constructor and it places programmer
defined values
Rule-2
Whenever we create an object with parameterized constructor,
defining the parameterized constructor is mandatory, otherwise
we get compile time error
Rule-3
Whenever we create an object with both default and
parameterized constructors then it is mandatory to the java
programmer to define both default and parameterized
constructors. Otherwise we get an error regarding default
constructor
Constructor Overloading
• A constructor is said to be overloaded if and only if
constructor name is same but its signature is different
• Signature represents the following points
1. Number of parameters
2. Type of parameters
3. Order of parameters
• At least one thing must be differentiated
Test t1=new Test(10,20);
Test t2=new Test(111);
Test t3=new Test(10.55f,20.99f);
Test t4=new Test(100,20.13f);
Test t5=new Test(10.11f,200);
Object Parameterized Constructor
• A constructor is said to be object parameterized if and only if it
always takes object as a parameter
Example:
Test t1=new Test(10,20);
Test t2=new Test(t1);
• The basic aim of object parameterized constructor is to copy
the content of one object into another object where both of its
belong to same type
Difference Between Default and Parameterized Constructors
Default Constructor
It is useful to initialize all
objects with same data
Default constructor does not
have any parameters
When data is passed at the time
of creating an object, default
constructor is called
Parameterized Constructor
It is useful to initialize each
object with different data
Parameterized constructor have
1 or more parameters
When data is passed at the time
of creating an object
parameterized constructor is
called
Difference Between Constructor and a Method
Constructor
A constructor is used to
initialize the instance variables
of a class
A constructor name and class
name should be same
Method
A method is used for any
general purpose processing or
calculations
A method’s name and class
name can be same or different
A constructor is called at the
time of creating the object
A constructor is called only
once per object
A method can be called after
creating the object
A method can be called several
times on the object
A constructor is called and
executed automatically
A method is executed only
when we call
RELATIONSHIPS IN JAVA
• Relationship in java makes us to understand how to get the
features of one class into another class
• The following are the relationships in java
1) is-a
2) has-a
3) uses-a
is-a Relationship
is-a relationship is one in which there exists one class will get the
features of another class through the concept of inheritance by
using extends keyword
Example:
class c1
{
………….
………….
}
class c2 extends c1
{
……………
……………
}
has-a relationship
Has-a relationship is one in which an object of one class is
created as a data member in another class
Example:
class c1
{
………..
………..
}
class c2
{
c1 o1=new c1();
……………….
}
Note:has-a relationship also known as part-of/kind-of
relationship
uses-a relationship
uses-a relationship is one in which a method of one class is using an
object of another class as a data member
Example:
class c1
{
………….
………….
}
class c2
{
void disp()
{
c1 o1=new c1();
…………..
}
}
INHERITANCE
Definition
The mechanism of obtaining data members from one class to
another class is known inheritance
The class which is giving data members to another class is known
as base class
The class which is getting data members from base class is
known as derived class
Base class
Derived class
int x=10;
•int y=20;
public void sum()
public void sub()
int z=30;
extends
public void mul()
Advantages of Inheritance
•
•
•
•
Application development time is less
Application memory space is less
Redundancy code is missed
We are able to get slogan of java i.e,. WORA (Write Once
Reuse Anywhere)
Types of Inheritance
1.
2.
3.
4.
5.
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
Single Inheritance
• Single Inheritance is one in which there exist single base class
and single derived class
Base
Class
Derived
Class
• Multilevel Inheritance
• In which there exist single base class, single derived class and
multiple intermediate base classes
• Intermediate base class is one, in one context it acts as base
class and in other context same class act as derived class
Hierarchical Inheritance
In which there exist single base class and multiple derived classes
Multiple Inheritance
Multiple inheritance is one in which there exist multiple base
classes and single derived class
Hybrid Inheritance
Combination of any available inheritance types
Inheritance is everywhere in Java.
class Test {
public static void main(String [] args) {
Test t1 = new Test();
Test t2 = new Test();
if (!t1.equals(t2))
System.out.println("they're not equal");
if (t1 instanceof Object)
System.out.println("t1's an Object");
}
}
Every class you'll ever use or ever write will inherit from class
Object.
Whenever you create a class, you automatically inherit all of
class Object's methods
The keyword ‘super’
• If we create an object to base class, we can access only the
base class members, but not the derived class members
• But if we create an object to derived class, all the members of
both base and derived classes are available to it
• This is the reason, we always create an object to derived class
in inheritance
• Sometimes the base class members and derived class members
may have same names
• In that case, by default sub class members are accessible
(SuperTest.java)
Private and Protected members in base class
• Private members are not accessible in derived class, but
protected members are available in derived class
(PrivateTest.java)
• ‘super’ refers to base class members from a derived class
• To refer variables
super.variable
• To refer methods
super.method() (SuperTest2.java)
• To refer constructor
super.variable
Overloading a Constructor (with in same class)
• Overloading a constructor is typically used to provide alternate
ways for clients to instantiate objects of your
class.(OverloadTest.java)
• The key point to get from this code example is, Rather than
calling super(), we're calling this(), and this() always means a
call to another constructor in the same class.
• Key Rule: The first line in a constructor must be a call to
super() or a call to this().
• A constructor can never have both a call to super() and a call to
this().
• Because each of those calls must be the first statement in a
constructor, you can't legally use both in the same constructor.
Inheritance Related To Constructor
• In inheritance by default the base class constructor is called
first then derived class constructor is called if we invoke
(create) derived class object (BarTest.java)
• Every constructor has, as its first statement, a call to the base
class constructor (super()), although remember that this call
can be inserted by the compiler. (In the case of default
constructor)
If the super constructor has arguments
• if your base class does not have a no-arg constructor, then in
your subclass you will not be able to use the default
constructor supplied by the compiler. (TShirt.java)
• where we've supplied a constructor for derived class that's
identical to the default constructor supplied by the
compiler(Tshirt1.java)
• If your super constructor has arguments, you must type in the
call to super(), supplying the appropriate
arguments.(TShirt2.java)
Constructor Chaining
Horse h = new Horse();
(Assume Horse extends Animal and Animal extends Object.)
1. Horse constructor is invoked. Every constructor invokes the
constructor of its base class with an (implicit) call to super()
2. Animal constructor is invoked (Animal is the base class of
Horse).
3. Object constructor is invoked (Object is the ultimate base class
of all classes, so class Animal extends Object even though you
don't actually type "extends Object" into the Animal class
declaration. It's implicit.) At this point we're on the top of the
stack.
4. Object instance variables are given their explicit values.
5. Object constructor completes.
6. Animal instance variables are given their explicit values (if
any).
7. Animal constructor completes.
8.Horse instance variables are given their explicit values (if any).
9. Horse constructor completes.
Constructor Chaining
4.Object()
3.Animal() calls super()
2.Horse calls super()
1.main() calls new Horse()
Method Overriding and Method Overloading
• Writing two or more methods in base and derived classes with
the same name and same signature is called as ‘method
overriding’
• A method signature represents method name and its
parameters
• The key benefit of overriding is the ability to define behavior
that's specific to a particular subclass type.
• ‘final’ methods never override (TestAnimals.java)
The rules for overriding a method
• The argument list must exactly match that of the overridden method.
• The access level can't be more restrictive than the overridden
method's. (TestAnimals2.java)
• The access level CAN be less restrictive than that of the overridden
method.(TestAnimals3.java)
• Instance methods can be overridden only if they are inherited by the
subclass. A subclass within the same package as the instance's
superclass can override any superclass method that is not marked
private or final.
• A subclass in a different package can override only those non-final
methods marked public or protected (since protected methods are
inherited by the subclass).
• You cannot override a method marked final.
• You cannot override a method marked static.
• If a method can't be inherited, you cannot override it.
Invoking a Base class Version of an Overridden Method
• You want to take advantage of some of the code in the base
class version of a method, yet still override it to provide some
additional specific behavior.
• It's like saying, "Run the base class version of the method
(InvokeSuper.java)
Examples of Legal and Illegal Method Overrides
public class Animal {
public void eat() { }
}
1.private void eat() { }//Access modifier is more restrictive
2.public void eat(String food) { }
(A legal overload, not an override, because the argument list
Changed)
3.public String eat() { }
(Not an override because of the return type, not an overload
either because there’s no change in the argument list)
Method Overloading
• A method can be overloaded in the same class or in a subclass
• Overloaded methods let you reuse the same method name in a
class, but with different arguments
Method Overloading rules
• Overloaded methods MUST change the argument list.
• Overloaded methods CAN change the return type.
• Overloaded methods CAN change the access modifier.
public void changeSize(int size, String name, float pattern) { }
Legal Examples
• public void changeSize(int size, String name) { }
• public int changeSize(int size, float pattern) { }
• public void changeSize(float pattern, String name) throws
IOException { }
Invoking Overloaded Methods
• A class might have three methods with the same name but with
different argument lists, which means the method is
overloaded.
• Deciding which of the matching methods to invoke is based on
the arguments.
• If you invoke the method with a String argument, the
overloaded version that takes a String is called.
• If you invoke a method of the same name but pass it a float,
the overloaded version that takes a float will run.
• If you invoke the method of the same name but pass it a Foo
object, and there isn't an overloaded version that takes a Foo,
then the compiler will complain that it can't find a match.
(TestAdder.java)
Object Reference as Method Parameter
• We can also pass class objects to methods, and return objects from
the methods
public Employee myMethod(Employee obj)
{
…………………
…………………
return obj;
}
• T he objects are passed to methods by values. It means, when we
send an object to a method, its bit by bit copy will be sent to the
method
• Any modifications to the object inside the method will not affect the
original copy outside the method
• (ObjectReference.java without inheritance)
class Animal { }
class Horse extends Animal { }
class UseAnimals1 {
public void doStuff(Animal a) {
System.out.println("In the Animal version");
}
public void doStuff(Horse h) {
System.out.println("In the Horse version");
}
public static void main (String [] args) {
UseAnimals ua = new UseAnimals();
Animal animalObj = new Animal();
//Animal animalRefToHorse = new Horse();
Horse horseObj = new Horse();
ua.doStuff(animalObj);
//ua.doStuff(animalRefToHorse);
ua.doStuff(horseObj);
}
}
• Even though the actual object at runtime is a Horse and not an
Animal, the choice of which overloaded method to call is NOT
dynamically decided at runtime.
• Which overridden version of the method to call is decided at
runtime based on object type, but which overloaded version of
the method to call is based on the reference type of the
argument passed at compile time.
class Clidders {
public final void flipper() { System.out.println("Clidder"); }
}
public class Clidlets extends Clidders {
public void flipper() {
System.out.println("Flip a Clidlet");
super.flipper();
}
public static void main(String [] args) {
new Clidlets().flipper();
}
}
What is the result?
A. Flip a Clidlet
B. Flip a Clidder
C. Flip a Clidder
Flip a Clidlet
D. Flip a Clidlet
Flip a Clidder
E. Compilation fails.
class Top {
public Top(String s) { System.out.print("B"); }
}
public class Bottom2 extends Top {
public Bottom2(String s) { System.out.print("D"); }
public static void main(String [] args) {
new Bottom2("C");
System.out.println(" ");
}
}
What is the result?
A. BD
B. DB
C. BDC
D. DBC
E. Compilation fails.
class Clidder {
private final void flipper() { System.out.println("Clidder"); }
}
public class Clidlet extends Clidder {
public final void flipper() { System.out.println("Clidlet"); }
public static void main(String [] args) {
new Clidlet().flipper();
}
}
What is the result?
A. Clidlet
B. Clidder
C. Clidder
Clidlet
D. Clidlet
Clidder
E. Compilation fails
class Uber {
static int y = 2;
Uber(int x) { this(); y = y * 2; }
Uber() { y++; }
}
class Minor extends Uber {
Minor() { super(y); y = y + 3; }
public static void main(String [] args) {
new Minor();
System.out.println(y);
}}
What is the result?
A. 6
B. 7
C. 8
D. 9
E. Compilation fails.
F. An exception is thrown.
D is correct.
Minor’s constructor makes an explicit call to Uber’s 1-arg
constructor, which makes an explicit (this) call to Uber’s noarg constructor, which increments y, then returns to the 1-arg
constructor, which multiples y * 2, and then returns to Minor’s
constructor, which adds 3 to y.
1. class Dog { }
2. class Beagle extends Dog { }
3.
4. class Kennel {
5. public static void main(String [] arfs) {
6. Beagle b1 = new Beagle();
7. Dog dog1 = new Dog();
8. Dog dog2 = b1;
9. // insert code here
10. } }
Which, inserted at line 9, will compile? (Choose all that apply.)
A. Beagle b2 = (Beagle) dog1;
B. Beagle b3 = (Beagle) dog2;
C. Beagle b4 = dog2;
D. None of the above statements will compile
1. class X { void do1() { } }
2. class Y extends X { void do2() { } }
3.
4. class Chrome {
5. public static void main(String [] args) {
6. X x1 = new X();
7. X x2 = new Y();
8. Y y1 = new Y();
9. // insert code here
10. } }
Which, inserted at line 9, will compile? (Choose all that apply.)
A. x2.do2();
B. (Y)x2.do2();
C. ((Y)x2).do2();
D. None of the above statements will compile.
What is the most restrictive access modifier that will allow
members of one class to have access to members of another
class in the same package?
A. public
B. abstract
C. protected
D. synchronized
E. default access
Given a method in a protected class, what access modifier do you
use to restrict access to that method to only the other members
of the same class?
A. final
B. static
C. private
D. protected
E. volatile
F. default access
Which of the following class level (nonlocal) variable
eclarations will not compile?
A. protected int a;
B. transient int b = 3;
C. public static final int c;
D. volatile int d;
E. private synchronized int e;
The synchronized modifier applies only to methods
Which two of the following are legal declarations for non nested
classes ?
A. final abstract class Test {}
B. public static interface Test {}
C. final public class Test {}
D. protected abstract class Test {}
E. protected interface Test {}
F. abstract public class Test {}
How many of the following are legal method declarations?
1 – protected abstract void m1();
2 – static final void m1(){}
3 – transient private native void m1() {}
4 – synchronized public final void m1() {}
5 – private native void m1();
6 – static final synchronized protected void m1() {}
A. 1
B. 2
C. 3
D. 4
E. 5
F. All of them
_ A, B, C, D, and F are incorrect because the only illegal
declaration is 3; transient applies only to variable declarations,
not to method declarations.
_ E. Statements 1, 2, 4, 5, and 6 are legal declarations.
POLYMORPHISM
• Polymorphism came from the two Greek words ‘poly’
meaning many and ‘morphos’ meaning forms
• The ability to exist in different forms is called ‘polymorphism’
• In java, a variable, an object or a method can exist in different
forms, to performing various tasks depending on the context
Polymorphism With Variables
System.out.println(a+b);
Java compiler decides the data type of result of the expression
a+b depending on the data types of a and b
Example:
If a and b both are floats then result is float
If a and b both are ints then result us int
If a is int b is float, then compiler converts a also into float and
then the result is float (Coercion.java)
What is coercion?
Coercion is the automatic conversion between different data types
done by the compiler
Polymorphism With Methods
• If the same method perform different tasks, then that method is
said to exhibit polymorphism
• It is possible only when the two method with the same name
and they can perform different tasks (having different bodies)
• Now , the crucial thing is decide which method is called in a
particular context
• This decision may be happen either at compile time or at
runtime
• The decision happen at compile time is called static
polymorphism or compile time polymorphism
• The decision happen at run time is called as dynamic or
runtime polymorphism
Dynamic Polymorphism
• The polymorphism exhibited at runtime is called dynamic
polymorphism it means when a method is called, method call
bound to the method body at the time of running the program
• Java compiler does not know which method is called at the
time of compilation
• Only JVM knows at runtime which method is executed
void add(int a, int b)
{
System.out.prinln(“Sum of two=“+(a+b));
}
void add(int a, int b, int c)
{
System.out.prinln(“Sum of three=“+(a+b+c));
}
s.add(10,15);
Here, JVM observes the signature of the methods. When there is
a difference in the method signatures, then the JVM
understands both methods are different and can call the
appropriate method
class One{
void calculate(double x)
{
System.out.println(“Square value=“+(x*x));}
}
class Two extends One{
void calculate(double x)
{
System.out.println(“Square root=“+Math.sqrt(x));}
}
class Test
{
public static void main(String[] args)
{
Two t=new Two();
t.calcualte(25);
}
}
Here, JVM calls the method depending on the class name of the object which is
used to call the method
public class Animal {
public void eat() {
System.out.println("Generic Animal Eating Generically");
}
}
public class Horse extends Animal {
public void eat() {
System.out.println("Horse eating hay ");
}
public void eat(String s) {
System.out.println("Horse eating " + s);
}
}
Method Invocation
Code Result
Animal a = new Animal();
a.eat();
Generic Animal Eating Generically
Horse h = new Horse();
h.eat();
Horse eating hay
Animal ah = new Horse();
ah.eat();
Horse eating hay
Polymorphism works—the actual object type
(Horse), not the reference type (Animal), is used
to determine which eat() is called.
Horse he = new Horse();
he.eat("Apples");
.
Horse eating Apples
The overloaded eat(String s) method is invoked
Animal a2 = new Animal();
a2.eat("treats");
Compiler error! Compiler sees that Animal class
doesn't have an eat() method that takes a String.
Animal ah2 = new Horse();
ah2.eat("Carrots");
Compiler error! Compiler still looks only at the
reference, and sees
that Animal doesn’t have an eat() method that
takes a String.
Compiler doesn’t care that the actual object might
be a Horse at
runtime.
Polymorphism With Static Methods
class Animal {
static void doStuff() {
System.out.print("a ");
}
}
class Dog extends Animal {
static void doStuff() {
System.out.print("d ");
}
public static void main(String [] args) {
Animal [] a = {new Animal(), new Dog(), new Animal()};
for(int x = 0; x < a.length; x++)
a[x].doStuff(); // invoke the static method
}
}
Output:a a a
• The polymorphism exhibited at compilation time is called
static polymorphism
• Here java compiler knows without any ambiguity which
method is called at the time of compilation
• Polymorphism With Private Methods
• Polymorphism With Final Methods
Type Casting
• Converting one data type into another data type is called ‘type
casting’
Types of Data Types
1) Primitive Data Types or Fundamental Data Type
2) Referenced Data Type or Advanced Data Type
Primitive Data Types or Fundamental Data Type
The data types which represents a single values are called
‘primitive data types’
Example: int, boolean.
Referenced Data Type or Advanced Data Type
These data types represent several values
Example: array, class
We can access an array or an object of a class in memory through
references. So, they are also called ‘referenced data types’
Note:
We can convert a primitive data type into another primitive data
type by using casting
Similarly, it is possible to convert a referenced data type into
another referenced data type by using casting
But we cannot convert a primitive data type into a referenced data
type by using casting
For this purpose, methods of wrapper classes should be used
Casting of Primitive Data Types
byte, short, char, int, long, float, double
Casting of primitive data types done in 2-ways they are
1) Widening
2) Narrowing
Widening
Converting a lower data type into a higher data type is called
wideing
char ch=‘A’;
int num=(int)ch;
Here, we are converting char type variable ‘ch’ into int type
int x=9678;
float sal=(float)x;
• Widening is safe because there will not be any loss of data or
precision or accuracy
• It is also called as implicit casting
Narrowing
Converting a higher data type into a lower data type is called
‘narrowing’
int n=66;
char ch=char(n);
Here we are converting int type into char type
double d=12.6789;
int n=(int)d; // n stores 12
(Widening )
class One
{
void show1()
{
System.out.println(“Super class method”);
}
}
class Two extends One
{
void show2()
{
System.out.println(“Sub class method”);
}
}
class Test
{
Public static void main(String args[])
{
One o;// super class reference
o=(One)new Two();// o is refereeing to sub class object
o.show1();
}
o.show1(); calls only super class method it is not possible to call
sub class method
So , in widening, the programmer can access all the super class
methods, but not the sub class methods
(Widening)
Generalization
(method overriding)
class One
{
void show1()
{
System.out.println(“Super class method”);
}
}
class Two extends One
{
void show1()
{
System.out.println(“Sub class method”);
}
}
class Test
{
Public static void main(String args[])
{
One o;// super class reference
o=(One)new Two();// o is refereeing to sub class object
o.show1();// sub class method
}
o.show1();// it is possible to access the sub class methods but not
super class methods.
The programmer will get only 50% functionality into his hands
(Narrowing)
class One
{
void show1()
{
System.out.println(“Super class method”);
}
}
class Two extends One
{
void show2()
{
System.out.println(“Sub class method”);
}
}
class Test
{
public static void main(String args[])
{
Two t; subclass reference
t=(Two)new One();// t is reffering to super class object
t.show1();//ClassCastException
t.show2();//ClassCastException
}
So, in narrowing using super class object, we cannot access any
of the methods of the super class or sub class.
So programmer will get 0% functionality in this case
class Test
{
public static void main(String args[])
{
One o;//super class reference
O=new Two();//reffering sub class object
Two t=(Two)o;//narrowing-convert class one’s reference type as class
two’s type
t.show1();
t.show2();
}
We convert the super class reference type into sub class reference type.
Then using the sub class reference, we try to call the methods. If an
object of sub class is created, it is possible to access all the methods
of the super class as well as the sub class.
• If the super class reference is used to refer to super class
object, naturally all the methods of super class are accessible
• If the sub class reference is used to refer to sub class object, all
the methods of the super class as well as sub class are
accessible since the sub class object avails a copy of super
class
• If widening is done by using sub class object only the super
class methods are accessible. If they are overridden, then only
the sub class methods are accessible
• If narrowing is done by using super class object, then none of
the super class or sub class methods are accessible. This is
useless
• If narrowing is done by using sub class object, then all the
methods of both super and sub classes are accessible to the
programmer
Abstract Class
• The rule is that any thing is written in the class is applicable
to all of its objects
• It means, a method is written in the class, it is available to all
of the class objects
class MyClass
{
void calculate(double x)
{
System.out.println("Square="+(x*x));
}
}
class Abstarct1
{
public static void main(String[] args)
{
MyClass obj1=new MyClass();
MyClass obj2=new MyClass();
MyClass obj3=new MyClass();
obj1.calculate(3);
obj2.calculate(4);
obj3.calculate(5);
}
}
• In the above program the requirement of all the objects is same
• But, some times the requirement of the objects will be
different and entirely dependent on the specific objects only
Example
• In the above program, if the first object wants to calculate
square value, the second object wants to calculate square root
value, third object wants to calculate cube value. In such a
case, how to write the calculate () method in MyClass?
Solution
Write the methods like calculate_square, calculate_root,
calculate_cube in MyClass, then all three methods are
available to all the three class objects it not advisable.
To serve each object with the one and only required method, we
can follow the steps
First, let us write a calculate() method in MyClass
If we write body for calculate() method, it is commonly available
to all the objects. So let us not write body for calculate()
method. Such a method is called as abstract method
Abstract classes
• An abstract classes can contain both abstract and nonabstract
methods, but that if even a single method is marked abstract,
the class must be marked abstract.
• An abstract class can never be instantiated.
• We can create a reference of abstract class
• Its sole purpose is to be extended (sub classed)
• It is illegal to have even a single abstract method in a class that
is not explicitly declared abstract
Example:
public class IllegalClass{
public abstract void doIt();
}
• Any class that extends an abstract class must implement all
abstract methods of the superclass, unless the subclass is also
abstract.
public abstract class Vehicle {
private String type;
public abstract void goUpHill(); // Abstract method
public String getType() { // Non-abstract method return type;
}
}
public abstract class Car extends Vehicle {
public abstract void goUpHill(); // Still abstract
public void doCarThings() {
// special car code goes here
}
}
public class Mini extends Car {
public void goUpHill() {
// Mini-specific going uphill code
}
}
public abstract class A {
abstract void foo();
}
class B extends A {
void foo(int I) { }
}
Abstract Methods
• An abstract method is a method that's been declared (as
abstract) but not implemented.
• Both the abstract class and the abstract methods should be
declared by using the keyword ‘abstract’.
public abstract void showSample();
• Notice that the abstract method ends with a semicolon instead
of curly braces.
• Three different clues tell you it's not an abstract method:
■ The method is not marked abstract.
■ The method declaration includes curly braces, as opposed to
ending in a semicolon. In other words, the method has a
method body.
■ The method provides actual implementation code.
• A method can never, ever, ever be marked as both abstract and
final, or both abstract and private
• Finally, you need to know that the abstract modifier can never
be combined with the static modifier
abstract static void doStuff(); //illegal
abstract class Car
{
int regno;
Car(int regno)
{
this.regno=regno;
}
public void fueltank()
{
System.out.println("fill the tank");
}
abstract void steering();
abstract void breaking();
}
class Maruthi extends Car
{
Maruthi(int regno)
{
super(regno);
}
void steering()
{
System.out.println("Maruthi having Normal Steering");
}
void breaking()
{
System.out.println("Maruthi having hydralic breaks");
}
}
class Santro extends Car
{
Santro(int regno)
{
super(regno);
}
void steering()
{
System.out.println("Santro having Power Steering");
}
void breaking()
{
System.out.println("Maruthi having air breaks");
}
}
class AbstractTest2
{
public static void main(String[] args)
{
Maruthi m1=new Maruthi(100);
Santro s1=new Santro(111);
Car ref;
ref=m1;
ref.fueltank();
ref.steering();
ref.breaking();
}
}
• It is perfectly possible to access all the members of the sub
class by using sub class object
• But prefer to use super class reference to access the sub class
features because, the reference variable can access only those
features of the sub class which have been already declared in
super class
• If we write an individual method in the sub class, the super
class reference cannot access that method
• This is to enforce discipline in the programmer not to add any
of their own features in the sub class other than whatever is
given in super class
class Employee
{
int x=10;
}
class Swap
{
public void swap(Employee obj1)
{
System.out.println(obj1.x+900);
}
}
class ObjectReferenceTest
{
public static void main(String[] args)
{
Employee Ram=new Employee();
Swap s=new Swap();
s.swap(Ram);
Employee Mohan=new Employee();
System.out.println(Mohan.x);
}
}
class One
{
public void calculate(float x)
{
System.out.println("float="+x);
}
}
class Two extends One
{
public void calculate(double x)
{
System.out.println("double="+x);
}
}
class IntTest
{
public static void main(String[] args)
{
Two t=new Two();
t.calculate(10);
System.out.println("Hello World!");
}
}
INTERFACE
• An interface is a contract.
• When you create an interface, you're defining a contract for
what a class can do, without saying anything about how the
class will do it.
• Interfaces can be implemented by any class, from any
inheritance tree.
• Any class type that implements this interface must agree to
write the code for the interface methods.“
• Interfaces are like a 100-percent abstract super class that
defines the methods a subclass must support, but not supply
any logic for the methods
• An abstract class can define both abstract and non-abstract
methods, an interface can have only abstract methods.
Rules To Define Interface
• All interface methods are implicitly public and abstract.
• All variables defined in an interface must be public, static, and
final— in other words, interfaces can declare only constants,
not instance variables.
• Interface methods must not be static.
• Interface methods are abstract, they cannot be marked final,
strictfp, or native.
• An interface can extend one or more other interfaces.
• An interface cannot extend anything but another interface.
• An interface cannot implement another interface or class.
• An interface must be declared with the keyword interface.
• Interface types can be used polymorphic ally
• A class can extend only one class (no multiple inheritance), but
it can implement many interfaces.
Interface Declaration
public abstract interface Rollable { }
• You just need to know that both of these declarations are legal, and
functionally identical:
public abstract interface Rollable { }
public interface Rollable { }
Interface Methods
public interface Bounceable {
public abstract void bounce();
public abstract void setBounceFactor(int bf);
}
The Above Code is Same as
public interface Bounceable {
void bounce(); // No modifiers
void setBounceFactor(int bf); // No modifiers
}
The following five method declarations, if declared within their
own interfaces, are legal and identical
1) void bounce();
2) public void bounce();
3) abstract void bounce();
4) public abstract void bounce();
5) abstract public void bounce();
• The following interface method declarations won't compile:
1) final void bounce(); // final and abstract can never be used //
together, and abstract is implied
2) static void bounce(); // interfaces define instance methods
3) private void bounce(); // interface methods are always public
4) protected void bounce(); // (same as above)
Declaring Interface Constants
• You're allowed to put constants in an interface. By doing so,
you guarantee that any class implementing the interface will
have access to the same constant.
• You need to remember one key rule for interface constants.
They must always be
public static final
• Because interface constants are defined in an interface, they
don't have to be declared as public, static, or final. They must
be public, static, and final, but you don't have to actually
declare them that way.
interface Foo {
int BAR = 42;
void go();
}
class Zap implements Foo {
public void go() {
BAR = 27;
}
}
• Illegal Interface constant definitions
public int x = 1; // Looks non-static and non-final, // but isn't!
int x = 1; // Looks default, non-final, // non-static, but isn't!
static int x = 1; // Doesn't show final or public
final int x = 1; // Doesn't show static or public
public static int x = 1; // Doesn't show final
public final int x = 1; // Doesn't show static
static final int x = 1 // Doesn't show public
Implementing an Interface
• Assuming an interface, Bounceable, with two methods:
bounce(), and setBounceFactor(), the following class will
compile:
public class Ball implements Bounceable {
public void bounce() { }
public void setBounceFactor(int bf) { }
}
An implementation class can itself be abstract!
abstract class Ball implements Bounceable { }
• In order to be a legal implementation class, must do the
following:
1) Provide concrete (nonabstract) implementations for all
methods from the declared interface.
2) Follow all the rules for legal overrides.
3) Maintain the signature of the interface method, and maintain
the same return type .
Rules
1. A class can implement more than one interface. It's perfectly
legal to say, for example, the following:
public class Ball implements Bounceable, Serializable, Runnable
{ ... }
2. An interface can itself extend another interface, but never
implement anything.
The following code is perfectly legal:
public interface Bounceable extends Moveable { } // ok!
3. An interface can extend more than one interface
public class Programmer extends Employee, Geek { }
interface Bounceable extends Moveable, Spherical { // ok!
void bounce();
void setBounceFactor(int bf);
}
interface Moveable {
void moveIt();
}
interface Spherical {
void doSphericalThing();
}
class Ball implements Bounceable {
public void bounce() { } // Implement Bounceable's methods
public void setBounceFactor(int bf) { }
public void moveIt() { } // Implement Moveable's method
public void doSphericalThing() { } // Implement Spherical
}
If class Ball fails to implement any of the methods from
Bounceable, Moveable, or Spherical, the compiler will jump
up and down wildly, red in the face, until it does. Unless, that
is, class Ball is marked abstract.
1) class Foo { }
class Bar implements Foo { }
2) interface Baz { }
interface Fi { }
interface Fee implements Baz { }
3) class Foo { }
interface Zee implements Foo { }
4) class Foo
interface Zoo extends Foo { }
5) interface Fi { }
interface Boo extends Fi { }
6) class Toon extends Foo, Button { }
7) class Zoom implements Fi, Baz { }
8) interface Vroom extends Fi, Baz { }
9)class Yow extends Foo implements Fi { }
Example
import java.util.*;
interface MyInter
{
public void connect();
public void disconnect();
}
class OracleDB implements MyInter
{
public void connect()
{
System.out.println("connecting To Oracle DataBase.......");
}
public void disconnect()
{
System.out.println("dis connecting To Oracle DataBase.......");
}
}
class SybaseDB implements MyInter
{
public void connect()
{
System.out.println("connecting To SyBase DataBase.......");
}
public void disconnect()
{
System.out.println("dis connecting To SyBase
DataBase.......");
}
}
class InterFaceDemo
{
public static void main(String[] args) throws Exception
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter The Class Name");
String name=sc.next();
Class c=Class.forName(name);
/*forName Method accepts the name of a class as string,
creates an and stores the class name in that object. this object
belongs to class Class */
MyInter mi=(MyInter)c.newInstance();
mi.connect();
mi.disconnect();
}
}
Multiple Inheritance using Interface
interface Father
{
float HT=6.2f;
void height();
}
interface Mother
{
float HT=5.2f;
void height();
}
class Child implements Father,Mother
{
public void height()
{
float ht=(Father.HT+Mother.HT)/2;
system.out.println(“Child’s height=“+ht);
}
}
class Multi
{
Public static void main(String[] args)
{
Child c1=new Child();
ch.height()l
}
}
Difference Between abstract class and an interface
Abstract class
Interface
When an abstract class is written, it is An interface is written when the
the duty of the programmer to provide programmer wants to leave the
sub class to it
implementation to the third party
An abstract class contains some
abstract methods and also some
concrete methods
An interface contains only abstract
methods
An abstract class contains instance
variables also
An interface can not contain instance
variables. It contains only constants
All the abstract methods of the
abstract class should be implemented
in its sub class
All the methods of the interface
should be implemented in its
implementation class
Abstract class is declared by using the Interface is declared using the
keyword abstract
keyword interface
interface Base {
boolean m1 ();
byte m2(short s);
}
Which code fragments will compile? (Choose all that apply.)
A. interface Base2 implements Base { }
B. abstract class Class2 extends Base {
public boolean m1() { return true; } }
C. abstract class Class2 implements Base { }
D. abstract class Class2 implements Base {
public boolean m1() { return (true); } }
E. class Class2 implements Base {
boolean m1() { return false; }
byte m2(short s) { return 42; } }
Which declare a compilable abstract class? (Choose all that
apply.)
A. public abstract class Canine { public Bark speak(); }
B. public abstract class Canine { public Bark speak() { } }
C. public class Canine { public abstract Bark speak(); }
D. public class Canine abstract { public abstract Bark speak(); }
Which is true? (Choose all that apply.)
A. "X extends Y" is correct if and only if X is a class and Y is an
interface.
B. "X extends Y" is correct if and only if X is an interface and Y
is a class.
C. "X extends Y" is correct if X and Y are either both classes or
both interfaces.
D. "X extends Y" is correct for all combinations of X and Y being
classes and/or interfaces
Exception Handling
Topics
1) Errors in Java Program
2) Exceptions
3) Exception Handling
4) Handling Multiple Exceptions
5) throws Clause
6) throw Clause
7) Types of Exceptions
8) Re-throwing an Exception
Errors in java program
Basically three types of errors in Java
1) Compile-time errors
These are syntactical errors found in java code,
due to which a program fails to compile
Example:
forgetting a semicolon at the end of a java
statement
2) Run-time errors
These errors represent inefficiency of the
computer system to execute a particular
statement
Example:
insufficient memory to store something
inability of the microprocessor to execute some
statements
public static void main()
Note: Run-time errors are not detected by the
java compiler. They are detected by the JVM,
only at runtime
3) Logical errors
These errors depict flaws in the logic of the
program
Example;
The programmer might be using a wrong
formula
Note: Logical errors are not detected either Java
Compiler or JVM
Exceptions
1) The term "exception" means "exceptional condition" and
is an occurrence that alters the normal program flow.
2) A bunch of things can lead to exceptions, including
hardware failures, resource exhaustion, and good old
bugs.
3) An exception is a run-time error
4) All exceptions occur only at runtime
5) Some exceptions are detected at compile time and some
others at runtime
6) The exceptions that are checked at compilation time by
the Java compiler are called ‘checked exceptions’ while
the exceptions that are checked by the JVM are called
‘unchecked exceptions’
5) A programmer can do something to avoid any
harm caused by the rise of exception
6) In case of error, the programmer cannot do
any thing and hence if error happens, it causes
some damage
7) All exceptions are declared as classes in java
8) The errors are also represented by classes
9) All these classes are descended from a super
called Throwable
Java Exception Type Hierarchy
Figure 6.2
2)
Exception Handling
To design the program in such a way that even if
there is an exception, all operations are
performed and only then the program should
be terminated is called exception handling
• Exception handling allows developers to detect
errors easily without writing special code to
test return values
• When an exceptional event occurs in Java, an exception is said
to be "thrown."
• The code that's responsible for doing something about the
exception is called an "exception handler," and it "catches" the
thrown exception.
• Exception handling works by transferring the execution of a
program to an appropriate exception handler when an
exception occurs
• For example, if you call a method that opens a file but the file
cannot be opened, execution of that method will stop, and code
that you wrote to deal with this situation will be run.
• Therefore, we need a way to tell the JVM what code to execute
when a certain exception happens.
• To do this, we use the try and catch keywords.
• The try is used to define a block of code in which exceptions
may occur. This block of code is called a guarded region .
• One or more catch clauses match a specific exception to a
block of code that handles it.
• Here's how it looks in pseudocode:
1. try {
2. // This is the first line of the "guarded region"
3. // that is governed by the try keyword.
4. // Put code here that might cause some kind of exception.
5. // We may have many code lines here or just one.
6. }
7. catch(MyFirstException) {
8. // Put code here that handles this exception.
9.// This is the next line of the exception handler.
10. // This is the last line of the exception handler.
11. }
12. catch(MySecondException) {
13. // Put code here that handles this exception
14. }
15.
16. // Some other unguarded (normal, non-risky) code begins here
• Execution of the guarded region starts at line 2.
• If the program executes all the way past line 5 with no
exceptions being thrown, execution will transfer to line 15 and
continue downward.
• However, if at any time in the try block an exception is thrown
of type MyFirstException, execution will immediately transfer
to line 7. Lines 8 through 10 will then be executed so that the
entire catch block runs, and then execution will transfer to line
15 and continue.
• Note that if an exception occurred on, say, line 3 of the try
block, the rest of the lines in the try block (4 and 5) would
never be executed.
• Once control jumps to the catch block, it never returns to
complete the balance of the try block.
• If you have one or more catch blocks, they must immediately
follow the try block.
• Additionally, the catch blocks must all follow each other,
without any other statements or blocks in between.
• Also, the order in which the catch blocks appear matters, as
we'll see a little later.
Using finally
• Execution transfers out of the try block as soon as an
exception is thrown, we can't put our cleanup code at the
bottom of the try block and expect it to be executed if an
exception occurs.
• Exception handlers are a poor place to clean up after the code
in the try block because each handler then requires its own
copy of the cleanup code.
• To address this problem, Java offers the finally block.
• If the try block executes with no exceptions, the finally block
is executed immediately after the try block completes.
• If there was an exception thrown, the finally block executes
immediately after the proper catch block completes.
1: try {
2: // This is the first line of the "guarded region".
3: }
4: catch(MyFirstException) {
5: // Put code here that handles this exception
6: }
7: catch(MySecondException) {
8: // Put code here that handles this exception
9: }
10: finally {
11: // Put code here to release any resource we
12: // allocated in the try clause.
13: }
14:
15: // More code here
• Execution starts at the first line of the try block, line 2. If there
are no exceptions thrown in the try block, execution transfers
to line 11, the first line of the finally block.
• If a MySecondException is thrown while the code in the try
block is executing, execution transfers to the first line of that
exception handler, line 8 in the catch clause.
• After all the code in the catch clause is executed, the program
moves to line 11, the first line of the finally clause
• If an exception is thrown, finally runs.
• If an exception is not thrown, finally runs.
• If the exception is caught, finally runs.
• If the exception is not caught, finally runs
try {
// do stuff
} catch (SomeException ex) {
// do exception handling
} finally {
// clean up
}
----------------------------------------------------------------------------try {
// do stuff
} finally {
//clean up
}
try {
// do stuff
}
// need a catch or finally here
System.out.println("out of try block");
-------------------------------------------------------------------------try {
// do stuff
}
// can't have code between try/catch
System.out.println("out of try block");
catch(Exception ex) { }
• It is illegal to use a try clause without either a catch clause or
a finally clause.
• Any catch clauses must immediately follow the try block. Any
finally clause must immediately follow the last catch clause (or
it must immediately follow the try block if there is no catch).
• It is legal to omit either the catch clause or the finally clause,
but not both.
Steps to handle Exception
Steps to Handing an Exception
Step1: The programmer should observe the
statements in his program where there may be a
possibility of exception. Such statements should
be written inside a try block looks like as follows
try{
statements;
}
Note: The greatness of try block is that even if some
exceptions arises it, the program will not
terminated. When JVM understands the there is
an exception, it stores the exception details in an
exception stack and then jumps into a catch block
Step2: The programmer should write the catch
block where he should display the exception
details to the user. This helps the user to
understand that there is some error in the
program. The programmer should also display
a message regarding what can be done to avoid
this error
catch (Exceptionclass ref)
{
statements;
}
We can display the exception details using any
one of the following ways
1) Using print() or println() methods, such as
System.out.println(ref);
2) Using printStackTrace() method of
Throwable class, which fetches the exception
details from the exception stack and display
them
Step3:The programmer should perform clean up
operations like closing the files and
terminating the threads. The programmer
should write this code in the finally block like
finally{
statements;
}
The specialty of finally block is that the
statements inside the finally block executed
irrespective of whether there is an exception or
not.
Method Stack or Call Stack
• Simply put, the call stack is the chain of methods that your
program executes to get to the current method.
• If your program starts in method main() and main() calls
method a(), which calls method b(), which in turn calls method
c(), the call stack consists of the following:
c
b
a
main
• We will represent the stack as growing upward
• If we move back down the call stack, we're moving from the
current method to the previously called method.
The call stack while method3() is running.
--------------------------------------------------------------------The order in which methods are put on the call stack
--------------------------------------------------------------------4 method3() method2 invokes method3
3 method2() method1 invokes method2
2 method1()
main invokes method1
1 main()
main begins
• As you can see, the last method called is at the top of the stack,
while the first calling method is at the bottom.
• The method at the very top of the stack trace would be the
method you were currently executing.
----------------------------------------------------------------------------The order in which methods complete
-----------------------------------------------------------------------------The call stack after method3() completes
Execution returns to method2()
1 method2() method2() will complete
2 method1() method1() will complete
3 main()
main() will complete and the JVM will exit
Propagating Uncaught Exceptions
• Imagine a building, say, five stories high, and at each floor there is a
balcony.
• Now imagine that on each balcony, one person is standing holding a
baseball mitt.
• Exceptions are like balls dropped from person to person, starting from the
roof.
• An exception is first thrown from the top of the stack (in other words, the
person on the roof), and if it isn't caught by the same person who threw it
(the person on the roof), it drops down the call stack to the previous
method, which is the person standing on the deck one floor down.
• If not caught there, by the person one floor down, the exception/ball again
drops down to the previous method (person on the next floor down), and so
on until it is caught or until it reaches the very bottom of the call stack
• This is called exception propagation.
• If an exception reaches the bottom of the call stack, it's like
reaching the bottom of a very long drop; the ball explodes, and
so does your program.
• An exception that's never caught will cause your application
to stop running. A description (if one is available) of the
exception will be displayed, and the call stack will be
"dumped.“
• If a method doesn't provide a catch clause for a particular
exception, that method is said to be "ducking" the exception
class TestEx {
public static void main (String [] args) {
doStuff();
}
static void doStuff() {
doMoreStuff();
}
static void doMoreStuff() {
int x = 5/0; // Can't divide by zero!
// ArithmeticException is thrown here
}
}
%java TestEx
Exception in thread "main" java.lang.ArithmeticException: /
by zero
at TestEx.doMoreStuff(TestEx.java:10)
at TestEx.doStuff(TestEx.java:7)
at TestEx.main(TestEx.java:3)
Example
class ExceptionExample {
public static void main(String args[]) {
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Example
// Handle an exception and move on.
import java.util.Random;
class HandleError {
public static void main(String args[])
{
int a=0, b=0, c=0;
Random r = new Random();
for(int i=0; i<32000; i++) {
try {
b = r.nextInt();
c = r.nextInt();
a = 12345 / (b/c);
}
catch (ArithmeticException e) {
System.out.println("Division by zero.");
a = 0; // set a to zero and continue
}
System.out.println("a: " + a);
}
}
}
Handling Multiple Exceptions
Most of the time here is possibility of more than
one exception present in the program. Un this
case, the programmer should write multiple
catch blocks to handle each one of them
Example
// Demonstrate multiple catch
statements.
class MultiCatch {
public static void main(String args[])
{
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch
blocks.");
}
}
Multiple Catch clauses
• More than one exception could be raised by a single piece of
code.
• To handle such a situation, two or more catch clauses are
specified, each catching a different type of exception.
• When an exception is thrown, each catch statement is
inspected in order, and the first one matching that exception
is executed. Others are bypassed and execution continues
after the try/catch block.
• Exception subclasses if any must come before any of their
super classes. Otherwise, the subclass would never be
reached because a catch statement that uses a superclass will
catch exceptions of that type plus any of its subclasses.
Example
// Demonstrate multiple catch
statements.
class MultiCatch {
public static void main(String args[])
{
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException
e) {
System.out.println("Array index oob: " +
e);
}
System.out.println("After try/catch
blocks.");
}
}
Example
/* This program contains an error. A
subclass must come before its
superclass in a series of catch
statements. If not, unreachable code
will be created and a compile-time
error will result.*/
class SuperSubCatch {
public static void main(String args[])
{
try {
int a = 0;
int b = 42 / a;
}
catch(Exception e) {
System.out.println("Generic
Exception catch.");
}
/* This catch is never reached because
ArithmeticException is a subclass
of Exception. */
catch(ArithmeticException e) {
// ERROR - unreachable
System.out.println("This is never
reached.");
}
}
}
Nested try statements
• try statements can be nested. ie a try statement can be inside
another try.
• Each time a try statement is entered, context of that
exception is pushed on the stack.
• If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match.
• This continues until one of catch statements succeeds, or until
all of the nested try statements are exhausted. The Java runtime system will handle if no catch statement
matches.(NestTry.java)
Example
// An example nested try statements.
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command line arg is used,
then an divide-by-zero exception will be
generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command line args are used
then generate an out-of-bounds
exception. */
if(a==2)
{
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds
exception
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out-ofbounds: " + e);
}
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
Exception Matching
• When an exception is thrown, Java will try to find (by looking
at the available catch clauses from the top down) a catch
clause for the exception type.
• If it doesn't find one, it will search for a handler for a
supertype of the exception.
• If it does not find a catch clause that matches a supertype for
the exception, then the exception is propagated down the call
stack.
• This process is called exception matching.
throw Clause
Even if the programmer is not handling runtime exceptions, the
Java compiler will not give any error related to runtime
exception
But the rule is that the programmer should handle checked
exceptions
In case the programmer does not want to handle the checked
exceptions, he should throw them out using throws clause
Otherwise, there will be an error flagged by java compiler
Exception Handling
Most of Java’s I/O classes (and many others) throw exceptions.
For example: Consider a function with a message readLine( ) directed to a
BufferedInputReader object
import java.io.*;
//needed for streams and IOException
public class ExceptionalExample {
public static void main(String [ ] args)
throws IOException
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println(“Enter a number”);
String str = br.readLine( );
The statement
“throwstoIOException”
is required
when
using readLine(
Provide
stream
readers
characters
as integers)
into
Read the
supplied
numberconvert
(as a String)
from (read
the keyboard.
It must
beprompt
included
in user
the header
of any function in which
a ).string,
then
the
for a number.
readLine( ) appears.
Exception Handling
If we fail to include the “throws IOException” clause in the main function
header we will see the following error reported when we compile the
program ExceptionalExample:
c:\javacode>javac ExceptionalExample.java
ExceptionalExample.java:10: unreported exception java.io.IOException; must be caught
or declared to be thrown
String str = readLine( );
^
1 error
c:\javacode>
Method readLine( ) throws an IOException. Any function that uses it must
either throw the same exception (and pass the buck to the operating
system to handle the exception) or catch the exception and provide its
own error handling methodology. In the previous example we chose the
first strategy.
Exception Handling
Example
Consider implementing the BufferReader readLine( ) example with trycatch clocks.
import java.io.*
public class ExceptionalExample {
public static void main(String [ ] args) //no throws clause used here
{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.println(“Enter a number”);
try {
String str = br.readLine( );
double num = Double.parseDouble(str);
}
Will throw NumberFormatException if str
cannot be converted to a double.
try block encapsulates
the readLine( ) method
and the conversion from
String to double.
Exception Handling
Example (continued)
//add the catch blocks
catch (IOException ioe) {
//print a message to the screen
System.out.println(ioe.toString( ));
}
catch (Exception e) {
catch the IOException object
thrown by readLine( )
Note! ioe is a handle
(reference) to an IOException
object thrown by readLine( )
//catch any other exception and print a message to the screen
System.out.println(e.toString( ));
}
finally {
System.exit(0);
}
Note! toString( ) is a method that all
Classes inherit (implicitly).
In the finally clause we ensure that the program
terminates
properly
– exit(0)
signifies
normal
Since both
catch blocks
have
the same
termination.
implementation in this example, there is no need to
single out IOException in a separate block.
Exception Handling
The anatomy of an exception
In the main( ) function of
Anbr.readLine(
error occurs) iswhile
called
inside of ato
ExceptionalExample
a attempting
The IOException is passed
to the
read
try block
from the
in
function
keyboard.
main(
An )br is
Message
is sent
to object
BufferedReader
object
called
catch block in function main( )
IOException
object
created.
referenced
by ioe is
toto
execute
its
created
and attatcher
isr.
toString( ) method (inherited from
implicit base class Object)
ExceptionalExample
try {
String str =br.readLine( );
}
catch (IOException ioe){
System.out.println(ioe.toString());
}
IOException
br:BufferedReader
new
readLine( ) {..}
toString( ) {…}
throw clause
It is used for throw an exception explicitly and catch it.
It is used in software testing to test whether a program is handling
all the exceptions as claimed by the programmer
throw clause can be used to throw our own exceptions
class Throw
{
static void demo()
{
try{System.out.println("Demo");
throw new NullPointerException("NULL EXCEPTION");
}
catch(NullPointerException ne)
{
System.out.println(ne);
}
}
}
class ThrowTest
{
public static void main(String[] args)
{
Throw.demo();
}
}
Used Defined Exceptions
Step1:
The user should create the exception class as a sub class to
Exception class
class MyException extends Exception
Step2:
The user can write a default constructor in his own class . He can
use it, in case he does not store any exception details
If the user does not want to create an empty object to his
exception class, he eliminates writing the default constructor
MyException() { }
Step3:
The user can create a parameterized constructor with a string as a
parameter. He can use this to store exception details. He can
call super class constructor from this and send the string there
MyException (String str)
{
super(str);
}
Step4:
When the user wants to raise his own exception, he should create
an object and throw it using throw clause
MyException me=new MyException(“Exception Details”);
throw me; (MyException.java)
Wrapper Classes
• Wrapper classes convert primitive data into objects and this is
needed on internet to communicate between two applications
• The classes in java.util package handle only objects and hence
wrapper classes help in this case also
• A wrapper class is a class whose object contains a primitive
data type.
•
Primitives & Wrappers
• Java has a wrapper class for each of the
eight primitive data types:
Primitive
Type
Wrapper
Class
Primitive
Type
Wrapper
Class
boolean
byte
char
double
Boolean
Byte
Character
Double
float
int
long
short
Float
Integer
Long
Short
Object Creation for Wrapper Class
The Wrapper Constructors
• All of the wrapper classes except Character provide two
constructors: one that takes a primitive of the type being
constructed, and one that takes a String representation of the
type being constructed—for example,
Integer i1 = new Integer(42);
Integer i2 = new Integer("42");
or
Float f1 = new Float(3.14f);
Float f2 = new Float("3.14f");
• The Character class provides only one constructor, which takes
a char as an argument—for example,
Character c1 = new Character('c');
• The constructors for the Boolean wrapper take either a boolean
value true or false, or a String.
• If the String's case-insensitive value is "true" the Boolean will
be true—any other value will equate to false.
• Until Java 5, a Boolean object couldn't be used as an
expression in a boolean test—for instance,
Boolean b = new Boolean("false");
if (b) // won't compile, using Java 1.4 or earlier
• As of Java 5, a Boolean object can be used in a boolean test,
because the compiler will automatically "unbox" the Boolean
to a boolean.
The valueOf() Methods
• The two (well, usually two) static valueOf() methods provided
in most of the wrapper classes give you another approach to
creating wrapper objects.
• Both methods take a String representation of the appropriate
type of primitive as their first argument, the second method
(when provided) takes an additional argument, int radix, which
indicates in what base (for example binary, octal, or
hexadecimal) the first argument is represented—for example,
Integer i2 = Integer.valueOf("101011", 2); // converts 101011
to 43 and assigns the value 43 to the Integer
object i2
or
Float f2 = Float.valueOf("3.14f"); // assigns 3.14 to the
// Float object f2
Using Wrapper Conversion Utilities
• As we said earlier, a wrapper's second big is converting stuff.
• The following methods are the most commonly used.
xxxValue()
• When you need to convert the value of a wrapped numeric to a
primitive, use one of the many xxxValue() methods.
• All of the methods in this family are noarg methods.
• There are 36 xxxValue() methods.
• Each of the six numeric wrapper classes has six methods, so that any
numeric wrapper can be converted to any primitive numeric type—
for example,
Integer i2 = new Integer(42); // make a new wrapper object
byte b = i2.byteValue(); // convert i2's value to a byte primitive
short s = i2.shortValue(); // another of Integer's xxxValue
// methods
double d = i2.doubleValue(); // yet another of Integer's
// xxxValue methods
or
Float f2 = new Float(3.14f); // make a new wrapper object
short s = f2.shortValue(); // convert f2's value to a short
// primitive
System.out.println(s); // result is 3 (truncated, not
// rounded)
Byte Class
The Byte class wraps a value of the primitive
type ’byte’ into in an object
Constructors
1) Byte(byte num)
So, we can create Byte object as: Byte obj=new Byte(120);
2) Byte(String str)
This constructor create a Byte object by
converting a string that contains a byte number
as:
Byte obj= new Byte(“120”);
import java.io.*;
class ByteDemo
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a byte number");
String s1=br.readLine();
Byte b1=new Byte(s1);
System.out.println("Enter a byte number");
String s2=br.readLine();
Byte b2=new Byte(s2);
int n=b1.compareTo(b2);
if(n==0)
System.out.println("Both Bytes are same");
else if(n<0)System.out.println(b1+ "is less");
else System.out.println(b2+ "is less");
}
}
Short Class
The Short class wraps a value of the primitive
type ’short’ into in an object
Constructors
1) Short(short num)
So, we can create Short object as: Short obj=new Short(120);
2) Byte(String str)
This constructor create a Short object by
converting a string that contains a short
number as:
Short obj= new Short(“120”);
import java.io.*;
class ShortDemo
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a short number");
String s1=br.readLine();
Short b1=new Short(s1);
System.out.println("Enter a short number");
String s2=br.readLine();
Short b2=new Short(s2);
boolean b=b1.equals(b2);
System.out.println(b);
}
}
Integer Class
The Integer class wraps a value of the primitive
type ’int’ into in an object
Constructors
1) Integer (int num)
So, we can create Integer object as: Integer obj=new
Integer(1200);
2) Integer (String str)
This constructor create a Integer object by
converting a string that contains a integer
number as:
Integer obj= new Integer(“1200”);
import java.io.*;
class IntegerDemo
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter an integer number");
String str=br.readLine();
int i=Integer.parseInt(str);
System.out.println("In Decimal:"+i);
str=Integer.toBinaryString(i);
System.out.println("In binary:"+str);
str=Integer.toHexString(i);
System.out.println("In Hexadecimal:"+str);
str=Integer.toOctalString(i);
System.out.println("In Octal:"+str);
Long Class
The Long class wraps a value of the primitive
type ’long’ into in an object
Constructors
1) Long (long num)
So, we can create Long object as: Long obj=new Long(12000);
2) Long (String str)
This constructor create a Long object by
converting a string that contains a long number
as:
Long obj= new Long(“12000”);
import java.io.*;
class LongDemo
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a long number");
String s1=br.readLine();
Long b1=new Long(s1);
System.out.println("Enter a long number");
String s2=br.readLine();
Long b2=new Long(s2);
boolean b=b1.equals(b2);
System.out.println(b);
}
}
Float Class
The Float class wraps a value of the primitive
type ’float’ into in an object
Constructors
1) Float (float num)
So, we can create Float object as: Float obj=new Float(12.23f);
2) Float (String str)
This constructor create a Float object by
converting a string that contains a float number
as:
Float obj= new Float(“12000”);
import java.io.*;
class FloatDemo
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a float number");
String s1=br.readLine();
Float b1=new Float(s1);
System.out.println("Enter a float number");
String s2=br.readLine();
Float b2=new Float(s2);
boolean b=b1.equals(b2);
System.out.println(b);
}
}
Double Class
The Double class wraps a value of the primitive
type ’double’ into in an object
Constructors
1) Double (double num)
So, we can create Float object as: Double obj=new
Double(12.23);
2) Double(String str)
This constructor create a Double object by
converting a string that contains a double
number as:
Float obj= new Float(“12000”);
import java.io.*;
class DoubleDemo
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a double number");
String s1=br.readLine();
Double b1=new Double(s1);
System.out.println("Enter a double number");
String s2=br.readLine();
Double b2=new Double(s2);
boolean b=b1.equals(b2);
System.out.println(b);
}
}
Boolean Class
The Boolean class object contains a primitive
‘boolean’ type data
Constructors
1) Boolean (boolean value)
Ex: Boolaen obj=new Boolean(true);
2) Boolean (String str)
Ex: Boolean obj=new Boolean(“false”);
import java.io.*;
class BooleanDemo
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a boolean value");
String s1=br.readLine();
Boolean b1=new Boolean(s1);
System.out.println("Enter a boolean value");
String s2=br.readLine();
Boolean b2=new Boolean(s2);
boolean b=b1.equals(b2);
System.out.println(b);
}
}
Character Class
The Character class wraps a value of the
primitive type char in an object
Constructor
1)Character(char ch)
Example: Character obj=new Character(‘a’);
import java.io.*;
class CharDemo
{ public static void main(String args[])throws Exception
{
char ch;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
while(true)
{
System.out.println("Enter a character value");
ch=(char)br.read();
System.out.println("You Entered...."+ch);
if(Character.isDigit(ch))
System.out.println("Enter a digit value");
else System.out.println("I don't know");
return;
}
}
}
I/O operations in JAVA
I/O Streams
1) A stream is a sequence of data.
2) An I/O Stream represents an input source or an
output destination.
3) A stream can represent many different kinds of
sources and destinations like disk files, devices,
other programs, a network socket, and memory
arrays.
4) Streams support many different kinds of data
like simple bytes, primitive data types, localized
characters, and objects.
5) Some streams simply pass on data, others
manipulate and transform the data in useful
ways.
Input Stream
A program uses an input stream to read data from a source, one item
at a time.
Output Stream
A program uses an output stream to write data to a
destination, one item at time.
General Stream Types
The general stream types are:
• Character and Byte Streams: Character streams
are the streams that read and write 16-bit
characters whereas Byte streams are the
streams that read and write 8-bit bytes.
• Input and Output Streams: Based on source or
destination
• Node and Filter Streams: Whether the data on
a stream is manipulated or transformed or not.
1) Input operations begin by opening a stream from the
source and using a read() method to obtain the data
via the stream. Similarly, output operations begin by
opening a stream to the destination and using a
write() method to send the data.
2) The package named java.io contains a set of input and
output stream classes that can be used to read and
write data.
3) The java.io package also provides specialized
InputStream and OutputStream subclasses that are
used for specialized types of input and output.
4) The InputStream class and OutputStream class are
abstract superclasses that define the behavior for
sequential input and output streams in Java.
5) Classes in java.io package are designed to be
“chained” or “wrapped”.
Classification of Stream Classes
• Streams are classified into ‘byte streams’ and ‘text streams’
Byte Streams
1) Byte streams represents data in the form of individual bytes
2) Byte streams are used to handle any characters(text), images , audio , and
video files.
3) For example, to store image file (.gif or .jpg), we should go for a byte
streams
4) If a class name ends with the word ‘Stream’ , then it comes under byte
streams
5) InputStream reads bytes and OutputStream writes bytes
Example
o FileInputStream
o FileOutputStream
o BufferedInputStream
o BufferedOutputStream
InputStream
OutputStream
FileOutputStream Example
import java.io.*;
class CreateFile
{
public static void main(String args[])throws IOException
{
//attach keyboard to DataInputStream
DataInputStream dis=new DataInputStream(System.in);
FileOutputStream fos=new FileOutputStream("myfile.txt");
System.out.println("Enter text (@ at the end):");
char ch;
while((ch=(char)dis.read())!='@')
fos.write(ch);
fos.close();
}//main
}//class
FileInputStream Example
import java.io.*;
class ReadFile
{
public static void main(String args[])throws IOException
{
FileInputStream fin=new FileInputStream("myfile.txt");
System.out.println("File Contents.");
int ch;
while((ch=fin.read())!=-1)
System.out.print((char)ch);
fin.close();
}//main
}//class
Other version
import java.io.*;
class CreateFile
{
public static void main(String args[])throws IOException
{
//attach keyboard to DataInputStream
DataInputStream dis=new DataInputStream(System.in);
//FileOutputStream fos=new FileOutputStream("myfile.txt");
FileOutputStream fout=new FileOutputStream("myfile.txt", true);
System.out.println("Enter text (@ at the end):");
char ch;
while((ch=(char)dis.read())!='@')
//fos.write(ch);
fout.write(ch);
//fos.close();
fout.close();
}//main
}//class
Limitations of Previous Program
fout.write(ch);
Let us estimate how much time it takes to read 100 characters
from the keyboard and write all of them into a file
Let us assume we read data from the keyboard into memory using
DataInputStream and it takes 1 second time to read 1 character
into memory
Let us assume that this character is written into the file by
FileOutputStream by spending another 1 second time. So, for
reading and writing a single character, a total time of 2 seconds
are used,
Thus, to read and write 100 characters, it takes 200 seconds time.
This is wasting a lot of time
• If Buffered classes are used, they provide a buffer (temporary
block of memory), which is first filled with characters and then
all the characters from the buffer can be at once written into
the file
• Buffered classes should be used always in connection to other
stream classes.
• For example, BufferedOutputStream can be used along with
FileOutputstream to write data into a file
• First, the DataInputstream reads data from keyboard by
spending 1 second time for each character.
• This characters is written into buffer. Thus, to read 100
characters into the buffer, it will take 100 seconds time
• When the buffer is full, then the FileOutputStream will write
entire buffer full of characters in a single step into file
Object-Oriented Program
Development Using Java: A
Class-Centered Approach
426
import java.io.*;
class BufferedCreateFile
{
public static void main(String args[])throws IOException
{
//attach keyboard to DataInputStream
DataInputStream dis=new DataInputStream(System.in);
FileOutputStream fout=new FileOutputStream("myfile.txt", true);
BufferedOutputStream bout=new BufferedOutputStream(fout, 1024);
System.out.println("Enter text (@ at the end):");
char ch;
while((ch=(char)dis.read())!='@‘)
bout.write(ch);
bout.close();
}//main
}//class
// here, the buffer size is declared as 1024 bytes. If the buffer size is not
specified, then a default buffer size of 512 bytes is used
import java.io.*;
class BufferedReadFile
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter File Name");
String fname= br.readLine();
FileInputStream fin=null;
try
{
fin=new FileInputStream(fname);
}
catch (FileNotFoundException fe)
{
System.out.println("File Not Found");
return;
}
BufferedInputStream bin=new BufferedInputStream(fin);
System.out.println("File Contents.");
int ch;
while((ch=fin.read())!=-1)
System.out.print((char)ch);
fin.close();
}//main
}//class
Text or Character Streams
• Text streams represents data as characters of each 2 bytes
• Character or text streams can always store and retrieve data in
the form of characters only
• It means text streams are more suitable for handling text files
like the ones we create in Notepad
• They are not suitable to handle the images, audio, or video
files
• If a class name ends with the word ‘Reader’ or ‘Writer’ then it
is taken as a text streams
• Reader reads text and Writer writes text
o FileReader
o FileWriter
o BufferedReader
o BufferedWriter
Character streams: For Unicode characters
Root classes for character streams:
• The Reader class
• The Writer class
• Both classes are abstract
1) The Java platform stores character values using Unicode
conventions.
2) Character stream I/O automatically translates this internal
format to and from the local character set..
3) All character stream classes are come down from Reader and
Writer.
4) As with byte streams, there are character stream classes of
FileReader and FileWriter that specialize in file I/O.
5) Reader and Writer are the abstract superclasses for character
streams in java.io package.
6) The Reader and Writer classes were added to JDK 1.1 to
support internationalization.
7) The Reader and Writer classes make it possible to work with
character streams rather than byte streams.
Reader
Writer
FileReader and FileWriter
FileReader is useful to read data in the form of
characters from a ‘text’ file
FileWriter is useful to create a file by writing a
characters into the file
Example on FileWriter
main(---) throws IOException
{
String str=“I am in CTS”+”\n I am in Hyd”;
//attach file to FileWriter
FileWriter fw=new FileWriter(“myfile”);
//read the character wise from string and write into FileWriter
for(int i=0;i<str.length();i++)
fw.write(str.charAt(i));
fw.close();
import java.io.*;
class CreateFileWriter
{
public static void main(String args[])throws IOException
{
String str="I am in CTS"+"\n I am in Hyderabad";
FileWriter fw=new FileWriter("CTS");
for(int i=0;i<str.length(); i++)
fw.write(str.charAt(i));
fw.close();
}//main
}//class
Example on FileReader
mian(---) throws IOException
{
int ch;
//check the file exits or not
FileReader fr=null;
try{ fr=new FileReader(“myfile”);}
catch(FileNotFoundException fe)
{ System.out.println(“File Not Found”);
return; }
//read from FileReader till the end of files
while(ch=fr.read())!=-1)
System.out.println((char)ch);
fr.close();
}
import java.io.*;
class ReadFileReader
{ public static void main(String args[])throws IOException
{
int ch;
FileReader fr=null;
try
{
fr=new FileReader("CTS");
}//try
catch(FileNotFoundException fe)
{
System.out.println("File Not Found");
return;
}//catch
while((ch=fr.read())!=-1)
System.out.print((char)ch);
fr.close();
}//main
}//class
Serialization
Serialization basics
• Serialization is the process of transforming an
in-memory object to a byte stream.
• Deserialization is the inverse process of
reconstructing an object from a byte stream to
the same state in which the object was
previously serialized.
• “Serializing out” and “serializing in” are also
used.
441
Serialization basics
• The requirements for serialization are
straightforward:
– Only class instances rather than primitive types
can be serialized.
– For an object to be serializable, its class must
implement the empty Serializable interface.
– An empty interface is called a marker interface.
442
Serialization basics
• The syntax for serialization is straightforward:
– An object is serialized by writing it to an
ObjectOutputStream.
– An object is deserialized by reading it from an
ObjectInputStream.
443
Serialization code
FileOutputStream out = new FileOutputStream( “save.ser” );
ObjectOutputStream oos = new ObjectOutputStream( out );
oos.writeObject( new Date() );
oos.close();
444
Deserialization code
FileInputStream in = new FileInputStream( “save.ser” );
ObjectInputStream ois = new ObjectInputStream( in );
Date d = (Date) ois.readObject();
ois.close();
445
Object Streams
• Object streams support I/O of objects:
• The object has to be of Serializable type
• The object stream classes are
ObjectInputStream and ObjectOutputStream:
• These classes implement ObjectInput and
ObjectOutput, which are sub interfaces of
DataInput and DataOutput
• An object stream can contain a mixture of
primitive and object values
Example:ObjectInputStream and ObjectOutputStream
List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
FileOutputStream fos = new FileOutputStream("list");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
oos.close();
FileInputStream fis = new FileInputStream("list");
ObjectInputStream ois = new ObjectInputStream(fis);
List anotherList = (List) ois.readObject();
ois.close();
The readObject method reads an object from the
ObjectInputStream
The writeObject method writes an object from
the ObjectOutputStream
transient and static fields
• A field marked as transient is not impacted by
serialization.
– During deserialization, transient fields are
restored to their default values (e.g., transient
numeric fields are restored to zero).
• static fields are not impacted by serialization.
450
Byte Streams
Byte Streams
Byte streams: For binary data
• Root classes for byte streams:
• The InputStream class
• The OutputStream class
Both classes are abstract
1. Programs use byte streams to perform input
and output of 8-bit bytes.
2. All byte stream classes are come down from
InputStream and OutputStream.
3. There are many byte stream classes like
FileInputStream and FileOutputStream.
4. They are implemented in much the same way.
They differ mainly in the way they are
constructed.
When not to use Byte Stream
Byte Stream represents a kind of low-level I/O
that you should avoid:
1. If the data contains character data, then the
best approach is to use character streams.
2. Byte streams should only be used for the most
primitive I/O.
3. All other streams are based on byte stream.
Simple byte stream input and output is shown in the
following diagram:
FileInputStream and FileOutputStream
FileInputStream is useful to read data from a file
in the form of sequence of bytes
FileOutputStream class belongs to byte stream
and stores the data in the form of individual
bytes. It can used to create text files
Example:FileInputStream
main method(----) throws IOException
{
FileInputStream fis=new FileInputStream(“myfile.txt”);
S.O.Pln(“File Contents”);
int ch;
while((ch=finread()!=-1)
S.O.Pln((char)ch);
fin.close();
}
The read() method reads all the characters from the file, it
reaches the end of the file. When there is no more data
available to read further, the read() method returns -1
Example:FileOutputStream
main(---) throws IOException
{
//attach keyboard to DataInputStream
DataInputStream dis=new DataInputStream(System.in);
//attach myfile to FileOutputStream
FileOutputStream fos=new FileOutputStream(“myfile.txt”);
System.out.println(“enter text @ at the end:”);
char ch;
//rea character from dis into ch. Then write them into fout
//repeat this as long as the read character is not@
while((ch=(char)dis.read())!=‘@’)
fout.write(ch);
fout.close();
End of Byte Streams
Character Stream
Character streams: For Unicode characters
Root classes for character streams:
• The Reader class
• The Writer class
• Both classes are abstract
1) The Java platform stores character values using Unicode
conventions.
2) Character stream I/O automatically translates this internal
format to and from the local character set..
3) All character stream classes are come down from Reader and
Writer.
4) As with byte streams, there are character stream classes of
FileReader and FileWriter that specialize in file I/O.
5) Reader and Writer are the abstract superclasses for character
streams in java.io package.
6) The Reader and Writer classes were added to JDK 1.1 to
support internationalization.
7) The Reader and Writer classes make it possible to work with
character streams rather than byte streams.
FileReader and FileWriter
FileReader is useful to read data in the form of
characters from a ‘text’ file
FileWriter is useful to create a file by writing a
characters into the file
Example on FileWriter
main(---) throws IOException
{
String str=“I am in CTS”+”\n I am in Hyd”;
//attach file to FileWriter
FileWriter fw=new FileWriter(“myfile”);
//read the character wise from string and write into FileWriter
for(int i=0;i<str.length();i++)
fw.write(str.charAt(i));
fw.close();
Example on FileReader
mian(---) throws IOException
{
int ch;
//check the file exits or not
FileReader fr=null;
try{ fr=new FileReader(“myfile”);}
catch(FileNotFoundException fe)
{ System.out.println(“File Not Found”);
return; }
//read from FileReader till the end of files
while(ch=fr.read())!=-1)
System.out.println((char)ch);
fr.close();
}
Character Stream and Byte Stream
• Character streams are often "wrapper" for byte
streams.
• The character stream uses the byte stream to
perform the physical I/O, while the character
stream handles translation between characters
and bytes. FileReader, for example, uses
FileInputStream, while FileWriter uses
FileOutputStream.
Line-Oriented I/O
• Character I/O usually occurs in bigger units
than single characters:
• For the line-oriented I/O, one common single
unit is the line that contains a string of
characters with a line terminator at the end.
• A line terminator can be a carriage-return or
linefeed sequence ("\r\n"), a single carriagereturn ("\r"), or a single line-feed ("\n").
Object-Oriented Program
Development Using Java: A
Class-Centered Approach
468
Object-Oriented Program
Development Using Java: A
Class-Centered Approach
469
Buffered Streams
• An unbuffered I/O means each read or write request
is handled directly by the underlying OS. This can
make a program much less efficient, because each
such request often triggers disk access, network
activity, or some other operation that is relatively
expensive.
• To reduce this kind of overhead, the Java platform
implements buffered I/O streams:
• Buffered input streams read data from a memory area
known as a buffer.
• Similarly, buffered output streams write data to a
buffer.
How to Create Buffered Streams?
• A program can convert an unbuffered stream
into a buffered stream using the wrapping
idiom. An unbuffered stream object is passed
to the constructor for a buffered stream class.
Example:
• Setting up FileWriter:
FileWriter fw = new FileWriter("prices.txt");
• Adding buffering for faster output:
BufferedWriter bw = new BufferedWriter(fw);
Buffered Stream Classes
• BufferedInputStream and
BufferedOutputStream create buffered byte
streams.
• BufferedReader and BufferedWriter create
buffered character streams.
Creating BufferedInputStream
File file = new File("myfile.txt");
FileInputStream fin = new FileInputStream(file);
BufferedInputStream bin = new BufferedInputStream(fin);
Creating BufferedOutputStream
FileOutputStream fos = new FileOutputStream(args[0]);
BufferedOutputStream bos = new BufferedOutputStream(fos);
Creating BufferedReader
FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
Creating BufferedWriter
FileWriter fw=new FileWriter("CTS123.txt");
BufferedWriter brw=new BufferedWriter(fw);
Flushing Buffered Streams
• It often makes sense to write out a buffer at critical
points, without waiting for it to fill. This is known as
flushing the buffer.
• Some buffered output classes support autoflush,
specified by an optional constructor argument:
• When autoflush is enabled, certain key events cause
the buffer to be flushed.
• For example, an autoflush PrintWriter object flushes
the buffer on every invocation of println or format.
• To flush a stream manually, invoke its flush method.
The flush method is valid on any output stream, but
has no effect unless the stream is buffered.
Data Streams
• Data streams support binary I/O of primitive
data type values (boolean, char, byte, short, int,
long, float, and double) as well as String
values.
• All data streams implement either the
DataInput interface or the DataOutput
interface.
• DataInputStream and DataOutputStream are
the implementations that are applied most
widely of these interfaces.
DataOutputStream
• DataOutputStream can only be created as a
wrapper for an existing byte stream object
DataInputStream
• Like DataOutputStream, DataInputStream
must be constructed as a wrapper for a byte
stream.
• End-of-file condition is detected by catching
EOFException, instead of testing for an invalid
return value
Example: DataInputStream
FileInputStream fis = new FileInputStream("myfile.txt");
DataInputStream dis = new DataInputStream(fis);
Example: DataOutputStream
FileOutputStream fos=new FileOutputStream(“test.dat”);
DataOutputStream out=new DataOutputStream(fos);
Object Streams
• Object streams support I/O of objects:
• The object has to be of Serializable type
• The object stream classes are
ObjectInputStream and ObjectOutputStream:
• These classes implement ObjectInput and
ObjectOutput, which are sub interfaces of
DataInput and DataOutput
• An object stream can contain a mixture of
primitive and object values
Example:ObjectInputStream and ObjectOutputStream
List list = Arrays.asList(new String[] { "A", "B", "C", "D" });
FileOutputStream fos = new FileOutputStream("list.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(list);
oos.close();
FileInputStream fis = new FileInputStream("list.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
List anotherList = (List) ois.readObject();
ois.close();
The readObject method reads an object from the
ObjectInputStream
The writeObject method writes an object from
the ObjectOutputStream
File Class
The File Class
• The File class is not a stream class.
• The File class is important because stream
classes manipulate File objects.
• The File class is an abstract representation of
actual files and directory pathname.
Constructors of File Class
1) File (String directoryPath)
2) File (String directoryPath,String filename)
3) File (File dirObj, String filename)
4) File(URI uriObj)
Here, directorypath is the path name of the file,
filename is the name of the file, dirObj is a
File object that specifies a directory, and
uriObj is a URI object describes a file
Syntax to create a File
File f1 = new File("MainClass.java");
System.out.println("File Name:" + f1.getName());
System.out.println("Path:" + f1.getPath());
Random Access File
• Random access files are files in which records
can be accessed in any order
– Also called direct access files
– More efficient than sequential access files
Need for Random Access Files
• Real-time applications require immediate
response
– Example: respond to customer query about a
bill
– Sequencing through records for account is
time-intensive
• Random (immediate) access meets real-time
need
– Directly read from or write to desired record
Example
• Consider the zip format. A ZIP archive
contains files and is typically compressed to
save space. It also contain a directory entry at
the end that indicates where the various files
contained within the ZIP archive begin
Accessing a specific file using
sequential access
•
•
Open the ZIP archive.
Search through the ZIP archive until you
locate the file you want to extract.
• Extract the file.
• Close the ZIP archive.
On an average, we have to read half of the zip
archive to find the required file
Accessing a specific file using
random access
• Open the ZIP archive.
• Seek to the directory entry and locate the entry
for the file you want to extract from the ZIP
archive.
• Seek (backward) within the ZIP archive to the
position of the file to extract.
• Extract the file.
• Close the ZIP archive.
This is more efficient as you read only the
directory entry and file that you want to
extract.
RandomAccessFiles class
• The RandomAccessFile class contains the same read(), write()
and close() methods as Input and OutputStream
• Also contains seek() that lets you select a beginning position
within the file before reading or writing data
• Includes capabilities for reading and writing primitive-type
values, byte arrays and strings
• NOT compatible with the stream/reader/writer models
• With a random-access file, you can seek to the desired position
and then read and write an amount of bytes
• Only support seeking relative to the beginning of the file
– Not relative to current position of file pointer
– However there are methods that report the current position
Methods to support seeking
long getFilePointer()
Returns the current offset in this file.
long length()
Returns the length of this file.
void seek(long pos)
Sets the file-pointer offset, measured from
the beginning of this file, at which the next
read or write occurs.
Constructor Summary
RandomAccessFile(File file, String mode)
Creates a random access file stream to read
from, and optionally to write to, the file
specified by the File argument.
RandomAccessFile(String name, String mode)
Creates a random access file stream to read
from, and optionally to write to, a file with the
specified name.
• The mode should be either “r” or “rw”
– No “w”
• When a RandomAccessFile is created in readonly mode a FileNotFoundException is
generated
• When a RandomAccessFile is created in readwrite a zero length file will be created
File Pointer
• RandomAccessFile supports file pointer which
indicates the current location in the file. When
the file is first created, the file pointer is set to
0, indicating the beginning of the file. Calls to
the read and write methods adjust the file
pointer by the number of bytes read or written.
Manipulate file pointer
• RandomAccessFile contains three methods for
explicitly manipulating the file pointer.
• int skipBytes(int) — Moves the file pointer
forward the specified number of bytes
• void seek(long) — Positions the file pointer
just before the specified byte
• long getFilePointer() — Returns the current
byte location of the file pointer
• To move the file pointer to a specific byte
f.seek(n);
• To get current position of the file pointer.
long n = f.getFilePointer();
• To find the number of bytes in a file
long filelength = f.length();
Creation of RandomAcess File
RandomAccessFile myfile = new RandomAccessFile("myfile.txt", "rw");
Serialization
Serialization basics
• Serialization is the process of transforming an
in-memory object to a byte stream.
• Deserialization is the inverse process of
reconstructing an object from a byte stream to
the same state in which the object was
previously serialized.
• “Serializing out” and “serializing in” are also
used.
505
Serialization basics
• The requirements for serialization are
straightforward:
– Only class instances rather than primitive types
can be serialized.
– For an object to be serializable, its class must
implement the empty Serializable interface.
– An empty interface is called a marker interface.
506
Serialization basics
• The syntax for serialization is straightforward:
– An object is serialized by writing it to an
ObjectOutputStream.
– An object is deserialized by reading it from an
ObjectInputStream.
507
Serialization code
FileOutputStream out = new FileOutputStream( “save.ser” );
ObjectOutputStream oos = new ObjectOutputStream( out );
oos.writeObject( new Date() );
oos.close();
508
Deserialization code
FileInputStream in = new FileInputStream( “save.ser” );
ObjectInputStream ois = new ObjectInputStream( in );
Date d = (Date) ois.readObject();
ois.close();
509
Object graphs
• If an object has references to other objects or
arrays, the entire object graph is serialized
when the object is serialized.
– The object graph consists of the object directly
serialized and any other objects or arrays to which
the object has direct or indirect references.
510
Nonserializable superclasses
• If a serializable class C has a nonserializable
superclass S, instances of C still can be
serialized if S has an accessible no-argument
constructor.
– S’s no-argument constructor is invoked
automatically during deserialization to construct
the “S-part” of the deserialized object.
511
Serialization and primitive types
• Technically, primitive types cannot be
serialized or deserialized. However, the
ObjectOutputStream implements the
DataOutput interface, which declares
methods such as writeInt to write primitive
types to streams.
• ObjectInputStream implements DataInput
for reading primitive types.
512
transient and static fields
• A field marked as transient is not impacted by
serialization.
– During deserialization, transient fields are
restored to their default values (e.g., transient
numeric fields are restored to zero).
• static fields are not impacted by serialization.
513
Version Control: Problem Scenario
• Imagine you create a class, instantiate it, and
write it out to an object stream
• That flattened object sits in the file system for
some time
• Meanwhile, you update the class file, perhaps
adding a new field
• What happens when you try to read in the
flattened object?
• – An exception will be thrown -- specifically,
the java.io.InvalidClassException
Unique Identifier
• Because all persistent-capable classes are
automatically given a unique identifier
• If the identifier of the class does not equal the
identifier of the flattened object, the exception
will be thrown
Customization
• Serialization and deserialization can be
customized by providing private callback
methods named writeObject and readObject,
respectively.
• The Externalizable interface can be
implemented by classes that need to have
complete control over serialization and
deserialization.
516
End Of I/O Operations in Java
COLLECTION FRAMEWORK
• The Collections Framework in Java gives you lists, sets, maps,
and queues to satisfy most of your coding needs.
So What Do You Do with a Collection?
• Add objects to the collection.
• Remove objects from the collection.
• Find out if an object is in the collection.
• Retrieve an object from the collection .
• Iterate through the collection, looking at each element (object)
one after another.
Key Interfaces of the Collections Framework
Collection
Set
SortedSet
List
Map
SortedMap
Queue
NavigableSet
NavigableMap
Key Classes of the Collections Framework
HashMap
HashSet
ArrayList
PriorityQueue
Hashtable
LinkedHashSet
Vector TreeMap
TreeSet
LinkedList
LinkedHashMap
Utility Classes
Collections Arrays
• Not all collections in the Collections Framework actually
implement the Collection interface.
• Specifically, none of the Map-related classes and interfaces
extend from Collection.
• So while SortedMap, Hashtable, HashMap, TreeMap, and
LinkedHashMap are all thought of as collections, none are
actually extended from Collection-with-a-capital-C .
1) collection (lowercase c), which represents any of the data
structures in which objects are stored and iterated over.
2) Collection (capital C), which is actually the
java.util.Collection interface from which Set, List, and Queue
extend.
3) Collections (capital C and ends with s) is the
java.util.Collections class that holds a pile of static utility
methods for use with collections.
Collection(I)
Set(I)
HashSet(C)
LinkedHashSet(C)
List(I)
SortedSet(I)
ArrayList(C)
Queue(I)
Vector(C)
NavigableSet(I)
LinkedList(C)
Map(I)
TreeSet(C)
SortedMap(I)
HashTable(C)
Object(c)
PriorityQueue(C)
HashMap(C)
NavigableMap(I)
LinkedHashMap(C)
Arrays (C )
Collections(C)
TreeMap(C)
All the collection classes in java.util package are the
implementation of different interfaces as shown below
Interface Type
Set
Implementation classes
HashSet,
LinkedHashSet,
TreeSet
List
Stack, LinkedList,
ArrayList, Vector
LinkedList,
PriorityQueue
Queue
Map<k,v>
HashMap, HashTable,
LinkedHashMap,
TreeMap
List Interface
• List interface is an ordered collection (sometimes called a
sequence).
• Lists can contain duplicate elements.
• The user of a List interface generally has exact control over
where in the each list element is inserted and can access
elements by their integer index (position).
• Access and manipulates elements based on their numerical
position in the list.
• Search for a specified object in the list and returns its
numerical position.
• List allow duplicate values and permits multiple null values
Cat
Dog
Bat
Bat
Lion Cat
Cow Bird Null Null
Implementation Classes of List Interface
• The following are the implementation class of List interface
1) Stack
2) LinkedList
3) ArrayList
4) Vector
Generics
• Real World Example
Roses
Chocolates
The buyer does not know
what these red shape boxes
contain. Hence the buyer
needs to open these boxes
every time to find what is
inside it
Bread
Here, the buyer is aware of what is inside the boxes. Since the box is labeled.
This makes his job easier since to know what he can put in and what he can
take out from the box
• Generic is a feature allows the programmer to specify the data
type to be stored in a collection or a class when developing the
program
• Compiler throws error if the data stored in different from the
data type specified in the generic
Generics Programmatically
public class Box
{
private Integer width;
public void addWidth(Integer width)
{
Assume that I have pass width
this.width=width;
as Float or Double to the Box
}
class
public Integer getWidth()
{
return width;
}
}
Generics Programmatically
public class Box<Type>
{
private Type width;
public void addWidth(Type width)
{
this.width=width; Type refers to the data type of the width field
which is declared as generic argument of the
}
class
public Type getWidth() Instead of declaring width as the Integer we
have declared as generic data type “Type”.
When declaring Box object, we can pass any
{
data type for Type which affects all the Type
return width;
declaration inside the class
Example: Box<Float> will declare a box object
}
whose width field data type is “Float”
}
Box<Float> box=new Box<Float>();
class Box<Type>
{
private Type width;
public void addWidth(Type width)
{
this.width=width;
}
public Type getWidth()
{
return width;
}
}
class BoxTest
{
public static void main(String[] args)
{
Box<Integer> box=new Box<Integer>();
box.addWidth(23);
Integer x=box.getWidth();
System.out.println(x);
}
}
Methods of Collection Interface
1. public int size (): This method is used for determining the
number of elements in Collection interface object.
2. public boolean add (java.lang.Object): This method is used for
adding an object to Collection object.
When we use this method to add the object to Collection objects
and List object, this method always returns true. Since,
Collection object and List object allows duplicates. When we
apply the same method with Set and SortedSet methods and
when we are trying to add duplicates, this method returns
false.
Collection Interface Methods
3. public boolean addAll (Collection):
• This method is used for adding the entire collection object at
the end of another Collection object.
• As long as we apply this method with List and Collection
interfaces, it returns true. Since,they allow duplicates.
• When we apply this method with Set and SortedSet, this
method may return false. Since, duplicates are not allowed.
Collection Interface Methods
4. public boolean isEmpty ():
• Returns true when there are no object found in Collection
interface object otherwise return false.
5. public Object [] toArray ():
• This method is used for extracting the data from Collection
objects of java.lang.Object class.
6. public Iterator iterator ():
• This method is used for extracting the data from Collection
framework object.
List Interface Methods
1. public Object get (int): This method is used for obtaining that
element from the specified position. If the get method is not
returning any value because of invalid position the value of
object of object is NULL.
2. public Object remove (int): This method is used for removing
the objects from List object based on position.
3. public Object remove (Object): This method is used for
removing the objects from List object based on content.
4. Public void add (int pos, Object): This method is used for
adding an object at the specified position.
5. public void addAll (int pos, Collection): This method is used
for adding one Collection object to another Collection object at
the specified position.
List Interface Methods
6. public List headList (Object obj): This method is used for
obtaining those objects Xi’s which are less than or equal to
target object (Xi≤obj).
7. public List tailList (Object obj): This method is used for
obtaining those objects Xi’s which are greater than target
object (Xi>obj or Xi≥(obj-1)).
8. public List subList (Object obj1, Object obj2): This method is
used for obtaining those values which are a part of List i.e.,
range of values [or] In subList method is select those values
Xi’s which are less than or equal to object 1 and greater than
object 2 (obj1≤Xi<obj2).
9. public ListIterator listIterator (): This method is used for
extracting the data from List object either in forward or in
backward or in both the directions. ListIterator is an interface
which extends Iterator interface.
ArrayList
• Implements form List interface
• ArrayList can grow and shrink in size dynamically based on
the elements stored hence can be considered as variable array
• Values are stored internally as an array hence random insert
and retrieval of elements are allowed
• Can be traversed using foreach loop iterators or indexes
• Initially gets created with an initial capacity, when this get’s
filled the list automatically grows
• Can hold only object type data
• Supports duplicate entries
• Arraylist is not synchronized
Creation of Arraylist
To create a ArrayList we use the following three constructors
1) Array List(): Constructs an empty list
2) ArrayList(Collection c): Construct a list from an existing
collection, containing the elements of the specified collection
3) ArrayList(int initialCapacity): Constructs an empty list with
specified initial capacity
ArrayList Methods
Return Type
Method Name
Useage
boolean
add(element obj)
Appends the specified element to the
end of the ArrayList. If the element is
added successfully then the preceding
method returns true
void
add(int position,
element obj)
Inserts the specified element at the
specified position in the ArrayList
Element
Remove(int position)
Removes the element at the specified
position in the ArrayList
Element
Remove(Object obj)
Removes the first occurrence of the
specified element obj from the
ArrayList, if it present
Void
Clear()
Removes all the elements from the
ArrayList
Element
Set(int position, element Replaces an element at the specified
obj)
position in the ArrayList with the
specified element obj
ArrayList Methods
Return Type
Method Name
Useage
Boolean
Contains(object obj)
Returns true if the ArrayList contains
the specified element obj
Element
Get(int position)
Return the element available at the
specified position
Int
indexOf(Object obj)
Returns the position of the first
occurrence of the specified element
obj in the list, or -1 if the element is
not found in the list
Int
lastIndexOf(Object obj)
Returns the position of the last
occurrence of the specified element
obj in the list, or -1 if the element is
not found in the list
Int
Size()
Return the number of elements
present in the ArrayList
Object[]
toArray()
Returns an Object class type array
containing all the elements in the
ArrayList in proper sequence
for-each Loop
For-each loop is like for loop which repeatedly executes a group
of statements for each element of the collection.
Format:
for(variable: collection-object)
{
statements
}
Here, the variable assumes each element in the collection-object
and the loop is executed as many times as there are number of
elements in the collection-object. If collection-object conatins
‘n’ elements the loop is executed exactly n times and the
variable stores each element in each loop
Iterator Interface
Iterator is an interface which always uses the extract the data from any
Collection object.
Methods in Iterator interface:
1. public boolean hasNext ()
2. public Object next ()
3. public Object remove ()
Method 1 is used for checking whether we have next element or not. If
next element available in Collection object it returns true otherwise
it returns false.
Method 2 is used for obtaining the next element in the Collection
object.
Method 3 is used for removing the element from Collection object.
Methods 2 and 3 can be used as long as method 1 returns true.
Iterator can retrieve the elements only in forward direction
ListIterator Interface
ListIterator is an interface which extends Iterator interface.
This interface contains the following methods:
public boolean hasNext()1
public boolean hasPrevious (); 2
public Object next();3
public Object previous (); 4
void remove();5
• Method-2 is used for checking weather we have previous
element or not, this method returns true as long as we have
previous elements otherwise false.
• Method-4 is used for obtaining previous element.
• ListIterator can retrieve the elements in forward and back ward
direction
LinkedList Class
• The LinkedList class extends AbstractSequentialList and
implements the List interface.
• LinkedList contains a group of elements in the form of nodes
• Each node will have three fields—the data field contains data
and the link field contains references to previous and next
nodes
Link
Data
Link
• LinkedList is very convenient to store data.
• Inserting the elements into the LinkedList and removing the
elements from the LinkedList is done quickly and takes same
amount of time
Creation of LinkedList
• The LinkedList class supports two constructors. The first
constructor builds an empty linked list:
LinkedList( )
• The following constructor builds a linked list that is initialized
with the elements of the collection c.
LinkedList(Collection c)
Methods of LinkedList
• void add(int index, Object element)
Inserts the specified element at the specified position index in this
list. Throws IndexOutOfBoundsException if the specified index is is
out of range (index < 0 || index > size()).
• boolean add(Object o)
Appends the specified element to the end of this list.
• void addFirst(Object o)
Inserts the given element at the beginning of this list.
• void addLast(Object o)
Appends the given element to the end of this list.
• Object removeFirst()
Removes and returns the first element from this list. Throws
NoSuchElementException if this list is empty.
• Object removeLast()
Removes and returns the last element from this list. Throws
NoSuchElementException if this list is empty.
Methods of LinkedList
• Object remove(int index)
Removes the element at the specified position in this list.
Throws NoSuchElementException if this list is empty.
• Object get(int index)
Returns the element at the specified position in this list.
Throws IndexOutOfBoundsException if the specified index is
is out of range (index < 0 || index >= size()).
• Object getFirst()
Returns the first element in this list. Throws
NoSuchElementException if this list is empty.
• Object getLast()
Returns the last element in this list. Throws
NoSuchElementException if this list is empty.
Methods of LinkedList
• int indexOf(Object o)
Returns the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this
element.
• int lastIndexOf(Object o)
Returns the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this
element.
• void clear()
Removes all of the elements from this list.
• boolean contains(Object o)
Returns true if this list contains the specified elememnt.
Vector Class
• Vector class store the elements similar to ArrayList, but Vector
is synchronized.
• It means even if several threads act on Vector object
simultaneously, the result will be reliable
• Vector is similar to ArrayList, but with two differences:
1. Vector is synchronized.
2. Vector contains many legacy methods that are not part of the
collections framework.
• Vector proves to be very useful if you don't know the size of
the array in advance or you just need one that can change sizes
over the lifetime of a program.
Creation of Vector Class
• The Vector class supports four constructors. The first form
creates a default vector, which has an initial size of 10:
Vector( )
• The second form creates a vector whose initial capacity is
specified by size:
Vector(int size)
• The third form creates a vector whose initial capacity is
specified by size and whose increment is specified by incr. The
increment specifies the number of elements to allocate each
time that a vector is resized upward:
Vector(int size, int incr)
• The fourth form creates a vector that contains the elements of
collection c:
Vector(Collection c)
Methods of Vector Class
• void add(int index, Object element)
Inserts the specified element at the specified position in this
Vector.
• boolean add(Object o)
Appends the specified element to the end of this Vector.
• boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the
end of this Vector, in the order that they are returned by the
specified Collection's Iterator.
• boolean addAll(int index, Collection c)
Inserts all of the elements in in the specified Collection into
this Vector at the specified position.
Vector Class Methods
• void addElement(Object obj)
Adds the specified component to the end of this vector,
increasing its size by one.
• int capacity()
Returns the current capacity of this vector.
• void clear()
Removes all of the elements from this Vector.
• boolean contains(Object elem)
Tests if the specified object is a component in this vector.
• Object elementAt(int index)
Returns the component at the specified index.
• Enumeration elements()
Returns an enumeration of the components of this vector.
Stack Class
• Stack is a subclass of Vector that implements a standard lastin, first-out stack.
• Stack only defines the default constructor, which creates an
empty stack. Stack includes all the methods defined by Vector,
and adds several of its own.
Stack( )
Methods of Stack
• boolean empty()
Tests if this stack is empty. Returns true if the stack is empty,
and returns false if the stack contains elements.
• Object peek( )
Returns the element on the top of the stack, but does not
remove it.
• Object pop( )
Returns the element on the top of the stack, removing it in
the process.
• Object push(Object element)
Pushes element onto the stack. element is also returned.
• int search(Object element)
Searches for element in the stack. If found, its offset from the
top of the stack is returned. Otherwise, .1 is returned.
Set Interface
• The Set interface is a collection that cannot
contain duplicate elements.
• The Set interface models the mathematical set
abstraction and is used to represent sets:
– Cards comprising a poker hand
– Courses making up the schedule of a student
– The processes running on a machine
• The Set interface contains only methods
inherited from Collection and adds the
restriction to prohibit the duplicate elements.
SortedSet Interface
• SortedSet interface is a set that maintains its
elements in ascending order. Several additional
operations are provided to take advantage of
the ordering.
– Sorted sets are used for naturally ordered sets, such
as word lists and membership roll.
Implementation Class of Set Interface
The implementations of Setinterface are:
• HashSet
• TreeSet
• LinkedHashSet
Set Interface Methods
• add( )
Adds an object to the collection
• clear( )
Removes all objects from the collection
• contains( )
Returns true if a specified object is an element within the collection
• isEmpty( )
Returns true if the collection has no elements
• iterator( )
Returns an Iterator object for the collection which may be used to
retrieve an object
• remove( )
Removes a specified object from the collection
• size( )
Returns the number of elements in the collection
HashSet Class
• HashSet extends AbstractSet and implements the Set interface.
• A HashSet is an unsorted, unordered Set.
• It uses the hashcode of the object being inserted, so the more
efficient your hashCode() implementation the better access
performance you'll get.
• Use this class when you want a collection with no duplicates
and you don't care about order when you iterate through it.
HashSet Creation
• The HashSet class supports four constructors. The first form
constructs a default hash set:
HashSet( )
• The following constructor form initializes the hash set by using the
elements of c.
HashSet(Collection c)
• The following constructor form initializes the capacity of the hash
set to capacity. The capacity grows automatically as elements are
added to the Hash.
HashSet(int capacity)
• The fourth form initializes both the capacity and the fill ratio (also
called load capacity) of the hash set from its arguments:
HashSet(int capacity, float fillRatio)
• Here the fill ratio must be between 0.0 and 1.0, and it determines
how full the hash set can be before it is resized upward. Specifically,
when the number of elements is greater than the capacity of the hash
set multiplied by its fill ratio, the hash set is expanded.
Methods of Hashset
• boolean add(Object o)
Adds the specified element to this set if it is not already present.
• void clear()
Removes all of the elements from this set.
• Object clone()
Returns a shallow copy of this HashSet instance: the elements
themselves are not cloned.
• boolean contains(Object o)
Returns true if this set contains the specified element
• boolean isEmpty()
Returns true if this set contains no elements.
• Iterator iterator()
Returns an iterator over the elements in this set.
• boolean remove(Object o)
Removes the specified element from this set if it is present.
• int size()
Returns the number of elements in this set (its cardinality).
LinkedHashSet
• This class extends HashSet, but adds no members of its own.
• A LinkedHashSet is an ordered version of HashSet that
maintains a doubly-linked List across all elements.
• Use this class instead of HashSet when you care about the
iteration order.
• When you iterate through a HashSet the order is unpredictable,
while a LinkedHashSet lets you iterate through the elements in
the order in which they were inserted.
Creation of LinkedHashSet
• The LinkedHashSet class supports four constructors. The first
form constructs a default hash set:
LinkedHashSet( )
• The following constructor form initializes the hash set by
using the elements of c.
LinkedHashSet(Collection c)
• The following constructor form initializes the capacity of the
hash set to capacity.
• The capacity grows automatically as elements are added to the
Hash.
LinkedHashSet(int capacity)
• The fourth form initializes both the capacity and the fill ratio
(also called load capacity) of the hash set from its arguments:
LinkedHashSet(int capacity, float fillRatio)
TreeSet Class
• TreeSet is an implementation of the Set interface that uses a
tree for storage.
• Objects are stored in sorted, ascending order.
• Access and retrieval times are quite fast, which makes TreeSet
an excellent choice when storing large amounts of sorted
information that must be found quickly.
Creation
• The TreeSet class supports four constructors. The first form
constructs an empty tree set that will be sorted in ascending
order according to the natural order of its elements:
TreeSet( )
• The second form builds a tree set that contains the elements of
c.
TreeSet(Collection c)
• The third form constructs an empty tree set that will be sorted
according to the comparator specified by comp.
TreeSet(Comparator comp)
• The fourth form builds a tree set that contains the elements of
ss:
TreeSet(SortedSet ss)
Map Interface
• A Map cares about unique identifiers.
• You map a unique key (the ID) to a specific value, where both
the key and the value are objects.
• The Map implementations let you do things like search for a
value based on the key, ask for a collection of just the values,
or ask for a collection of just the keys.
• The keys should have unique values
HashMap Class
• HashMap is a collection that stores elements in the form of
key-value pairs
• If key is provided later, its corresponding value can be easily
retrieved from the HashMap
• Keys should be unique.
• This means we cannot use duplicate data for keys in the
HashMap.
• However, HashMap is not synchronized and hence while using
multiple threads on HashMap object, we get unreliable results
• We can write HashMap class as
class HashMap(k,v)
Here k represents the type element and v represents the type of
value element
Creation of HashMap
• The HashMap class supports four constructors. The first form
constructs a default hash map:
HashMap( )
• The second form initializes the hash map by using the
elements of m:
HashMap(Map m)
• The third form initializes the capacity of the hash map to
capacity:
HashMap(int capacity)
• The fourth form initializes both the capacity and fill ratio of
the hash map by using its arguments:
HashMap(int capacity, float fillRatio)
HashMap Class
HashMap<String, Integer> hm=new HashMap<String,Integer>()
Here, we did not mention any capacity for the HashMap. The
default initial capacity of this HashMap will be taken as 16 and
the load factor as 0.75. Load factor represents at what level the
HashMap capacity should be doubled.
For example, the product of capacity and load factor= 16*
0.75=12. This represents that after the 12 th key-value pair into
the HashMap, its capacity will become 32.
HashMap Methods
• Object put(Object key, Object value)
This method stores key-value pair into the HashMap
• Object get(Object key)
Returns the value to which the specified key is mapped in this
identity hash map, or null if the map contains no mapping for
this key.
• Set keySet()
This method, when applied on HashMap converts it into a Set
where only keys will be stored
• Collection values()
Returns a collection view of the values contained in this map.
• Object remove(Object key)
Removes the mapping for this key from this map if present.
• int size()
Returns the number of key-value mappings in this map.
HashMap Class Methods
• boolean isEmpty()
Returns true if this map contains no key-value mappings.
• void clear()
Removes all mappings from this map.
Map.Entry interface
• entrySet() method declared by the Map interface returns a Set
containing the map entries
• Each of these set element is a Map.Entry object
• Map.Entry is generic and is declared like
interface Map.Entry<K,V>
Here, K specifies the type of keys, and V represents the types of
values
HashMap Examples
A school offers medals to the students of tenth based on the
following criteria
• If(Marks>=90) : Gold
• If(Marks between 80 and 90) : Silver
• If(Marks between 70 and 80) : Bronze
• Note: Marks between 80 and 90 means à marks>=80 and
marks<90
• Write a function which accepts the marks of students as a
Hashmap and return the details of the students eligible for
the medals along with type of medal.
• The input hashmap contains the student registration number
as key and mark as value.
• The output hashmap should contain the student registration
number as key and the medal type as value.
Create a method which accepts an array of numbers and returns
the numbers and their squares in an HashMap
**************************************************
Create a method that accepts a character array and count the
number of times each character is present in the array. Add
how many times each character is present to a hash map with
the character as key and the repetitions count as value
In a certain television game show, a couple is considered as a
perfect couple if both the husband’s and wife’s name contains
the same set of characters. Each couple is provided with an ID.
Write a method which can accept a Hashmap with ID as key
and the husband’s and wife’s name separated with “-” as
value. The method should generate the list of perfect couples
based on the above mentioned criteria and return their IDs as
List object.
LinkedHashMap
• The LinkedHashMap collection maintains insertion order
• Although it will be somewhat slower than HashMap for
adding and removing elements
• You can expect faster iteration with a LinkedHashMap.
HashTable
• HashTable is similar to HashMap which can store elements in
the form of key-value pairs
• Hashtable is the synchronized counterpart to HashMap.
• Another difference,though, is that while HashMap lets you
have null values as well as one null key, a Hashtable doesn't
let you have anything that's null.
Creation of HashTable
• The Hashtable defines four constructors.
• The first version is the default constructor:
Hashtable( )
• The second version creates a hash table that has an initial size
specified by size:
Hashtable(int size)
• The third version creates a hash table that has an initial size
specified by size and a fill ratio specified by fillRatio.
• This ratio must be between 0.0 and 1.0, and it determines how full
the hash table can be before it is resized upward.
Hashtable(int size, float fillRatio)
• The fourth version creates a hash table that is initialized with the
elements in m.
• The capacity of the hash table is set to twice the number of
elements in m. The default load factor of 0.75 is used.
Hashtable(Map m)
Methods of HashTable
• void clear( )
Resets and empties the hash table.
• Object clone( )
Returns a duplicate of the invoking object.
• boolean contains(Object value)
Returns true if some value equal to value exists within the hash
table. Returns false if the value isn't found.
• boolean containsKey(Object key)
Returns true if some key equal to key exists within the hash table.
Returns false if the key isn't found.
• boolean containsValue(Object value)
Returns true if some value equal to value exists within the hash
table. Returns false if the value isn't found.
• Enumeration elements( )
Returns an enumeration of the values contained in the hash table.
• Object get(Object key)
Returns the object that contains the value associated with
key. If key is not in the hash table, a null object is returned.
• boolean isEmpty( )
Returns true if the hash table is empty; returns false if it
contains at least one key.
• Enumeration keys( )
Returns an enumeration of the keys contained in the hash
table.
• Object put(Object key, Object value)
Inserts a key and a value into the hash table. Returns null if
key isn't already in the hash table; returns the previous value
associated with key if key is already in the hash table.
• Object remove(Object key)
Removes key and its value. Returns the value associated with
key. If key is not in the hash table, a null object is returned.
• int size( )
Returns the number of entries in the hash table.
• String toString( )
Returns the string equivalent of a hash table.
TreeMap
• The TreeMap class implements the Map interface by using a
tree.
• A TreeMap provides an efficient means of storing key/value
pairs in sorted order, and allows rapid retrieval.
• You should note that, unlike a hash map, a tree map
guarantees that its elements will be sorted in ascending key
order.
Creation of TreeMap
• The TreeMap class supports four constructors.
• The first form constructs an empty tree map that will be
sorted by using the natural order of its keys:
TreeMap( )
• The second form constructs an empty tree-based map that
will be sorted by using the Comparator comp:
TreeMap(Comparator comp)
• The third form initializes a tree map with the entries from m,
which will be sorted by using the natural order of the keys:
TreeMap(Map m)
• The fourth form initializes a tree map with the entries from
sm, which will be sorted in the same order as sm:
TreeMap(SortedMap sm)
TreeMap Methods
• void clear()
Removes all mappings from this TreeMap.
• Object clone()
Returns a shallow copy of this TreeMap instance.
• Comparator comparator()
Returns the comparator used to order this map, or null if this
map uses its keys' natural order.
• boolean containsKey(Object key)
Returns true if this map contains a mapping for the specified
key.
• boolean containsValue(Object value)
Returns true if this map maps one or more keys to the
specified value.
• Set entrySet()
Returns a set view of the mappings contained in this map.
• Object firstKey()
Returns the first (lowest) key currently in this sorted map.
• Object get(Object key)
Returns the value to which this map maps the specified key.
• SortedMap headMap(Object toKey)
Returns a view of the portion of this map whose keys are
strictly less than toKey.
• Set keySet()
Returns a Set view of the keys contained in this map.
• Object lastKey()
Returns the last (highest) key currently in this sorted map.
• Object put(Object key, Object value)
Associates the specified value with the specified key in this map.
• void putAll(Map map)
Copies all of the mappings from the specified map to this map.
• Object remove(Object key)
Removes the mapping for this key from this TreeMap if present.
• int size()
Returns the number of key-value mappings in this map.
• SortedMap subMap(Object fromKey, Object toKey)
Returns a view of the portion of this map whose keys range from
fromKey, inclusive, to toKey, exclusive.
• SortedMap tailMap(Object fromKey)
Returns a view of the portion of this map whose keys are greater
than or equal to fromKey.
• Collection values()
Returns a collection view of the values contained in this map.
Comparators
• By default TreeSet and TreeMap classes store their elements
by using what java refers to as “natural ordering”, which is
usually the ordering that you expect (A before B, 1 before 2)
• If you want to order elements a different way, then specify a
Comparator when you construct the set or map
• Comparator is a generic interface that has this declaraton
interface Comparator<T>
Here, Tspecifies the type of objectbeing compared
The Comparator interface provides two methods: compare() and
equals()
int comapre(T obj1, T obj2)
Returns---Zero if the objects are equal
Returns---+ve value if obj1 is greater than obj2
Other wise Returns --- -ve value
boolean equals(Object obj)
Here, obj is the object to be tested for equality.
The method returns true if obj and the invoking object are both
Comparator objects and use the same ordering
Otherwise, returns false
Overriding is unnecessary, and most simple comparators will not
do so
The Date Class
•
Its API design didn't do a good job of handling
internationalization and localization situations.
• In its current state, most of its methods have been
deprecated, and for most purposes you'll want to use the
Calendar class instead of the Date class.
• An instance of the Date class represents a single date and
time. Internally, the date and time is stored as a primitive
long.
• Specifically, the long holds the number of milliseconds (you
know, 1000 of these per second), between the date being
represented and January 1, 1970.
The Calendar Class
• Manipulating dates using the Date class is tricky.
• The Calendar class is designed to make date manipulation
easy
• While the Calendar class has about a million fields and
methods, once you get the hang of a few of them the rest
tend to work in a similar fashion.
• When you first try to use the Calendar class you might notice
that it's an abstract class.
• You can't say
Calendar c = new Calendar(); // illegal, Calendar is abstract
• In order to create a Calendar instance, you have to use one of
the overloaded getInstance() static factory methods:
Calendar cal = Calendar.getInstance();
• When you get a Calendar reference like cal, from above, your
Calendar reference variable is actually referring to an instance
of a concrete subclass of Calendar.
• You can't know for sure what subclass you'll get but it won't
matter to you.
• You'll be using Calendar's API.
• Okay, so now we've got an instance of Calendar.
Serial Vs. Parallel Processes
COUNTER 2
COUNTER
COUNTER 1
Q
Please
MULTITHREADING
Process Vs Thread
• Process are executables which runs in separate memory space
• Threads are small piece which runs in shared memory space
with in a process
• So , in nutshell process is a container for threads all threads
runs inside the process
Example:
Microsoft word application
A process called winword.exe started
Spell check and auto save threads running inside the process
Problem Statement
• Mr.Tim was developing an application where he has a
requirement where user can register his profile in the
application, assume registration has 2-steps
1) Validation user details------takes 3-seconds
2) Validate user, citizenship------takes 4-seconds
Requirement
The customer wants to complete the registration is less than 5seconds
Tim achieved this by using Multithreading
Single Thread Model
Tim Application
Validate User
citizen ship
(4-seconds)
Validate User
Details
(3-seconds)
Multithread Model
Tim Application
Validates User Details
(4-seconds)
Validate User Details
(3-seconds)
The process will be completed in 4-seconds since both the
threads works in parallel
Multitasking
• Refer to a computer’s ability to perform multiple jobs
concurrently
• More than one program are running concurrently
Example:
In windows you can run Ms-Word, Media Player at the same
time. You will working on Ms-Word and in parallel Medis
Player might play some music
Multithreading
• A thread is a single sequence of execution with in a
process/program
• This refers to multiple threads of control flow with in a single
program
• Each program can run multiple threads of control with in it
Thread-1
Thread-2
Thread-3
Process-1
Process-2
CPU
Process-3
Benefits of Multithreading
•
•
•
•
To reduce execution time of a process
Support multiple operation of functions
Increase system efficiency
Less overhead compare to multitasking
Application Thread
• The JVM creates a thread (T1) object which invokes the
main() method and starts the application
• The thread executes the statements of the program one by one
or starts other thread
• After executing all the statements , the method returns and the
thread dies
• T1------Application Thread
Running of Multiple Threads
• Each thread has its private run-time stack for storing variables
and data
• If two threads execute the same method, each will have its
own copy of stack to the method local variables
• The object instance variables are shared across all the threads,
they are not thread safe
public class Calculator
The result variable will be shared by
{
both the threads
int result=200;
Assume thread t1 sets the class variable
public void add(int a, int b) result to 200
For thread t2 result is 200
{
int c=a+b;
}
}
Assume Two Threads t1 and t2
t1
c=5
6=6
b=2
b=5
a=3
t2
a=1
Single and Multithreaded Processes
Single-threaded Process
Multiplethreaded Process
Threads of
Execution
Single instruction stream
Multiple instruction stream
Common
Address Space
A single threaded program
class ABC
{
….
public void main(..)
{
…
..
}
}
607
begin
body
end
A Multithreaded Program
Main Thread
start
Thread A
start
start
Thread B
Thread C
Threads may switch or exchange data/results
608
How to create Java Threads
There are two ways to create a Java thread:
1.
Extend the java.lang.Thread class
2.
Implement the java.lang.Runnable interface
Threading Mechanisms...
• Create a class that extends the Thread class
• Create a class that implements the Runnable
interface
Thread
MyThread
[a]
610
Runnable
MyClass
[b]
Extending the Thread class
1) In order to create a new thread we may
subclass java.lang.Thread
Example: class Myclass extends Thread
2) Write run()method in above class. The run
method is where the action of the thread takes
place.
Example: public void run()
{
Statements;
}
3) Create an object to Myclass, so that the run() method
is available for execution
Example: Myclass obj= new Myclass();
4) Create a thread and attach the thread to the object obj
Example: Thread t=new Thread(obj);
or
Thread t=new Thread(obj, “threadname”);
5) Run the thread we should use start() method of
Thread class
Example: t.start();
class MyThread extends Thread {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx1 {
public static void main(String [] args ) {
MyThread obj = new MyThread();
Thread t=new Thread(obj);
t.start();
}
}
Limitation of Above Approach
• The limitation with this approach (besides being a poor design
choice in most cases) is that if you extend Thread, you can't
extend anything else.
class MyThread extends Thread {
public void run() {
System.out.println("Important job running in MyThread");
}
public void run(String s) {
System.out.println("String in run is " + s);
}
}
class ThreadEx2 {
public static void main(String [] args ) {
MyThread obj = new MyThread();
Thread t=new Thread(obj);
//t.run("hello");
t.start();
obj.run("hello");
}
}
• The overloaded run(String s) method will be ignored by the
Thread class unless you call it yourself.
• The Thread class expects a run() method with no arguments,
and it will execute this method for you in a separate call stack
after the thread has been started.
• With a run(String s) method, the Thread class won't call the
method for you, and even if you call the method directly
yourself, execution won't happen in a new thread of execution
with a separate call stack.
• It will just happen in the same call stack as the code that you
made the call from, just like any other normal method call.
Threads by implementing Runnable interface
• Create a class that implements the interface Runnable and
override run() method:
class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
• Creating Object:
MyThread myObject = new MyThread();
• Creating Thread Object:
Thread thr1 = new Thread( myObject );
• Start Execution:
617 thr1.start();
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
t.start();
}
}
618
class MyThread extends Thread {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx1 {
public static void main(String [] args ) {
MyThread t=new MyThread();
t.start();
}
}
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx3 {
public static void main(String [] args ) {
MyThread t = new MyThread();
t.start();
}
}
• If you create a thread using the no-arg constructor, the thread will call its
own run() method when it's time to start working.
==============================================
• To have code run by a separate thread, you still need a Thread instance.
• But rather than combining both the thread and the job (the code in the
run()method) into one class, you've split it into two classes—the Thread
class for the thread-specific code and your Runnable implementation class
for your job-that-should-be-run-by-athread code. (Another common way to
think about this is that the Thread is the "worker," and the Runnable is the
"job" to be done.)
• First, you instantiate your Runnable class:
• MyRunnable r = new MyRunnable();
• Next, you get yourself an instance of java.lang.Thread (somebody has to
run your job…), and you give it your job!
• Thread t = new Thread(r); // Pass your Runnable to the Thread
class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
}
class ThreadEx3 {
public static void main(String [] args ) {
MyThread t = new MyThread();
Thread t1=new Thread(t);
t1.start();
}
}
• You can pass a single Runnable instance to multiple Thread
objects, so that the same Runnable becomes the target of
multiple threads, as follows:
public class TestThreads {
public static void main (String [] args) {
MyRunnable r = new MyRunnable();
Thread foo = new Thread(r);
Thread bar = new Thread(r);
Thread bat = new Thread(r);
}
}
• Giving the same target to multiple threads means that several
threads of execution will be running the very same job (and
that the same job will be done multiple times).
Performing Single Tasking using Threads
class A extends Thread
{
public void run()
{
task1();
task2();
task3();
}
void task1()
{
for(int i=1;i<=5;i++)
{
System.out.println("\t From ThreadA: i= "+i);
}
System.out.println("Exit from A");
}
void task2()
{
for(int j=1;j<=5;j++)
{
System.out.println("\t From ThreadA: j= "+j);
}
System.out.println("Exit from B");
}
void task3()
{
for(int k=1;k<=5;k++)
{
System.out.println("\t From ThreadA: k= "+k);
}
System.out.println("Exit from c");
}
}
class ThreadTest
{
public static void main(String args[])
{
Thread t=new Thread(new A());
t.start();
}
}
MultiTasking using Threads
In multitasking several threads executed at a
time. For this purpose, we need more than one
thread
class Theatre implements Runnable
{
String str;
Theatre(String str)
{
this.str=str;
}
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println(str+" :"+i);
try
{
Thread.sleep(2000);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
}
class TheatreTest
{
public static void main(String[] args)
{
Theatre obj1=new Theatre("cut the ticket");
Theatre obj2=new Theatre("Show the seat");
Thread t1=new Thread(obj1);
Thread t2=new Thread(obj2);
t1.start();
t2.start();
System.out.println("Hello World!");
}
}
Method Name
Description
currentThread()
To know currently running thread
start()
To start a thread
Sleep(milliseconds)
To stop execution of a thread for a
specific time
getName()
To get the name of the thread
setName()
To set a new name to a thread
getPriority()
To get the priority of a thread
setPriority()
To set the priority of a thread
isAlive()
To test a thread is still alive
join()
To wait a thread dies
Sleep Method
Java thread may be forced to sleep (suspended)
for predefined time
Syntax: Thread.sleep(milliseconds);
Example
public class SleepMessages {
public static void main(String args[]) throws InterruptedException {
String importantInfo[] = {"Red","Orange","Green"};
for (int i = 0; i < importantInfo.length; i++)
{
Thread.sleep(10000);
System.out.println(importantInfo[i]);
if(importantInfo[i]=="Red")
{
System.out.println("Please Stop");
}
if(importantInfo[i]=="Orange")
{
System.out.println("Ready to Start");
}
if(importantInfo[i]=="Green")
{
System.out.println("Move");
}
//Pause for 4 seconds
//Print a message
//System.out.println(importantInfo[i]);
}
}
}
Thread priorities
Thread priorities are used by the thread
scheduler to decide when each thread should
be allowed to run
To set a thread’s priority, use the setPriority()
method which is a member of Thread
Syntax:
final void setPriority(int level)
MIN_PRIORITY and MAX_PRIORITY
(1-10)
class TestA extends Thread {
public void run() {
System.out.println("TestA Thread started");
for (int i = 1; i <= 4; i++) {
System.out.println("\t From thread TestA
:i=" + i);
}
System.out.println("exit from TestA");
}
}
class TestB extends Thread {
public void run() {
System.out.println("TestB Thread started");
for (int j = 1; j <= 4; j++) {
System.out.println("\t From thread TestB
:j=" + j);
}
System.out.println("exit from TestB");
}
}
class TestC extends Thread {
public void run() {
System.out.println("testC Thread started");
for (int k = 1; k <= 4; k++) {
System.out.println("\t From thread TestC
:K=" + k);
}
System.out.println("exit from TestC");
}
}
public class TestThread {
public static void main(String args[]) {
TestA A = new TestA();
TestB B = new TestB();
TestC C = new TestC();
C.setPriority(10);
B.setPriority(2);
A.setPriority(1);
A.start();
B.start();
C.start();
System.out.println(" End of main thread");
}
}
Multiple Threads working on a Single Object
• Multiple threads acting on single object means two or more
threads should share the same object (same run() method)
• In this case we get unreliable results(Unsafe.java)
Thread Synchronization
Shared Resources
• If one thread tries to read the data and other thread
tries to update the same data, it leads to inconsistent
state.
• This can be prevented by synchronising access to the
data.
• Use “Synchronized” method:
public synchronized void update()
{
• …
}
644
Synchronization
t1
t2.wait till t1 comes out
mutex o
mutex or synchronization object
What can you do about it?
• synchronized is a keyword that can be
applied to a method to say that one and only
one thread will have access to this method at
a time.
public synchronized void sum() {
}
(unsafe2.java)
class Display
{
public synchronized void show(String name)
{
for(int i=0;i<5;i++)
{
System.out.println("Good Morning:");
try
{
Thread.sleep(200);
}
catch(InterruptedException e){}
System.out.println(name);
}
}
class MyThread extends Thread
{
Display d;
String name;
MyThread(Display d, String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.show(name);
}
}
class SynchronizedDemo
{
public static void main(String a[])
{
Display d=new Display();
MyThread t1=new MyThread(d,"java");
MyThread t2=new MyThread(d,"Sun");
t1.start();
t2.start();
}
}
Synchronized Blocks
Class was not created by you, but by a third
party, and you do not have access to the source
code. Thus, you can’t add synchronized to the
appropriate methods within the class. How can
access to an object of this class be
synchronized? The solution is synchronized
block
(unsafe1.java)
Deadlock of Threads
• When a thread has locked an object and waiting for another
object to be released by another thread, and the other thread is
also waiting for the first thread to release the first object, both
the threads will continue waiting forever. This is called
‘Thread deadlock’
• There is no specific solution for the problem of deadlock. It
depends on the logic used by the programmer
• (Deadlock.java, PreventDeadLock.java)
Inter Thread Communication
Inter Thread communication mechanism via the
following methods:
• wait( ): This method tells the calling thread to give
up the monitor and go to sleep until some other thread
enters the same monitor and calls notify( ).
• notify( ): This method wakes up the first thread that
called wait( ) on the same object.
• notifyAll( ): This method wakes up all the threads
that called wait( ) on the same object.c The highest
priority thread will run first.
• These methods are implemented as final methods in
Object, so all classes have them. All three methods
can be called only from within a synchronized
context
Restaurant Example: The waitperson must
wait for the chef to prepare a meal. When the
chef has a meal ready, the chef notifies the
waitperson, who then gets the meal and goes
back to waiting.
The chef represents the producer, and the
waitperson represents the consumer.
(Communicate.java,Communicate1.java)
Thread Group
A thread group represents several threads as a single group.
The main advantage of taking several threads as a group is that
by using a single method, we will be able to control all the
threads in the group
To create a thread group,
ThreadGroup tg=new ThreadGroup(“groupname”);
To add a thread to this group
Thread t1=new Thread(tg, targetobject, “threadname”);
To add another thread group to this group
ThreadGroup tg1=new ThreadGroup(tg, “groupname”)
To know parent of a thread or a thread group
Tg.getParent();
• To know the parent thread group of a thread
t.getThreadGroup()
To know number of threads actively running in a thread group
Tg.activeCount();
ThreadGroup
“Thread groups are best viewed as an
unsuccessful experiment, and you may simply
ignore their existence.”
Joshua Bloch, software architect at Sun
657
Daemon Threads
• Daemon threads are “background” threads, that provide
services to other threads, e.g., the garbage collection
thread
• The Java VM will not exit if non-Daemon threads are
executing
• The Java VM will exit if only Daemon threads are
executing
• Daemon threads die when the Java VM exits
658