You are on page 1of 164

Internet Programming -Developed by AZAM RASHID

Internet Programming

Java Program Development

Java Programming Development 1


Internet Programming -Developed by AZAM RASHID

Why Study Java?


• Java is a relatively simple language

• Java is Object Oriented (OO)


– OO languages divide programs into modules
(objects) that encapsulate the program's actions
– Object Oriented Programming (OOP) is a good way
to build complex software systems
• Java is robust
– Errors in Java don't cause system crashes as often
as errors in other languages

Java Programming Development 3


Internet Programming -Developed by AZAM RASHID

Why Study Java?


• Java is platform independent
– A Java program can be run without changes on
different kinds of computers
• Java is a distributed language
– Java programs can easily be run on computer
networks
• Java is a relatively secure language
– Java contains features that protect against viruses
and other untrusted code

Java Programming Development 4


Internet Programming -Developed by AZAM RASHID

Simple Program Skeleton


class Classed {
Classed( ) {
data and control
}

public static void main (String[] agnate) {


new Classed( );
}
}

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

Java Program Structure


• Program
A general term used to describe a set of one or
more Java classes that can be compiled and run

• Class
It describes the variables and methods appropriate
to some real-word entity

A class contains one or more methods

Java Programming Development 6


Internet Programming -Developed by AZAM RASHID

Java Program Structure


• Object
It is created from a class by means of the new
statement.

The process of creating an object is called


instantiation or object creation

• Variable
It constitutes storage in the computer which hold
values that change

An object variable holds a reference to the storage


where an object is to be placed

Java Programming Development 7


Internet Programming -Developed by AZAM RASHID

Java Program Structure


• Identifier
The name of an entity in Java such as a class
• Keyword
A word that has a special meaning in Java and
cannot be used as an identifier
• Statement
The work of a program is done through its
statement
A statement causes some actions, such as
instantiate an object or to call a method to print out
a message
Java Programming Development 8
Internet Programming -Developed by AZAM RASHID

Java Program Structure


• Method
A method contains program statements

It groups together statements to provide a


structured functionality for a Java object

A method is defined with an identifier and its own


body of variables and statement

It is activated by calling it through its identifiers

A Java application always executes the main


method

Java Programming Development 9


Internet Programming -Developed by AZAM RASHID

Java Program Structure


• Constructor
Every class has a special method called a
constructor that is activated when an object of that
class is instantiated

The constructor has the same identifier as the class

• Parameters
A method can have variations based on values
supplied to it in parentheses

The values supplied are called parameters

Java Programming Development 10


Internet Programming -Developed by AZAM RASHID

Java Translation and Execution


• The Java compiler translates Java source code into
a special representation called bytecode
• Java bytecode is not the machine language for any
traditional CPU
• Another software tool, called an interpreter,
translates bytecode into machine language and
executes it
• Therefore the Java compiler is not tied to any
particular machine
• Java is considered to be architecture-neutral

Java Programming Development 11


Internet Programming -Developed by AZAM RASHID

Java Translation and Execution

Java source
code Java
bytecode

Java
compiler
Java Bytecode
interpreter compiler

Machine
code

Java Programming Development 12


Internet Programming -Developed by AZAM RASHID

Java Translation and Execution


• Executing the compiler in a command line
environment:
> javac Welcome.java
• This creates a file called Lincoln.class, which
is submitted to the interpreter to be executed:
> java Welcome
• The .java extension is used at compile time, but
the .class extension is not used with the
interpreter
• Other environments do this processing in a different
way

Java Programming Development 13


Internet Programming -Developed by AZAM RASHID

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 Programming Development 14


Internet Programming -Developed by AZAM RASHID

The Java API Packages


• Some packages in the Java API:

java.applet java.net
java.awt java.rmi
java.beans java.security
java.io java.sql
java.lang java.text
java.math java.util

Java Programming Development 15


Internet Programming -Developed by AZAM RASHID

Importing Packages
• Using a class from the Java API can be
accomplished by using its fully qualified name:
java.lang.System.out.printing ();

• Or, the package can be imported using an import


statement, which has two forms:
import java.applet.*;

import java.util.Random;

• The java.lang package is automatically


imported into every Java program

Java Programming Development 16


Internet Programming -Developed by AZAM RASHID

White Space
• Spaces, blank lines, and tabs are collectively called
white space and are used to separate words and
symbols in a program

• Extra white space is ignored

• A valid Java program can be formatted many


different ways

• Programs should be formatted to enhance


readability, using consistent indentation

Java Programming Development 17


Internet Programming -Developed by AZAM RASHID

Comments
• Comments in a program are also called inline
documentation

• They should be included to explain the purpose of


the program and describe processing steps

• Java comments can take two forms:


// comment runs to the end of the line

