Você está na página 1de 336

MODULE 1

INTRODUCTION TO JAVA
Java conceived by James Gosling, Patrick Naughton, Chris Wrath,
Ed Frank and Mike Sheridan at Sun Microsystems, inc. in 1991.
Their aim was to develop portable, platform-independent language
that could be used to produce code that would run on a variety of
CPUs under differing environments .This language was initially called
“Oak", but was renamed “Java” in 1995.
WHAT IS JAVA

• Java is a programming language, a runtime system, a set of


development tools, and an application programming interface (API).
JAVA’S MAGIC
• Java language that use predefined software packages of the Java
API. The developer compiles his or her programs using the Java
compiler. This results in what is known as compiled byte code.
Bytecode is in a form that can be executed on the Java virtual
machine, the core of the java run time system.
• JIT (Just In Time) compiler is part of JVM, that compiles bytecode
into executable code on realtime on a piece by piece demand
basis. It is not possible to compile entire program into executable
code all at once since java perform many runtime checks that can
be done only at runtime. So a JIT compiler compiles code as it is
needed, during execution.
Java’s Features
• Simple
• Secure
• Portable
• Object Oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High Performance
• Distributed
• Dynamic
Byte Code and Java Virtual Machine

• Existing Development Environment

Binary
File

Compiler(Pentium) Pentium

Source Binary
Code File

Compiler(PowerPC) PowerPC

Binary
%cc Hello.c –o Hello File
% Hello
Compiler(SPARC) SPARC

Run Binary
Code
Bytecodes and the Java Virtual Machine

• Java Development Environment

Java
Interpreter
Java Compiler
(Pentium) Pentium
Java Java
Java
Code ByteCode
Interpreter
(Independent on
Java Compiler Platform)
PowerPC
(PowerPC)
Java
/>javac Hello.java Interpreter
Hello.class created

/> java Hello Java Compiler SPARC


(SPARC)
Run JVM Byte
Code
Garbage Collection
• Dynamically allocated objects automatically released in java.
When no reference to an object exists, that object is assigned
to be no longer needed and the memory occupied by the object
can be reclaimed.
• Garbage collection occurs during the execution of program
• When an object no longer has any valid references to it, it can
no longer be accessed by the program
• It is useless, and therefore called garbage
• Java performs automatic garbage collection periodically,
returning an object's memory to the system for future use
JAVA SAMPLE PROGRAM

class Example{
public static void main(String args[ ]) {
System.out.println (“First Program”);
}
}
//Call this file as Example.java
Compiling the Program
 To compile the Example program, execute the compiler, javac,
specify the name of the source file on the command line
C:\> javac Example.java
The javac compiler creates a file called Example.class that
contains the bytecode version of the program. The byte code is
the intermediate representation of the program that contains
instructions the JVM will execute.
 To actually run the program, we must use the java application
launcher called java
C:\> java Example
 When the program is run, the following output is displayed
First Program
Platform Independent

Platform Independent

javac Example.class
Example.java
Java source code bytecode
JVM

OS/Hardware
CLOSER LOOK AT PROGRAM

• The keyword class is used to declare that a new class is


being declared
• Example is an identifier that is the name of the class
• public-access specifier
• static-allows main() to be called without having to instantiate
a particular instance of the class
• main()-This is the line at which the program will begin
executing
• String args[ ]-declares a parameter named args ,which is an
array of instances of the class String
• args- receives any command line arguments
System.out.println

• System-is a predefined class that provides access to the


system.out is a variable in this class
• out-is the output stream that is connected to the console
• println()-method in the output stream.
can be used to output values of any of java’s built-in types
Module 2
CLASS
• A class is that it defines a new data type. Once defined this
new type can be used to create objects of that type.
• A class is a template for an object and an object is an instance
of a class
General Form
class classname{
type instance variable1;
type instance variable2;
…………………………….
type methodname(parameterlist){
body
}
}
 The data or variables defined within a class are called instance
variables because each instance of the class contains its own
copy of these variables.
 The code is contained within methods
 Methods and variables defined within a class are called
members of the class
Parameter and Arguments
 A parameter is a variable defined by a method that receives a
value when the method is called.
 An argument is a value that is passed to a method when it is
invoked.
Method
Method
General Form
type name(parameterlist) {
body
}
 type –the type of the data returned by the method .If the method doesn’t return
any value, it's return type is void
return value;
value is the value returned
 name-name of the method
 parameterlist -is a sequence of type and identifier pair separated by commas
Method Modifiers

• public: anyone can access public methods.


• protected: only methods of the same package or of subclasses can
access protected method.
• private: only methods of the same class (not methods of a subclass)
can access a private method.
• friendly: default, can only be called by objects of classes in the
same package.
• abstract: no code. Abstract methods may only appear within an
abstract class.
public abstract void setHeight (double newHeight);
• static: is associated with the class, not with specific instances of the
class.
– Static methods can be used to change the state of static
variables associated with a class.
• final: cannot be overridden by a subclass.
Constructor
 A constructor initializes an object immediately upon creation. It
has the same name as the class in which it resides and is
syntactically similar to a method
 Once defined, the constructor is automatically called immediately
after the object is created, before the new operator completes.
 Constructor have no return type, not even void
 This is because the implicit return type of a class constructor is
the class itself
 When we do not explicitly define a constructor for a class, then
java creates a default constructor for the class. The default
constructor automatically initializes all instance variables to zero.
Once we define our own constructor, the default constructor is
no longer used
this keyword

 this keyword can be used inside any method to refer to the


current object. this is always a refer to the invoking object
 If we use the same name for local variables and instance
variables ,the local variables hides the instance
variables.To overcome the instance variable hiding we use
this

finalize()

 Inside this method we will specify those actions that must be


performed before an object is destroyed
 protected void finalize() {
……………………………
……………………………
}
• Declaring Java Class
• Basic syntax of a Java Class
< modifier> class < name> {
< attribute_declaration>*
< constructor_declaration>*
< method_declaration>*
}
The < name> can be any legal identifier. It is the name of the class
being declared. There are several possible < modifier> (private,
public or protected) but for now, use only public; this declares that
the class is accessible to the universe. The body of the class
declares the set of data attributes, constructors, and methods
associated with the class.
Note: * here means 0 or more
Example
public class Book
{
private String bookName; //declare variable
public Book (String inputName) //declare constructor
{
bookName = inputName;
}
public String getBookName() //declare method
{
return bookName;
}
}
Variables

• A variable is defined by the combination of an identifier , a type ,


and an optional initializer
• Basic form
– type identifier [=value] ;
– Type-name of the class/interface
– Identifier – name of the variable
– We can initialize the variable by specifying an equal sign
and a value
Variable Modifiers
• public: anyone can access public instance variables.
• protected: only methods of the same package or of
subclasses can access protected instance variables.
• private: only methods of the same class (not methods of a
subclass) can access private instance variables.
• friendly: default, can be accessed by any class in the
same package.
• static: declare a variable that is associated with the class,
not with individual instances of the class.
– Static variables are used to store “global” information
about a class.
– Static variables exist even if no instance of their class
is created.
• final: must be assigned an initial value, and then can
never be assigned a new value after that.
– If it is a base type, then it is a constant.
– If it is an object variable, then it will always refer to the
same object.
Declaring Variables
Basic Syntax of a variable

<modifier> <type> <name> = <default_value>;

The part in red is optional

<type> can be datatype or <class name>:

• Example
public class Book
{
private String bookName = “No Name”; //declare variable
public int bookId; //Default value
private double float = 0.0;
}
Declaring Methods
• Basic Syntax of a method
< modifier> <return_type> <name> (<parameter>*) {
< statement>*
}
the format of < parameter> is
< parameter_type> <parameter_name>,
• Example
public class Book {
private String bookName; //declare variable
public void setBookName (String newName)
{bookName = newName;}
public String getBookName() //declare method
{return bookName;}
}
Declaring Objects
 Book javaBook=new Book()
 new operator dynamically allocates (at run time)
memory for an object and returns a reference to it.
This reference is more or less the address in memory
of the object allocated by new. This reference is then
stored in the variable.
 Advantage - can create as many or as few objects as
it needs during the execution of the program.

Important Thing About Returning values

 The type of data returned by a method must be


compatible with the return type specified by a method
 The variable receiving the value returned by a method
must also be compatible with the return type specified
for the method
• Access Object Members
The ‘dot’ notation: <object>.<member>
• This is used to access object members including variables and
methods
• Examples
javaBook.setBookName ( “New Book Name”);
javaBook.bookId = 123; //only permissible if x is public
MODULE 3
Comments
/* This kind of comment can span multiple lines */
// This kind is to the end of the line
/**
* This kind of comment is a special
* ‘javadoc’ style comment
*/

Comments should contain only information that is relevant to


reading and understanding the program

Doc comments can be extracted to HTML files using the


javadoc tool.
Identifiers and Keywords

Identifiers are used to name Java language entities ( class,


methods, variables, member variables etc) . They begin with a
Unicode letter, underscore character (_), or dollar sign ($).
Subsequent characters consist of these characters and the
digits 0–9. Identifiers are case sensitive, and cannot be the
same as a reserved word or the boolean values True or False or
the null value. Avoid using the dollar sign character; it is
intended for use by compiler-generated identifiers.

Valid Identifiers – MyIdentifier, $MyIdentifier, My_Identifier, My_Identifier1


