Beruflich Dokumente
Kultur Dokumente
Internet Programming
Class Welcome {
Welcome() {
System.out.printing("Welcome!"); }
public static void main(String[] rags) {
new Welcome(); }
}
Java Programming Development 5
Internet Programming -Developed by AZAM RASHID
• Class
It describes the variables and methods appropriate
to some real-word entity
• Variable
It constitutes storage in the computer which hold
values that change
• Parameters
A method can have variations based on values
supplied to it in parentheses
Java source
code Java
bytecode
Java
compiler
Java Bytecode
interpreter compiler
Machine
code
Class Libraries
• The Java API is a class library, a group of classes
that support program development
• Classes in a class hierarchy are often related by
inheritance
• The classes in the Java API is separated into
packages
• The System class, for example, is in package
java.lang
• Each package contains a set of classes that relate
in some way
java.applet java.net
java.awt java.rmi
java.beans java.security
java.io java.sql
java.lang java.text
java.math java.util
Importing Packages
• Using a class from the Java API can be
accomplished by using its fully qualified name:
java.lang.System.out.printing ();
import java.util.Random;
White Space
• Spaces, blank lines, and tabs are collectively called
white space and are used to separate words and
symbols in a program
Comments
• Comments in a program are also called inline
documentation
Identifiers
• Identifiers are the words a programmer uses in a
program
Reserved Words
• Some identifiers, called reserved words, have specific
meanings in Java and cannot be used in other ways
Literals
• A literal is an explicit data value used in a program
• Integer literals:
25 69 -4288
• String literals:
"The result is: "
Internet Programming
Java DataTypes and Operators
Integers
• There are four separate integer primitive data types
Floating Point
• There are two floating point types:
Approximate Approximate
Type Storage Min Value Max Value
Characters
• A char value stores a single character from the
Unicode character set
Characters
• The ASCII character set is still the basis for many
other programming languages
uppercase letters A, B, C, …
lowercase letters a, b, c, …
punctuation period, semi-colon, …
digits 0, 1, 2, …
special symbols &, |, \, …
control characters carriage return, tab, ...
Boolean
• A boolean value represents a true or false
condition
Wrappers
• For each primitive data type there is a
corresponding wrapper class. For example:
Primitive Type Wrapper Class
int Integer
double Double
char Character
boolean Boolean
Variables
• A variable is an identifier that represents a location
in memory that holds a particular type of data
• For example:
int total;
Variables
• Multiple variables can be declared on the same
line:
int total, count, sum;
• See Piano_Keys.java
Representing Integers
• There are four types of integers in Java, each
providing a different bits to store the value
byte s 7 bits
short s 15 bits
int s 31 bits
long s 63 bits
Conversions
• Each data value and variable is associated with a
particular data type
Widening Conversions
• Widening conversions are generally safe because
they go from a smaller data space to a larger one
From To
Narrowing Conversions
• Narrowing conversions are more dangerous
because they usually go from a smaller data space
to a larger one
Assignment Statements
• An assignment statement takes the following form:
variable-name = expression;
Constants
• A constant is similar to a variable except that they
keep the same value throughout their existence
• They are specified using the reserved word final
in the declaration
• For example:
final double PI = 3.14159;
Constants
• When appropriate, constants are better than
variables because:
– they prevent inadvertent errors because their value
cannot change
Escape Sequences
• An escape sequence is a special sequence of
characters preceded by a backslash (\)
Numeric Input
• Converting a string that holds an integer into the
integer value can be done with a method in the
Integer wrapper class:
Expressions
• An expression is a combination of operators and
operands
• The arithmetic operators include addition (+),
subtraction (-), multiplication (*), and division (/)
Division
• If the operands of the / operator are both
integers, the result is an integer (the fractional part
is truncated)
• If one or more operands to the / operator are
floating point values, the result is a floating point
value
• The remainder operator (%) returns the integer
remainder after dividing the first operand by the
second
• The operands to the % operator must be integers
Division
• The remainder result takes the sign of the
numerator
Expression Result
17 / 5 3
17.0 / 5 3.4
17 / 5.0 3.4
9 / 12 0
9.0 / 12.0 0.75
6 % 2 0
14 % 5 4
-14 % 5 -4
Operator Precedence
• The order in which operands are evaluated in an
expression is determined by a well-defined
precedence hierarchy
Operator Precedence
• Multiplication, division, and remainder have a
higher precedence than addition and subtraction
Expression: 5 + 12 / 5 - 10 % 3
Order of evaluation: 3 1 4 2
Result: 6
Operator Precedence
Expression Result
2 + 3 * 4 / 2 8
3 * 13 + 2 41
(3 * 13) + 2 41
3 * (13 + 2) 45
4 * (11 - 6) * (-8 + 10) 40
(5 * (4 - 1)) / 2 7
Performing Conversions
• In Java, conversion between one data type and
another can occur three ways
Casting
• A cast is an operator that is specified by a type
name in parentheses
• It is placed in front of the value to be converted
• The following example truncates the fractional part
of the floating point value in money and stores the
integer portion in dollars
dollars = (int) money;
• The value in money is not changed
• If a conversion is possible, it can be done through a
cast
• The statement
count++;
is essentially equivalent to
count = count + 1;
is equivalent to
++count;
total = count++;
total = ++count;
Assignment Operators
• Often we perform an operation on a variable, then
store the result back into that variable
is equivalent to
num = num + count;
Assignment Operators
• There are many such assignment operators, always
written as op= , such as:
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
Assignment Operators
• The right hand side of an assignment operator can
be a complete expression
Therefore
result /= (total-MIN) % num;
is equivalent to
result = result / ((total-MIN) % num);
Program Development
• The creation of software involves four basic
activities:
– establishing the requirements
– creating a design
– implementing the code
– testing the implementation
Requirements
• Requirements specify the tasks a program must
accomplish (what to do, not how to do it)
Design
• A program follows an algorithm, which is a step-by-
step process for solving a problem
Implementation
• Implementation is the process of translating a
design into source code
Testing
• A program should be executed multiple times with
various input in an attempt to find errors
Internet Programming
Program Structure
Program Constructs 66
Internet Programming -Developed by AZAM RASHID
Program Structure
• Instead of a linear fashion for execution program,
we can now examine how to making decision for
alternatives
• Topic 5 focuses on:
– decisions and loops
– block statement
– if statements
– if..else statements
– nested if statements
– for statements
– while statement
– do..while statement
Program Constructs 67
Internet Programming -Developed by AZAM RASHID
The if Statement
• The Java if statement has the following syntax:
if (condition)
statement;
Program Constructs 68
Internet Programming -Developed by AZAM RASHID
The if Statement
false
condition
true
statement
Program Constructs 69
Internet Programming -Developed by AZAM RASHID
Boolean Expressions
• The condition of an if statement must evaluate to
a true or false result
== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
<= greater than or equal to
Program Constructs 70
Internet Programming -Developed by AZAM RASHID
Block Statements
• Several statements can be grouped together into a
block statement
Program Constructs 71
Internet Programming -Developed by AZAM RASHID
Program Constructs 72
Internet Programming -Developed by AZAM RASHID
false
condition
true
statement1 statement2
Program Constructs 73
Internet Programming -Developed by AZAM RASHID
Nested if Statements
• The body of an if statement or else clause can
be another if statement
Program Constructs 74
Internet Programming -Developed by AZAM RASHID
Multiway Selection
false true
isSleeping
complicated structure
has one entry and
one exit.
Program Constructs 75
Internet Programming -Developed by AZAM RASHID
Program Constructs 76
Internet Programming -Developed by AZAM RASHID
Program Constructs 77
Internet Programming -Developed by AZAM RASHID
while (condition)
statement;
Program Constructs 78
Internet Programming -Developed by AZAM RASHID
false
condition
true
statement
Program Constructs 79
Internet Programming -Developed by AZAM RASHID
Program Constructs 80
Internet Programming -Developed by AZAM RASHID
Infinite Loops
• The body of a while loop must eventually make
the condition false
Program Constructs 81
Internet Programming -Developed by AZAM RASHID
Logical Operators
• There are three logical operators in Java:
Operator Operation
! Logical NOT
&& Logical AND
|| Logical OR
Program Constructs 82
Internet Programming -Developed by AZAM RASHID
Logical NOT
• The logical NOT is also called logical negation or
logical complement
• If a is true, !a is false; if a is false, then !a is true
false true
true false
Program Constructs 83
Internet Programming -Developed by AZAM RASHID
Logical AND
• The expression a && b is true if both a and b are
true, and false otherwise
Program Constructs 84
Internet Programming -Developed by AZAM RASHID
Logical OR
• The expression a || b is true if a or b or both are
true, and false otherwise
a b a || b
Program Constructs 85
Internet Programming -Developed by AZAM RASHID
Logical Operators
• Conditions in selection statements and loops can
use logical operators to form more complex
expressions
System.out.println ("Processing...");
Program Constructs 86
Internet Programming -Developed by AZAM RASHID
Logical Operators
• Full expressions can be evaluated using truth tables
Program Constructs 87
Internet Programming -Developed by AZAM RASHID
Program Constructs 88
Internet Programming -Developed by AZAM RASHID
• For example:
larger = (num1 > num2) ? num1 : num2;
Program Constructs 89
Internet Programming -Developed by AZAM RASHID
Program Constructs 90
Internet Programming -Developed by AZAM RASHID
Program Constructs 91
Internet Programming -Developed by AZAM RASHID
switch (expression) {
case value1:
statement-list1
case value2:
statement-list2
case …
Program Constructs 92
Internet Programming -Developed by AZAM RASHID
Program Constructs 93
Internet Programming -Developed by AZAM RASHID
• the do statement
• the for statement
Program Constructs 94
Internet Programming -Developed by AZAM RASHID
The do Statement
• The do statement has the following syntax:
do
statement
while (condition);
Program Constructs 95
Internet Programming -Developed by AZAM RASHID
The do Statement
statement
true
condition
false
Program Constructs 96
Internet Programming -Developed by AZAM RASHID
The do Statement
• The key difference between a do loop and a while
loop is that the body of the do loop will execute at
least once
• If the condition of a while loop is false initially, the
body of the loop is never executed
• Another way to put this is that a while loop will
execute zero or more times and a do loop will
execute one or more times
Program Constructs 97
Internet Programming -Developed by AZAM RASHID
which is equivalent to
initialization;
while (condition) {
statement;
increment;
}
Program Constructs 98
Internet Programming -Developed by AZAM RASHID
Program Constructs 99
Internet Programming -Developed by AZAM RASHID
initialization
false
condition
true
statement
increment
System.out.println (count);
sum += num;
System.out.println (sum);
Internet Programming
Objects and Classes
Objects
• An object has:
– state - descriptive characteristics
– behaviors - what it can do (or be done to it)
Classes
• A class is a blueprint of an object
• It is the model or pattern from which objects are
created
• A class defines the methods and types of data
associated with an object
• Creating an object from a class is called
instantiation; an object is an instance of a particular
class
• For example, the Account class could describe
many bank accounts, but toms_savings is a
particular bank account with a particular balance
Object and Classes 108
Internet Programming -Developed by AZAM RASHID
Creating Objects
• The new operator creates an object from a class:
Account toms_savings = new Account ();
Constructors
• A constructor is a special method used to set up an
object
• It has the same name as the class
• It can take parameters, which are often used to
initialize some variables in the object
• For example, the Account constructor could be
set up to take a parameter specifying its initial
balance:
Object References
• The declaration of the object reference variable and
the creation of the object can be separate activities:
Account toms_savings;
toms_savings.deposit (35.00);
Expression Range
Math.abs (rand.newInt()) % 6 + 1 1 to 6
Math.abs (rand.newInt()) % 10 + 1 1 to 10
Math.abs (rand.newInt()) % 101 0 to 100
Math.abs (rand.newInt()) % 11 + 20 20 to 30
Math.abs (rand.newInt()) % 11 - 5 -5 to 5
References
• An object reference holds the memory address of
an object
bishop1
Assignment
• The act of assignment takes a copy of a value and
stores it in a variable
num2 = num1;
Before After
num1 num2 num1 num2
5 12 5 5
Reference Assignment
• For object references, the value of the memory
location is copied:
bishop2 = bishop1;
Before After
Methods
• A class contains methods; prior to defining our own
classes, we must explore method definitions
• We've defined the main method many times
statement-list
Methods
• A method definition:
int cube;
return cube;
} // method third_power
Methods
• A method may contain local declarations as well as
executable statements
} // method third_power
method2();
method1();
Parameters
• A method can be defined to accept zero or more
parameters
Parameters
• When a parameter is passed, a copy of the value is
made and assigned to the formal parameter
• Both primitive types and object references can be
passed as parameters
• When an object reference is passed, the formal
parameter becomes an alias of the actual
parameter
• See Parameter_Passing.java
• Usually, we will avoid putting multiple methods in
the class that contains the main method
Defining Classes
• The syntax for defining a class is:
class class-name {
declarations
constructors
methods
}
Defining Classes
class Account {
int account_number;
double balance;
Account (int account, double initial) {
account_number = account;
balance = initial;
} // constructor Account
void deposit (double amount) {
balance = balance + amount;
} // method deposit
} // class Account
Constructors
• A constructor:
– is a special method that is used to set up a newly
created object
– often sets the initial values of variables
– has the same name as the class
– does not return a value
– has no return type, not even void
Default Constructors
• If no constructor is coded, Java provides a default
constructor.
public CyberPet() { }
account_number
2908371
Class
balance
573.21
int account_number
double balance
account_number
4113787
balance
9211.84
Encapsulation
• You can take one of two views of an object:
– internal - the structure of its data, the algorithms
used by its methods
– external - the interaction of the object with other
objects in the program
Encapsulation
• An object should be self-governing; any changes to
the object's state (its variables) should be
accomplished by that object's methods
Encapsulation
• An encapsulated object can be thought of as a
black box; its inner workings are hidden to the
client
toms_savings deposit
withdraw
client
add_interest
produce_statement
Static Variables
• Normally, each object has its own data space
Static Methods
• Normally, we invoke a method through an instance
(an object) of a class
Static Methods
• The main method is static; it is invoked by the
system without creating an object
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
Object and Classes 140
Internet Programming -Developed by AZAM RASHID
Overloaded Methods
• The println method is overloaded:
println (String s)
println (int i)
println (double d)
etc.
• The lines
Overloaded Methods
• 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
• See Casino.java
Internet Programming
Inheritance
Inheritance 144
Internet Programming -Developed by AZAM RASHID
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
Inheritance 145
Internet Programming -Developed by AZAM RASHID
Inheritance
• Inheritance relationships are often shown
graphically, with the arrow pointing to the parent
class:
Vehicle
Car
Inheritance 146
Internet Programming -Developed by AZAM RASHID
Deriving Subclasses
• In Java, the reserved word extends is used to
establish an inheritance relationship
// class contents
• See Words.java
Inheritance 147
Internet Programming -Developed by AZAM RASHID
Inheritance 148
Internet Programming -Developed by AZAM RASHID
Inheritance 149
Internet Programming -Developed by AZAM RASHID
Inheritance 150
Internet Programming -Developed by AZAM RASHID
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
• See Messages.java
Inheritance 151
Internet Programming -Developed by AZAM RASHID
Inheritance 153
Internet Programming -Developed by AZAM RASHID
Class Hierarchies
• A child class of one parent can be the parent of
another child, forming class hierarchies:
Business
Retail_Business Service_Business
Inheritance 154
Internet Programming -Developed by AZAM RASHID
Class Hierarchies
• Two children of the same parent are called siblings
Inheritance 155
Internet Programming -Developed by AZAM RASHID
Inheritance 157
Internet Programming -Developed by AZAM RASHID
Inheritance 158
Internet Programming -Developed by AZAM RASHID
Holiday day;
Inheritance 159
Internet Programming -Developed by AZAM RASHID
Inheritance 160
Internet Programming -Developed by AZAM RASHID
Polymorphism
• A polymorphic reference is one which can refer to
one of several possible methods
• Suppose the Holiday class has a method called
celebrate, and the Christmas class overrode it
Inheritance 161
Internet Programming -Developed by AZAM RASHID
Polymorphism
• In general, it is the type of the object being
referenced, not the reference type, that determines
which method is invoked
• See Messages2.java
Inheritanc 162
Internet Programming -Developed by AZAM RASHID
Polymorphism
• Note that, because all classes inherit from the
Object class, an Object reference can refer to
any type of object
• A Vector is designed to store Object references
Inheritance 163
Internet Programming -Developed by AZAM RASHID
Polymorphism
Staff_Member
Employee Volunteer
Hourly Executive
Inheritance 164