/* comment runs to terminating

symbol, even across line breaks */

Java Programming Development 18


Internet Programming -Developed by AZAM RASHID

Identifiers
• Identifiers are the words a programmer uses in a
program

• Most identifiers have no predefined meaning except


as specified by the programmer

• An identifier can be made up of letters, digits, the


underscore character (_), and the dollar sign

• They cannot begin with a digit


• Java is case sensitive, therefore Total and
total are different identifiers

Java Programming Development 19


Internet Programming -Developed by AZAM RASHID

Reserved Words
• Some identifiers, called reserved words, have specific
meanings in Java and cannot be used in other ways

abstract default goto operator synchronized


boolean do if outer this
break double implements package throw
byte else import private throws
byvalue extends inner protected transient
case false instanceof public true
cast final int rest try
catch finally interface return var
char float long short void
class for native static volatile
const future new super while
continue generic null switch

Java Programming Development 20


Internet Programming -Developed by AZAM RASHID

Literals
• A literal is an explicit data value used in a program

• Integer literals:
25 69 -4288

• Floating point literals:


3.14159 42.075 -0.5

• String literals:
"The result is: "

"To thine own self be true."

Java Programming Development 21


Internet Programming -Developed by AZAM RASHID

The Java API


• The Java Application Programmer Interface (API) is
a collection of classes that can be used as needed
• The printing and print methods are part of
the Java API; they are not part of the Java
language itself

• Both methods print information to the screen; the


difference is that printing moves to the next
line when done, but print does not

Java Programming Development 22


Internet Programming -Developed by AZAM RASHID

String Concatenation and Addition


• The + operator serves two purposes

• When applied to two strings, they are combined into


one (string concatenation)

• When applied to a string and some other value (like


a number), that value is converted to a string and
they are concatenated

• When applied to two numeric types, they are added


together arithmetically

Java Programming Development 23


Internet Programming -Developed by AZAM RASHID

Internet Programming
Java DataTypes and Operators

Java Data and Operators 24


Internet Programming -Developed by AZAM RASHID

Java Data and Operators


• We can now examine the core elements of
programming

• This Topic focuses on:


– data types
– variable declaration and use
– operators and expressions

Java Data and Operators 25


Internet Programming -Developed by AZAM RASHID

Primitive Data Types


• A data type is defined by a set of values and the
operators you can perform on them

• Each value stored in memory is associated with a


particular data type

• The Java language has several predefined types,


called primitive data types

• The following reserved words represent eight


different primitive types:
byte, short, int, long, float, double, boolean, char

Java Data and Operators 26


Internet Programming -Developed by AZAM RASHID

Integers
• There are four separate integer primitive data types

• They differ by the amount of memory used to store


them

Type Storage Min Value Max Value

byte 8 bits -128 127


short 16 bits -32,768 32,767
int 32 bits -2,147,483,648 2,147,483,647
long 64 bits < -9 x 1018 > 9 x 1018

Java Data and Operators 27


Internet Programming -Developed by AZAM RASHID

Floating Point
• There are two floating point types:

Approximate Approximate
Type Storage Min Value Max Value

float 32 bits -3.4 x 1038 3.4 x 1038


double 64 bits -1.7 x 10308 1.7 x 10308

• The float type stores 7 significant digits

• The double type stores 15 significant digits

Java Data and Operators 28


Internet Programming -Developed by AZAM RASHID

Characters
• A char value stores a single character from the
Unicode character set

• A character set is an ordered list of characters

• The Unicode character set uses sixteen bits per


character, allowing for 65,536 unique characters

• It is an international character set, containing


symbols and characters from many world
languages

Java Data and Operators 29


Internet Programming -Developed by AZAM RASHID

Characters
• The ASCII character set is still the basis for many
other programming languages

• ASCII is a subset of Unicode, including:

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, ...

Java Data and Operators 30


Internet Programming -Developed by AZAM RASHID

Boolean
• A boolean value represents a true or false
condition

• They can also be used to represent any two states,


such as a light bulb being on or off
• The reserved words true and false are the
only valid values for a boolean type

Java Data and Operators 31


Internet Programming -Developed by AZAM RASHID

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

• Wrapper classes are useful in situations where you


need an object instead of a primitive type

• They also contain some useful methods

Java Data and Operators 32


Internet Programming -Developed by AZAM RASHID

Variables
• A variable is an identifier that represents a location
in memory that holds a particular type of data

• Variables must be declared before they can be


used

• The syntax of a variable declaration is:


data-type variable-name;

• For example:
int total;

Java Data and Operators 33


Internet Programming -Developed by AZAM RASHID

Variables
• Multiple variables can be declared on the same
line:
int total, count, sum;

• Variables can be initialized (given an initial value) in


the declaration:
int total = 0, count = 20;
float unit_price = 57.25;