Invalid Identifiers – My Identifier, My-Identifier, 1MyIdentifier
KEYWORDS
• There are 50 keywords defined in the java language .These
keywords combined with the syntax of the operators and separators
form the foundation of the java language. These keywords cannot
be used as names for a variable,class or method.
abstract double int super
boolean else interface switch
break extendslong synchronized
byte final native this
case finally new throw
catch float package throws
char for private transient*
class goto* protected try
const* if public void
continue implements return volatile
default import short while
do instanceof static strictfp
assert enum
PRIMITIVE TYPES
• Variables
• Types
– char 16bits Unicode character data
– boolean Boolean Variable
– byte 8 bits signed integer
– short 16 bits signed integer
– int 32 bits signed integer
– long 64 bits signed integer
– float 32 bits signed floating point number
– double 64 bits signed floating point number
Integers
 1.Byte-signed 8 bit type ( Range -128 to 127)
 2. short-signed 16 bit (Range -32768 to 32767)
 3. int-signed 32 bit type( Range -2,147,483,648 to 2,147,483,647
 4.long-signed 64 bit type

Floating Type
• Floating point numbers ,also known as real numbers,are used when evaluating
expressions that require fractional precision
• 2 types
• float-single precision value that uses 32 bit of storage
• double-double precision value that uses 64 bit of storage
– Faster than single precisions
Characters

• Is a 16 bit type
• Range is 0 to 65536
• No negative chars

Boolean
• Only two possible values-true and false
• This the type returned by all relational operators
• This is the type required by the conditional expressions that
govern the control statements such as if and for
Variables
• A variable is defined by the combination of an identifier , a type ,
and an optional initializer
• Basic form
– type identifier [=value] ;
– Type-name of the class/interface
– Identifier – name of the variable
– We can initialize the variable by specifying an equal sign and
a value

varName=value; float x, y, x;

Value assignments int num = 100;


long m = 21234234L
varName = value; double type : .5 0.8 9e-2 -9.3e-5
float type : 1.5e-3f;
Example for assigning value

Primitive types are special data types built into the


language; they are not objects created from a class.
A literal is the source code representation of a fixed
value; literals are represented directly in your code
without requiring computation.

boolean result = true;


char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;
int decVal = 26; // The number 26, in decimal
int octVal = 032; // The number 26, in octal
int hexVal = 0x1a; // The number 26, in hexadecimal
Literals
• A literal is any “constant” value that can be used in an assignment
or other expression.
– The null object reference (this is the only object literal)
– Boolean: true and false
– Integer: 176, -52, 176L, -52L
– Floating point: 3.1415, 3.1415F, 2.14E2
– Character: ‘a’ or ‘?’
• Special character constants: ‘\n’, ‘\t’,’\b’, ‘\r’, ‘\f’, ‘\\’, ‘\’’, ‘\”’
– String literals: “dogs all around” or “jump”
NAMING CONVENTION

Naming conventions make programs more understandable


by making them easier to read. They can also give
information about the function of the identifier-for example,
whether it's a constant, package, or class-which can be
helpful in understanding the code.

Classes
Class names should be nouns, in mixed case with the first letter of
each internal word capitalized. Try to keep your class names simple
and descriptive.
Example : class Student, class NameReader

Interfaces
Interface names should be capitalized like class names.

Example : interface Grade


Methods
Methods should be verbs, in mixed case with the first letter
lowercase, with the first letter of each internal word
capitalized.

Example :run(), runFast(), getBackground()

Variables
Except for variables, all instance, class, and class constants are in
mixed case with a lowercase first letter. Internal words start with
capital letters. Variable names should not start with underscore _
or dollar sign $ characters, even though both are allowed.
Variable names should be short yet meaningful. The choice of a
variable name should be mnemonic- that is, designed to indicate to
the casual observer the intent of its use. One-character variable
names should be avoided except for temporary "throwaway"
variables. Common names for temporary variables are i, j, k, m,
and n for integers; c, d, and e for characters.
Example :int i; char c; float myWidth;
Constants

The names of variables declared class constants and of ANSI


constants should be all uppercase with words separated by
underscores ("_"). (ANSI constants should be avoided, for ease of
debugging.)

Example
static final int MIN_WIDTH = 4; static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;
Example :Class containing primitive data elements

class Number
{
public static void main(String args[ ])
{
private int num1=5, num2;
System.out.println(“ Number 1 = “ + num1);
}
}
//Save the file as Number.java
Example :Declaring Class objects

class Box {
double width;
double height;
double depth; }
class BoxDemo {
public static void main (String args[]) { double vol;
Box mybox = new Box();
mybox.width=10; mybox.height = 20; mybox.depth = 10;
vol = mybox.width*mybox.height*mybox.depth;
System.out.println (“Volume is “+vol);
}
}
MODULE 4
Flow of Control

• Branching
• Loops
• exit(n) method
• Boolean data type and expressions
What is “Flow of Control”?

• Flow of Control is the execution order of instructions in a


program
• All programs can be written with three control flow elements:
1. Sequence - just go to the next instruction
2. Selection - a choice of at least two
• either go to the next instruction
• or jump to some other instruction
3. Repetition - a loop (repeat a block of code)
at the end of the loop
• either go back and repeat the block of code
• or continue with the next instruction after the block
• Selection and Repetition are called Branching since these are
branch points in the flow of control
Java Flow Control Statements

Sequence Branching: Selection


• the default • if
• Java automatically executes • if-else
the next instruction unless you • if-else if-else if- … - else
use a branching statement • switch

Branching: Repetition
• while
• do-while
• for
Definition of Boolean Values

• Branching: there is more than one choice for the next instruction
• Which branch is taken depends on a test condition which evaluates
to either true or false
• In general:
if test is true then do this, otherwise it is false, do something else
• Variables (or expressions) that are either true or false are called
boolean variables (or expressions)
• So the value of a boolean variable (or expression) is either
true or false
• boolean is a primitive data type in Java
Boolean Expressions

• Boolean expressions can be thought of as test conditions


(questions) that are either true or false
• Often two values are compared
• For example:
Is A greater than B?
Is A equal to B?
Is A less than or equal to B?
etc.
• A and B can be any data type (or class), but they should be the
same data type (or class)
Java Comparison Operators

Math
Compound Boolean Expressions

• Use && to AND two or more conditions


(returns true if both conditions are true)
• Use || to OR two or more conditions
(returns true if any of the conditions are true
• Use ! to NOT ( negate the value )
• For example, write a test to see if B is either 0 or between the
values of B and C :
(B == 0) || (A <= B && B < C)
• In this example the parentheses are not required but are added for
clarity
– Use a single & for AND and a single | for OR to avoid short-
circuit evaluation and force complete evaluation of a boolean
expression
Java if statement

• Simple selection
• Do the next statement if test is true or skip it if false
• Syntax:
if (Boolean_Expression)
Action if true;//execute only if true
next action;//always executed
• Note the indentation for readability (not compile or execution
correctness)
if Example

if(eggsPerBasket < 12)


//begin body of the if statement
System.out.println(“Less than a dozen eggs per basket”);
//end body of the if statement
totalEggs = numberOfEggs * eggsPerBasket;
System.out.println(“You have a total of + totalEggs + “ eggs.”);

• The body of the if statement is conditionally executed


• Statements after the body of the if statement always execute
Java Statement Blocks:
Compound Statements
• Action if true can be either a single Java statement or a set of
statements enclosed in curly brackets (a compound statement, or
block)
• For example:
All statements between
if(eggsPerBasket < 12) braces are controlled by if
{ //begin body of the if statement
System.out.println(“Less than a dozen ...”);
costPerBasket = 1.1 * costPerBasket
} //end body of the if statement

totalEggs = numberOfEggs * eggsPerBasket;


System.out.println(“You have a total of “+ totalEggs + “ eggs.”);
Two-way Selection: if-else
• Select either one of two options
• Either do Action1 or Action2, depending on test value
• Syntax:
if (Boolean_Expression)
{
Action1 //execute only if true
}
else
{
Action2//execute only if false
}
Action3//always executed
if-else Examples
• Example with single-statement blocks:
if(time < limit)
System.out.println(“You made it.”);
else
System.out.println(“You missed the deadline.”);

• Example with compound statements:


if(time < limit) {
System.out.println(“You made it.”);
bonus = 100;
}
else {
System.out.println(“You missed the deadline.”);
bonus = 0;
}
Multibranch selection:
if-else if-else if-…-else
• One way to handle situations with more than two possibilities
• Syntax:
if(Boolean_Expression_1)
Action_1
else if(Boolean_Expression_2)
Action_2
.
.
.
else if(Boolean_Expression_n)
Action_n
else
Default_Action
if-else if-else if-…-else Example

if(score >= 90)


grade = ‘A’);
else if (score >= 80)
grade = ‘B’;
else if (score >= 70)
grade = ‘C’;
else if (score >= 60)
grade = ‘D’;
else
grade = ‘E’;
Multibranch selection:
switch

• Another way to program multibranch selection


• Controlling_Expression must be char, int, short or
byte
• Controlling Expression and Case_Label must be same
type
• When a break statement is encountered, control goes to the
first statement after the switch.
Multibranch selection:
switch
• break may be omitted
switch(Controlling_Expression)
{
case Case_Label:
statements
… Can be any number of
break; cases like this one.
case Case_Label:
statements

break;
default:
statements Default case is optional.

break;
}
switch Example

switch (seatLocationCode)
{
case 1: System.out.println(“Orchestra”);
price = 40.00;
break;
case 2: System.out.println(“Mezzanine”);
price = 30.00;
break;
case 3: System.out.println(“Balcony”);
price = 15.00;
break;
default: System.out.println(“Unknown seat code”);
break;
}
Repetition: Loops
• Structure:
– Usually some initialization code
– body of loop
– loop termination condition
• Several logical organizations
– counting loops
– sentinel-controlled loops
– infinite loops
– minimum of zero or minimum of one iteration
• Several programming statement variations
– while
– do-while
– for
while Loop
• Syntax:
while(Boolean_Expression)
{
//body of loop Something in body of loop
First_Statement; should eventually cause
Boolean_Expression to be
...
false.
Last_Statement;
}
• Initialization statements usually precede the loop.
• Boolean_Expression is the loop termination condition.
• May be either counting or sentinel loop
– Good choice for sentinel loop
while : a counting loop example
• A loop to sum first 10 natural numbers

//Loop initialization
int count = 1;
int total =0;
while(count <= 10) //Loop termination condition
{ //Body of loop

total = total + count;


count++; //Loop termination counter
}
while
a sentinel controlled loop example
• A loop to sum positive integers entered by the user
• next is the sentinel
• The loop terminates when the user enters a negative number
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ir); //will study later
//Initialization
int next = 0;
int total = 0;
while(next >= 0) //Termination condition
{ //Body
total = total + next;
next = Integer.parseInt(br.readLine( ));
}
while: A Minimum of Zero Iterations

• Because the first input value read and the test precedes the loop,
the while loop body may not execute at all
//Initialization
int next = 0;
int total = 0;
while(next >= 0)//Termination condition
{ //Body
total = total + next;
next = SavitchIn.readLineInt();
}
• since the first number is zero the loop body never executes
do-while Loop

• Syntax
do
Something in body of loop
{ //body of loop should eventually cause
First_Statement; Boolean_Expression to be
... false.
Last_Statement;
} while(Boolean_Expression);
• Initialization code may precede loop body
• Loop test is after loop body so the body must execute at least
once (minimum of at least one iteration)
• May be either counting or sentinel loop
– Good choice for sentinel loop
do-while Example

int count = 1;
int number = 10;
do //Display integers 1 - 10 on one line
{
System.out.print(count + “ “ );
count++;
}while(count <= number);

• Note System.out.print() is used and not System.out.println()


so the numbers will all be on one line
for Loop
• Good choice for counting loop
• Initialization, loop test, and loop counter change are part of the
syntax
• Syntax:
for(Initialization; Boolean_Expression; After_Loop_Body)
loop body;
Execution sequence:
1. Initialization - executes only once, before the loop body is
executed the first time
2. Boolean_Expression - the loop test
3. loop body - execute only if loop test is true
4. After_Loop_Body - typically changes the loop counter
5. Boolean_Expression - Repeat the loop test (step 2), etc.
The exit Method
• If you have a program if (userIn == 'e')
situation where it is pointless System.exit(0);
to continue execution you else if (userIn == 'c')
can terminate the program
with the exit(n) method {
• n is often used to identify if //statements to do work
the program ended normally }
or abnormally else
• n is conventionally 0 for {
normal termination and non- System.out.println("Invalid entry");
zero for abnormal termination
//statements to something
appropriate
}
Some Practical Considerations
When Using Loops
• The most common loop errors are unintended infinite loops and
off-by-one errors in counting loops
• Sooner or later everyone writes an unintentional infinite loop
– To get out of an unintended infinite loop enter ^C (control-C)
• Loops should tested thoroughly, especially at the boundaries of
the loop test, to check for off-by-one and other possible errors

Tracing a Variable in a Loop


• Tracing a variable: print out the variable each time through the loop
• A common technique to test loop counters and troubleshoot off-by-one and other
loop errors
• If no built-in utility is available, insert temporary output statements to print values.
The Type boolean
• A primitive type
• Can have expressions, values, constants, and variables just as with
any other primitive type
• Only two values: true and false
• Can use a boolean variable as the condition in an if statement
• Using a boolean variable as the condition can make an if statement
easier to read by avoiding a complicated expression.

if (systemsAreOK)
System.out.println(“Initiate launch sequence.”);
else
System.out.println(“Abort launching sequence”);
boolean Variables in Assignments
• A boolean expression evaluates to one of the two values true or
false.
• The value of a boolean expression can be assigned to a boolean
variable:
int number = -5; Parentheses are not
boolean isPositive; necessary here.
isPositive = (number > 0);
if (isPositive) Parentheses are necessary here.
System.out.println(“positive”);
else
System.out.println(“negative or zero”);

• There are simpler and easier ways to write this small program, but
boolean variables are useful in keeping track of conditions that
depend on a number of factors.
Truth Tables for boolean Operators

&& (and) || (or)


Value of A Value of B A && B Value of A Value of B A || B
true true true true true true
true false false true false true
false true false false true true
false false false false false false

! (not)

Value of A !A
true false
false true
Precedence

An example of using precedence rules to see which operators in


following expression should be done first:
score < min/2 – 10 || score > 90
• Division operator has highest precedence of all operators used here
so treat it as if it were parenthesized:
score < (min/2) – 10 || score > 90
• Subtraction operator has next highest precedence :
score < ((min/2) – 10) || score > 90
• The < and > operators have equal precedence and are done in left-
to-right order :
(score < ((min/2) – 10)) || (score > 90)
• The last expression is a fully parenthesized expression that is
equivalent to the original. It shows the order in which the operators in
the original will be evaluated.
Precedence Rules

Highest Precedence
• First: the unary operators: +, -, ++, --, and !
• Second: the binary arithmetic operators: *, /, %
• Third: the binary arithmetic operators: +, -
• Fourth: the boolean operators: <, >, =<, >=
• Fifth: the boolean operators: ==, !=
• Sixth: the boolean operator &
• Seventh: the boolean operator |
• Eighth: the boolean operator &&
• Ninth: the boolean operator ||
Lowest Precedence
Short-Circuit Evaluation

• Short-circuit evaluation—only evaluating as much of a boolean


expression as necessary.
• Example:

if ((assign > 0) && ((total/assign) > 60))


System.out.println(“Good work”);
else
System.out.println(“Work harder.”);
• If assign > 0 is false, then the complete expression cannot be
true because AND is only true if both operands are true.
• Java will not evaluate the second part of the expression.
• Short-circuit evaluation prevents a divide-by-zero exception when
assign is 0.
The break Statement

• It is used to “break” out of the innermost switch, for, while, or


do-while statement body.
• The break statement can also be used in a labeled form to
jump out of an outer-nested loop or switch statement.
boolean foundFlag = false;
zeroSearch:
for (int i=0; i<a.length; i++) {
for (int j=0; j<a[i].length; j++) {
if (a[i][j] == 0) {
foundFlag = true;
break zeroSearch;
}
}
}
The continue Statement
• Syntax: continue [<label>];
• The continue statement can only be used inside loops.
• The continue statement causes the execution to skip over the
remaining steps of the loop body in the current iteration.
boolean foundFlag = false;
zeroSearch:
for (int i=0; i<a.length; i++) {
for (int j=0; j<a[i].length; j++) {
if (a[i][j] == 0) {
foundFlag = true;
System.out.println(“Row “ + i +”Column” +j );
continue zeroSearch;
}
}
}
MODULE 5
Arrays
An array is a fixed size sequential collection of elements of
identical types.
They are created with either a new operator or array initializes
The storage space for arrays is allocated from the garbage-
collected heap.
The element in an array are indexed by the integers 0 to n- 1,
where n is the size of the array.
Array Characteristics
• List of values.
• A list of values where every member is of the same type.
• Each member in an array is called an element.
• Each array has a variable name associated with it.
• Each element in an array has an index.
• Indexing always starts with zero.
Array Syntax
• Declaring – Allocates an array variable.
• Creating – Allocates space for the elements and fills the array variable with
the address of the first element.
• Initializing – Filling the elements with initial values.
• Populating – adding elements to an Array.

