Title: Course Overview
1Course Overview
- Java Programming 1. Introduction
- The way to use JAVA Eclipse for your
convenience - Simple program printing Hello, World no basic
knowledge , just code! - Java Programming 2. Introduction to Objects,
Everything is an object - Learning the Object-Oriented Programming Style
using JAVA - Java Programming 3. Controlling program flow
- Learning to manipulate objects data using
operators
2Chap 3. Controlling program flow Java
Programming 2
- Data Mining Lab, Lee Seung-Kyung
3Controlling program flow
- Like a sentient creature, a program must
manipulate its world and make choices during
execution - In Java you manipulate objects and data using
operators - you make choices with execution control
statements - Java was inherited from C, so most of these
statements - operators will be familiar to C and C
programmers - Java has also added some improvements and
simplifications.
4Using Java operators
- All operators produce a value from their operands
- An operator takes one or more arguments and
produces a new value - The arguments are in a different form than
ordinary method calls, but the effect is the same - Reasonably comfortable with the general concept
of operators from your previous programming
experience - Addition (), subtraction and unary minus (-),
multiplication (), division (/) and assignment
() - All work much the same in any programming
language. - Almost all operators work only with primitives
(primitive type, e.g. int, long, float, ... See
the class material Java 2) - The exceptions are , and !, which
work with all objects (and are a point of
confusion for objects) - In addition, the String class supports and
(what does operator in String class
mean?.. Test it!)
5Using Java operators - Precedence
- Precedence Specific rule to determine the order
of evaluation -
- Operator precedence defines how an expression
evaluates when several operators are present - The easiest one to remember is that
multiplication and division happen before
addition and subtraction - Programmers often forget the other precedence
rules, - so you should use parentheses to make the order
of evaluation explicit - For example
- A X Y - 2/2 Z
-
- has a very different meaning from the same
statement with a particular grouping of
parentheses - A X (Y - 2)/(2 Z)
6Using Java operators - Assignment
- Assignment is performed with the operator
- Take the value of the right-hand side (called
the rvalue) and copy it into the left-hand side
(called the lvalue) - An rvalue is any constant, variable or
expression that can produce a value, - But an lvalue must be a distinct, named
variable. (That is, there must be a physical
space to store a value) - For instance, you can assign a constant value to
a variable (A 4) - But you cannot assign anything to constant value
it cannot be an lvalue. (You cant say 4 A) - Assignment of primitives
- Assignment of primitives is quite
straightforward. - Since the primitive holds the actual value and
not a handle to an object (handle? See the class
material Java 2), - when you assign primitives you copy the contents
from one place to another - For example, if you say A B for primitives,
then the contents of B is copied into A - If you then go on to modify A, B is naturally
unaffected by this modification - This is what youve come to expect as a
programmer for most situations
7Using Java operators - Assignment
- Assignment of objects
- When you assign objects, however, things change
- Whenever you manipulate an object, what youre
manipulating is the handle - So when you assign from one object to another
youre actually copying a handle from one place
to another - This means that if you say C D for objects,
- You end up with both C and D pointing to the
object that, originally, only D pointed to - // Aliasing Example
- class Number
- int i
-
- public class Assignment
- public static void main(String args)
- Number n1 new Number()
- Number n2 new Number()
- n1.i 9
handle
object
n1
Before n1 n2
n2
n1
n1 n2
n2
n1
After n1 n2
n2
8Using Java operators - Assignment
What if you dont want aliasing to occur in this
case? You could forego the assignment and say
n1.i n2.i - Manipulating the fields within
objects is messy and goes against good
object-oriented design principles. - This is a
non-trivial topic (detail may be explained in
the future class) In the meantime, you should
keep in mind that assignment for objects can add
surprises.
9Using Java operators - Assignment
- Think about this code
- Aliasing during method calls (Aliasing will also
occur when you pass an object into a method) - // Passing objects to methods may not be what
you're used to. - class Letter
- char c
-
-
- public class PassObject
- static void f(Letter y)
- y.c 'z'
-
- public static void main(String args)
- Letter x new Letter()
- x.c 'a'
- System.out.println("1 x.c " x.c)
- f(x)
10Mathematical operators
- The basic mathematical operators are the same as
the ones available in most programming languages
- - addition (), subtraction (-), division (/),
multiplication () and modulus () - Shorthand notation
- Java also uses a shorthand notation to perform
an operation and an assignment at the same time - For example, to add 4 to the variable x and
assign the result to x, use x 4 - // Demonstrates the mathematical operators
- import java.util.
-
- public class MathOps
- // Create a shorthand to save typing
- static void prt(String s)
- System.out.println(s)
-
11Mathematical operators
public static void main(String args)
Random rand new Random() // Create a random
number generator, sees with current time by
default int i, j, k j rand.nextInt()
100 // think the range of j, what
is the upper bound of j???? k
rand.nextInt() 100 pInt("j",j)
pInt("k",k) // just shorthand to print a
string and an int i j k pInt("j k",
i) i j - k pInt("j - k", i) i k /
j pInt("k / j", i) i k j pInt("k
j", i) i k j pInt("k j", i) j
k pInt("j k", j) u v pInt("u
v", u) u - v pInt("u - v", u) u
v pInt("u v", u) u / v pInt("u /
v", u) // Other primitives??? Check for
float, char, byte, short, int, long, double
///
12Mathematical operators
- Unary minus and plus operators
- The unary minus (-) and unary plus () are the
same operators as binary minus and plus - The compiler figures out which use is intended
by the way you write the expression - For instance, the statement
- x -a
-
- The compiler is able to figure out
- x a -b
-
- but the reader might get confused, so it is more
clear to say - x a (-b)
-
- The unary minus produces the negative of the
value - Unary plus provides symmetry with unary minus,
although it doesnt do much.
13Mathematical operators
- Auto increment and decrement
- Java, like C, is full of shortcuts
- Shortcuts can make code much easier to type, and
either easier or harder to read. - Two of the nicer shortcuts increment
(auto-increment operator), decrement operators
(auto-decrement operator) - The decrement operator is -- and means decrease
by one unit. - The increment operator is and means increase
by one unit. - For example, If A is an int, the expression A
is equivalent to (A A 1) - Prefix and postfix versions
- There are two versions of each type of operator,
often called the prefix and postfix versions - Pre-increment means the operator appears
before the variable or expression - A or A
- Post-increment means the operator appears
after the variable or expression - A or A
14Mathematical operators
// Demonstrates the and -- operators public
class AutoInc public static void
main(String args) int i 1 prt("i
" i) prt("i " i) //
Pre-increment prt("i " i) //
Post-increment prt("i " i) prt("--i
" --i) // Pre-decrement prt("i-- "
i--) // Post-decrement prt("i " i)
static void prt(String s)
System.out.println(s) ///
15Relational operators
- Relational operators generate a boolean result
- They evaluate the relationship between the
values of the operands - A relational expression produces true if the
relationship is true, and false if the
relationship is untrue - The relational operators
- less than (lt), greater than (gt), less than or
equal to (lt), greater than or equal to (gt),
equivalent (), not equal (!) - Relational operator with objects?? Testing object
equivalence - The relational operators and ! also work with
all objects - But their meaning often confuses the first-time
Java programmer - Heres an example
-
- public class Equivalence
- public static void main(String args)
- Integer n1 new Integer(47)
- Integer n2 new Integer(47)
- System.out.println(n1 n2)
- System.out.println(n1 ! n2)
16Relational operators
What if you want to compare the actual contents
of an object for equivalence? You must use the
special method equals( ) that exists for all
objects (not primitives, which work fine with
and !) Heres how its used public class
EqualsMethod public static void main(String
args) Integer n1 new Integer(47)
Integer n2 new Integer(47)
System.out.println(n1.equals(n2))
/// If you create your own class, well..
class Value int i public class
EqualsMethod2 public static void main(String
args) Value v1 new Value() Value v2
new Value() v1.i v2.i 100
System.out.println(v1.equals(v2)) // Is it
sufficient??? Does it work well??? ///
17Relational operators
- The result is false!!!
- This is because the default behavior of
equals( ) is to compare handles - So unless you override equals( ) in your new
class you wont get the desired behavior - Unfortunately, you wont learn about overriding
until next class (when I dont know exactly..) - but being aware of the way equals( ) behaves
might save you some grief in the meantime - Most of the Java library classes implement
equals( ) so that it compares the contents of
objects instead of handles
18Logical operators
- The logical operators AND (), OR () and NOT
(!) - Producing a boolean value of true or false based
on the logical relationship of its arguments - This example uses the relational and logical
operators - // Relational and logical operators
- import java.util.
-
- public class Bool
- public static void main(String args)
- Random rand new Random()
- int i rand.nextInt() 100
- int j rand.nextInt() 100
- prt("i " i)
- prt("j " j)
- prt("i gt j is " (i gt j))
- prt("i lt j is " (i lt j))
- prt("i ! j is " (i ! j))
-
19Logical operators
Short-circuiting When dealing with logical
operators you run into a phenomenon called short
circuiting. // Demonstrates short-circuiting
behavior with logical operators. public class
ShortCircuit static boolean test1(int val)
System.out.println("test1(" val ")")
System.out.println("result " (val lt 1))
return val lt 1 static boolean test2(int
val) System.out.println("test2(" val
")") System.out.println("result " (val lt
2)) return val lt 2 static boolean
test3(int val) System.out.println("test3("
val ")") System.out.println("result "
(val lt 3)) return val lt 3 public
static void main(String args) if(test1(0)
test2(2) test3(2)) // Are all
conditions (test1,2,3) tested???? Well Test
Think.. System.out.println("expression is
true") else System.out.println("express
ion is false") ///
20Bitwise operators
- Bitwise operator to manipulate individual bits
- You were often manipulating hardware directly
and had to set the bits in hardware registers - Java was originally designed to be embedded in
TV set-top boxes, so this low-level orientation
still made sense - However, you probably wont use the bitwise
operators much (Actually This is important ???) - The bitwise AND operator () produces a one in
the output bit if both input bits are one - otherwise it produces a zero
- The bitwise OR operator () produces a one in
the output bit - if either input bit is a one and produces a zero
only if both input bits are zero - The bitwise, EXCLUSIVE OR, or XOR (), produces
a one in the output bit - if one or the other input bit is a one, but not
both - The bitwise NOT (, also called the ones
complement operator) is a unary operator it
takes only one argument - Bitwise NOT produces the opposite of the input
bit a one if the input bit is zero, a zero if
the input bit is one - The left-shift operator (ltlt) produces the
operand to the left of the operator shifted to
the left by the number of bits specified after
the operator (inserting zeroes at the lower-order
bits)
21Ternary if-else operator
- boolean-exp ? value0 value1
- This operator is unusual because it has three
operands - It is truly an operator because it produces a
value - If boolean-exp evaluates to true, value0 is
evaluated and its result becomes the value
produced by the operator - If boolean-exp is false, value1 is evaluated and
its result becomes the value produced by the
operator. - Of course, you could use an ordinary if-else
statement (described later), but the ternary
operator is much terser - You should be somewhat wary of using it on an
everyday basis its easy to produce unreadable
code!!! - Heres an example
- static int ternary(int i)
- return i lt 10 ? i 100 i 10
-
-
- You can see that this code is more compact than
what youd need to write without the ternary
operator
22Common pitfalls when using operators
One of the pitfalls when using operators is
trying to get away without parentheses when
you are even the least bit uncertain about how an
expression will evaluate. This is still true in
Java An extremely common error in C and C
looks like this while(x y) //
.... The programmer was trying to test for
equivalence () rather than do an assignment In
C and C the result of this assignment will
always be true if y is nonzero, and youll
probably get an infinite loop In Java, what
happen??? Hint the result of this expression is
not a boolean
23Casting operators
- The word cast is used in the sense of casting
into a mold - Java will automatically change one type of data
into another when appropriate - For instance,
- if you assign an integral value to a
floating-point variable, - the compiler will automatically convert the int
to a float - Casting allows you to make this type conversion
explicit, or to force it when it wouldnt
normally happen - void casts()
- int i 200
- long l (long)i
- long l2 (long)200
-
- The cast is possible but superfluous
- since the compiler will automatically promote an
int value to a long when necessary - You can still put a cast in to make a point or
to make your code more clear
24Casting operators
- Narrowing conversion case
- Converting from a data type that can hold more
information to one that doesnt hold as much - The risk of losing information.
- - When you use the narrowing conversion without
the casting operator, what happen? Check - Promotion
- In general, the largest data type in an
expression is the one that determines the size of
the result of that expression - If you multiply a float and a double, the result
will be double if you add an int and a long, the
result will be long.
25Casting operators
Narrowing conversion case public class
CastingNumbers public static void
main(String args) double above 0.7,
below 0.4 System.out.println("above "
above) System.out.println("below "
below) System.out.println("(int)above "
(int)above) // 0? 1? System.out.println(
"(int)below " (int)below) // 0? 1?
///
26Precedence revisited
Complain about the complexity of remembering
operator precedence . A student suggested a
mnemonic that is simultaneously a commentary
Ulcer Addicts Really Like C A lot. Of course,
with the shift and bitwise operators distributed
around the table it is not a perfect mnemonic,
but for non-bit operations it works.
27Overflow Problem
Dont be lulled into thinking everything is
safe!!! If you multiply two ints that are big
enough, youll overflow the result. //
Surprise! Java lets you overflow public class
Overflow public static void main(String
args) int big 0x7fffffff // max int
value // 0x.. Hexadecimal prt("big "
big) int bigger big 4 prt("bigger
" bigger) static void prt(String s)
System.out.println(s) /// The output
of this is big 2147483647 bigger -4
// This is the overflow problem
28Execution control
- If-else
- While
- Do-while
- For
- Switch
- Goto??? Well
Iteration statement
29Execution control
- if-else
- Probably the most basic way to control program
flow - The else is optional, so you can use if in two
forms - if(Boolean-expression) statement
- or
- if(Boolean-expression) statementelse
statement - As an example
- static int test(int testval)
- int result 0
- if(testval gt target)
- result -1
- else if(testval lt target)
- result 1
- else
- result 0 // match
30Execution control
- return
- The return keyword has two purposes
- - it specifies what value a method will return
(if it doesnt have a void return value) - it causes that value to be returned immediately.
The test( ) method above can be rewritten to take
advantage of this - static int test2(int testval)
- if(testval gt target)
- return -1
- if(testval lt target)
- return 1
- return 0 // match
-
-
- Theres no need for else because the method will
not continue after executing a return
31Iteration
while, do-while and for control looping and are
sometimes classified as iteration statements A
statement repeats until the controlling
Boolean-expression evaluates to false The form
for a while loop is while(Boolean-expression)
statement The Boolean-expression is evaluated
once at the beginning of the loop and again
before each further iteration of the
statement // Demonstrates the while loop public
class WhileTest public static void
main(String args) int i 1 while(i
lt 10) i
System.out.println(i) //
What is value of variable i ???? Test it!!!!
///
32do-while
- The form for do-while is
- do statementwhile(Boolean-expression)
- The sole difference between while and do-while
- The statement of the do-while always executes at
least once, even if the expression evaluates to
false the first time - In a while, if the conditional is false the
first time the statement never executes - In practice, do-while is less common than while
- public class DoWhileTest
- public static void main(String args)
- int i 1
- do
- i
- System.out.println(i)
- while (i lt 10)
33for
- A for loop performs initialization before the
first iteration - Then it performs conditional testing
- At the end of each iteration, some form of
stepping. - The form of the for loop is
- for(initialization Boolean-expression step)
statement - Any of the expressions initialization,
Boolean-expression or step can be empty - The expression is tested before each iteration,
- as soon as it evaluates to false execution will
continue at the line following the for statement - At the end of each loop, the step executes
- for loops are usually used for counting tasks
- // Demonstrates "for" loop by listing
- public class ListCharacters
- public static void main(String args)
- for (int i0ilt7i)
34The comma operator
public class CommaOperator public static void
main(String args) for(int i 1, j i
10 i lt 5 i, j i 2)
System.out.println("i " i " j " j)
/// Heres the output i 1 j 11 i
2 j 4 i 3 j 6 i 4 j 8 You can see that in
both the initialization and step portions the
statements are evaluated in sequential order
Also, the initialization portion can have any
number of definitions of one type
35break and continue
- Inside the body of any of the iteration
statements - you can also control the flow of the loop by
using break and continue - break quits the loop without executing the rest
of the statements in the loop - continue stops the execution of the current
iteration and goes back to the beginning of the
loop - This program shows examples of break and continue
within for and while loops - // Demonstrates break and continue keywords
- // Compare two iteration (for, while)
- public class BreakAndContinue
- public static void main(String args)
- for(int i 0 i lt 100 i)
- if(i 74) break // Out of for loop
- if(i 9 ! 0) continue // Next iteration
- System.out.println(i)
-
- int i 0
36The infamous goto
- The goto keyword has been present in programming
languages from the beginning - Indeed, goto was the genesis of program control
in assembly language - if condition A, then jump here, otherwise jump
there. - .
- By the publication of the famous Goto considered
harmful paper by Edsger Dijkstra -
- - Therefore I omit to explain it
- If you want to know goto really. Read the
book about the program language
37switch
- The switch is sometimes classified as a selection
statement - The switch statement selects from among pieces of
code based on the value of an integral
expression. - Its form is
- switch(integral-selector) case
integral-value1 statement break case
integral-value2 statement break case
integral-value3 statement break case
integral-value4 statement break case
integral-value5 statement break //
default statement - Integral-selector is an expression that produces
an integral value - The switch compares the result of
integral-selector to each integral-value - If it finds a match, the corresponding statement
(simple or compound) executes. - If no match occurs, the default statement
executes.
38switch
- Each case ends with a break, which causes
execution to jump to the end of the switch body - This is the conventional way to build a switch
statement, but the break is optional - If it is missing, the code for the following
case statements execute until a break is
encountered - Although you dont usually want this kind of
behavior, it can be useful to an experienced
programmer - Note the last statement, for the default,
doesnt have a break - Because the execution just falls through to
where the break would have taken it anyway - The switch statement is a clean way to implement
multi-way selection - But it requires a selector that evaluates to an
integral value such as int or char - If you want to use, for example, a string or a
floating-point number as a selector, it wont
work in a switch statement - For non-integral types, you must use a series of
if statements
39switch
// Demonstrates the switch statement public class
VowelsAndConsonants public static void
main(String args) for(int i 0 i lt 100
i) char c (char)(Math.random() 26
'a') // Math.random() Find the Java document
System.out.print(c " ") switch(c)
case 'a' case 'e' case
'i' case 'o' case 'u'
System.out.println("vowel")
break case 'y' case 'w'
System.out.println("Sometimes a vowel")
break default
System.out.println("consonant")
///
40Homework 2
In Calculator Class of Homework 1 Problem 1.
(10) In Calculator Class, add the summation
function using for statement (Calculator.java)
int summation(int from, int
to) Problem 2. (10) In Calculator Class, add the
summation2 function using while statement
(Calculator.java) Problem 3. (10) Write the test
code for random two integer numbers in the main
method (Homework2.java) Problem 4. (10) In
Homework2.java, Add the method testing whether
given integer number is odd or even. boolean
isOdd(int number) Problem 5. (10) In the main
method in Homework2.java,
write the code to sum up the odd number in the
range of 1,10
41Homework 2
- Be Careful of Below Policy (Upgraded Policy.
Check it out!!!!) - Subject of E-mail IIC2009_StduentNumber_Name_
HW2.zip - Including following Java Files and Report
- Homework2.java Calculator.java
- Report.doc
- Report
- Result and Explanation
- 1 pages for all problems !!! (Dont worry)
- Simple and Clear
- Due 1200 p.m 2009-04-13 (I give you more time
First of all read the class material !!!! There
is the solutions) - E-Mail to sklee83_at_snu.ac.kr
- Points
- Problem 1 15 Points
- Problem 2 15 Points