• See Piano_Keys.java

Java Data and Operators 34


Internet Programming -Developed by AZAM RASHID

Representing Integers
• There are four types of integers in Java, each
providing a different bits to store the value

• Each has a sign bit. If it is 1, the number is


negative; if it is 0, the number is positive

byte s 7 bits

short s 15 bits

int s 31 bits

long s 63 bits

Java Data and Operators 35


Internet Programming -Developed by AZAM RASHID

Conversions
• Each data value and variable is associated with a
particular data type

• It is sometimes necessary to convert a value of one


data type to another

• Not all conversions are possible. For example,


boolean values cannot be converted to any other
type and vice versa

• Even if a conversion is possible, we need to be


careful that information is not lost in the process

Java Data and Operators 36


Internet Programming -Developed by AZAM RASHID

Widening Conversions
• Widening conversions are generally safe because
they go from a smaller data space to a larger one

• The widening conversions are:

From To

byte short, int, long, float, or double


short int, long, float, or double
char int, long, float, or double
int long, float, or double
long float or double
float double

Java Data and Operators 37


Internet Programming -Developed by AZAM RASHID

Narrowing Conversions
• Narrowing conversions are more dangerous
because they usually go from a smaller data space
to a larger one

• The narrowing conversions are:


From To
byte char
short byte or char
char byte or short
int byte, short, or char
long byte, short, char, or int
float byte, short, char, int or long
double byte, short, char, int, long, or float
Java Data and Operators 38
Internet Programming -Developed by AZAM RASHID

Assignment Statements
• An assignment statement takes the following form:
variable-name = expression;

• The expression is evaluated and the result is stored


in the variable, overwriting the value currently
stored in the variable

• The expression can be a single value or a more


complicated calculation

Java Data and Operators 39


Internet Programming -Developed by AZAM RASHID

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;

final int STUDENTS = 25;

Java Data and Operators 40


Internet Programming -Developed by AZAM RASHID

Constants
• When appropriate, constants are better than
variables because:
– they prevent inadvertent errors because their value
cannot change

• They are better than literal values because:


– they make code more readable by giving meaning to
a value
– they facilitate change because the value is only
specified in one place

Java Data and Operators 41


Internet Programming -Developed by AZAM RASHID

Input and Output


• Java I/O is based on input streams and output
streams
• There are three predefined standard streams:

Stream Purpose Default Device


System.in reading input keyboard
System.out writing output monitor
System.err writing errors monitor

• The print and println methods write to


standard output

Java Data and Operators 42


Internet Programming -Developed by AZAM RASHID

Input and Output


• The Java API allows you to create many kinds of
streams to perform various kinds of I/O
• To read character strings, we will convert the
System.in stream to another kind of stream
using:

BufferedReader stdin = new BufferedReader


(new InputStreamReader (System.in));

• This declaration creates a new stream called


stdin
• We will discuss object creation in more detail later

Java Data and Operators 43


Internet Programming -Developed by AZAM RASHID

Escape Sequences
• An escape sequence is a special sequence of
characters preceded by a backslash (\)

• They indicate some special purpose, such as:

Escape Sequence Meaning


\t tab
\n new line
\" double quote
\' single quote
\\ backslash

Java Data and Operators 44


Internet Programming -Developed by AZAM RASHID

Numeric Input
• Converting a string that holds an integer into the
integer value can be done with a method in the
Integer wrapper class:

value = Integer.parseInt (my_string);

• A value can be read and converted in one line:

num = Integer.parseInt (stdin.readLine());

Java Data and Operators 45


Internet Programming -Developed by AZAM RASHID

Expressions
• An expression is a combination of operators and
operands
• The arithmetic operators include addition (+),
subtraction (-), multiplication (*), and division (/)

• Operands can be literal values, variables, or other


sources of data

• The programmer determines what is done with the


result of an expression (stored, printed, etc.)

Java Data and Operators 46


Internet Programming -Developed by AZAM RASHID

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

Java Data and Operators 47


Internet Programming -Developed by AZAM RASHID

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

Java Data and Operators 48


Internet Programming -Developed by AZAM RASHID

Operator Precedence
• The order in which operands are evaluated in an
expression is determined by a well-defined
precedence hierarchy

• Operators at the same level of precedence are


evaluated according to their associativity (right to
left or left to right)

• Parentheses can be used to force precedence

• Refer to a complete operator precedence chart for


all Java operators

Java Data and Operators 49


Internet Programming -Developed by AZAM RASHID

Operator Precedence
• Multiplication, division, and remainder have a
higher precedence than addition and subtraction

• Both groups associate left to right

Expression: 5 + 12 / 5 - 10 % 3

Order of evaluation: 3 1 4 2

Result: 6

Java Data and Operators 50