Declaring an Array
• int [] scores ;
– Allocates a variable that can “point” to an array of integers
– Array variables declared but not created have a value of NULL
Inspecting a declared array

Creating an Array
• int [] values = new int[6] ;
• Default values for integer arrays - zero
Creating, Initializing and
Populating an array

• After an array is declared:


– scores = new int [6] ; //create
– scores = {3,5,6,7,4,3}; // initialize
– Using a loop with a variable for the index to
populate an array.
Declaring, Creating, Initializing
• int [] scores = new int [6] ;
• scores = {23, 34, 55, 64, 23, 21};
• int[] scores = {23, 34, 55, 64, 23, 21};

Accessing Elements
• int grade = scores[index] ;
• where index represents the specific element.
Accessing Elements
• int grade = scores[index] ;
• where index represents the specific element.

Number of elements in any array


• System.out.println(numbers.length);
• Note - NO parentheses

Code to copy arrays


for (index = 0 ; index<ar1.length;index++) {
ar2[index]=ar1[index];
}
THE JAVA LIBRARY
String Handling
String Basics
• String is a sequence of characters
• Java implements Strings as objects of type String
• When we create a String object, you are created a string that
cannot be change the characters that comprise that string
• When we need an altered version of an existing string, a new
string object is created that contains the modifications.Th original
string is left unchanged
• A variable declared as a string refernce can be changed to point
at some other String object
String Constructors
• String s=new String() -will create an instance of String with no
characters in it.

• String(char chars[]) - to create a String initialized by an array of


characters

• String(char chars[], int startIndex,int numChars) – startIndex


specifies the index at which the subrange begins, and numChars
specifies the number of characters to use

• String(String strObj) – we can construct a String character


sequence as another string object
String Length
 The length of a string is the number of characters that it contains
 To obtain this value,call the length() method
 Syntax - int length()

String Literals
 For each string literals in our program, java automatically
constructs a String object
 String s2=“abc”;
OR
 char chars[]={‘a’,’b’,’c’};
String s1=new String(chars);
String Concatenation

 + operator concatenates two strings, producing a string object as


the result
 To break a long string into smaller pieces, use the + to
concatenate them
 To concatenate strings with other data types use + operator to
concatenate them

String Comparison
 equals() – to compare two strings for equality. It returns true if the
strings contain the same characters in the same order, and else
false.The comparsion is case sensititve
 equalsIgnoreCase() – to perform a comparison that ignores case
differences
• regionMatches() – compares a specific region inside a string
with another specific region in another string
• startsWith() and endsWith() – startsWith() method determines
whether a given string begins with a specified string. endsWith()
determines whether the string in question ends with a specified
string.
• == - compares two object references to see whether they refer
to the same instance
• compareTo() – compares whether two strings are identical. A string is
less than another if it comes before the other in dictionary order. A
string is greater than another if it comes after the other in dictionary
order
• compareToIgnoreCase()-case difference are ignored
Searching Strings

Searching Strings
• indexOf() – searches for the first occurrence of a character
or substring
• lastIndexOf()- searches for the last occurrence of a character
or substring
Modifying a String
• concat()-concatenate two strings.performs the same function
as +
• replace()-replaces all occurrences of one character in the
invoking string with another character
• trim()-returns a copy of the invoking string from which any
leading and trailing white space.
Additional String Methods
• toLowerCase()-converts all the characters in a string
from uppercase to lowercase
• toUpperCase()-converts all the characters in a string
from lowercase to uppercase
• valueOf()- converts data from its internal format into a
human- readable form

StringBuffer
• Represents growable and writeable character
sequences
• StringBuffer()
• StringBuffer(int size)
• StringBuffer(String str)
• StringBuffer(CharSequence chars)
StringBuffer
• Represents growable and writeable character sequences
• StringBuffer()
• StringBuffer(int size)
• StringBuffer(String str)
• StringBuffer(CharSequence chars)

String Methods
• length() – gives the current length of a StringBuffer
• capacity()- total allocated capacity can be found through this
method
• charAt()- the value of a single character can be obtained from a
StringBuffer
• setCharAt()-we can set the value of a character within a
StringBuffer
• getChars() – to copy a substring of a StringBuffer into an array
• append() – concatenates the string representation of any other
type of data to the end of the invoking StringBuffer object
• insert() – inserts one string into another
• reverse() – reverse the characters within a StringBuffer object
• delete() – deletes a sequence of characters from the invoking
object
• deleteCharAt() – deletes the character at the index specified by
location.
• replace() – replace one set of characters with another set
inside a StringBuffer object
• substring() – obtain a portion of a StringBuffer
MODULE 6
Inheritance
• Inheritance allows a software developer to derive a new class from
an existing one
• The existing class is called the parent class, or superclass, or base
class
• The derived class is called the child class or subclass.
• As the name implies, the child inherits characteristics of the parent
• In programming, the child class inherits the methods and data
defined for the parent class

100
Inheritance
• Inheritance relationships are often shown graphically, with the arrow
pointing to the parent class:

Vehicle

Car

• Inheritance should create an is-a relationship, meaning the child is-a


more specific version of the parent

101
Using Inheritance
•Inheritance describes relationships where an instance of the subclass is
a special case of the superclass
–Called "is a" relationships because the subclass "is a" special case
(specialization) of the superclass
•e.g.: A floating point number is a number. A number is an object.
•Inheritance cannot describe "has a" relationships
–This is usually done using the class' fields and their associated
methods
•e.g., A floating point number has a sign, a radix and a mantissa
–Collections provide generalized ways to handle “has a” relations
Float

sign radix mantissa


Multiple Inheritance
•Java does not support multiple inheritance
–Every Java class except Object has exactly one immediate
superclass (Object does not have a superclass)
–You can force classes that are not related by inheritance to implement a
common set of methods using interfaces

Dad
Interface
MomClass DadClass MomClass

BabyClass BabyClass
Inheriting Fields and Methods
•Each subclass inherits the fields of its superclass
–These fields may have been inherited from Object
classes further up in the hierarchy equals(Object)
•Each subclass inherits the methods of its
superclass
–An object will understand all messages its class Number
or superclass has inherited or implemented byteValue()
doubleValue()
Integer zero = new Integer(0); floatValue()
if (zero.equals(x)) { intValue()
byte b = zero.byteValue(); longValue()
… shortValue()
}

Integer
Access Modifiers
•Variables and methods in Java have access restrictions, described by the
following access modifiers:
–private:
•Access is limited to the class in which the member is declared
•Example: private int x;
–default (this means no modifier is used):
•Access is limited to the package in which the member is declared
•Example: int x;
–protected:
•Access is limited to the package in which the member is declared, as
well as all subclasses of its class
•Example: protected void setName() { . . . }
–public:
•The member is accessible to all classes in all packages
•Example: public String getName() { . . . }
Deriving Subclasses
In Java, the reserved word extends is used to establish
an inheritance relationship

class Car extends Vehicle {


// class contents
}

The protected Modifier


• The visibility modifiers determine which class members get inherited
and which do not
• Variables and methods declared with public visibility are inherited,
and those with private visibility are not
• But public variables violate our goal of encapsulation
• The protected visibility modifier allows a member to be inherited,
but provides more protection than public does 106
The super Reference
• Constructors are not inherited, even though they have public
visibility
• Yet we often want to use the parent's constructor to set up the
"parent's part" of the object
• The super reference can be used to refer to the parent class,
and is often used to invoke the parent's constructor

Defined vs. Inherited


• A subtle feature of inheritance is the fact that even if a method or
variable is not inherited by a child, it is still defined for that child
• An inherited member can be referenced directly in the child class,
as if it were declared in the child class
• But even members that are not inherited exist for the child, and can
be referenced indirectly through parent methods
107
Overriding Methods
• A child class can override the definition of an inherited method
in favor of its own
• That is, a child can redefine a method it inherits from its parent
• The new method must have the same signature as the parent's
method, but can have different code in the body
• The object type determines which method is invoked

The super Reference Revisited


• The super reference can be used to invoke any method from the
parent class
• This ability is often helpful when using overridden methods
• The syntax is:
super.method(parameters)
108
Overloading vs. Overriding
• Don't confuse the concepts of overloading and overriding
• Overloading deals with multiple methods in the same class with the
same name but different signatures
• Overriding deals with two methods, one in a parent class and one in
a child class, that have the same signature
• Overloading lets you define a similar operation in different ways for
different data
• Overriding lets you define a similar operation in different ways for
different object types

109
Class Hierarchies

•Every object belongs to a class


–The objects that are members of a
class are its instances Object
extends
•Every class (except Object) has a
superclass
–In Java, Object is the root of the Number
entire class hierarchy
extends

•When defining new classes, the


developer must decide which class is
Integer
the appropriate superclass
instantiates

Integer zero = new Integer(0);


Class Hierarchy Example
•Object-oriented systems allow classes to be defined in terms of other
classes

•Mountain bikes, racing bikes, and tandems are all different kinds of
bicycles, so they are all subclasses of the bicycle class

•The superclass is the bicycle


class

•Subclasses inherit variables


and methods from the
superclass
Class Hierarchies
• Two children of the same parent are called siblings
• Good class design puts all common features as high in the
hierarchy as is reasonable
• Class hierarchies often have to be extended and modified
to keep up with changing needs
• There is no single class hierarchy that is appropriate for all
situations

The Object Class


• All objects are derived from the Object class
• If a class is not explicitly defined to be the child of an existing class,
it is assumed to be the child of the Object class
• The Object class is therefore the ultimate root of all class
hierarchies
• The Object class contains a few useful methods, such as
toString(), which are inherited by all classes 112
References and Inheritance
• An object reference can refer to an object of its class, or to an object
of any class related to it by inheritance
• For example, if the Holiday class is used to derive a child class
called Christmas, then a Holiday reference could actually be
used to point to a Christmas object:
Holiday day;
day = new Christmas();
• Assigning a predecessor object to an ancestor reference is
considered to be a widening conversion, and can be performed by
simple assignment
• Assigning an ancestor object to a predecessor reference can also
be done, but it is considered to be a narrowing conversion and must
be done with a cast
• The widening conversion is the most useful
113
Specialization and
Generalization
Object
•A subclass is a specialization
equals(Object)
of its superclass
–Specialize the state and
behavior by adding fields and
extending or changing methods Number
byteValue()
•A superclass is a generalization of
doubleValue()
its subclasses
floatValue()
–Common state and behavior can
intValue()
be moved to the superclass
longValue()
where it is available to all
shortValue()
subclasses
–Only needs to be written once

Integer Float Byte


Overriding Methods
–Subclasses are not limited to the state and behavior of their
superclass
–You can extend or change superclass behavior by overriding the
inherited method in the subclass
–To override a superclass‘s method, create a new method in the
subclass with the same name and parameter list (signature)
–The new method will be used and replaces or refines the method of
the same name in the superclass
public class MyClass extends Object {
public boolean equals(Object o) {
if (o==null)

}
}
Method Lookup
When a method is invoked, the lookup begins in the object's class
definition

If the method is not found in the object's own class, the search
continues in the superclass and up the hierarchy until it is found

When the method is found, it will be invoked on the object to


which the method was passed

If the method was never implemented in any of the classes in the
hierarchy, an error is issued at compile time
Inheritance and Static Methods
A class can use all the static methods that are defined in its superclass as though
they were defined in the class itself

Static methods cannot be overridden

superclass
static String t = "test";
public static String superTest(String s) {
s += " was the arg.";
return s;
}

subclass
public static void main(String[] args){
System.out.println(superTest(t));
}
Inheritance and Constructors
•Only constructors within the class being instantiated and within the
immediate superclass can be invoked
•Constructors in the superclass are invoked with the keyword super and
the parameter list
–The parameter list must match that of an existing constructor in the
superclass
•Constructors in the same class are invoked with the keyword this and
the parameter list
•The first line of your constructor can be one of:
– super(…);
– this(…);
The Superclass in Object
Construction
• Superclass objects are built before the subclass
–The compiler supplies an implicit super() call for all constructors

•super(…) initializes superclass members

•If the first line of your constructor is not a call to another constructor,
super() is called automatically
–Zero argument constructor in the superclass is called as a result
–This can cause an error if the superclass does not have a zero-
argument constructor
Default Constructors

•If you do not provide any constructors, a default zero-argument


constructor is provided for you

