for use of ist410 students onlyintro-1 java programming

114
For use of IST410 Stu dents only Intro-1 JAVA PROGRAMMING

Post on 19-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-1

JAVA PROGRAMMING

Page 2: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-2

Course Objectives

Write and Test simple Java Applications and applets Use object-oriented concepts in writing Java programs Explore concepts of abstraction, inheritance and

polymorphism and apply these to Java classes Write Graphical User Interfaces (GUI) using Swing classes Write and use event handlers Write Database applications Explore java’s collection framework Other topics such as time permits

Page 3: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-3

Java Language

Java was originally called Oak and was designed for use in embedded consumer electronics applications

It was later repositioned for internet based applications Java is now a general-purpose, strongly typed, multi-

threaded, class-based, object-oriented language It is like C/C++ in many respects It excludes a number of C/C++ features and includes

concepts from other object-oriented languages Java programs are machine-independent

Page 4: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-4

Java Language

Java is an interpreted high-level language It includes automatic space management and garbage

collection It is a strongly typed language i.e. all its variables and

expressions have a known type at the compile time A Java program is compiled to a ‘bytecode’ instruction set

defined by the Java Virtual Machine (JVM) Specification Java language is implemented in a series of ‘packages’ or

libraries

Page 5: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-5

Writing a Procedural Program Java Style

// First Java Program, Procedural

public class MyProceduralGreetings {

public static void main(String args[]) {

System.out.println("Hello Java Gurus");

}

}

System.out.println sends output to the console All Java programs automatically use a package called

java.lang

Page 6: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-6

Compiling and running a program

A Java source file has an extension of java The name of the source file is EXACTLY same as the

name of the class There is EXACTLY one class definition per source file For the class named MyProceduralGreetings,

the name of the source file is

MyProceduralGreetings.java The javac command is used to compile a java program

Page 7: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-7

Compiling and running a program

We use java development kit (jdk) from Sun to compile and execute all of our java programs

jdk is a command-line oriented software comprising of a number of components

To compile > javac MyProceduralGreetings.java Error-free compilation results in a file called

MyProceduralGreetings.class For the present, we assume that our default (or current)

directory is the same as the directory where our source code lives

Page 8: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-8

Compiling and running a program

MyProceduralGreetings.class is the byte code translation of MyProceduralGreetings

To run this program, we invoke the java interpreter> java MyProceduralGreetings

The java interpreter executes a java program by interpreting bytecode instructions

Notice that an executable is not produced since an executable is machine-dependent

For the present, jdk is available free of cost from Sun; visit http://java.sun.com

Page 9: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-9

First Object Oriented Program

// First Java Program, OOPpublic class MyGreetingsOOP {

public void greetAll() { System.out.println("Hello Java Gurus"); } public static void main(String args[]) { MyGreetingsOOP mg = new

MyGreetingsOOP(); mg.greetAll(); }} Even though main ‘method’ is coded in the class, consider

main to be part of a different class - to be discussed later

Page 10: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-10

Compiling and running revisited

We store the source for MyGreetingsOOP in a file named MyGreetingsOOP.java

Notice the name of the source file is EXACTLY same as the name of the class

We compile this file with javac

>javac MyGreetingsOOP.java We execute the byte code using the java interpreter

>java MyGreetingsOOP

Page 11: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-11

Java Development Kit (jdk)

jdk is a combination of a number of programs The core part of jdk includes (not limited to)

javac - Java Compiler java - Interpreter jre - Java Runtime Interpreter appletviewer - Limited applet browser javadoc - Document generator jar - Archive tool jdb - Debugger others - javap (disassembler), javakey (digital signature), javah (C

Header and stub file generator) The documentation for the Java language is available from javasoft

as a separate download: http://www.javasoft.com

Page 12: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-12

Advantages of Java

Portability: Java programs are compiled into a machine-independent byte code - any standard JVM can execute the byte code

Garbage collection Java incorporates automatic memory management ‘Unreachable’ objects are removed by the garbage collector Garbage collection results in release of memory to the free store Garbage collection is a low-priority activity

Improved code security Syntactic requirement of the language is verified Access requirements are verified Type-safety is ensured Existence of classes and methods are checked

Page 13: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-13

A note on JVM

JVM can be thought of as a ‘real machine’ It can be implemented in software and/or hardware It provides all features that a real machine is expected to

provide Instruction set Memory allocation and management Registers System stack Garbage-collected heap

Byte code must be compatible with the JVM specification

Page 14: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-14

Execution speed

Arguably, the most significant criticism of java programs is the ‘relatively slow’ execution speed

Java programs are interpreted - makes development faster - no rebuild time is necessary

Speed of execution can be improved by using JIT compilers

Many current JVMs come with built-in JIT compilers that translate the source to native code on the fly; execution speed is improved in these cases

Speed of execution can also be improved through judicious coding practices - beyond the scope of this discussion