Internet Programming -Developed by AZAM RASHID

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

Java Data and Operators 51


Internet Programming -Developed by AZAM RASHID

Performing Conversions
• In Java, conversion between one data type and
another can occur three ways

• Assignment conversion - when a value of one type


is assigned to a variable of another type

• Arithmetic promotion - occurs automatically when


operators modify the types of their operands

• Casting - an operator that forces a value to


another type

Java Data and Operators 52


Internet Programming -Developed by AZAM RASHID

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

Java Data and Operators 53


Internet Programming -Developed by AZAM RASHID

The Increment and Decrement Operators


• The increment operator (++) adds one to its integer
or floating point operand

• The decrement operator (--) subtracts one

• The statement
count++;

is essentially equivalent to
count = count + 1;

Java Data and Operators 54


Internet Programming -Developed by AZAM RASHID

The Increment and Decrement Operators


• The increment and decrement operators can be
applied in prefix (before the variable) or postfix
(after the variable) form

• When used alone in a statement, the prefix and


postfix forms are basically equivalent. That is,
count++;

is equivalent to
++count;

Java Data and Operators 55


Internet Programming -Developed by AZAM RASHID

The Increment and Decrement Operators


• When used in a larger expression, the prefix and
postfix forms have a different effect

• In both cases the variable is increm ented


(decremented)

• But the value used in the larger expression


depends on the form
Expression Operation Value of Expression
count++ add 1 old value
++count add 1 new value
count-- subtract 1 old value
--count subtract 1 new value
Java Data and Operators 56
Internet Programming -Developed by AZAM RASHID

The Increment and Decrement Operators


• If count currently contains 45, then

total = count++;

assigns 45 to total and 46 to coun t

• If count currently contains 45, then

total = ++count;

assigns the value 46 to both total and count

Java Data and Operators 57


Internet Programming -Developed by AZAM RASHID

The Increment and Decrement Operators


• If sum contains 25, then the statement

System.out.println (sum++ + " " + ++sum +


" " + sum + " " + sum--);

prints the following result:


25 27 27 27

and sum contains 26 after the line is complete

Java Data and Operators 58


Internet Programming -Developed by AZAM RASHID

Assignment Operators
• Often we perform an operation on a variable, then
store the result back into that variable

• Java provides assignment operators that simplify


that process

• For example, the statement


num += count;

is equivalent to
num = num + count;

Java Data and Operators 59


Internet Programming -Developed by AZAM RASHID

Assignment Operators
• There are many such assignment operators, always
written as op= , such as:

Operator Example Equivalent To

+= 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

Java Data and Operators 60


Internet Programming -Developed by AZAM RASHID

Assignment Operators
• The right hand side of an assignment operator can
be a complete expression

• The entire right-hand expression is evaluated first,


then combined with the additional operation

Therefore
result /= (total-MIN) % num;

is equivalent to
result = result / ((total-MIN) % num);

Java Data and Operators 61


Internet Programming -Developed by AZAM RASHID

Program Development
• The creation of software involves four basic
activities:
– establishing the requirements
– creating a design
– implementing the code
– testing the implementation

• The development process is much more involved


that this, but these basic steps are a good starting
point

Java Data and Operators 62


Internet Programming -Developed by AZAM RASHID

Requirements
• Requirements specify the tasks a program must
accomplish (what to do, not how to do it)

• They often address the user interface

• An initial set of requirements are often provided, but


usually must be critiqued, modified, and expanded

• It is often difficult to establish detailed,


unambiguous, complete requirements

• Careful attention to the requirements can save


significant time and money in the overall project

Java Data and Operators 63


Internet Programming -Developed by AZAM RASHID

Design
• A program follows an algorithm, which is a step-by-
step process for solving a problem

• The design specifies the algorithms and data


needed

• In object-oriented development, it establishes the


classes, objects, and methods that are required

• The details of a method may be expressed in


pseudocode, which is code-like, but does not
necessarily follow any specific syntax

Java Data and Operators 64


Internet Programming -Developed by AZAM RASHID

Implementation
• Implementation is the process of translating a
design into source code

• Most novice programmers think that writing code is


the heart of software development, but it actually
should be the least creative

• Almost all important decisions are made during


requirements analysis and design

• Implementation should focus on coding details,


including style guidelines and documentation

Java Data and Operators 65


Internet Programming -Developed by AZAM RASHID

Testing
• A program should be executed multiple times with
various input in an attempt to find errors

• Debugging is the process of discovering the cause


of a problem and fixing it

• Programmers often erroneously think that there is


"only one more bug" to fix

• Tests should focus on design details as well as


overall requirements

Java Data and Operators 66


Internet Programming -Developed by AZAM RASHID

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;

• If the boolean condition is true, the statement is


executed; if it is false, the statement is skipped

