Java Tutorial
-
Upload
kashif2146 -
Category
Documents
-
view
24 -
download
1
Transcript of Java Tutorial
Java Programming Development 1
Java Program Development
Internet Programming
Internet Programming -Developed by AZAM RASHID
Java Programming Development 3
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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 4
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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 5
Simple Program Skeletonclass 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(); }}
Internet Programming -Developed by AZAM RASHID
Java Programming Development 6
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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 7
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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 8
Java Program Structure
• IdentifierThe name of an entity in Java such as a class
• KeywordA word that has a special meaning in Java and cannot be used as an identifier
• StatementThe 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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 9
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 mainmethod
Internet Programming -Developed by AZAM RASHID
Java Programming Development 10
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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 11
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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 12
Java Translation and Execution
Java sourcecode
Machinecode
Javabytecode
Javainterpreter
Bytecodecompiler
Javacompiler
Internet Programming -Developed by AZAM RASHID
Java Programming Development 13
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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 14
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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 15
The Java API Packages
• Some packages in the Java API:
java.appletjava.awtjava.beansjava.iojava.langjava.math
java.netjava.rmijava.securityjava.sqljava.textjava.util
Internet Programming -Developed by AZAM RASHID
Java Programming Development 16
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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 17
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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 18
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 */
Internet Programming -Developed by AZAM RASHID
Java Programming Development 19
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 andtotal are different identifiers
Internet Programming -Developed by AZAM RASHID
Java Programming Development 20
Reserved Words
• Some identifiers, called reserved words, have specific meanings in Java and cannot be used in other ways
abstractbooleanbreakbytebyvaluecasecastcatchcharclassconstcontinue
defaultdodoubleelseextendsfalsefinalfinallyfloatforfuturegeneric
gotoifimplementsimportinnerinstanceofintinterfacelongnativenewnull
operatorouterpackageprivateprotectedpublicrestreturnshortstaticsuperswitch
synchronizedthisthrowthrowstransienttruetryvarvoidvolatilewhile
Internet Programming -Developed by AZAM RASHID
Java Programming Development 21
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."
Internet Programming -Developed by AZAM RASHID
Java Programming Development 22
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
Internet Programming -Developed by AZAM RASHID
Java Programming Development 23
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
Internet Programming -Developed by AZAM RASHID
Java DataTypes and Operators
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 24
Internet Programming
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 25
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 26
Integers
• There are four separate integer primitive data types
• They differ by the amount of memory used to store them
Type
byteshortintlong
Storage
8 bits16 bits32 bits64 bits
Min Value
-128-32,768-2,147,483,648< -9 x 1018
Max Value
12732,7672,147,483,647> 9 x 1018
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 27
Floating Point
• There are two floating point types:
• The float type stores 7 significant digits
• The double type stores 15 significant digits
Type
floatdouble
Storage
32 bits64 bits
ApproximateMin Value
-3.4 x 1038
-1.7 x 10308
ApproximateMax Value
3.4 x 1038
1.7 x 10308
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 28
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 29
Characters
• The ASCII character set is still the basis for many other programming languages
• ASCII is a subset of Unicode, including:
uppercase letterslowercase letterspunctuationdigitsspecial symbolscontrol characters
A, B, C, …a, b, c, …period, semi-colon, …0, 1, 2, …&, |, \, …carriage return, tab, ...
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 30
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 31
Wrappers
• For each primitive data type there is a corresponding wrapper class. For example:
• Wrapper classes are useful in situations where you need an object instead of a primitive type
• They also contain some useful methods
Primitive Type
intdoublechar
boolean
Wrapper ClassIntegerDouble
CharacterBoolean
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 32
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;
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 33
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 34
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
short
int
long
s 7 bits
s 15 bits
s 31 bits
s 63 bits
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 35
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 36
Widening Conversions
• Widening conversions are generally safe because they go from a smaller data space to a larger one
• The widening conversions are:
From
byteshortcharintlongfloat
To
short, int, long, float, or doubleint, long, float, or doubleint, long, float, or doublelong, float, or doublefloat or doubledouble
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 37
Narrowing Conversions
• Narrowing conversions are more dangerousbecause they usually go from a smaller data space to a larger one
• The narrowing conversions are:Frombyteshortcharintlongfloatdouble
Tocharbyte or charbyte or shortbyte, short, or charbyte, short, char, or intbyte, short, char, int or longbyte, short, char, int, long, or float
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 38
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 39
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 finalin the declaration
• For example:
final double PI = 3.14159;
final int STUDENTS = 25;
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 40
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 41
Input and Output
• Java I/O is based on input streams and output streams
• There are three predefined standard streams:
• The print and println methods write to standard output
Stream
System.inSystem.outSystem.err
Purpose
reading inputwriting outputwriting errors
Default Device
keyboardmonitormonitor
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 42
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 theSystem.in stream to another kind of stream using:
BufferedReader stdin = new BufferedReader
(new InputStreamReader (System.in));
• This declaration creates a new stream calledstdin
• We will discuss object creation in more detail later
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 43
Escape Sequences
• An escape sequence is a special sequence of characters preceded by a backslash (\)
• They indicate some special purpose, such as:
Escape Sequence
\t\n\"\'\\
Meaningtabnew linedouble quotesingle quotebackslash
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 44
Numeric Input
• Converting a string that holds an integer into the integer value can be done with a method in theInteger wrapper class:
value = Integer.parseInt (my_string);
• A value can be read and converted in one line:
num = Integer.parseInt (stdin.readLine());
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 45
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.)
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 46
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 47
Division
• The remainder result takes the sign of the numerator
Expression
17 / 517.0 / 517 / 5.0
9 / 129.0 / 12.0
6 % 214 % 5-14 % 5
Result
33.43.4
00.75
04-4
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 48
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 49
Operator Precedence
• Multiplication, division, and remainder have a higher precedence than addition and subtraction
• Both groups associate left to right
Expression:
Order of evaluation:
Result:
5 + 12 / 5 - 10 % 3
6
43 21
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 50
Operator Precedence
Expression
2 + 3 * 4 / 2
3 * 13 + 2(3 * 13) + 23 * (13 + 2)
4 * (11 - 6) * (-8 + 10)
(5 * (4 - 1)) / 2
Result
8
414145
40
7
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 51
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 52
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 53
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;
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 54
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;
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 55
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
Expressioncount++++countcount----count
Operationadd 1add 1
subtract 1subtract 1
Value of Expressionold valuenew valueold valuenew value
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 56
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 57
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 58
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;
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 59
Assignment Operators
• There are many such assignment operators, always written as op= , such as:
Operator
+=-=*=/=%=
Example
x += yx -= yx *= yx /= yx %= y
Equivalent To
x = x + yx = x - yx = x * yx = x / yx = x % y
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 60
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);
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 61
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 62
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 63
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 inpseudocode, which is code-like, but does not necessarily follow any specific syntax
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 64
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 65
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
Internet Programming -Developed by AZAM RASHID
Java Data and Operators 66
Program Structure
Internet Programming
Internet Programming -Developed by AZAM RASHID
Program Constructs 66
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 67
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 68
The if Statement
statement
conditionfalse
true
Internet Programming -Developed by AZAM RASHID
Program Constructs 69
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 tonot equal to
less thanless than or equal to
greater thangreater 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
Internet Programming -Developed by AZAM RASHID
Program Constructs 71
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 72
The if-else Statement
statement1
conditionfalse
true
statement2
Internet Programming -Developed by AZAM RASHID
Program Constructs 73
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)
Internet Programming -Developed by AZAM RASHID
Program Constructs 74
Multiway Selection
• We can embed if-then-else clauses to create multiwayselection structures.
• Note that this complicated structure has one entry and one exit.
isSleeping
“I’m sleeping”isEating
“I’m eating”isThinking
“I’m thinking”
true
true
true
false
false
false
“I don’t knowwhat I’m doing”
Internet Programming -Developed by AZAM RASHID
Program Constructs 75
Selection Statements: Examples
if (isEating)return "Eating";
if (isSleeping)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");
Simple If
Multiway Selection
if (isEating)System.out.println("Is Eating");
elseSystem.out.println("Is NOT Eating");
If-then-else
Internet Programming -Developed by AZAM RASHID
Program Constructs 76
The Dangling Else Problem
• The programmer must be careful to match each elsewith 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.
if (condition1)if (condition2)
System.out.println("One");else
System.out.println("Two");
if (condition1)if (condition2)
System.out.println("One");else
System.out.println("Two");
if (condition1)if (condition2)
System.out.println("One");else
System.out.println("Two");
Correct IndentationIncorrect Indentation
Internet Programming -Developed by AZAM RASHID
Program Constructs 77
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 78
The while Statement
statement
conditionfalse
true
Internet Programming -Developed by AZAM RASHID
Program Constructs 79
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 80
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 81
Logical Operators
• There are three logical operators in Java:
• They all take boolean operands and produceboolean results
• Logical NOT is unary (one operand), but logical AND and OR are binary (two operands)
Operator
!&&||
Operation
Logical NOTLogical ANDLogical OR
Internet Programming -Developed by AZAM RASHID
Program Constructs 82
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
falsetrue
!a
truefalse
Internet Programming -Developed by AZAM RASHID
Program Constructs 83
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
falsefalsetruetrue
b
falsetruefalsetrue
a && b
falsefalsefalsetrue
Internet Programming -Developed by AZAM RASHID
Program Constructs 84
Logical OR
• The expression a || b is true if a or b or both are true, and false otherwise
a
falsefalsetruetrue
b
falsetruefalsetrue
a || b
falsetruetruetrue
Internet Programming -Developed by AZAM RASHID
Program Constructs 85
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 86
Logical Operators
• Full expressions can be evaluated using truth tables
total < MAX
falsefalsetruetrue
found
falsetruefalsetrue
!found
truefalsetruefalse
total < MAX&& !found
falsefalsetruefalse
Internet Programming -Developed by AZAM RASHID
Program Constructs 87
The Conditional Operator
• Java has a conditional operator that evaluates aboolean 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
Internet Programming -Developed by AZAM RASHID
Program Constructs 88
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 89
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 90
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 91
The switch Statement
• The syntax of the switch statement is:
switch (expression) {
case value1:
statement-list1
case value2:
statement-list2
case …
}
Internet Programming -Developed by AZAM RASHID
Program Constructs 92
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 93
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 94
The do Statement
• The do statement has the following syntax:
do
statement
while (condition);
• The statement is executed until the conditionbecomes false
• It is similar to a while statement, except that its termination condition is evaluated after the loop body
Internet Programming -Developed by AZAM RASHID
Program Constructs 95
The do Statement
statement
condition
false
true
Internet Programming -Developed by AZAM RASHID
Program Constructs 96
The do Statement
• The key difference between a do loop and a whileloop 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
Internet Programming -Developed by AZAM RASHID
Program Constructs 97
The for Statement
• The syntax of the for loop is
for (initialization; condition; increment)
statement;
which is equivalent to
initialization;
while (condition) {
statement;
increment;
}
Internet Programming -Developed by AZAM RASHID
Program Constructs 98
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 99
The for Statement
statement
conditionfalse
true
initialization
increment
Internet Programming -Developed by AZAM RASHID
Program Constructs 100
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);
}
Internet Programming -Developed by AZAM RASHID
Program Constructs 101
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
Internet Programming -Developed by AZAM RASHID
Program Constructs 102
The break and continue statements
• The break statement, which we used with switchstatements, 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
Internet Programming -Developed by AZAM RASHID
Program Constructs 103
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 breakstatement except when needed in switchstatements, and avoid the continue statement altogether
Internet Programming -Developed by AZAM RASHID
Program Constructs 104
Objects and Classes
Internet Programming
Internet Programming -Developed by AZAM RASHID
Object and Classes 105
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 106
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 107
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 108
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 109
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);
Internet Programming -Developed by AZAM RASHID
Object and Classes 110
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);
Internet Programming -Developed by AZAM RASHID
Object and Classes 111
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 112
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.langpackage (and is therefore automatically imported)
• Many helpful methods are defined in the String class
Internet Programming -Developed by AZAM RASHID
Object and Classes 113
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 114
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 115
The Random Class
Expression
Math.abs (rand.newInt()) % 6 + 1
Math.abs (rand.newInt()) % 10 + 1
Math.abs (rand.newInt()) % 101
Math.abs (rand.newInt()) % 11 + 20
Math.abs (rand.newInt()) % 11 - 5
Range
1 to 6
1 to 10
0 to 100
20 to 30
-5 to 5
Internet Programming -Developed by AZAM RASHID
Object and Classes 116
References
• An object reference holds the memory address of an object
Chess_Piece bishop1 = new Chess_Piece();
• All interaction with an object occurs through a reference variable
• References have an effect on actions such as assignment
bishop1
Internet Programming -Developed by AZAM RASHID
Object and Classes 117
Assignment
• The act of assignment takes a copy of a value and stores it in a variable
• For primitive types:
num2 = num1;
Before
num1
5
num2
12
After
num1
5
num2
5
Internet Programming -Developed by AZAM RASHID
Object and Classes 118
Reference Assignment
• For object references, the value of the memory location is copied:
bishop2 = bishop1;
Before
bishop1 bishop2
After
bishop1 bishop2
Internet Programming -Developed by AZAM RASHID
Object and Classes 119
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
}
Internet Programming -Developed by AZAM RASHID
Object and Classes 120
Methods
• A method definition:
int third_power (int number) {
int cube;
cube = number * number * number;
return cube;
} // method third_power
Internet Programming -Developed by AZAM RASHID
Object and Classes 121
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 122
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 asmain) has a void return type
• The return statement specifies the value that will be returned
• Its expression must conform to the return type
Internet Programming -Developed by AZAM RASHID
Object and Classes 123
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
method1();method2();
Internet Programming -Developed by AZAM RASHID
Object and Classes 124
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 125
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 126
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 127
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 128
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 129
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() { }
Internet Programming -Developed by AZAM RASHID
Object and Classes 130
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 131
Classes and Objects
Class
Objects
int account_numberdouble balance
account_number
balance
2908371
573.21
account_number
balance
4113787
9211.84
Internet Programming -Developed by AZAM RASHID
Object and Classes 132
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 133
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 134
Encapsulation
• An encapsulated object can be thought of as a black box; its inner workings are hidden to the client
client
toms_savings deposit
withdraw
add_interest
produce_statement
Internet Programming -Developed by AZAM RASHID
Object and Classes 135
The static Modifier
• The static modifier can be applied to variables or methods
• It associates a variable or method with the classrather than an object
• This approach is a distinct departure from the normal way of thinking about objects
Internet Programming -Developed by AZAM RASHID
Object and Classes 136
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 137
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.langpackage contains several static mathematical operations
Math.abs (num) -- absolute value
Math.sqrt (num) -- square root
Internet Programming -Developed by AZAM RASHID
Object and Classes 138
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 139
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 140
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
Internet Programming -Developed by AZAM RASHID
Object and Classes 141
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 -Developed by AZAM RASHID
Object and Classes 142
Overloading and Method Signatures
• A method name is overloaded if there is more than one method with the same name:
• Methods are uniquely identified by their method signatures, which include the name, number and type of arguments, and return type of a method.
public CyberPet () { } // Constructor #1public CyberPet (String str) // Constructor #2{
name = str;}
Internet Programming -Developed by AZAM RASHID
Object and Classes 143
Inheritance
Internet Programming
Internet Programming -Developed by AZAM RASHID
Inheritance 144
Inheritance
• Inheritance allows a software developer to derive a new class from an existing one
• The existing class is called the parent class, orsuperclass, 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
Internet Programming -Developed by AZAM RASHID
Inheritance 145
Inheritance
• Inheritance relationships are often shown graphically, with the arrow pointing to the parent class:
• Inheritance should create an is-a relationship, meaning the child is-a more specific version of the parent
Vehicle
Car
Internet Programming -Developed by AZAM RASHID
Inheritance 146
Deriving Subclasses
• In Java, the reserved word extends is used to establish an inheritance relationship
class Car extends Vehicle {
// class contents
}
• See Words.java
Internet Programming -Developed by AZAM RASHID
Inheritance 147
The protected Modifier
• The visibility modifiers determine which class members get inherited and which do not
• Variables and methods declared with publicvisibility are inherited, and those with privatevisibility 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
Internet Programming -Developed by AZAM RASHID
Inheritance 148
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
Internet Programming -Developed by AZAM RASHID
Inheritance 149
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
Internet Programming -Developed by AZAM RASHID
Inheritance 150
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
Internet Programming -Developed by AZAM RASHID
Inheritance 151
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
Internet Programming -Developed by AZAM RASHID
Inheritance 152
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)
Internet Programming -Developed by AZAM RASHID
Inheritance 153
Class Hierarchies
• A child class of one parent can be the parent of another child, forming class hierarchies:
Business
Service_BusinessRetail_Business
K-MartMacy's Kinko's
Internet Programming -Developed by AZAM RASHID
Inheritance 154
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
Internet Programming -Developed by AZAM RASHID
Inheritance 155
Inheritance: The Square Class
• Inheritance allows us to specialize a class.
public class Rectangle {private double length; private double width;public Rectangle (double l, double w) {
length = l;width = w;
} // Rectangle()
public double calculateArea() {
return length * width;} // calculateArea()
} // Rectangle
public class Square extends Rectangle {
public Square (double side) {super(side, side); // Superconstructor
}} // Square
A Square is a Rectangle whose length = width
Internet Programming -Developed by AZAM RASHID
Inheritance 156
Using the Square Class
public class TestSquare{
public static void main(String argv[]){
Square square = new Square ( 100 );System.out.println( "square's area is " + square.calculateArea() );
}} // TestSquare
The inherited calculateArea()method can be used just as if it
were defined in Square
Create a new Square with a side of 100
Output Produced
square’s area is 10000.0
Internet Programming -Developed by AZAM RASHID
Inheritance 157
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
Internet Programming -Developed by AZAM RASHID
Inheritance 158
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 Holidayreference could actually be used to point to a Christmas object:
Holiday day;
day = new Christmas();
Internet Programming -Developed by AZAM RASHID
Inheritance 159
References and Inheritance
• Assigning a predecessor object to an ancestorreference 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
Internet Programming -Developed by AZAM RASHID
Inheritance 160
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
Internet Programming -Developed by AZAM RASHID
Inheritance 161
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
Internet Programming -Developed by AZAM RASHID
Inheritanc 162
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
Internet Programming -Developed by AZAM RASHID
Inheritance 163
Polymorphism
Staff_Member
VolunteerEmployee
ExecutiveHourly
Internet Programming -Developed by AZAM RASHID
Inheritance 164