•If you implement any constructor, Java will no longer provide you with
the default zero-argument constructor
–You can write your own zero-argument constructor which behaves
like the default constructor (makes an implicit call to super())
More on this and super
• this and super can be used in instance methods and
constructors in Java
–They cannot be used in class (static) methods
• The keyword super lets you use code from a superclass when
you are overriding a method
• this and super affect method look-up
–this: method look-up starts in the current class
–super: method look-up starts in the immediate superclass
Wrapper Classes

• The java.lang package contains wrapper classes


that correspond to each primitive type:
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
void Void
• The following declaration creates an Integer object which represents
the integer 40 as an object

Integer age = new Integer(40);

• An object of a wrapper class can be used in any situation where a


primitive value will not suffice

• For example, some objects serve as containers of other objects

• Primitive values could not be stored in such containers, but wrapper


objects could be
• Wrapper classes also contain static methods that help manage
the associated type
• For example, the Integer class contains a method to convert an
integer stored in a String to an int value:
num = Integer.parseInt(str);
• The wrapper classes often contain useful constants as well
• For example, the Integer class contains MIN_VALUE and
MAX_VALUE which hold the smallest and largest int values
Autoboxing

• Autoboxing is the automatic conversion of a primitive value to a


corresponding wrapper object:

Integer obj;
int num = 42;
obj = num;

• The assignment creates the appropriate Integer object

• The reverse conversion (called unboxing) also occurs automatically


as needed
Number Class

• Abstract Class
• Super Class of Integer, Long, Float, Double
• Method
– abstract int intValue() : Convert into int type
– abstract long longValue() : Convert into long type
– abstract float floatValue() : Convert into float type
– abstract double doubleValue() : Convert into double type
Integer Class

• Constant
– public static final int MAX_VALUE = 2147483647
– public static final int MIN_VALUE = -2147483648
• Method
– static int parseInt(String s) :
• Convert a Number in String into int type
– static int parseInt(String s , int radix) :
• Convert a number in String into int type with radix
– static String toBinaryString(int i) :
• Convert into binary string form
– static String toHexString(int i) :
• Convert into hexadecimal string form

Interger.parseInt(s);
Interger.parseInt(s);
Integer.toBinaryString(i);
Integer.toBinaryString(i);
Double Class
• Constant
public static final double MAX_VALUE =1.79769313486231570e+308
public static final double MIN_VALUE = 4.94065645841246544e-308
public static final double NaN = 0.0 / 0.0
public static final double NEGATIVE_INFINITY = -1.0 / 0.0
public static final double POSITIVE_INFINITY = 1.0 / 0.0

• the parameter is NaN or not.


static boolean isInfinite(double v) :
Check whether the parameter is infinite or not.
static Double valueOf(String s) : Method
static long doubleToLongBits(double value) :
Convert the bits represented by double type into long type bit pattern
static boolean isNaN(double v) :
Check whether Convert String into Double type
Boolean Class
• Constant
– public static final Boolean TRUE = new Boolean(true)
– public static final Boolean FALSE = new Boolean(false)

• Method
– Boolean(boolean b) :
• Constructor to create boolean object receiving the initial
value b
– Boolean(String s) :
• Constructor to receive the string value "true“ or "false“
– boolean booleanValue() :
• Return the boolean value of object
– static boolean getBoolean(String name) :
• Return the boolean value of system attribute
– static Boolean valueOf(String s) :
• Return the Boolean value correspond to string s
Character Class

• Constant
– public static final int MAX_RADIX = 36
– public static final char MAX_VALUE =‘\ffff’
– public static final int MIN_RADIX = 2
– public static final char MIN_VALUE =’\0000’

• Method
– Character(char value) : Constructor to initialize the object as
value
– char charValue() : Convert into char type
– static boolean isDigit(char ch) : Test whether is digit?
– static boolean isLetter(char ch) : Test whether is letter?
– static boolean isLetterOrDigit(char ch) : Return when it is letter
or digit.
MODULE 7
The static Modifier
• The static modifier can be applied to variables or methods
• It associates a variable or method with the class rather
than an object
• This approach is a distinct departure from the normal way
of thinking about objects

Static Variables
• Normally, each object has its own data space
• If a variable is declared as static, only one copy of the variable
exists for all objects of the class
private static int count;
• Changing the value of a static variable in one object changes it for
all others
• Static variables are sometimes called class variables 132
Static Methods
• Normally, we invoke a method through an instance (an object)
of a class
• If a method is declared as static, it can be invoked through the
class name; no object needs to exist
• For example, the Math class in the java.lang package contains
several static mathematical operations
Math.abs (num) -- absolute value
Math.sqrt (num) -- square root
• The main method is static; it is invoked by the system without
creating an object
• Static methods cannot reference instance variables, because
instance variables don't exist until an object exists
• However, they can reference static variables or local variables
• Static methods are sometimes called class methods
133
Overloaded Methods
• Method overloading is the process of using the same method
name for multiple methods
• The signature of each overloaded method must be unique
• The signature is based on the number, type, and order of the
parameters
• The compiler must be able to determine which version of the
method is being invoked by analyzing the parameters
• The return type of the method is not part of the signature
• The println method is overloaded:
println (String s),println (int i) , println (double d) etc.
• The lines
System.out.println ("The total is:"); System.out.println (total);
invoke different versions of the println method
134
• Constructors are often overloaded to provide multiple ways to set
up a new object
Account (int account) {
account_number = account;
balance = 0.0;
} // constructor Account

Account (int account, double initial) {


account_number = account;
balance = initial;
} // constructor Account

135
Modifier – Final
• Final variable
– Value can not be changed
– Must be initialized in every constructor
– Attempts to modify final are caught at compile time
• Final static variable
– Used for constants
– Example final static int Increment = 5;

• Final method
– Method can not be overloaded by subclass
– Private methods are implicitly final
• Final class
– Class can not be a superclass (extended)
– Methods in final class are implicitly final 136
Modifier – Final
• Final classes
– Prevent inheritance / polymorphism
– May be useful for
• Security
• Object oriented design
• Example – class String is final
– Programs can depend on properties specified in Java library API
– Prevents subclass from bypassing security restrictions

137
Abstract Classes
• An abstract class cannot be instantiated
• It is used in a class hierarchy to organize common features at
appropriate levels
• An abstract method has no implementation, just a name and
signature
• An abstract class often contains abstract methods
• Any class that contains an abstract method is by definition abstract
• The modifier abstract is used to define abstract classes and
methods
• The children of the abstract class are expected to define
implementations for the abstract methods in ways appropriate for
them
138
Abstract Classes
• If a child class does not define all abstract methods of the parent, then the
child is also abstract
• An abstract class is often too generic to be of use by itself
• An abstract method cannot be declared as final, because it must be
overridden in a child class
• An abstract method cannot be declared as static, because it cannot be
invoked without an implementation
• Abstract classes are placeholders that help organize information and
provide a base for polymorphic references

139
Interfaces
• We've used the term interface to mean the set of service methods
provided by an object
• That is, the set of methods that can be invoked through an object
define the way the rest of the system interacts, or interfaces, with that
object
• The Java language has an interface construct that formalizes this
concept
• A Java interface is a collection of constants and abstract methods
• A class that implements an interface must provide implementations
for all of the methods defined in the interface
• This relationship is specified in the header of the class:
class class-name implements interface-name {
}

140
Interfaces
• An interface can be implemented by multiple classes
• Each implementing class can provide their own unique version of the
method definitions
• An interface is not a class, and cannot be used to instantiate an object
• An interface is not part of the class hierarchy
• A class can be derived from a base class and implement one or more
interfaces
• Unlike interface methods, interface constants require nothing special of
the implementing class
• Constants in an interface can be used in the implementing class as if they
were declared locally
• This feature provides a convenient technique for distributing common
constant values among multiple classes

141
Interfaces
• An interface can be derived from another interface, using the
extends reserved word
• The child interface inherits the constants and abstract methods of
the parent
• Note that the interface hierarchy and the class hierarchy are distinct
• A class that implements the child interface must define all methods in
both the parent and child
• An interface name can be used as a generic reference type name
• A reference to any object of any class that implements that interface
is compatible with that type
• For example, if Philosopher is the name of an interface, it can be
used as the type of a parameter to a method
• An object of any class that implements Philosopher can be passed to
that method
142
Interfaces
• Note the similarities between interfaces and abstract classes
• Both define abstract methods that are given definitions by a particular
class
• Both can be used as generic type names for references
• However, a class can implement multiple interfaces, but can only be
derived from one class
• A class that implements multiple interfaces specifies all of them in its
header, separated by commas
• The ability to implement multiple interfaces provides many of the
features of multiple inheritance, the ability to derive one class from
two or more parents
• Java does not support multiple inheritance

143
Packages
• A Java package is a collection of classes
• The classes in a package may or may not be related by inheritance
• A package is used to group similar and interdependent classes
together
• The Java API is composed of multiple packages
• The import statement is used to assert that a particular program will
use classes from a particular package

• A programmer can define a package and add classes to it


• The package statement is used to specify that all classes defined in
a file belong to a particular package
• The syntax of the package statement is:
package package-name;
• It must be located at the top of a file, and there can be only one
package statement per file
144
Packages
• The classes must be organized in the directory structure such that
they can be found when referenced by an import statement
• There is a CLASSPATH environment variable on each computer
system that determines where to look for classes when referenced

• The import statement specifies particular classes, or an entire


package of classes, that can be used in that program
• Import statements are not necessary; a class can always be
referenced by its fully qualified name in-line
• If two classes from two packages have the same name and are
used in the same program, they must be referenced by their fully
qualified name

145
Packages
• As a rule of thumb, if you will use only one class from a
package, import that class specifically
• If two or more classes will be used, use the * wildcard character
in the import statement to provide access to all classes in the
package

146
MODULE 8
EXCEPTION BASICS
• Is an abnormal condition that arises in a code sequence at
run time.
• An exception is a run time error.
• When an exception condition arises, an object representing
that exceptions created and thrown in the method that
caused the error. That method may choose to handle the
exception itself or pass it on.
• Eitherway at some point, the exception is caught and
processed. Exceptions can be generated by the java run time
system or they can be manually generated by your code
TYPES OF EXCEPTION
• All exception types are subclasses of the built in class
Throwable
• Exception class is used for exceptional conditions that user
programs should catch
• This is also the class that you will subclass to create our own
custom exception types
• Runtime exceptions are automatically defined for the
programs that we write and include things such as division by
zero and invalid array indexing
• Errors defines exceptions that are not excepted to be caught
under normal circumstances by our program
ERROR
• Is an irrecoverable condition occurring at run time
• We cannot repair them at runtime

USING TRY-CATCH
• When we use multiple catch statements, it is important to
remembers that exception subclasses must come before any of
their super class.
• This is because a catch statement that uses a super class will catch
exceptions of that type plus any of its subclasses
• Thus a subclass would never be reached if it came after its super
class
• If no catch statement matches, then the java run time system will
handle the exception
THROW
• Normally we are catching exceptions that are thrown by the java run time
system. But it is possible to throw an exception explicitly using the throw
statement
• Throw is used to manually throw an exception of type Throwable class or a sub
class of Throwable
• The flow of execution stops immediately after the throw statement, any
subsequent statements are not executed
• Eg-throw new NullPointerException(“thrown exception”);
THROWS
• A throws clause lists the types of exception that a method
might throw. This is necessary for all exceptions, except Error
or Runtime Exception and their sub classes
• All other exceptions that is a method can throw must be
declared in the throws clause
• If they are not, a compile time error will result
• If a method is capable of causing an exception that it does not
handle,it must specify this behavior so that the callers of the
method can guard themselves against that exception.We do
this by including throws clause in the methods declaration
• Eg-static void throwOne() throws…
MODULE 10
GUI Elements
• The key elements of a Java graphical user interface are:
– GUI components
– layout managers
– event processing

• GUI components, such as text fields and buttons, are the screen
elements that a user manipulates with the mouse and keyboard
• Layout managers govern how the components appear on the
screen
• Events signal important user actions, like a mouse click

154
GUI with Components
• Components are a group of classes which belong to the class
Component
• The basic and frequently used components are
Button Checkbox Choice Frame Panel
Label

List Scrollbar TextArea TextField