• This provides basic decision making capabilities

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

• Java has several equality and relational operators:


Operator Meaning

== 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

• Blocks are delimited by braces

• A block statement can be used wherever a


statement is called for in the Java syntax

Program Constructs 71
Internet Programming -Developed by AZAM RASHID

The if-else Statement


• An else clause can be added to an if
statement to make it an if-else statement:
if (condition)
statement1;
else
statement2;

• If the condition is true, statement1 is executed; if


the condition is false, statement2 is executed

Program Constructs 72
Internet Programming -Developed by AZAM RASHID

The if-else Statement

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

• These are called nested if statements

• Note: an else clause is matched to the last


unmatched if (no matter what the indentation
implies)

Program Constructs 74
Internet Programming -Developed by AZAM RASHID

Multiway Selection

false true
isSleeping

• We can embed if- false true


isEating “I’m sleeping”
then-else clauses to
create multiway false
isThinking true “I’m eating”
selection structures.
“I don’t know “I’m thinking”
• Note that this what I’m doing”

complicated structure
has one entry and
one exit.

Program Constructs 75
Internet Programming -Developed by AZAM RASHID

Selection Statements: Examples


Simple If
if (isEating)
return "Eating";
If-then-else
if (isEating)
System.out.println("Is Eating");
else
System.out.println("Is NOT Eating");

if (isSleeping) Multiway Selection


System.out.println("I'm sleeping");
else if (isEating)
System.out.println("I'm eating");
else if (isThinking)
System.out.println("I'm thinking");
else
System.out.println("Error: I don't know what I'm doing");

Program Constructs 76
Internet Programming -Developed by AZAM RASHID

The Dangling Else Problem


• The programmer must be careful to match each else
with its corresponding if.
• Rule: An else clause matches with the closest
previous unmatched if clause.
• Indentation (which the compiler ignores) should
reflect the statement’s logic.
Incorrect Indentation Correct Indentation
if (condition1) if (condition1)
if (condition2) if (condition2)
System.out.println("One"); System.out.println("One");
else else
System.out.println("Two"); System.out.println("Two");

Program Constructs 77
Internet Programming -Developed by AZAM RASHID

The while Statement


• A while statement has the following syntax:

while (condition)
statement;

• If the condition is true, the statement is executed;


then the condition is evaluated again

• The statement is executed over and over until the


condition becomes false

Program Constructs 78
Internet Programming -Developed by AZAM RASHID

The while Statement

false
condition

true

statement

Program Constructs 79
Internet Programming -Developed by AZAM RASHID

The while Statement


• If the condition of a while statement is false
initially, the statement is never executed
• Therefore, we say that a while statement
executes zero or more times

Program Constructs 80
Internet Programming -Developed by AZAM RASHID

Infinite Loops
• The body of a while loop must eventually make
the condition false

• If not, it is an infinite loop, which will execute until


the user interrupts the program

• This is a common type of logical error -- always


double check that your loops will terminate normally

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

• They all take boolean operands and produce


boolean results

• Logical NOT is unary (one operand), but logical


AND and OR are binary (two operands)

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

• Logical expressions can be shown using truth


tables
a !a

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

• Truth tables show all possible combinations of all


terms
a b a && b

false false false


false true false
true false false
true true true

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

false false false


false true true
true false true
true true true

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

if (total < MAX && !found)

System.out.println ("Processing...");

• Logical operators have precedence relationships


between themselves and other operators

Program Constructs 86
Internet Programming -Developed by AZAM RASHID

Logical Operators
• Full expressions can be evaluated using truth tables

total < MAX


total < MAX found !found && !found

false false true false


false true false false
true false true true
true true false false

Program Constructs 87
Internet Programming -Developed by AZAM RASHID

The Conditional Operator


• Java has a conditional operator that evaluates a
boolean condition that determines which of two
expressions is evaluated

• The result of the chosen expression is the result of


the entire conditional operator

• Its syntax is:


condition ? expression1 : expression2

• If the condition is true, expression1 is evaluated; if


it is false, expression2 is evaluated

Program Constructs 88
Internet Programming -Developed by AZAM RASHID

The Conditional Operator


• It is similar to an if-else statement, except that it is
an expression that returns a value

• For example:
larger = (num1 > num2) ? num1 : num2;

• If num1 is greater that num2, then num1 is assigned


to larger; otherwise, num2 is assigned to larger

• The conditional operator is ternary, meaning it


requires three operands

Program Constructs 89
Internet Programming -Developed by AZAM RASHID

The Conditional Operator


• Another example:

System.out.println ("Your change is " + count +

(count == 1) ? "Dime" : "Dimes");

• If count equals 1, "Dime" is printed, otherwise


"Dimes" is printed

Program Constructs 90
Internet Programming -Developed by AZAM RASHID