Page 15: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-15

java language Packages

As mentioned earlier, the java language is organized into a number of packages

Java compiler is preprogrammed to include classes defined in the java.lang package

Other packages, if needed, must be ‘imported’ into the source

For example, to use graphics capabilities of java, a program needs to import java.awt package

import java.awt.*; A program may import any number of packages

Page 16: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-16

Java source file layout

The source definition of a class may have up to three components

An optional package definition Any number of (optional) import statements The class definition

package project.accounting;import java.awt.*;import java.io.*;import java.awt.event.*;

public class MyClass { // Class definition }

Optional declaration

Page 17: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-17

Java documentation

Page 18: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-18

Basics of Java Language

Page 19: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-19

Objectives

Statements Comments Variables, declaration and naming Primitive data types String data type Simple expressions and operators

Page 20: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-20

Comments

Single line comment// This is a single line comment.

Multiple line comment/* This is the beginning of a multiple line comment. The comment can span any number of lines and is exactly same as that in C and C++.

*/ Documenting comments- used by javadoc utility

/** Starts with a slash and is followed by 2 asteriks; can span multiple lines; can be placed anywhere in the code.*/

Page 21: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-21

Literals

A literal is a fixed value that can be a primitive type, or a String, or null

Integer Literal - An integer number, that can be expressed using decimal, octal or hexadecimal formats

Decimal literals can be 0 or start with a non-zero digit Octal literals start with 0 and are followed by octal digits Hexadecimal literals start with 0x or 0X and are followed by

hexadecimal digits (0,1,2,...,9,A,B,C,D,E,F) Long integer literals are specified with L or l (letter l) suffix

0 20 21345678L -234L 03217 0xabC43ffL 0X23CAFF

Page 22: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-22

Literals

Floating-Point Literal - A real number that can be single precision or double precision Floating point literals can be written in conventional

decimal or in scientific notation Single precision numbers are designated by F or f;

double precision by D or d

34.20f -.23f 3.14D 1E20D 2.0E-20D Boolean Literal- exactly two

true false

Page 23: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-23

Literals

Character Literal - Any unicode character surrounded by single quotes - the character set of Java is unicode, a 16 bit coding sequence

‘z’ ‘?’ ‘\u23AF’ ‘3’ ‘\b’ ‘\n’ ‘\t’ String Literal - Any set of unicode characters surrounded

by double quotes

“A quick java program”

“Hello world”

“Hello\nWorld contains a new line”

Page 24: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-24

Java keywords

Java language defines a number of keywords These keywords have predefined meaning to the compiler

and must be used in context All keywords are written in lower case Keyword list includes const and goto. These are reserved

words and not used in the language Keyword list also includes true and false that are

technically boolean literals Similarly, null is a literal An identifier name cannot be the same as a keyword

Page 25: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-25

Java keywords

abstract default if private throwboolean do implements protected throwsbreak double import public transientbyte else instanceof return trycase extends int short voidcatch final interface static volatilechar finally long super whileclass float native switchconst for new synchronize

dcontinuepackage

goto package this

Page 26: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-26

Identifiers names

Must start with a letter A letter is any Unicode character including

a - z A - Z _ (underscore) and $ sign Can be followed by any number of unicode letters or digits Have no predefined length Are case sensitive

The following two names are not equalMyName myName

Cannot be a Java reserved word Even if legal, do not use underscore and $ sign for names

Page 27: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-27

Identifier Naming Convention

class Names - Nouns or noun phrases, mixed case, first letter of each word capitalized

Employee

WaterCraft Method Names - Verbs or Verb phrases, mixed case, first

word in all lower case, first letter of all subsequent words capitalized

getEmployeeName()

setSpeedLimit()

accelerate()

Page 28: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-28

Identifier Naming Convention

Field Names - Nouns, noun phrases, or abbreviations for nouns, mixed case, first word in all lower case, first letter of all subsequent words capitalized

interestRate

height Constant Names - all upper case, words separated by

hyphens

PI

MIN_RATE

MAX_HEIGHT

Page 29: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-29

Statement

Each statement ends with a semicolon int p = 20;

System.out.println(“Value of p is “+p); Any number of white spaces can separate tokens

Normal way: int p = 20;Abnormal but legal:

int p

= 20;

White space is defined as a space, tab, or a newline character

Page 30: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-30

Primitive data types

Java data types are broadly categorized into two groups primitive types

boolean type char type integral types floating point types

non-primitive types Non-primitives data items represent objects; objects need

to be constructed before they can be used

Page 31: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-31

Primitive data types

All numeric data types are signed All data items are of fixed length irrespective of

underlying hardware and operating system

Type Sizechar 16 bitsbyte 8 bitsshort 16 bitsint 32 bitslong 64 bitsfloat 32 bitsdouble 64 bits

Page 32: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-32

boolean data type

Declaration - two forms in general

boolean flag;

flag = false; // false is a constant

boolean flag = false; // definition Two boolean constants:

false

true Default initialization when used as an instance variable

false

Page 33: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-33

char Data type

Used to store one Unicode character Unicode characters are 16 bits Declaration

char middleInitial = ‘K’; Default Initialization = ‘\u0000’ (null) Special characters with Escape sequence

‘\b’ Backspace ‘\t’ Tab ‘\n’ Newline‘\f’ Formfeed ‘\r’ CR \” Double quote\’ Single quote \\ Backslash\xxx Octal value between 000 and 0377\uxxxx where x is a Hex character

Page 34: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-34

Integral Data types

All integral types are signed

Numeric literals are

23 056 (Octal) 0xAB9C Default type of a numeric integer literal is int

Type bits Default Min Val Max Val

byte 8 0 -27 27-1

short 16 0 -215 215-1

int 32 0 -231 231-1

long 64 0L -263 263-1

Page 35: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-35

Integral Data types

Can we assign any integral type to any other?

byte b1 = 2; //compiler does the conversion

byte b2 = 233; //fails, 233 is an int, and too big

int i1 = 40; //OK, correct size and type

int i2 = 40L; //fails, constant is a long, 64 bits

long l1 = 200; //int always fits in a long

long l2 = 200L; //OK, correct size and type A smaller size integer can always be assigned to a larger

size integer variable

Page 36: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-36

Floating Point Data types

float and double are two floating point types All floating point types are signed

f or F is used to designate floats; d or D for doubles floating point literals are

10.27 2.34E10 0.3123F 300.10E-10D Default of a floating point numeric literal is double

Type bits Default

float 32 0.0f

double 64 0.0d

Page 37: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-37

Floating point Data types

Assignment compatibility

float f1 = 3.14; //fails, 3.14 is a double

float f2 = 3.14f; //OK, both are floats

double d1 = 3.14; //OK, 3.14 is a double

double d2 = 3.14f; //float always fits in a double

double d3 = 20E10D; //OK, both are double

Page 38: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-38

String Data type

Not a primitive type Strings are objects Declaration and compile-time creation

String s1 = “Java String”; Notice capital S in a String data type declaration Strings can also be created during run-time

String s2 = new String(“Java String”); Each String knows its length: length() String is an immutable object s1, s2 are references to objects

Page 39: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-39

Declaration of variables

All variables used in a program must be declared before they can be used.

As in other languages, a variable is declared once and is used as many times as necessary

int size = 3;double interestRate = 0.075;char middleInitial = ‘K’;String greetings = “Hello”;

The variable name should be meaningful and follow the naming convention discussed earlier

Page 40: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-40

Declaration of Constants

Declarationfinal int SIZE = 3;final double PI = 3.14;final char BACK_SPACE = ‘\b’;

final is a keyword and makes the identifier a constant A constant can be used wherever the associated value

would have been legal Names of constants are written using upper case letters Names with multiple words are separated by underscore

Page 41: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-41

Simple Arithmetic Operators

Associativity

++ -- +(unary) - (unary) right to left

* / % left to right

+ - left to right

+= -= *= /= %= right to left

Shown above in order of precedence Not a complete list Precedence can be changed with parenthesis

Page 42: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-42

Simple Arithmetic Operations

Comments-p Unary minus+p Unary plus

5 * 3 => 15 5.0 * 3.0 => 15.0 Multiplication5 / 3 => 1 5.0 / 3.0 => 1.6667 Division, note integer division5 % 3 => 2 Modulo, Integer operation only5 + 3 => 8 5.0 + 3.0 => 8.0 Addition5 - 3 => 2 5.0 - 3.0 => 2.0 Subtractiondouble p = 5 / 2.0; p is assigned 2.5;“John “+”Smith” => “John Smith” Overloaded +, concat

“Problem”+(1+2) => “Problem3” Numbers are promoted

“Problem”+1+2 => “Problem12” Numbers are promoted

Page 43: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-43

Simple Arithmetic Operations

Integral variables can be incremented or decremented by 1 using the unary ++ and -- operators respectively

Order of increment or decrement changes based on prefix or postfix use of these operators

Commentsa++ ; ++a; Add 1 to aa-- ; -- a; Subtract 1 from aa = ++b; Same as: b = b+1; a = b;a = b++; Same as: a = b; b = b+1;a = -- b; Same as: b = b-1; a = b;a = b--; Same as: a = b; b = b-1;

Page 44: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-44

Simple Arithmetic Operations

Java defines a number of shortcut assignment operators that combine the assignment operator (=) with another operator such as +, *, and %.

Operator Statement Explanation+= a += 2; Same as a = a+ 2;-= a -= b*2 – 3; Same as a = a – (b*2 – 3);*= a *= 2; Same as a = a*2;/= a /= 2; Same as a = a / 2;%= a %= 2; Same as a = a % 2;

Page 45: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-45

Promotion of numeric variables

byte Automatic promotion as shown by arrowsshortint charlongfloatdouble

Smaller sized variables/expressions can always be assigned to larger sized variables; they always fit

Assignment of larger sized values/expressions to smaller sized variables need explicit casting

int large = 20;byte small = (byte) large;

Page 46: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-46

Casting Integral Variables and Expressions

int large = 20;byte small = (byte) large;

Only the low order 8 bits are retained Similar bit extraction occurs while casting a large integer

to a smaller integer Casting needed for some expressions

byte a1 = 2;byte a2 = 3;byte a3 = a1 + a2; // will not compile

butbyte a3 = (byte) (a1+a2); // will be OK, why?

Page 47: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-47

Casting of primitive types

General format of castingvar1 = (type of var1) (expression);

One numeric type can be cast as other Numeric types cannot be cast as boolean char type cannot be cast as boolean Casting a real to integral type results in truncation of the

fractional part If the original expression is too big for the size of the

target variable, unpredictable result can occur; no error is reported

Casting among objects will be discussed at a later time

Page 48: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-48

Putting it together

We look at two examples here; these examples are not quite general, but get us started

Example #1Assume we have been given a count of pennies; we need to convert them to dollars, quarters, dimes, nickels and pennies

Example #2Assume we have been given a temperature in degree Celsius; we need to convert the temperature to Farenheit and print out the result

Page 49: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-49

PennyConverter.java

public class PennyConverter {public static void main(String args[]) {

int noOfPennies = Integer.parseInt(args[0]);final int DOLLAR = 100;final int QUARTER = 25;final int DIME = 10;final int NICKEL = 5; int penniesLeft;// Calculate number of Dollarsint dollars = noOfPennies / DOLLAR;penniesLeft = noOfPennies % DOLLAR;// Calculate number of Quartersint qrs = penniesLeft / QUARTER;penniesLeft %= QUARTER;

Command line argument is received and converted to an integer

Page 50: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-50

PennyConverter.java

// Calculate number of Dimesint dimes = penniesLeft / DIME;penniesLeft %= DIME; // Calculate number of Nickelsint nickels = penniesLeft / NICKEL;penniesLeft %= NICKEL; // Print resultsSystem.out.println("Starting number of pennies "+noOfPennies);System.out.println("Equals");System.out.print(dollars+" Dollars ");System.out.print(qrs+" Quarters ");System.out.print(dimes+" Dimes ");System.out.println(nickels+" Nickels");System.out.println("Pennies left = "+penniesLeft);

}}

Page 51: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-51

TempConvert.java

public class TempConvert {

public static void main (String args[]) {

double celsius = Double.parseDouble(args[0]);

double fheit = celsius * 9/5 + 32;

System.out.println("Input temperature in degree C = "+celsius);

System.out.println("Equivalent Farenheit = "+fheit);

}

}

Command line argument converted to a double

Page 52: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-52

Exercise

The objective is to calculate the area of a circle. The radius of the circle is taken as a command line argument. Area = PI * r2 where r is the radius of the circle. Hint: Use Math class (java.lang package) constant PI and the pow functions

Your objective is to calculate the cost of covering a room with wall paper. The room dimensions areLength = 10ft, Width = 12ft 6inches, Height = 8ftThe labor cost is $18 per roll. A wastage of about 5% should be included in determining the number of rolls needed. Standard wall paper rolls cover 22 sq ft. Cost of a roll of wall paper varies. For our sample, we can use a cost $15.75 per roll and this can be read in as a command line input.

Page 53: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-53

Control Structures

Page 54: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-54

Objectives

Conditional statements Boolean expressions and operators Iteration: for, while, and do Breaking out of a loop Skipping an iteration

Page 55: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-55

Conditional Statement: if

A program can make decisions using the if constructif (boolean expression) { // simple if

action;

} action is executed if the boolean expression is evaluated to be

true. action can be a block of statements char jobCode = ‘P’; if ( jobCode != ‘P’) {

System.out.println(“The employee is not a programmer”); }

Page 56: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-56

Conditional Statement: if/else

An if statement can have an optional else component if (boolean expression) {

truth action;} else {

false action; }

truth action is executed if the boolean expression is true false action is executed if the boolean expression is false Both truth and false action can be blocks that include

other control flow statements including ifs and loops.

Page 57: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-57

Conditional Statement: if/else

char jobCode = ‘P’;

if ( jobCode != ‘P’) {

System.out.println (“The employee is not a programmer”);

System.out.println ( “Pay the employee from the staff budget”);

} else {

System.out.println(“The employee is a programmer”);

System.out.println(“Salary is from the project budget” );

} A boolean expression uses relational and/or logical

operators

Page 58: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-58

Relational operators

Six relational operators are defined

Numbers are compared algebraically Characters are compared using their unicode values

Operator Example true if== a == b a and b are equal!= a != b a and b are not equal> a > b a is greater than b>= a >= b a is greater than or equal to b< a < b a is less than b<= a <= b a is less than or equal to b

Page 59: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-59

Equality of Objects

We can apply = = to compare objects We illustrate object equality using Strings, the only type

of object we have seen yet. Our discussion does apply to all objects To understand comparison of objects, let us start by

looking at the memory maps of primitive variables vis-a-vis objects

Page 60: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-60

Memory Allocation for primitive variables

Space is allocated by the compiler immediately for primitive variables

int noOfMonths; // Allocate space

noOfMonths = 12; // Assign 12 to noOfMonths

12

Page 61: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-61

Memory Allocation: String Variables

String name;

name is a reference to a String object Space is allocated only for the reference An object needs to be constructed before it can be used

name = “Hello World”;

Memory is allocated at theCompilation time for name,a reference

Hello World

Object is constructedat a different memory location

Page 62: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-62

Back to equality of objects

When we compare two primitive type of variables for equality, we compare contents of these two variables

When we compare two objects using = = operator, we compare objects’ references and not the objects themselves

Notice that the reference to an object (reference variable) does not ‘contain’ the object, but merely points to the object

For any object, the = = operator compares references only, and not objects

Page 63: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-63

Example: comparing String

String s1 = “JavaPrograms”;

String s2 = “JavaPrograms”;

String s3 = “javaprograms”;

String s4 = new String(“JavaPrograms”);

if (s1 = = s2) …. // true, however, what are we comparing?

if (s1 = = s3) …. // false, different Strings and references

if (s1 = = s4) … // false, different object references

String can be constructed this way during run-time

Page 64: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-64

Back to equality of objects

equals() method can be used to compare contents of two Strings

if (s1.equals(s4)) …. // true

if (s1.equalsIgnoreCase(s3)) ….// true

equalsIgnoreCase() method ignores case of characters while comparing two Strings

equals() is an inherited method from the class Object Equality or inequality of any two objects can be

determined using the equals() method

Page 65: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-65

while Loop

while enables a program to execute a set of tasks iteratively The while loop has the form

while (boolean expression) {action;

} The order of operation of while

Evaluate the boolean expression If the boolean expression is true, execute the action, and then re-

evaluate the boolean expression If the boolean expression is false, exit the loop

The action can include any valid java statement including other loops

Page 66: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-66

while Loop Example

Starting with 0, print all integers up to (and including) a randomly generated integer int index, lastNumber; lastNumber = (int)(Math.random()*50); index = 0; while (index <= lastNumber) {

System.out.print(index+” “); index++;

} System.out.println(“ “);

Page 67: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-67

Infinite Loop

A loop may execute infinitely: an error condition Consider the code of the last slide with a minor

modificationindex = 0;while (index <= lastNumber) {

System.out.print(index+” “);// index++;

} The loop above is infinite since the boolean expression

controlling the loop never becomes false Care is needed to ensure that the loop does terminate

ERROR: Index not updated

Page 68: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-68

while and if Example

public class AddOdds { public static void main(String args[]) {

int n; // number of odd integers long sum = 0; // Total of integers int i = 1; // indexing variable int num = 1; n = Integer.parseInt(args[0]); while ( i <= n) {

if (num % 2 != 0) {System.out.println(" "+num);sum += num;i++;

}num++;

} System.out.println("Sum of first "+n+" odd integers = "+sum);

}}