• For each of the above components there are corresponding
classes
• Using a class an object of desired type can be created
• Each class have their own constructors for initialization of the
objects
• When an object is created and initialized, it then can be placed
on an applet by the add() method, which is defined in their
corresponding classes
Abstract Windowing Toolkit
j a v a . a w t A p p l e t
B o r d e r L a y o u t
C a r d L a y o u t
C h e c k b o x P a n e l
C o l o r W i n d o w
C o m p o n e n t
D i m e n s i o n B u t t o n D i a l oF gi l e D i a l o g
E v e n t C a n v a s
F r a m e
F l o w L a y o u tC h e c k b o x
F o n t C h o i c e
F o n t M a t r i c sC o n t a i n e r
G r a p h i c s L a b e l
G r i d B a g C o Ln si s t tr a i n t T e x t A r e a
G r i d B a g L a yS o c ur ot l l b a r
G r i d L a y o u tT e x t C o m p o n e n t T e x t F i e l d
I m a g e C o l o r M o d e l
I n s e t s C r o p I m a g e F i l t e r
M e n u C o m p o n e n t D i r e c t C o l o r M o d e l
M e d i a T r a c k M e re n u B a r F i l t e r e d I m a g e S o u r c e
P o i n t M e n u I t e m I m a g e C o n s u m e r
P o l y g o n I m a g e F i l t e r
R e c t a n g l e M e n u I m a g e O b s e r v e r
T o o l k i t C h e c k B o x M I m e n a ug Ie t P e rm o d u c e r
A W T E r r o r I n d e x C o l o r M o d e l
A W T E x c e p t i o n M e m o r y I m a g e S o u r c e
R G B I m a g e F i l t e r
Event-Driven Programming
• Programs with GUIs must respond to events, generated by GUI
components, that indicate that specific actions have occurred
• A special category of classes, called listeners, wait for events to
occur
• Therefore, a GUI program is composed of:
– the code that presents the GUI to the user
– the listeners that wait for events to occur
– the specific code that is executed when events occur

157
Event-Driven Programming
• There is a listener interface defined for each event type
• Each listener interface contains the abstract methods required to
respond to specific events
• A listener class implements a particular listener interface
• Listeners are "added" to a particular GUI component
• When a component generates an event, the method corresponding
to that event is executed in the listener

158
The GUI Program Model

Listeners

Add listeners Handle events

Program-
GUI
specific
Event effects

159
Event Interfaces

• Multiple listeners can be added to a component


• Multiple components can be processed by the same listener
• Furthermore, one listener class can implement multiple listener
interfaces
• Therefore one class can listen for many types of events

160
Containers

• A container is a special category of GUI components that group


other components
• All containers are components, but not all components are
containers
• An applet is a container
• Therefore, buttons, text fields, and other components can be added
to an applet to be displayed
• Each container has an associated layout manager to control the
way components in it are displayed
161
Containers
• Some containers must be attached to another graphical surface:
– panel
– applet

• An applet is attached to a browser or appletviewer window


• Other containers can be moved independently:
– window
– frame
– dialog

162
Containers
Component

Container

Panel Window

Applet Frame Dialog

163
Component Hierarchies
• A GUI is created when containers and other components are put
together
• The relationships between these components form a component
hierarchy
• For example, an applet can contain panels which contain other
panels which contain buttons, etc.
• Careful design of the component hierarchy is important for visually
pleasing and consistent GUIs

164
GUI Components
• There are several GUI components that permit specific kinds of user
interaction:
– labels
– text fields
– text areas
– lists
– buttons
– scrollbars

165
Labels
• A label defines a line of text displayed on a GUI
• Labels are static in the sense that they cannot be selected or
modified by the human user once added to a container
• A label is instantiated from the Label class
• The Label class contains several constructors and methods for
setting up and modifying a label's content and alignment

166
Text Fields and Text Areas

• A text field displays a single line of text in a GUI


• It can be made editable, and provide a means to get input from the
user
• A text area is similar, but displays multiple lines of text
• They are defined by the TextField and TextArea classes
• A text area automatically has scrollbars on its bottom and right sides

167
Lists
• A list, in the Java GUI sense, is used to display a list selectable
strings
• A list component can contain any number of strings and can be
instantiated to allow multiple selections within it
• The size of the list is specified by the number of visible rows or
strings within it
• A scrollbar will automatically appear on the right side of a list if the
number of items exceed the visible area
• A list is defined by the List class

168
Buttons
• The java.awt package supports four distinct types of buttons:
– Push buttons
– Choice Buttons
– Checkbox buttons
– Radio buttons

• Each button type serves a particular purpose

169
Push Button
• A push button is a single button which can be created with or
without a label
• A system is usually designed such that when a push button is
pressed, a particular action occurs
• It is defined by the Button class

170
Choice button
• A choice button is a single button which displays a list of choices
when pushed
• The user can then scroll through and choose the appropriate option
• The current choice is displayed next to the choice button
• It is defined by the Choice class

171
Checkbox button
• A checkbox button can be toggled on or off
• A set of checkbox buttons are often used to define a set of options
as a group, though one can be used by itself
• If used in a group, more than one option can be chosen at any one
time
• Defined by the Checkbox class

172
Radio buttons
• A radio button, like a checkbox button, is toggled on or off
• Radio buttons must be grouped into a set, and only one button can
be selected at any one time
• When one button of a group is selected, the currently selected
button in that group is automatically reset
• They are used to select among a set of mutually exclusive options
• Radio button sets are defined by the Checkbox and
CheckboxGroup classes

173
Scrollbars
• A scrollbar is a slider that indicates a relative position or quantity
• They are automatic on text areas and list components, but can be
used independently
• The position of the slider in the range corresponds to a particular
numeric value in a range associated with the scrollbar
• A scrollbar is defined by the Scrollbar class

174
Applets and its Applications

• Applets are small Java programs that are primarily used in Internet
computing

• Applets can be transported over the Internet from one computer to other and
viewed by a browser

• With applet we can process graphics, audio, image, animation, games and
many more...

• Java has enabled WWW to create multimedia Web pages


Applet Geometry

A p p l e t V i e w e r : H e l lo W o r ld . c l a s s
( 0 , 0 )
height

H e l l o W o r l d

( w i d t h , h e i g h t )

A p p l e t l o a d e r . s t a r t e d
w i d t h
Applet Embedding HTML

< H T M L >
< !
. . . . . . . . . .
. . . . . . . . . . C o m m e n t S e c t i o
! >

< H E A D >

T i t l e T a g H e a d S e c t i o n

< / H E A D >

< B O D Y >

A p p l e t T a g B o d y S e c t i o n

< / B O D Y >

< H T M L >
Applet Embedding HTML
Example

<HTML>
<!This is a simple HTML page
>

<HEAD>
<TITLE>
HTML Page Practice
</TITLE>
<HEAD>

<BODY>
<CENTER>
Welcome to the World of Applet
</CENTER>
<BR>
<RIGHT>
<APPLET
CODE = HelloWorld.class
WIDTH = 400
HEIGHT = 200
</APPLET>
</RIGHT>
</BODY>
</HTML>
Parameters to Applet
Example

public class HelloWorldWithParameters extend Applet