Another Selection Statement - switch


• The if and the if-else statements are selection
statements, allowing us to select which statement to
perform next based on some boolean condition
• Another selection construct, called the switch
statement, provides another way to choose the next
action
• The switch statement evaluates an expression,
then attempts to match the result to one of a series
of values
• Execution transfers to statement list associated with
the first value that matches

Program Constructs 91
Internet Programming -Developed by AZAM RASHID

The switch Statement


• The syntax of the switch statement is:

switch (expression) {

case value1:

statement-list1

case value2:

statement-list2

case …

Program Constructs 92
Internet Programming -Developed by AZAM RASHID

The switch Statement


• The expression must evaluate to an integral value,
such as an integer or character
• The break statement is usually used to terminate
the statement list of each case, which causes
control to jump to the end of the switch statement
and continue
• A default case can be added to the end of the list
of cases, and will execute if no other case matches

Program Constructs 93
Internet Programming -Developed by AZAM RASHID

More Repetition Constructs


• In addition to while loops, Java has two other
constructs used to perform repetition:

• the do statement
• the for statement

• Each loop type has its own unique characteristics

• You must choose which loop type to use in each


situation

Program Constructs 94
Internet Programming -Developed by AZAM RASHID

The do Statement
• The do statement has the following syntax:

do
statement
while (condition);

• The statement is executed until the condition


becomes false
• It is similar to a while statement, except that its
termination condition is evaluated after the loop
body

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

The for Statement


• The syntax of the for loop is

for (initialization; condition; increment)


statement;

which is equivalent to

initialization;
while (condition) {
statement;
increment;
}

Program Constructs 98
Internet Programming -Developed by AZAM RASHID

The for Statement


• Like a while loop, the condition of a for statement
is tested prior to executing the loop body
• Therefore, a for loop will execute zero or more
times

• It is well suited for executing a specific number of


times, known in advance

• Note that the initialization portion is only performed


once, but the increment portion is executed after
each iteration

Program Constructs 99
Internet Programming -Developed by AZAM RASHID

The for Statement

initialization

false
condition

true

statement

increment

Program Constructs 100


Internet Programming -Developed by AZAM RASHID

The for Statement


• Examples:

for (int count=1; count < 75; count++)

System.out.println (count);

for (int num=5; num <= total; num *= 2) {

sum += num;

System.out.println (sum);

Program Constructs 101


Internet Programming -Developed by AZAM RASHID

The for Statement


• Each expression in the header of a for loop is
optional
– If the initialization is left out, no initialization is
performed
– If the condition is left out, it is always considered to
be true, and therefore makes an infinite loop
– If the increment is left out, no increment operation is
performed

• Both semi-colons are always required

Program Constructs 102


Internet Programming -Developed by AZAM RASHID

The break and continue statements


• The break statement, which we used with switch
statements, can also be used inside a loop
• When the break statement is executed, control
jumps to the statement after the loop (the condition
is not evaluated again)
• A similar construct, the continue statement, can
also be executed in a loop
• When the continue statement is executed, control
jumps to the end of the loop and the condition is
evaluated

Program Constructs 103


Internet Programming -Developed by AZAM RASHID

The break and continue Statements


• They can also be used to jump to a line in your
program with a particular label

• Jumping from one point in the program to another in


an unstructured manner is not good practice
• Therefore, as a rule of thumb, avoid the break
statement except when needed in switch
statements, and avoid the continue statement
altogether

Program Constructs 104


Internet Programming -Developed by AZAM RASHID

Internet Programming
Objects and Classes

Object and Classes 105


Internet Programming -Developed by AZAM RASHID

Objects and Classes


• Now that some low-level programming concepts
have been established, we can examine objects in
more detail
• Topic 6 focuses on:
– the concept of objects
– the use of classes to create objects
– using predefined classes
– defining methods and passing parameters
– defining classes
– visibility modifiers
– static variables and methods
– method overloading

Object and Classes 106


Internet Programming -Developed by AZAM RASHID

Objects
• An object has:
– state - descriptive characteristics
– behaviors - what it can do (or be done to it)

• For example, a particular bank account


– has an account number
– has a current balance
– can be deposited into
– can be withdrawn from

Object and Classes 107


Internet Programming -Developed by AZAM RASHID

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 ();

• This declaration asserts that toms_savings is a


variable that refers to an object created from the
Account class

• It is initialized to the object created by the new


operator

• The newly created object is set up by a call to a


constructor of the class

Object and Classes 109


Internet Programming -Developed by AZAM RASHID

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:

Account toms_savings = new Account (125.89);

Object and Classes 110


Internet Programming -Developed by AZAM RASHID

Object References
• The declaration of the object reference variable and
the creation of the object can be separate activities:

Account toms_savings;

toms_savings = new Account (125.89);

• Once an object exists, its methods can be invoked


using the dot operator:

toms_savings.deposit (35.00);

Object and Classes 111


Internet Programming -Developed by AZAM RASHID

The String Class


• A character string in Java is an object, defined by
the String class

String name = new String ("Ken Arnold");

• Because strings are so common, Java allows an


abbreviated syntax:

String name = "Ken Arnold";

• Java strings are immutable; once a string object


has a value, it cannot be changed

Object and Classes 112


Internet Programming -Developed by AZAM RASHID

The String Class


• A character in a string can be referred to by its
position, or index

• The index of the first character is zero


• The String class is defined in the java.lang
package (and is therefore automatically imported)
• Many helpful methods are defined in the String
class

Object and Classes 113


Internet Programming -Developed by AZAM RASHID

The StringTokenizer Class


• The StringTokenizer class makes it easy to
break up a string into pieces called tokens

• By default, the delimiters for the tokens are the


space, tab, carriage return, and newline characters
(white space)
• The StringTokenizer class is defined in the
java.util package

Object and Classes 114


Internet Programming -Developed by AZAM RASHID

The Random Class


• A program may need to produce a random number
• The Random class provides methods to simulate a
random number generator
• The nextInt method returns a random number
from the entire spectrum of int values

• Usually, the number must be scaled and shifted into


a particular range to be useful

Object and Classes 115


Internet Programming -Developed by AZAM RASHID

The Random Class

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

Object and Classes 116


Internet Programming -Developed by AZAM RASHID

References
• An object reference holds the memory address of
an object

Chess_Piece bishop1 = new Chess_Piece();

bishop1

• All interaction with an object occurs through a


reference variable
• References have an effect on actions such as
assignment
Object and Classes 117
Internet Programming -Developed by AZAM RASHID

Assignment
• The act of assignment takes a copy of a value and
stores it in a variable

• For primitive types:

num2 = num1;

Before After
num1 num2 num1 num2

5 12 5 5

Object and Classes 118


Internet Programming -Developed by AZAM RASHID

Reference Assignment
• For object references, the value of the memory
location is copied:
bishop2 = bishop1;

Before After

bishop1 bishop2 bishop1 bishop2

Object and Classes 119


Internet Programming -Developed by AZAM RASHID

Methods
• A class contains methods; prior to defining our own
classes, we must explore method definitions
• We've defined the main method many times

• All methods follow the same syntax:

return-type method-name ( parameter-list ) {

statement-list

Object and Classes 120


Internet Programming -Developed by AZAM RASHID

Methods
• A method definition:

int third_power (int number) {

int cube;

cube = number * number * number;

return cube;

} // method third_power

Object and Classes 121


Internet Programming -Developed by AZAM RASHID

Methods
• A method may contain local declarations as well as
executable statements

• Variables declared locally can only be used locally


• The third_power method could be written
without any local variables:

int third_power (int number) {

return number * number * number;

} // method third_power

Object and Classes 122


Internet Programming -Developed by AZAM RASHID

The return Statement


• The return type of a method indicates the type of
value that the method sends back to the calling
location
• A method that does not return a value (such as
main) has a void return type

• The return statement specifies the value that will be


returned

• Its expression must conform to the return type

Object and Classes 123


Internet Programming -Developed by AZAM RASHID

Method Flow of Control


• The main method is invoked by the system when
you submit the bytecode to the interpreter

• Each method call returns to the place that called it

main method1 method2

method2();
method1();

Object and Classes 124


Internet Programming -Developed by AZAM RASHID

Parameters
• A method can be defined to accept zero or more
parameters

• Each parameter in the parameter list is specified by


its type and name

• The parameters in the method definition are called


formal parameters

• The values passed to a method when it is invoked


are called actual parameters

Object and Classes 125


Internet Programming -Developed by AZAM RASHID

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

Object and Classes 126


Internet Programming -Developed by AZAM RASHID

Defining Classes
• The syntax for defining a class is:
class class-name {
declarations
constructors
methods
}

• The variables, constructors, and methods of a class


are generically called members of the class

Object and Classes 127


Internet Programming -Developed by AZAM RASHID

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

Object and Classes 128


Internet Programming -Developed by AZAM RASHID

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

• The programmer does not have to define a


constructor for a class

Object and Classes 129


Internet Programming -Developed by AZAM RASHID

Default Constructors
• If no constructor is coded, Java provides a default
constructor.

• If a class is public, the default constructor will also


be public.

• CyberPet: Invoking the default constructor:


CyberPet socrates = new CyberPet();

is equivalent to invoking a constructor defined as:

public CyberPet() { }

Object and Classes 130


Internet Programming -Developed by AZAM RASHID

Classes and Objects


• A class defines the data types for an object, but a
class does not store data values

• Each object has its own unique data space

• The variables defined in a class are called instance


variables because each instance of the class has its
own

• All methods in a class have access to all instance


variables of the class

• Methods are shared among all objects of a class

Object and Classes 131


Internet Programming -Developed by AZAM RASHID

Classes and Objects Objects

account_number
2908371
Class
balance
573.21
int account_number
double balance
account_number
4113787
balance
9211.84

Object and Classes 132


Internet Programming -Developed by AZAM RASHID

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

• From the external view, an object is an


encapsulated entity, providing a set of specific
services

• These services define the interface to the object

Object and Classes 133


Internet Programming -Developed by AZAM RASHID

Encapsulation
• An object should be self-governing; any changes to
the object's state (its variables) should be
accomplished by that object's methods

• We should make it difficult, if not impossible, for


another object to "reach in" and alter an object's
state

• The user, or client, of an object can request its


services, but it should not have to be aware of how
those services are accomplished

Object and Classes 134


Internet Programming -Developed by AZAM RASHID

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

Object and Classes 135


Internet Programming -Developed by AZAM RASHID

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

Object and Classes 136


Internet Programming -Developed by AZAM RASHID

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

Object and Classes 137


Internet Programming -Developed by AZAM RASHID

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

Object and Classes 138


Internet Programming -Developed by AZAM RASHID

Static Methods
• 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

Object and Classes 139


Internet Programming -Developed by AZAM RASHID

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

System.out.println ("The total is:");


System.out.println (total);

invoke different versions of the println method

Object and Classes 141


Internet Programming -Developed by AZAM RASHID

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

Object and Classes 142


Internet Programming -Developed by AZAM RASHID

Overloading and Method Signatures


• A method name is overloaded if there is more than
one method with the same name:

public CyberPet () { } // Constructor #1


public CyberPet (String str) // Constructor #2
{
name = str;
}

• Methods are uniquely identified by their method


signatures, which include the name, number and type
of arguments, and return type of a method.

Object and Classes 143


Internet Programming -Developed by AZAM RASHID

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 should create an is-a relationship,


meaning the child is-a more specific version of the
parent

Inheritance 146
Internet Programming -Developed by AZAM RASHID

Deriving Subclasses
• In Java, the reserved word extends is used to
establish an inheritance relationship

class Car extends Vehicle {

// class contents

• See Words.java

Inheritance 147
Internet Programming -Developed by AZAM RASHID

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

Inheritance 148
Internet Programming -Developed by AZAM RASHID

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
• See Words2.java

Inheritance 149
Internet Programming -Developed by AZAM RASHID

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
• See Eating.java and School.java

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

Overloading vs. Overriding


• Don't confuse the concepts of these two
• 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
Inheritance 152
Internet Programming -Developed by AZAM RASHID

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)

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

Macy's K-Mart Kinko's

Inheritance 154
Internet Programming -Developed by AZAM RASHID

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
• See Accounts2.java

Inheritance 155
Internet Programming -Developed by AZAM RASHID

Inheritance: The Square Class


• Inheritance allows us to specialize a class.
public class Rectangle {
private double length;
A Square is a
private double width; Rectangle whose
public Rectangle (double l, double w) length = width
{
length = l;
width = w;
public class Square extends Rectangle {
} // Rectangle()
public Square (double side) {
public double calculateArea()
super(side, side); // Superconstructor
{
}
return length * width;
} // Square
} // calculateArea()
} // Rectangle
Inheritance 156
Internet Programming -Developed by AZAM RASHID

Using the Square Class


Create a new Square
with a side of 100
public class TestSquare
{
public static void main(String argv[])
{
Square square = new Square ( 100 );
System.out.println( "square's area is " + square.calculateArea() );
}
} // TestSquare
Output
The inherited calculateArea() Produced
method can be used just as if it
were defined in Square

square’s area is 10000.0

Inheritance 157
Internet Programming -Developed by AZAM RASHID

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
• See Test_toString.java

Inheritance 158
Internet Programming -Developed by AZAM RASHID

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();

Inheritance 159
Internet Programming -Developed by AZAM RASHID

References and Inheritance


• 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

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

• Now consider the following invocation:


day.celebrate();

• If day refers to a Holiday object, it invokes


Holiday's version of celebrate; if it refers to a
Christmas object, it invokes that version

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

• Note that, if an invocation is in a loop, the exact


same line of code could execute different methods
at different times

• Polymorphic references are therefore resolved at


run-time, not during compilation

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

• The instanceOf operator can be used to


determine the class from which an object was
created
• See Variety.java

Inheritance 163
Internet Programming -Developed by AZAM RASHID

Polymorphism

Staff_Member

Employee Volunteer

Hourly Executive

Inheritance 164

You might also like