Beruflich Dokumente
Kultur Dokumente
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
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
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
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
finalize()
• 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.
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;
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.
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
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”?
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
Math
Compound Boolean Expressions
• 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
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
• 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);
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
! (not)
Value of A !A
true false
false true
Precedence
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
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
Accessing Elements
• int grade = scores[index] ;
• where index represents the specific element.
Accessing Elements
• int grade = scores[index] ;
• where index represents the specific element.
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
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
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
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
109
Class Hierarchies
•Mountain bikes, racing bikes, and tandems are all different kinds of
bicycles, so they are all subclasses of the bicycle class
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
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
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
•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 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
Integer obj;
int num = 42;
obj = num;
• 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
• 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
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
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
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
Program-
GUI
specific
Event effects
159
Event Interfaces
160
Containers
162
Containers
Component
Container
Panel Window
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
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
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...
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
import java.applet.Applet;
import java.awt.*;
add(b1);
b2 = new Button ( );
add(b2);
}
}
To create a Checkbox
import java.awt.*;
import java.awt.applet.*;
frame.show ( )
}
}
To create a Panel
import java.awt.* ;
import java.awt.applet.*;
}
}
To create a Label
To create a Label
import.java.awt.*;
import.java.applet.*;
add(left);
add (right );
add (center );
import java.awt.*;
import java.applet.*;
import java.awt.*;
import java.applet.* ;
public class TextFieldDemo extends Applet {
public void init ( ) {
add ( new TextField("Type your Name", 20);
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" ;
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
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
201
Border Layout
North
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
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
Example:
public void actionPerformed(ActionEvent e)
The above code contains the handler for the ActionEvent e that
occurred.
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
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
Method Description
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 (String text) Creates a new button with the specified text.
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
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);
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
– 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
• 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
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:
• 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:
Program I ‘ M A S T R I N G \n Device
Having
1. Reader: text-input
2. Writer: text-output
3. InputStream: byte-input
4. OutputStream: byte-output
How to do I/O
import java.io.*;
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( );
}
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) { }
}
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
The difference:
No difference in usage, only in output format
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
• 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.*;
• 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 opens a socket at port 80 for the host, which is the usually place
where the Web server is listening.
import java.io.*;
import java.net.*;
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.
import java.net.*;
import java.io.*;
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