{
String aString;
int anInteger;

public void init()


{
aString = getParameter("string");
anInteger =
Integer.parseInt(getParameter("intVal");
<APPLET
if(aString == null)
CODE = HelloWorld.class
aString = "Hi";
WIDTH = 400
aString = "Hello" + aString;
LENGTH = 200
ALLIGN = RIGHT
}
<PARAM NAME = "string" VALUE =
public void paint(Graphics g)
"Java">
{
<PARAM NAME = "intVal" VALUE = 96
String intToString;
>
g.drawString(aString, 10, 75);
>
intToString = String.valueOf(anInteger);
</APPLET>
g.drawString(intToString, 100, 75);
}
To create a Button

import java.applet.Applet;
import java.awt.*;

public class ButtonTest extends Applet {


public void init( ) {
Button b1,b2;

b1 = new Button ("Welcome");

add(b1);
b2 = new Button ( );

add(b2);
}
}
To create a Checkbox

import java.awt .*;


import java.applet.*;

public class CheckboxText extends Applet {


public void init ( ) {
Checkbox c1 = new Checkbox ( );
Checkbox c2 = new Checkbox ( " Solaris 2.x");
Checkbox c3 = new Checkbox ( "Macintosh", null,
false);
Checkbox c4 = new Checkbox ( "Windows 95", null,
true);
add (c1);
add (c2);
add (c3);
add (c4);
}
}
To create a Choice
To create a Choice
import java.awt.*;
import java.applet.*;
public class ChoiceDemo extends Applet {
public void init ( ) {
int width = Integer.parseInt (getParameter( " width" ));
int height = Integer.parseInt (getParameter(" height"));

Choice os = new Choice ( );


Choice browser = new Choice ( );
os.addItem ( " Windows 95" );
os.addItem ( " Solaris 2.x " );
os.addItem ( " Mac OS 7.5 ");
browser.addItem (" Netscape Navigator 2.0");
browser.addItem ( "Internet Explorer 4.0" );
browser.addItem ("Hot Java ") ;
add (os);
add (browser );
os.reshape ( 0, 0, width/2, height/2 );
browser.reshape (0, height/2, width, height);
}
}
To create a Frame

import java.awt.*;
import java.awt.applet.*;

public class MyFrame {


public static void main (String args[ ] ) {
Frame frame = new Frame ( " Frame in Java
" );
frame.resize (500, 500);
frame.setBackground (Color.blue );

frame.show ( )

}
}
To create a Panel
import java.awt.* ;
import java.awt.applet.*;

public class MyPanel {


public static void main ( String args [ ] ) {
Frame frame = new Frame( "Frame with
panel");
Panel panel = new Panel( );
frame.resize(200, 200);
frame setBackground (Color.blue);
frame.setLayout (null);
panel.resize (100, 100) ;
panel.setBackground (Color.yellow );
frame.add (panel);
frame.show ( );

}
}
To create a Label
To create a Label

import.java.awt.*;
import.java.applet.*;

public class LabelDemo extends Applet {


public void init ( ) {
setLayout (null );
int width = Integer.parseInt ( getParameter ("width" ));
int height = Integer.parseInt (get.Parameter (" height" ));
Label left = new Label ( );
Label center = new label ( " Center", Label.CENTER);
Label right = new Label("Right", Label.RIGHT);

add(left);
add (right );
add (center );

left.reshape ( 0, 0, width, height/3);


right.reshape(0, height/3, width, height/3);
center.reshape (0, 2 * height/3 , width, height/3);
}
}
To create a List
To create a List

public class ListDemo extends Applet {


public void init ( ) {
setLayout (null );
int width = Integer.parseInt (getParameter (" width" ) );
int height = Integer.parseInt (getParameter (" height" ) );

List os = new List (3, true);


List browser = new List (5, false);
os.addItem ( " Windows 95" );
os.addItem ("Solaris 2.x " );
os.addItem (" Mac OS 7.5 " );
browser.addItem ("Netscape Navigator" );
browser.addItem ("Internet Explorer" );
browser.addItem ("Hot Java" );
browser.addItem ("Mosaic" );
browser.addItem ("Applet Viewer" );
browser.select(1) ;
add(os);
add(browser);
os.reshape (0, 0, width, height /2 );
browser. reshape ( 0, height /2, width, height /2 );
}
}
To create a Scrollbar
To create a Scrollbar

import java.awt.*;
import java.applet.*;

public class ScrollDemo extends Applet {


public void init ( ) {
setLayout( new Borderlayout ( ) );
int width = Integer.parseInt (getParameter (" width" ));
int height = Integer.parseInt (getParameter (" height"));
Scrollbar hScroll = new Scrollbar ( Scrollbar. HORIZONTAL, 50, width /10,
0, 100 );
Scrollbar vScroll = new Scrollbar ( Scrollbar.VERTICAL, 50, hight /2, 0,
100);
add (hScroll );
add (vScroll );
}
}
To create a Text field
To create a Text field

import java.awt.*;
import java.applet.* ;
public class TextFieldDemo extends Applet {
public void init ( ) {
add ( new TextField("Type your Name", 20);

Label login = new Label ( "Login : " , Label.LEFT );


Label pswd = new Label ( "Password : " , Label.CENTER );

TextField log = new TextField (8) ;


TextField pas = new TextField (8);
pas.setEchoCharacter ( '*' ); // echo hide the type
pass

add (login); add (log);


add (pswd ); add (pass );
}
}
To create a Text Area
To create a Text Area

import java.awt.*;
import java.applet.*;
public class TextAreaDemo extends Applet {
TextArea text;
String multiLineText =
" To learn Java, you will first"
+ " need to obtain \ n two different pieces of "
+ "softwares : \ n "
+ " The first is the JDK (Java Development Kit"
+ "and \n the second piece of software "
+ "is a Java capable browser."
+ " \n JDK software is needed for Writing, "
+ " Compiling, and Testing Java applet \n and
+ " Applications.\n \n" ;

public void init ( ) {


setLayout(null);
text = new TextArea (multiLineText, 20, 40);
add (text);
}
}
Drawing Geometric Figures
• Drawing Lines
• Drawing Rectangles
• Drawing Ovals
• Drawing Arcs
• Drawing Polygons

Drawing Lines
drawLine(x1, y1, x2, y2);

Drawing Rectangles
• drawRect(x, y, w, h);
• fillRect(x, y, w, h);
Drawing Rounded Rectangles
• drawRoundRect(x, y, w, h, aw, ah);
• fillRoundRect(x, y, w, h, aw, ah);

Drawing Ovals
• drawOval(x, y, w, h);
• fillOval(x, y, w, h);

Drawing Arcs
• drawArc(x, y, w, h, angle1, angle2);
• fillArc(x, y, w, h, angle1, angle2);
Layout Managers
• There are five predefined layout managers in the
• java.awt package:
– flow layout
– border layout
– card layout
– grid layout
– grid bag layout

• Each container has a particular layout manager associated with it by


default
• A programmer can also create custom layout managers

198
Flow Layout
• Components are placed in a row from left to right in the order in
which they are added
• A new row is started when no more components can fit in the
current row
• The components are centered in each row by default
• The programmer can specify the size of both the vertical and
horizontal gaps between the components
• Flow layout is the default layout for panels and applet

199
Grid Layout
• Components are placed in a grid with a user-specified number of
columns and rows
• Each component occupies exactly one grid cell
• Grid cells are filled left to right and top to bottom
• All cells in the grid are the same size

200
Border Layout
• Defines five locations each of which a component or components
can be added
– North, South, East, West, and Center

• The programmer specifies the area in which a component should


appear
• The relative dimensions of the areas are governed by the size of the
components added to them

201
Border Layout

North

West Center East

South

202
Card Layout
• Components governed by a card layout are "stacked" such that only
one component is displayed on the screen at any one time
• Components are ordered according to the order in which they were
added to the container
• Methods control which component is currently visible in the
container

203
Grid Bag Layout
• Designed as a two-dimensional grid of columns and rows
• However, not all cells in the grid are the same size
• Components may span multiple columns and rows
• Each component in a grid bag layout is associated with a set of
constraints, defined by the GridBagConstraints class
• A grid bag layout is the most versatile, and most complex, of the
predefined layout managers

204
GUI Design
• Careful design of a graphical user interface is key to a viable
software system
• To the user, the user interface is the system
• For each situation, consider which components are best suited and
how they should best be arranged

205
finally

• The finally block will execute


Whether or not an exception is thrown.If an exception is
thrown, the finally block will execute even if no catch statement
matches the exception
 If a finally block is associated with a try , the finally block will
be executed upon conclusion of the try
• The reason for using the finally block is any unreleased
resources can be released and the memory can be freed
• We can omit the finally block when there is a catch block
associated with that try block
• A try block should have atleast a catch or a finally block
CHECKED EXCEPTION
• Checked exception are ones which you expect beforehand to
be raised when an exceptional condition occur and so write
your code in a try catch block to handle that sufficiently
• Checked exceptions are sub classes of exception

UNCHECKED EXCEPTION
• Unchecked exceptions are the ones which cannot be handled in
the code
• Unchecked exceptions are subclasses of Run Time Exception
MODULE 11
What is an Event?
• GUI components communicate with the rest of the applications
through events.
• The source of an event is the component that causes that event to
occur.
• The listener of an event is an object that receives the event and
processes it appropriately.
Handling Events
• Every time the user types a character or clicks the mouse, an event
occurs.
• Any object can be notified of any particular event.
• To be notified for an event,
 The object has to be registered as an event listener on the
appropriate event source.
 The object has to implement the appropriate interface.
An example of Event Handling

public class SwingApplication implements ActionListener {


...
JButton button = new JButton("I'm a Swing button!");
button.addActionListener(this);
....
public void actionPerformed(ActionEvent e) { numClicks++;
label.setText(labelPrefix + numClicks);
}
}
The Event Handling process
• When an event is triggered, the JAVA runtime first determines its
source and type.
• If a listener for this type of event is registered with the source, an
event object is created.
• For each listener to this type of an event, the JAVA runtime
invokes the appropriate event handling method to the listener and
passes the event object as the parameter.
What does an Event Handler require?
• It just looks for 3 pieces of code!
• First, in the declaration of the event handler class, one line of code
must specify that the class implements either a listener interface or
extends a class that implements a listener interface.
public class DemoClass implements ActionListener {
• Second, it looks for a line of code which registers an instance of the
event handler class as a listener of one or more components
because, as mentioned earlier, the object must be registered as an
event listener.
anyComponent.addActionListener(instanceOf DemoClass);
• Third, the event handler must have a piece of code that implements
the methods in the listener interface.
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}
Types of Events
• Below, are some of the many kinds of events, swing components
generate.
Act causing Event Listener Type
User clicks a button, presses ActionListener
Enter, typing in text field
User closes a frame WindowListener
Clicking a mouse button, while MouseListener
the cursor is over a component
User moving the mouse over a MouseMotionListener
component
Component becomes visible ComponentListener

Table or list selection changes ListSelectionListener


The Event classes
• An event object has an event class as its reference data type.
• The Event object class
 Defined in the java.util package.
• The AWT Event class
 An immediate subclass of EventObject.
 Defined in java.awt package.
 Root of all AWT based events.
Event Listeners
Event listeners are the classes that implement the
<type>Listener interfaces.
Example:
1. ActionListener receives action events
2. MouseListener receives mouse events.
The following slides give you a brief overview on some of the listener
types.
The ActionListener Method
• It contains exactly one method.

Example:
public void actionPerformed(ActionEvent e)
The above code contains the handler for the ActionEvent e that
occurred.

The MouseListener Methods


• Event handling when the mouse is clicked.
public void mouseClicked(MouseEvent e)
• Event handling when the mouse enters a component.
public void mouseEntered(MouseEvent e)
• Event handling when the mouse exits a component.
public void mouseExited(MouseEvent e)
• Event handling when the mouse button is pressed on a
component.
public void mousePressed(MouseEvent e)
• Event handling when the mouse button is released on a
component.
public void mouseReleased(MouseEvent e)

The MouseMotionListener
• Invoked when the mouse button is pressed over a
component and dragged. Called several times as the
mouse is dragged
public void mouseDragged(MouseEvent e)
• Invoked when the mouse cursor has been moved onto a
component but no buttons have been pushed.
public void mouseMoved(MouseEvent e)
The WindowListener Methods
• Invoked when the window object is opened.
public void windowOpened(WindowEvent e)
• Invoked when the user attempts to close the window object from the
object’s system menu.
public void windowClosing(WindowEvent e)
• Invoked when the window object is closed as a result of calling
dispose (release of resources used by the source).
public void windowClosed(WindowEvent e)
• Invoked when the window is set to be the active window.
public void windowActivated(WindowEvent e)
• Invoked when the window object is no longer the active window
public void windowDeactivated(WindowEvent e)
• Invoked when the window is minimized.
public void windowIconified(WindowEvent e)
• Invoked when the window is changed from the minimized state to
the normal state.
public void windowDeconified(WindowEvent e)
Hierarchy of event objects

Note: The number


of event objects is
much greater then
specified in
diagram…Due to
space constraints,
only some of them
are represented in
the figure
Additional Listener Types
• Change Listener • Item Listener
• Container Listener • Key Listener
• Document Listener • Property Change Listener
• Focus Listener • Table Model Listener
• Internal Frame Listener

Adapter classes for Event Handling


Why do you need adapter classes?
Implementing all the methods of an interface involves a lot of work.
If you are interested in only using some methods of the interface.
Adapter classes
Built-in in JAVA
Implement all the methods of each listener interface with more than
one method.
Implementation of all empty methods
Adapter classes - an Illustration.
• Consider, you create a class that implements a MouseListener
interface, where you require only a couple of methods to be
implemented. If your class directly implements the
MouseListener, you must implement all five methods of this
interface.
• Methods for those events you don't care about can have empty
bodies

• What is the result?


 The resulting collection of empty bodies can make the code
harder to read and maintain.
• To help you avoid implementing empty bodies, the API generally
includes an adapter class for each listener interface with more
than one method. For example, the MouseAdapter class
implements the MouseListener interface.
Illustration (contd..)
public class MyClass implements MouseListener {
... someObject.addMouseListener(this);
/* Empty method definition. */
public void mousePressed(MouseEvent e) { }
/* Empty method definition. */
public void mouseReleased(MouseEvent e) { }
/* Empty method definition. */
public void mouseEntered(MouseEvent e) { }
/* Empty method definition. */
public void mouseExited(MouseEvent e) { }
public void mouseClicked(MouseEvent e) {
//Event listener implementation goes here...
}
}
How to use an Adapter class?
/* Using an adapter class
*/
public class MyClass extends MouseAdapter {
....
someObject.addMouseListener(this);
....
public void mouseClicked(MouseEvent e) {
...//Event listener implementation goes
// here
}
}
Using Inner classes for Event Handling
• Consider that you want to use an adapter class but you don’t
want your public class to inherit from the adapter class.
• For example, you write an applet with some code to handle
mouse events. As you know, JAVA does not permit multiple
inheritance and hence your class cannot extend both the Applet
and MouseAdapter classes.

• Use a class inside your Applet subclass that extends the


MouseAdapter class.
public class MyClass extends Applet { ...
someObject.addMouseListener(new MyAdapter());
...
class MyAdapter extends MouseAdapter { public void
mouseClicked(MouseEvent e) {
//Event listener implementation here... }
} }
Creating GUI applications with Event
Handling.
• Guidelines:
1. Create a GUI class
 Describes the appearance of your GUI application.
1. Create a class implementing the appropriate listener interface
 May refer to the same class as step 1.
3. In the implementing class
 Override all methods of the appropriate listener interface.
 Describe in each method how you want to handle the
events.
 May give empty implementations for the methods you
don’t need.
4. Register the listener object with the source
 The object is an instantiation of the listener class specified
in step 2.
 Use the add<Type>Listener method.
Design Considerations
• The most important rule to keep in mind about event listeners is
that they must execute quickly. Because, all drawing and event-
listening methods are executed in the same thread, a slow event
listener might make the program seem unresponsive. So,
consider the performance issues also when you create event
handlers in your programs.
• You can have choices on how the event listener has to be
implemented. Because, one particular solution might not fit in all
situations.
For example, you might choose to implement separate classes
for different types of listeners. This might be a relatively easy
architecture to maintain, but many classes can also result in
reduced performance .
Common Event-Handling
Issues
1. You are trying to handle certain events from a component, but it
doesn’t generate the events it should.
 Make sure you have registered the right kind of listener to
detect the events.
 Make sure you have registered the listener on the right object.
 Make sure you have implemented the event handler correctly,
especially, the method signatures.
2. Your combo box isn’t generating low level events like focus
events.
 Since combo boxes are compound components, i.e.,
components implemented using multiple components, combo-
boxes do not fire the low-level events that simple components
fire.
3. The document for an editor pane is not triggering document
events.
 The document instance for an editor pane might change when
loading text from a URL. Thus your listeners might be listening
for events on an unused document.
 Hence, make sure that the code adjusts for possible changes
to the document if your program dynamically loads text into an
editor pane.
MODULE 12
SWING
 Swing is a package that lets you create applications that use a
flashy Graphical User Interface (or GUI) instead of a dull console
interface.
 The Swing API provides many different classes for creating various
types of user interface elements.
 Three classes: JFrame, JPanel, and JLabel. These classes are
part of a larger collection of classes that are all related through
inheritance.
 The Swing family tree splits at the Component class into one group
of classes that are derived from the JComponent class, and
another branch that descends from the Window class.
The Swing Class Hierarchy
Description of Classes
• Object: All classes ultimately derive from Object, thus this class is at
the top of the tree.
• Component: represents an object that has a visual representation that
can be shown on-screen and that can interact with users. This class
defines some basic methods that are available to all Swing classes.
• Container: builds on the basic visual capabilities of the Component
class by adding the ability to hold other containers.
• Window: a specialized type of container object that has a border, a title
bar, buttons that minimize, maximize, and close the window, and that
can be repositioned and possibly even resized by the user.
• Frame: a type of Window that serves as the basis for Java GUI
applications. Frame is an AWT class that has been improved upon by
the JFrame class.
Description of Classes
• JFrame: the Swing version of the older Frame class. Most of the
Swing applications include at least one JFrame object.
• JComponent: is the basis for all other Swing components except
for frames.
• JPanel: used to organize and control the layout of other
components such as labels, buttons, text fields, etc. In most
Swing applications, one or more panels are added to a frame.
Then, when the frame is displayed, the components that were
added to its panels are made visible.
• JLabel: creates a label that displays a simple text value.
JFrame Constructors and
Methods
Constructor Description
JFrame ( ) Creates a new frame with no title.
JFrame (String title) Creates a new frame with the specified
title.
Method Description
void add (Component c) Adds the specified component to the
frame.
JMenuBar getJMenuBar ( ) Gets the menu for this frame.
void pack ( ) Adjusts the size of the frame to fit the
components added to it.
void remove (Component c) Removes the specified component
from the frame.
Method Description
void setDefaultCloseOperation Sets the action taken when the user closes
the frame. Always specify JFrame.EXIT ON
CLOSE.
void setIconImage (Icon image) Sets the icon displayed when the frame is
minimized.
void setLayout Sets the layout manager used to control
(LayoutManager layout) how components are arranged when the
frame is displayed. The default is the
BorderLayout manager.

void setLocation Sets the x and y position of the frame on-


(int x, int y) screen. The top-left corner of the screen is
0, 0.
void setLocationRelativeTo Centers the frame on-screen if the
(Component c) parameter is null.
Method Description
void setResizeable Sets whether or not the size of the
(boolean value) frame can be changed by the user.
The default setting is true (the frame
can be resized).
void setSize (int width, int height) Sets the size of the frame to the
specified width and height.

void Sets the menu for this frame.


setJMenuBar(JMenuBarMenu)
JPanel Class
• A panel is a type of container that's designed to hold a group
of components so they can be displayed on a frame. The
normal way to display a group of controls such as text fields,
labels, buttons, and other GUI widgets is to add those controls
to a panel, and then add the panel to the frame.
• You can bypass the panel and add the controls directly to the
frame if you want, but using a separate panel to hold the
frames control is almost always a good idea.
JPanel Constructors and
Methods
Constructor Description
JPanel () Creates a new panel.
JPanel (boolean Creates a new panel. If the parameter is true,
isDoubleBuffered) the panel uses a technique called double-
buffering.
JPanel (LayoutManager layout) Creates a new panel with the specified layout
manager. The default layout manager is
FIowLayout.
Method Description
void add (Component c) Adds the specified component to the panel.

void remove (Component c) Removes the specified component from the


panel.
Method Description

void setLayout Sets the layout manager used to control how


(LayoutManager layout) components are arranged when the panel is
displayed. The default is the FIowLayout
manager.
void setLocation (int x, int y) Sets the x and y position of the frame-screen.
The top-left corner of the screen is 0, 0.

void setSize (int width, int Sets the size of the frame to the specified width
height) and height.
void setToolTipText (String Sets the tooltip text that's displayed if the user
text) rests the mouse over an empty part of the
panel.
Labels
• A label is a component that simply displays text. Labels are used
for a variety of purposes: to display captions for other controls
such as text fields or combo boxes, to display informational
messages, or to show the results of a calculation or a database
lookup.
• A label can also display an image, or it can display both an image
and some text. And you have complete control over the
appearance of the text.
• You can specify the font, size, whether the text is bold, italic, or
underlined, what color the text is displayed as, and so on.
JLabels Constructors and Methods

Constructor Description

JLabel ( ) Creates a new label with no initial text.

Method Description

String getText ( ) Returns the text displayed by the label.

void setText (String text) Sets the text displayed by the label.

void setToolTipText (String text) Sets the tooltip text that's displayed if the
user rests the mouse over the label for a
few moments.
void setVisible (boolean value) Shows or hides the label.
• Next to labels, the Swing component used most is the JButton component which creates a
button the user can click.
• The constructors of the JButton class are similar to the constructors for the JLabel class. You
can either create an empty button or a button with a text.

Constructor Description

JButton ( ) Creates a new button with no initial text.

JButton (String text) Creates a new button with the specified text.

doClick ( ) Triggers an action event for the button as if the


user clicked it.
String getText () Returns the text displayed by the button.
Layout of Components
• The layout of components on a panel (or frame) is controlled by a
layout manager, which determines the final placement of each
component.
• The layout manager takes the size of the component, the size of the
panel, and the position of other nearby components into account when
it makes its decisions.
• Swing provides seven different layout managers to choose from. Each
has its own way of deciding where each component goes.
• The default layout manager for panels is called FlowLayout. It places
components one after another in a row, and starts a new row only
when it gets to the end of the panel (or the frame that contains it).
• With FlowLayout (and with the other layout managers too), the layout
changes if the user changes the size of the frame. The size of the
frame makes a big difference in how FlowLayout arranges controls.
• You can always call the frame's setResizeable (false) method to
prevent the user from resizing the frame.
• For many (if not most) Swing applications, one can use more than
one panel to display the components with each panel having a
different layout manager. With this technique, one can create complex
layouts with lots of components arranged in any way wanted.
• If needed, one can always turn off the layout manager altogether. To
do that, call the panel's setLayout method with null set as the
parameter. Then, use absolute positioning, which allows setting the x
and y position and the size of each component by calling its
setBounds method.
• Controlling the layout of components on a panel is one of the hardest
things about using Swing. But following the key points outlined above
will make life of a Java developer more efficient.
The Color Class
Color c = new Color(r, g, b);
r, g, and b specify a color by its red, green, and blue components.

Example:
Color c = new Color(128, 100, 100);
You can use the following methods to set the component’s
background and foreground colors:
setBackground(Color c)
setForeground(Color c)

Example:

setBackground(Color.yellow); setForeground(Color.red);
The Font Class
Font myFont = Font(name, style, size);

Example:
Font myFont = new Font ("SansSerif ", Font.BOLD, 16);
Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12);
public void paint(Graphics g) {
Font myFont = new Font ("Times", Font. BOLD, 16);
g.setFont(myFont);
g.drawString ("Welcome to Java", 20, 40);
//set a new font
g.setFont(new Font ("Courier", Font.BOLD+Font.ITALIC, 12));
g.drawString ("Welcome to Java", 20, 70);
}
MODULE 13
MULTI THREADED PROGRAMMING

Perform Multiple Tasks Using…


Thread
– Definition – sequentially executed stream of instructions
– Shares address space with other threads
– Has own execution context
• Program counter, call stack (local variables)
– Communicate via shared access to data
– Multiple threads in process execute same program
– Also known as “lightweight process”
Motivation for Multithreading
1. Captures logical structure of problem
– May have concurrent interacting components
– Can handle each component using separate thread
– Simplifies programming for problem
• Example

Web Server uses Multiple simultaneous


threads to handle … web browser requests
Motivation for Multithreading
2. Better utilize hardware resources
– When a thread is delayed, compute other threads
– Given extra hardware, compute threads in parallel
– Reduce overall execution time
• Example

Multiple simultaneous Handled faster by


web browser requests… multiple web servers
Multithreading Overview
• Threads
– Creating Java threads
– Thread states
– Scheduling
• Synchronization
– Data races
– Locks
– Wait / Notify
Thread Basics
• A multithreaded program contains two or more parts that can
run concurrently. Each part of such a program is called a
thread and each thread defines a separate path of execution
• Multithreading is a specialized form of multitasking

Creating Threads
• Two approaches
– Thread class
public class Thread extends Object { … }
– Runnable interface
public interface Runnable {
public void run(); // work ⇒ thread
}
Implement Runnable
• The easiest way to create a thread is to create a class that
implements the Runnable interface
• Runnable abstracts a unit of executable code
• To implement a Runnable,a class need only implement a
single method called run()
• public void run()

Extending Thread
• The second way to create a thread is to create a class that
extends Thread, and then to create an instance of that class
• The extending class must override the run() method, which is
the entry point for the new thread
• It must also call start() to begin execution of the new thread
Thread Class
public class Thread extends Object
implements Runnable {
public Thread();
public Thread(String name); // Thread name
public Thread(Runnable R); // Thread ⇒ R.run()
public Thread(Runnable R, String name);

public void run(); // if no R, work for thread


public void start(); // begin thread execution
...
}
Thread Class Methods
public class Thread extends Object {

public static Thread current Thread()
public String getName()
public void interrupt()
public boolean is Alive()
public void join()
public void setDaemon()
public void setName()
public void setPriority()
public static void sleep()
public static void yield()
}
Methods that manage threads
• getName()-obtain a thread’s name
• getPriority()-obtain a thread’s priority
• is Alive()-Determine if a thread is still running
• join()-wait for a thread to terminate
• run()- Entry point for the thread
• sleep()-Suspend a thread for a period of time
• start()-Start a thread by calling its run method

Choosing an approach
• The thread class defines several methods that can be
override by a derived class. Of these methods, the only
one that must be overridden is run(). This is the same
method required when you implement Runnable

• If we are not overriding any of Thread’s other methods, it


is probably best simply to implement Runnable
Creating Threads in Java
1. Thread class
– Extend Thread class and override the run method
• Example
public class MyT extends Thread {
public void run() {
… // work for thread
}
}
MyT T = new MyT () ; // create thread
T.start(); // begin running thread
… // thread executing in parallel
Creating Threads in Java
2. Runnable interface
– Create object implementing Runnable interface
– Pass it to Thread object via Thread constructor
• Example
public class MyT implements Runnable {
public void run() {
… // work for thread
}
}
Thread T = new Thread(new MyT); // create thread
T.start(); // begin running thread
… // thread executing in parallel
Creating Threads in Java
• Note
– Thread starts executing only if start() is called

– Runnable is interface
• So it can be multiply inherited
• Required for multithreading in applets
Threads – Thread States
• Java thread can be in one of these states
– New – thread allocated & waiting for start()
– Runnable – thread can begin execution
– Running – thread currently executing
– Blocked – thread waiting for event (I/O, etc.)
– Dead – thread finished
• Transitions between states caused by
– Invoking methods in class Thread
• new(), start(), yield(), sleep(), wait(), notify()…
– Other (external) events
• Scheduler, I/O, returning from run()…
Threads – Thread States
• State diagram
new start
notify, notifyAll,
new runnable
IO complete,
sleep expired,
yield,
scheduler join complete
time
slice
running blocked
IO, sleep,
terminate wait, join

dead
Daemon Threads
• Java threads types
– User
– Daemon
• Provide general services
• Typically never terminate
• Call setDaemon() before start()
• Program termination
1. All user threads finish
2. Daemon threads are terminated by JVM
3. Main program finishes
Threads – Scheduling
• Scheduler
– Determines which runnable threads to run
– Can be based on thread priority
– Part of OS or Java Virtual Machine (JVM)
• Scheduling policy
– Nonpreemptive (cooperative) scheduling
– Preemptive scheduling
Non-preemptive Scheduling
• Threads continue execution until
– Thread terminates
– Executes instruction causing wait (e.g., IO)
– Thread volunteering to stop (invoking yield or sleep)
Preemptive Scheduling

• Threads continue execution until


– Same reasons as non-preemptive scheduling
– Preempted by scheduler
Java Thread Example
public class ThreadExample extends Thread {
public void run() {
for (int i = 0; i < 3; i++)
System.out.println(i);
try {
sleep ((int) (Math. random() * 5000)); // 5 secs
} catch (Interrupted Exception e) { }
}
public static void main(String[] args) {
new Thread Example ().start();
new Thread Example ().start();
System.out.println ("Done");
}
}
Java Thread Example – Output

• Possible outputs
– 0,1,2,0,1,2,Done // thread 1, thread 2, main()
– 0,1,2,Done,0,1,2 // thread 1, main(), thread 2
– Done,0,1,2,0,1,2 // main(), thread 1, thread 2
– 0,0,1,1,2,Done,2 // main() & threads interleaved

main (): thread 1, thread 2, println Done

thread 1: println 0, println 1, println 2

thread 2: println 0, println 1, println 2


Synchronization
• when two or more threads need access to a shared resource, they
need some way to ensure that the resource will be used by only
one thread at a time. The process by which this is achieved is
called synchronization
• java implements synchronization using ‘synchronized’ keyword

Deadlock
• A special type of error that need to avoid that relates to multitasking is
deadlock, which occurs when two threads have a circular dependency on
a pair of synchronized objects
• It occurs when two threads time-slice in just the right way
• It may involve more than two threads and two synchronized objects
An example for deadlock
• Suppose one thread enters the monitor on object X and another
thread enters the monitor on object Y. If the thread in X tries to call
any synchronized method on Y, it will block as expected. However, if
the thread in Y, in turn, tries to call any synchronized method on X,
the thread waits forever, because to access
X, it would have to release its own lock on Y so that the first thread
could complete
Wait and Notify
• Allows two threads to cooperate
• Based on a single shared lock object

When wait is invoked, the thread releases the lock and suspends
execution. At some future time, another thread will acquire the same
lock and invoke Object.notifyAll, informing all threads waiting on that
lock that something important has happened:

There is a second notification method, notify, which wakes up a single


thread. Because notify doesn't allow you to specify the thread that is
woken up, it is useful only in massively parallel applications — that is,
programs with a large number of threads, all doing similar chores. In
such an application, you don't care which thread gets woken up.
Wait and Notify: Code
• Consumer:
synchronized (lock) {
while (!resourceAvailable()) {
lock.wait();
}
consumeResource();
}

• Producer:
produce Resource();
synchronized (lock) {
lock.notifyAll();
}
Thread Priorities and
Thread Scheduling
• Example program
• Create a class derived from Thread
• Use sleep method
– Overview
• Create four threads, which sleep for random amount of time
• After they finish sleeping, print their name
– Program has two classes
• PrintThread
– Derives from Thread
– Instance variable sleepTime
• ThreadTester
– Creates four PrintThread objects
1 // ThreadTester.java
2 // Show multiple threads printing at different intervals.
3
4 public class ThreadTester {
5 public static void main( String args[] )
6 {
7 PrintThread thread1, thread2, thread3, thread4;
8
9 thread1 = new PrintThread( "thread1" );
10 thread2 = new PrintThread( "thread2" ); Class ThreadTester
11 thread3 = new PrintThread( "thread3" );
12 thread4 = new PrintThread( "thread4" );
1. main
13
14 System.err.println( "\nStarting threads" );
15 1.1 Initialize objects
16 thread1.start(); main terminates after starting the
17 thread2.start(); PrintThreads, but the application
18 thread3.start();
does not end until the last thread dies. 1.2 start
19 thread4.start(); ---------------
20
21 System.err.println( "Threads started\n" ); Class PrintThread
22 }
23 }
1. extends Thread
24
25 class PrintThread extends Thread {
26 private int sleepTime; 1.1 Instance variable
27
28 // PrintThread constructor assigns name to thread
29 // by calling Thread constructor
30 public PrintThread( String name )
31 { Call superclass
32 super( name ); constructor to assign
33 name to thread.
34 // sleep between 0 and 5 seconds
35 sleepTime = (int) ( Math.random() * 5000 );
36
37 System.err.println( "Name: " + getName() +
38
start calls ";
the run method.
sleep: " + sleepTime );
39 }
40 sleep can throw an exception, so it 1.2 Constructor
41 // execute the thread is enclosed in a try block.
42 public void run() 1.2.1 Randomize
43 {
sleepTime
44 // put thread to sleep for a random interval
45 try {
46 System.err.println( getName() + " going to sleep" ); 2. run
47 Thread.sleep( sleepTime );
48 }
2.1 sleep
49 catch ( InterruptedException exception ) {
50 System.err.println( exception.toString() );
51 }
52
53 // print thread name
54 System.err.println( getName() + " done sleeping" );
55 }
56 }
MODULE 14
Simple Java I/O

Streams
• All modern I/O is stream-based
• A stream is a connection to a source of data or to a destination for
data (sometimes both)
• An input stream may be associated with the keyboard
• An input stream or an output stream may be associated with a file
• Different streams have different characteristics:
– A file has a definite length, and therefore an end
– Keyboard input has no specific end
JAVA distinguishes between 2 types of streams:

Text – streams, containing ‘characters‘

Program I ‘ M A S T R I N G \n Device

Binary Streams, containing 8 – bit information

Program 01101001 11101101 00000000 Device


Text Vs Binary Files
• Text files are more readable by humans
• Binary files are more efficient
– computers read and write binary files more easily than text
• Java binary files are portable
– they can be used by Java on different machines
– Reading and writing binary files is normally done by a
program
– text files are used only to communicate with humans

Java Text Files Java Binary Files


• Source files • Executable files (created
• Occasionally input files by compiling source files)
• Occasionally output files • Usually input files
• Usually output files
• Streams in JAVA are Objects, of course!

Having

• 2 types of streams (text / binary) and


• 2 directions (input / output)

results in 4 base-classes dealing with I/O:

1. Reader: text-input
2. Writer: text-output
3. InputStream: byte-input
4. OutputStream: byte-output
How to do I/O

import java.io.*;

• Open the stream


• Use the stream (read, write, or both)
• Close the stream

• Java I/O is very powerful, with an overwhelming number of options


• Any given kind of I/O is not particularly difficult
• The trick is to find your way through the maze of possibilities
Opening a stream
• There is data external to your program that you want to get, or you want to put
data somewhere outside your program
• When you open a stream, you are making a connection to that external place
• Once the connection is made, you forget about the external place and just use
the stream

Example
• A FileReader is a used to connect to a file that will be used for input:
FileReader fileReader = new FileReader(fileName);
• The fileName specifies where the (external) file is to be found
• You never use fileName again; instead, you use fileReader
Using a stream
int ch;
• Some streams can be used only for input, others only for output, still others for
ch = fileReader.read( );
both
• Using a stream means doing input from it or output to it
•• But
Theit’sfileReader.read() methodneed
not usually that simple--you reads
to one character
manipulate andinreturns
the data some wayit as
as
itan integer,
comes in or or -1 out
goes if there are no more characters to read
• The meaning of the integer depends on the file encoding (ASCII,
Unicode, other)

Example
int ch;
ch = fileReader.read( );
The fileReader.read() method reads one character and returns it as
an integer, or -1 if there are no more characters to read
• The meaning of the integer depends on the file encoding (ASCII,
Unicode, other)
Manipulating the input data
• Reading characters as integers isn’t usually what you want to do
• A BufferedReader will convert integers to characters; it can also
read whole lines
• The constructor for BufferedReader takes a FileReader parameter:
BufferedReader bufferedReader =
new BufferedReader(fileReader);

Reading lines
String s;
s = bufferedReader.readLine( );

• A BufferedReader will return null if there is nothing more to read


Closing
• A stream is an expensive resource
• There is a limit on the number of streams that you can have open at
one time
• You should not have more than one stream open on the same file
• You must close a stream before you can open it again
• Always close your streams!
Text files
• Text (.txt) files are the simplest kind of files
– text files can be used by many different programs
• Formatted text files (such as .doc files) also contain binary
formatting information
• Only programs that “know the secret code” can make sense
formatted text files
• Compilers, in general, work only with text
Writing a text file

– Create a stream object and


associate it with a disk-file
– Give the stream object the
desired functionality
– write data to the stream
– close the stream.
Class: FileWriter
Frequently used methods:
My Line Reader class

class Line Reader {


BufferedReader bufferedReader;

LineReader(String fileName) {...}

String read Line( ) {...}

void close( ) {...}


}
Basics of the Line Reader constructor
• Create a FileReader for the named file:
FileReader fileReader =
new FileReader(fileName);
• Use it as input to a BufferedReader:
BufferedReader bufferedReader =
new BufferedReader(fileReader);
• Use the BufferedReader; but first, we need to catch possible Exceptions
The full Line Reader constructor
LineReader(String fileName) {
FileReader fileReader = null;
try { fileReader = new FileReader(fileName); }
catch (FileNotFoundException e) {
System.err.println
("Line Reader can't find input file: " + fileName);

}
buffered Reader = new BufferedReader(fileReader);
}

read Line
String readLine( ) {
try {
return bufferedReader.readLine( );
}
catch(IOException e) {}
return null;
}
close
void close() {
try {
bufferedReader.close( );
}
catch(IOException e) { }
}

• read lines from a file, a readLine method in the BufferedReader


class
• The constructor for BufferedReader takes a Reader as an
argument
• An InputStreamReader is a kind of Reader
• A FileReader is a kind of InputStreamReader
Class: ReadText
Frequently used Methods:
The LineWriter class
class LineWriter {
PrintWriter printWriter;
LineWriter(String fileName) {...}
void writeLine(String line) {...}
void close( ) {...}
}

Constructor for LineWriter


LineWriter(String fileName) {
try {
printWriter =
new PrintWriter(
new FileOutputStream(fileName), true);
}
catch(Exception e) {
System.err.println (“ LineWriter can't " +
"use output file: " + fileName);
} }
Flushing the buffer
• When you put information into a buffered output
stream, it goes into a buffer
• The buffer may not be written out right away
• If your program crashes, you may not know how far it
got before it crashed
• Flushing the buffer is forcing the information to be
written out

PrintWriter
• Buffers are automatically flushed when the program ends normally
• Usually it is your responsibility to flush buffers if the program does not end
normally
• PrintWriter can do the flushing for you
public PrintWriter(OutputStream out,
boolean autoFlush)
writeLine
void writeLine(String line) {
printWriter.println(line);
}

close

void close( ) {
printWriter.flush( );
try { printWriter.close( ); }
catch(Exception e) { }
}
Binary Files

• Stores binary images of information identical to the binary


images stored in main memory
• Binary files are more efficient in terms of processing time
and space utilization
• drawback: not ‘human readable‘, i.e. you can‘t use a
texteditor (or any standard-tool) to read and understand
binary files
Writing Binary Files
Class: FileOutputStream
... see FileWriter

The difference:
No difference in usage, only in output format

Reading Binary Files


Class: FileInputStream
... see FileReader

The difference:
No difference in usage, only in output format
Example 1: Copying a Textfile
import java.io.*;
public class IOTest {
public static void main(String[] args) {
try {
BufferedReader myInput = new
BufferedReader(new FileReader("IOTest1.java"));
BufferedWriter myOutput = new
BufferedWriter(new FileWriter("Test.txt"));
int c;
while ((c=myInput.read()) != -1)
myOutput.write(c);
myInput.close();
myOutput.close();
}catch(IOException e){}
}
}
Java Networking
Network Programming
• Mechanisms by which software running on two or more
computational devices can exchange messages
– Desktop Computers
– PDAs / Set Top Boxes / Mobile Telephones?
• Java is a network centric programming language
• Java abstracts details of network implementation behind a
standard API
– Portable (and future proof) . . .
– but may be rather limiting
Internet Protocol (IP)
• Abstracts away the details of the physical network
implementations
• All traffic uses the same rules to move from machine to machine
– Easy to write programs
– Easy to build network hardware
• Works with Datagrams: small discrete packets of data (rather
like a letter)
• A way of uniquely addressing machines using 32 bit addresses:
giving 4 billion possible addresses (like a zip code)
• A system for numbering ports on each machine (like a post office
box)
• Port numbers allow several services to operate from a machine
at the same time
Common well known ports

• Ports 20/21 File Transfer Protocol


• Port 23 Telnet
• Port 25 Simple Mail Transport Proto.
• Port 79 Finger
• Port 80 HTTP
• Port 110 POP3 (Post Office Protocol)
• All well known ports in the range 1..1023
Internet Protocol (IP)

• The Internet consists of a large number of independent sub-


networks
• A mechanism for relaying datagrams from one network to
another (routing)
• For routing to work each organisation must have a well known
prefix (all UWA addresses start with the bytes 130.95)
IP Addresses and Java

• Java has a class java.net.InetAddress which abstracts


network addresses
• Serves three main purposes:
– Encapsulates an address
– Performs name lookup (converting a host name into an IP
address)
– Performs reverse lookup (converting the address into a host
name)
Transmission Control Protocol

• TCP is built on top of IP


• Provides the illusion of a continuous flow (or stream) of data
between sender and receiver (rather like a telephone call)
• Splits up streams into strings of small datagrams which are sent
in succession
• Contains an error recovery mechanism to recover datagrams
which are lost
• These features make application development simpler and so it
is widely used
• Used by FTP / Telnet and numerous other network applications
Basic Networking Classes
• java.net lists over 30 classes. A few of the key ones:

• InetAddress
– the class that represents IP addresses and contains operations f
or manipulating them
• URL
– used to retrieve the Web page at the given URL

• URLConnection
– also used to retrieve a Web page
– allows extra parameters to be sent to the URL
• e.g HTTP request headers

continued
• Socket
– the client-side socket class for TCP
• ServerSocket
– the server-side socket class for TCP
• DatagramSocket
– allows a client or server to send/receive UDP packets

Finding an IP Address
• Java’s InetAddress class makes the mapping between
hostnames and IP addresses.
WhatIP.java
import java.io.*;
import java.net.*;

public class WhatIP


{
public static void main(String args[])
throws IOException
{ InetAddress addr =
InetAddress.getByName(args[0]);
System.out.println("Inet address is "+ addr);
}
}
Use
Carried out from a DOS
prompt on my Windows machine.
Sockets (Java Style)
• Stream Sockets
– the client/server connection exists for the entire duration of
the request and answer
• similar to a telephone call
– a connection-oriented service
• corresponds to TCP
Java has separate classes for client and server stream sockets

• 2. Datagram Sockets
– the client/server send messages (packets or datagrams)
to each other
• similar to the postal service
• corresponds to UDP
Java has classes for datagram sockets and packets
Pinging ping is a DOS command, not Java.
Sockets and GET
• GetSocketPage.java retrieves the page:
http://<host name>/index.html
e.g.
http://fivedots.coe.psu.ac.th/index.html

• It prints the text of the page to stdout.

• It opens a socket at port 80 for the host, which is the usually place
where the Web server is listening.

• It sends the HTTP GET message:


GET /index.html
Diagram
GET /index.html
80
Web
server
Web page
GetSocketPage (as text)
client host
GetSocketPage.java

import java.io.*;
import java.net.*;

public class GetSocketPage


{
public static void main(String args[])
throws IOException
{
Socket sock = new Socket(args[0],80);
:
BufferedReader dis =
new BufferedReader(
new InputStreamReader(
sock.getInputStream() ));
String line;
while ((line = dis.readLine()) != null)
System.out.println(line);

sock.close();
}
} // end of GetSocketPage.java
• GetSocketPage.java converts the socket connection into a
BufferedReader for input, and a PrintStream for output
– uses readLine()for socket input
– uses println() for socket output

Use
C> javac GetSocketPage.java
C> java GetSocketPage fivedots
<html>
<head>
<title>Un title page</title>
</head>
<meta http-equiv="Content-Type" content="text/html; c
harset=windows-874">
<style type="text/css">
:
C>
URL Object
• GetURLPage.java is using a URL object.

• A URL object allows a Web page to be retrieved as a stream of


text
– our program prints the text to stdout.
GetURLPage.java

import java.net.*;
import java.io.*;

public class GetURLPage {


public static void main(String args[])
{
try {
URL url = new URL(args[0]);

BufferedReader dis =
new BufferedReader(
new InputStreamReader(
url.openStream() ));
:
String line;
while ( (line = dis.readLine()) != null )
System.out.println(line);

dis.close();
}
catch (Exception e)
{ System.out.println(e); }
}

} // end of GetURLPage.java
Thank you

Você também pode gostar