Title: CTEC 1641
1CTEC 1641
- Lecture 3 Java Basics - II
2Operators
- Operators are special symbols used for
mathematical functions, some types of assignment
statements, and logical comparisons. - Five basic operators are
- Addition (e.g. 3 4)?
- Subtraction - (e.g. 5 7)?
- Multiplication (e.g 5 5)?
- Division / (e.g.14 / 7)?
- Modulus (e.g 11 5)?
3Operators con't
- If results are put into an integer are floating
point, it will be truncated - Watch your types! (e.g. concatenation for
Strings is )?
4Assignment Operators
- Assignment operators are 'shorthand' for common
assignments - Four assignment operators are
- x y (x x y)?
- x - y (x x y)?
- x y (x x y)?
- x / y (x x/y)?
5Assignment Operators - con't
- Sometimes it is better to use normal assignments
instead of assignment operators. - Simplicity Readability
- Do not always evaluate as you think. (i.e. if x
20 and y 5. Do the following two assignments
equal? - x x / y 5
- x / y 5
6Incrementing Decrementing
- Incrementing a variable means to add 1 to its
value, and decrementing means to subtract 1 from
its value. - x (x x 1)?
- y-- (y y - 1)?
7Inc. Dec. - con't
- If the '' or '--' are before the variable then
the value is incremented/decremented before the
value is returned. - If the '' or '--' are after the variable then
the value is incremented/decremented after the
value is returned. - for (int i 0 i gt 1 i)
- for (int i 0 i gt 1 i)
8Comparison Operators
- Equal
-
- x 3
- Not Equal
- !
- x ! 3
- Less Than
- lt
- x lt 3
- x lt 3
- Greater Than
- gt
- x gt 3
- x gt 3
9Operator Precedence
- ( ) - Are used to group expressions
- -- !
- new (type) expression
- / Multiplication, division, modulus
- - Addition, subtraction
- ltlt gtgt gtgtgt Bitwise left and right shift
- lt gt lt gt Relational comparison tests
- ! Equality
- AND
- XOR
- OR
- Logical AND
- Logical OR
- ? Shorthand for if-the-else
- - / Various assignments
- ltlt gtgt gtgtgt More assignments
10Exponents
- Many C,C programmers are used to the ''
notation for exponents. This will not work in
Java. - double r 2.0 3.0
- Instead you will have to use the Math class
- double b Math.pow(2.0,3.0)
- Need to import lava.lang.Math
11java.lang.Math
- Often we will need to do more complex math
operations. - The java.lang.Math class allows us to do many
common math operations without having to code
them ourselves.
12java.lang.Math con't
- Some common operations are
- exponents
- absolute values
- trig functions (sine, cosine, tangent)?
- min, max values
- Round
- Truncation
- Randoms
- Conversion between degrees and radians
- log functions
- ..etc
13Branching Statements
- Along with looping, branching is one of the key
aspects of programming languages. Otherwise code
is simple executed in sequence. - Allows block(s) of code to be executed based on
the evaluation of expressions.
14if
- The if conditional uses a Boolean expression to
decide whether a statement, or statement block
should be executed. If the expression produces a
true value, the statement is executed.
if (SomeVariable lt 3) System.out.println("The
variable is less than three!")
if (AVariable gt 4) TheVariable
(TheVariable 2) 4 System.out.println("The
value of TheVariable " TheVariable)
15if-else
- The else statement lets you execute a statement,
or a block of statements if the 'if' evaluates to
false. - Always used with an 'if'
if (isMoving) currentSpeed-- else
System.out.println("The bicycle has
already stopped!")
16else if
- The else-code part can also be another if
statement. An if statement written this way
sets up a sequence of condition's, each tested
one after the other in top-down order. If one of
the conditions is found to be true, the body-code
for that if statement is executed. Once executed,
no other conditions are tested and execution
continues after the sequence. - Source http//www.exampledepot.com/egs/Java20Lan
guage/If.html
17else if continued
// Converts the time, which is in milliseconds,
into a // more readable format with higher
units public String getTimeUnit(long time)
String unit "ms" if (time gt
3652460601000L) unit
"years" time / 3652460601000L
else if (time gt 2460601000)
unit "days" time /
2460601000 else if (time gt
60601000) unit "hr"
time / 60601000 else if (time gt
601000) unit "min"
time / 601000 else if (time gt 1000)
unit "sec" time /
1000 // Execution continues
here if any of the conditions match
return time " " unit
18switch
- A switch statement works with the following data
types - byte
- short
- char
- int
- enumerated types
- Often allows for cleaner code relative to other
decision structures
19switch con't
String comment // The generated insult. int
which (int)(Math.random() 3) // Result is
0, 1, or 2. switch (which) case 0 comment
"You look so much better than usual."
break case 1 comment "Your work is
up to its usual standards."
case 2 comment "You're quite competent for so
little experience." break
default comment "Oops -- something is wrong
with this code." //Source
http//www.leepoint.net/notes-java/flow/switch/swi
tch-general.html
20Looping
- Will repeat a block of code until a given
condition is true. - Java has the following looping structures
- while
- do-while
- for
- for-each
21while
- A while loop will repeat a statement, or block of
statements, over and over until it evaluates to
true. - Programmer must ensure condition is met
eventually, otherwise program will infinitely
loop. - Comes in single statement, or block form.
22while con't
while (x1) random(x)
while ( number lt 6 ) // Keep going as long as
number is lt 6. System.out.println(number)
number number 1 // Go on to the next
number.
23do-while
- Sometimes a programmer wants to evaluate the
conditions at the bottom of a loop. - With a do-while, the statement, or statements
within the block, are executed at least once. (Be
sure you want this to happen!)?
Counter1 5 do System.out.println("The
Counter value is " Counter1) Counter1
Counter1 1 while (Counter1 lt 11)
24for
- Often a programmer wants to execute a given block
of statements, or individual statement, a fixed
number of times. - Java 'for' loops combine many of the requirements
for looping - Variable declaration/initialization
- Expression evaluation
- Incrementation / Decrementation
25for con't
int i // A counter variable int fact // The
factorial of n fact 1 for (i 1 i lt n i)
fact fact i // for
int fact // The factorial of n fact 1 for
(int i 1 i lt n i) fact fact i
// for
26for - each
- Often one needs to easy move through a
collection, or array, in an easy fashion. The
'for-each' loop does this.
//Using a for-each loop double ar 1.2, 3.0,
0.8 int sum 0 for (double d ar) // d
gets successively each value in ar. sum
d
//Using a traditional for loop double ar
1.2, 3.0, 0.8 int sum 0 for (int i 0 i lt
ar.length i) // i indexes each element
successively. sum ari
27break / continue / return
- Java supports three types of controlling
statements to use in loops - break
- continue
- return
- 'break' statements can be labelled or unlabelled
- An unlabelled 'break' statement will bring you to
the statement just after the loop
28break con't
- Labelled break statement terminate at the end of
the labelled loop. - Labelled breaks allow you to control nested loops
29break examples
for (int counter 1 counter lt 500 counter
)? int i counter 1.05
if (counter 250) break
search for (i 0 i lt
arrayOfInts.length i) for (j
0 j lt arrayOfIntsi.length j)
if (arrayOfIntsij searchfor)
foundIt true
break search
//Source http//java.sun.com/docs/books/tu
torial/java/nutsandbolts/branch.html
30continue
- The continue statement allows the program to skip
the current iteration of the loop. - Stops at the continue statement and begins
execution at the top of the loop - continue statement can be labelled. If labelled,
it will continue execution at the labelled loop.
This gives control in nested loop situations.
31continue examples
for (int i 0 i lt max i) if (igt50)
continue
test for (int i 0 i lt max i)
int n 16 while (n-- ! 0)
if (nlt5)
continue test
32return
- The 'return' statement exits the current method
and returns control to the caller - Can return a value, or not
- If returning a value, the data type returned must
match the returned value, otherwise the method
should be declared with void.
33print println
- To communicate to the terminal
- Commands automatically handle conversion to
string. - System.out.println(14) will display '14' on the
screen. - System.out.println(14) will display '14' on
the screen. - Strings have to be within double-quotes (i.e.
blah)? - print will output the string to screen without a
new-line, whereas println will move the cursor to
the next line.
34print / println Example
public class Root public static void
main(String args) int i 2
double r Math.sqrt(i)
System.out.print("The square root of ")
System.out.print(i) System.out.print("
is ") System.out.print(r)
System.out.println(".") i 5 r
Math.sqrt(i) System.out.println("The
square root of " i " is " r ".")
The square root of 2 is 1.4142135623730951.
The square root of 5 is 2.23606797749979. //Sourc
e http//java.sun.com/docs/books/tutorial/essenti
al/io/formatting.html
35A Simple Program
- Use a text editor of your choice to write the
following program. - Compile program using javac
- Execute program using java
public class HelloWorld public static void
main( String args )? System.out.println(
"Hello, Cruel World!" )
36A Simple Program con't
- Modify your base program in order to make it
perform the following - Counts between 1 and 100
- For every even number, it lets the user know the
number and that it is even (i.e. The number 4 is
even)?.
37Basic Input
- Often there is a need to prompt the user to enter
text - Requires the Java.io class
- Input comes in as a String type and needs to be
converted to the correct type.
38Input Example
import java.io. class GettingAFloatOrDouble
public static void main(String args) throws
IOException BufferedReader in new
BufferedReader(new InputStreamReader(System.in))
System.out.println("Please input a name and
press Enter ") String Name
in.readLine() System.out.println("Please
input an Id and press Enter ") int Id
Integer.parseInt(in.readLine())
System.out.println("Please input Hours worked and
press Enter ") double Hours
Double.parseDouble(in.readLine())
System.out.println("The Employee name is
"Name) System.out.println("The Employee
ID is "Id) System.out.println("The
number of hours worked byt the employee is
"Hours)
39A Simple Program Round II
- Change the name of the class
- Modify the program in order to prompt the user
for a integer input. - Use the integer input to determine what number to
count up to
40Exceptions
- Java uses exceptions to handle errors
- An exception is something that disrupts the
normal flow of a program (i.e. a file read
error)? - Exceptions are handled using the try, catch, and
finally blocks - The 'try' block is the code that might generate
the exception - The 'catch' block is code that will execute if
the try block generates an exception
41Exceptions con't
- You can have one or more catch blocks associated
with a try block - Exceptions must be handled
- The 'finally' block always executes when the try
block is complete. - The 'finally' block should be where clean-up code
is put since it will always be executed,
regardless of an exception.
42finally
- The finally block is also executed when a return
is called, making it helpful to put an object
into a given state before exiting.
43Exception Example
try float in Float.parseFloat(input)
catch (NumberFormatException nfe)
System.out.println(input " is no a valid
number.") finally System.out.println(The
sky is falling)