AddOdds.javaProgram to add first n odd integers. User supplies value of n through command line

Page 69: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-69

for Loop

The for loop has the formfor (initializations; boolean expression; update)

action; The order of operation of for loop

Execute the initialization statement(s) Test the boolean expression

If the boolean expression is true, execute the action, execute the update statement(s) re-evaluate the boolean expression

If the boolean expression is false, exit the loop The action can be a block and include any valid java

statement including other loops

Page 70: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-70

for Loop

for (int i= 0; i < 10; i++) {

System.out.println(“Value of i is “+ i);

}

Other forms

for (int i = 0, j = 4; i < 3; i++, j--) { //action}

for ( ; i < 3; i++, j--) { //action } // no initialization

for ( ; i < 3; ) { //action } // no initialization & update

for ( ; ; ) { //action } // infinite loop

Page 71: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-71

for Loop Example

find the factorial of a random integer less than 10

int index, number;

int factorial = 1;number = (int)(Math.random()*10);for (index = 1; index <= number; index++) {

factorial *= index;}

System.out.println( “Factorial of “+ number+ “ is “+ factorial); Any for loop can be written as a while loop and vice-versa

Page 72: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-72

Exercise

Rewrite the example of adding first n odd integers. However, use the for loop to solve the problem. Value for n is taken as a command line input. The example is on slide #68

Page 73: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-73

do while Loop

• do while loop is similar to while loop• do while loop has the form

do {action;

} while (boolean expression);• The order of operation of do while

– Execute the action– Test the boolean expression– If the boolean expression is true, execute the action

again and re-evaluate the boolean expression– If the boolean expression is false, exit the loop

• action is executed at least once unlike while

Page 74: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-74

do while Loop Example

• Generate a random number between 0 and 10 until a 7 is generatedint answer;

do {

answer = (int)(Math.random()*10);

} while ( answer != 7);

Page 75: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-75

Exercise

Rewrite the example of adding first n odd integers. However, use the do while loop to solve the problem. As before, accept the value of n as a command line argument. The example is on slide #68

Page 76: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-76

Logical operators

Java language defines 3 logical operators && - read as ‘and’|| - read as ‘or’! - read as ‘not’

The first two operators are used to connect two or more boolean expressions

Operator Example true if&& a == b && c != d a and b are equal and c and d are not

equal|| a == b || c == d a and b are equal, or c and d are

equal! !(a > b) a is NOT greater than b

Page 77: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-77

And operator

Each of the boolean expressions connected by and must be true for the entire boolean expression to be true

Assuming b1 and b2 to be two boolean expressionsif (b1 && b2) ....

b1 b2 b1 && b2T T TT F FF T FF F F

Page 78: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-78

Or operator

Only one of the boolean expressions connected by or must be true for the entire boolean expression to be true

Assuming b1 and b2 to be two boolean expressionsif (b1 || b2) ....

b1 b2 b1 || b2T T TT F TF T TF F F

Page 79: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-79

Not operator and precedence

Not operator tests whether the opposite of the boolean expression is true

Assuming b1 to be a boolean expressionif ( !b1 ) ....

b1 !b1 (not b1)T FF T

If we mix these logical operators in a boolean expression, nots are evaluated first, followed by ands and then ors

Parenthesis can be used to change the order of evaluation

Page 80: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-80

Short-circuit evaluation of expressions connected by logical operators

Evaluation of a boolean expression continues only until the final outcome can be determined; the entire expression may not be evaluated

if (( 5 < 2) && (3 < 4)) ....The second half of the above (3 < 4) is not evaluated since (5 < 2) is false i.e. the final outcome of the boolean is known as soon as (5 < 2) is evaluated to be false

if ((1 < 2) || ( 4 != 5)) .... The second half of this boolean (4 != 5) is not evaluated

since (1 < 2) is true i.e. the final outcome is known as soon as (1 < 2) is evaluated to be true

Page 81: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-81

Examples of if statement

Find whether a number is even and greater than 100

int number = (int)(Math.random()*150);if ((number > 100) && (number % 2) = = 0) System.out.println( number+“ is even and > 100”);else System.out.println( number+ “ is either odd or <= 100”);

Page 82: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-82

while Loop with Logical operators

Test whether a random number is primeint index = 2, number, canBeDivided = 0;number = (int)(Math.random()*100);while (index < number/2 && canBeDivided == 0) {

if ((number % index) == 0) canBeDivided = 1;index++;

} if (canBeDivided == 1)

System.out.println( number+ “ is not prime”); else

System.out.println(number+ “ is prime”);

Page 83: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-83

Common Pitfalls

Assume you want to express a condition which reads as “it is not equal to 10 or 15”if ( x != 10 || x !=15) ... bad, true in all casesif (!(x == 10 || x == 15) ... is correctif ( x != 10 && x != 15) ... is also correct

In general, following rules apply !(b1 || b2) is same as !b1 && !b2

!(b1 && b2) is same as !b1 || !b2where b1 and b2 are boolean expressions

Page 84: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-84

Nesting ifs

Assuming b1, b2, b3 to be boolean expressionsif ( b1) if (b2) if (b3)

action1; // executes if all of b1, b2, b3 are trueelse action2; // executes if b1, b2 are true, b3 is false

else action3; // executes if b1 is true, b2 is false

else action4; // executes if b1 is false

Each action can be a block

Page 85: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-85

Nesting ifs: Pitfall

if (maritalStatus = = ‘S’) if (gender = = ‘M’) if (age >= 18 && age <= 26)

System.out.println(“Found interesting male”); else

System.out.println(“Found single Female”);• The message and indentation show our intention; we

would like to capture the alternative to the gender test • However, our code reports a female when it encounters a

gender of M and age outside the range of 18 to 26• else is always associated with the immediate preceding

if

Page 86: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-86

Nesting ifs: Pitfall

• We can correct the problem by inserting braces to force association of else with if as shown below

if (maritalStatus == ‘S’) if (gender == ‘M’) { if (age >= 18 && age <= 26)

System.out.println(“Found interesting male”);

} else System.out.println(“Found single Female”);

Page 87: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-87

Nesting ifs: Pitfall

• Assume we have to check for wetness of a road and current temperature

if (road == ‘W’) // Wet road if (temp > 0)

System.out.println(“Wet road”); System.out.println(“Stay back from the next car”);

else System.out.println(“Possible icy road”); System.out.println(“Drive with extreme caution”);else System.out.println(“Road is possibly dry”); System.out.println(“Drive carefully anyway”);

There are many problems with this code. Canwe identify all ofthem and correctthe problems?

Page 88: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-88

Cascading ifs

Assuming b1, b2, b3 to be boolean expressionsif ( b1)

action1; // executes if b1 is trueelse if (b2)

action2; // executes if b1 is false and b2 is trueelse if (b3) action3; // executes if b1, b2 are false and b3 is trueelse

action4; // executes if all of b1, b2, and b3 are false Each action can be a block

Page 89: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-89

Examples of cascading ifs

Print the sign of a given number

int number = (int)(Math.random()*100 - Math.random()*100);

if (number > 0)System.out.println( number+ “ is positive”);

else if (number == 0)System.out.println(number+ “ is zero”);

elseSystem.out.println(number+ “ is negative”);

Page 90: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-90

Exercise

We are interested in determining the tax we owe. We live in a place with a simple tax code. The income is read in as a command line argument.

Income Base tax Additional percent0 - 14999.99 0 15%15000 - 29999.99 2250 24 % over 1500030000 - 49999.99 5850 31% over 3000050000 - 12050 37% over 50000

For example, a person with an income of 35000 pays a tax of 5850 + 31% of (35000-30000).

Page 91: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-91

switch Statement

Syntaxswitch (selection expression) { case constant1: //action for constant1

break; case constant2: //action for constant2

break; case constant3: //action for constant3

break;default: //default action

break;}

Page 92: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-92

switch Statement

selection expression is a variable or expression that yields a char or an integral value

Each case defines a constant break is an optional entry; execution of the action block

continues until a break is encountered or the switch statement is completed

default is an optional entry and is executed if none of the specified cases match

Page 93: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-93

Example of a switch Statement

Select an option from a set of choiceschar option;option = (char)(‘a’+(int)(Math.random()*26));switch (option) { case ‘a’: System.out.println(“option is a”); break; case ‘d’: System.out.println(“option is d”); break; case ‘x’: case ‘q’: System.out.println(“option is x or q”); break; default: System.out.println(“option is not a, d, x, or q”);

break;}

Page 94: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-94

Exercise: switch Statement

Assume that a company uses 5 types of trucks for shipping its merchandize with the following carrying capacities

Truck type capacity1 2000 lbs2 3500 lbs3 7500 lbs4 7500 lbs5 18000 lbs

Write a switch statement that tests for the truck type and prints out a message indicating carrying capacity. Accept the truck type as a command line argument

Page 95: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-95

Nesting of loops

A loop can be nested within another loopfor (i=0; i < 5; i++)

for (j = 4; j > 2; j--) System.out.println(i+“ ”+,j);

for (i=0; i < 5; i ++) { j = 4; while ( j >2) {

System.out.println(i+“ ”+j);j--;

}}

Page 96: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-96

Nesting of ifs and loops

A loop can be nested within an if; and an if can be nested within a loop

for (i=0; i < 5; i++)if (condition) {

/* action */}

if (condition) {for (i=0; i < 5; i ++) {

j = 4; while ( j >2) {

System.out.println(i+” “+j);j--;

}}

}

Page 97: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-97

Exercise: Nesting of ifs and loops

Generate a random integer between 1 and 200. Test the integer to see if it is an odd number. If it is odd, print the value. Terminate the program when 10 odd integers are found, or any integer more than 190 is found.

Page 98: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-98

Early loop termination: break

while ( boolean expression) {// do many activitiesif ( some condition is true)

break;// do other activities

} out of loop break can be used in any type of loop Execution of break results in the termination of the

immediate loop that surrounds the break statement

Page 99: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-99

Example of early loop termination: break

test whether a given number is primeint index = 2, number, canBeDivided = 0;number = (int)(Math.random()*100);while (index < number/2) {

if ((number % index) == 0) { canBeDivided = 1;

break; }

index++; } if (canBeDivided == 1)

System.out.println( number+ “ is not prime”); else

System.out.println(number+ “ is prime”);

Page 100: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-100

Skipping an iteration: continue

do { // some interesting stuffif ( some condition is true)

continue;// do other interesting stuff

} while ( boolean expression)

continue can be used in any type of loop All statements after the continue, but within the loop

surrounding the continue statement, are skipped Loop execution resumes with the next iteration

Page 101: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-101

Example of continue

All iterations are skipped unless the iteration index is a multiple of 20

int i = 100; int index = 0; while ( index <= i) { index++;

if ( index % 20 != 0)continue;

System.out.println( index+ “ is a multiple of 20”); }

Page 102: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-102

Exercise

We are going to implement a simple program to analyze monthly high temperatures. We will generate a set of high temperatures between 0 and 95 and compute the number of hot days (temperature 85 or higher), pleasant days (between at least 60 but less than 85), and cool days (less than 60). We live in a tropical country where the temperature never goes below 0. Print a count of high, pleasant and cool days, as well as the average temperature for the period. Use Math.random() to generate the temperatures. Number of temperatures to be analyzed is read in as a command line argument.

Page 103: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-103

Additional Operators

Page 104: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-104

Operators

Operators are same as in C: shown in the order of their precedence

Operators Associativity[] . () left to right! ~ ++ -- +(unary) - (unary) right to left* / % left to right+ - left to right<< >> >>> left to right< <= > >= instanceof left to right== != left to right

Page 105: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-105

Operators

List of operators, in their order of precedence (contd)Operators Associativity& left to right^ left to right| left to right&& left to right|| right to left?: left to right= += -= *= /= %=&= |= ^ <<= >>= >>>= right to left

Page 106: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-106

Operators

~ Complement (or One’s Complement)var1 ---> 11001011~var1 ---> 00110100Reverse the bits

<< Logical shift Left => Multiply the original value by 2d where d is the number of effective bits shifted

var1 ---> 01101011var1 << 1 ---> 11010110var1 << 2 ---> 10101100int var1 = 100; var1 <<= 1; // var1 = 200

var1 <<= 2; // var1 = 400var1 <<= 4; // var1 = 1600

Page 107: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-107

Operators

>> Arithmetic shift Right => Divide the original value by 2d where d is the number of effective bits shifted

var1 --->01101011 var1 >> 1 ---> 00110101

var1 --->10101100 var1 >> 2 ---> 11101011 Notice the fill bit is same as the sign bit

int var1 = 100; var1 >>= 1; // var1 = 50

var1 >>= 2; // var1 = 25

int var2 = -400; var2 >>= 4; // var2 = -25

var2 = -2560; var2 >>= 8; // var2 = -10

Page 108: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-108

Operators

>>> Logical shift Right => Divide the original value by 2d where d is the number of effective bits shifted, however, the fill bit is 0

var1 ---> 01101011 var1 >>> 1 ---> 00110101var1 ---> 10101100 var1 >>> 2 ---> 00101011int var1 = 100; var1 >>>= 1; // var1 = 50

var1 >>>= 2; // var1 = 25 Calculation of effective bits

if n is the number bits to be shifted for an integer, then d = n % 32

Therefore, var1 = var1 >> 32; assuming var1 is type int. Effective bits calculated similarly for all shift operators

Page 109: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-109

Operators

| (Or) Can be used both as bit and logical operator.

– As bit operator 11010011

10110101

__________________

11110111

– As logical operator: if (b1 | b2) ...

As expected, the logical expression is true if either b1 or b2 is true. However, both b1 and b2 are evaluated; no short-circuit is applied as in the case || operator.

Page 110: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-110

Java Flavor: break and continue

Page 111: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-111

Breaking out of a Loop

while ( boolean expression) {// do many activitiesif ( some condition is true)

break;// do other interesting stuff otherwise

} out of loop break can be used in any type of loop break allows the loop to be terminated However, the loop terminated is the immediate loop that

controls the break statement break label allows exit out of any named loop

Page 112: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-112

Breaking out of a labeled Looppublic class BreakTest { public static void main (String [] args) { int i, j, k; outer: for (i=0; i < 5; i++) { System.out.println(" Out "+i); inner: for (j = 0; j < 5; j++) { System.out.print(" In "+j); if (j == 2) break outer; System.out.print(" Mark A "); for (k=4; k > 0; k--) { System.out.print(" "+k); if ( k == 1) break inner; } System.out.println("Point A"); } // end inner System.out.println("Point B"); } // end outer } //end main } //end BreakTest class out of “outer”

loop

Page 113: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-113

Skipping an iteration

do { // do many activitiesif ( some condition is true)

continue;// do other interesting stuff otherwise

} while ( boolean expression) continue can be used in any type of loop as a result of continue, rest of the loop is skipped for that

iteration Only portions of the immediate loop surrounding the

continue statement is skipped continue label allows skipping iteration of any named

loop

Page 114: For use of IST410 Students onlyIntro-1 JAVA PROGRAMMING

For use of IST410 Students only Intro-114

Skipping portions of a labeled Looppublic class SkipTest { public static void main (String [] args) { int i, j, k; outer: for (i=0; i < 5; i++) { System.out.println(" Out "+i); inner: for (j = 0; j < 5; j++) { System.out.print(" In "+j); if (j == 2) continue outer; System.out.print(" Mark A "); for (k=4; k > 0; k--) { System.out.print(" "+k); if ( k == 1) continue inner; } // end k loop System.out.println("Point A"); } // end j loop System.out.println("Point B"); } // end i loop } // end main }