You are on page 1of 35

CSE/IT 213 - Flow Control

New Mexico Tech


September 11, 2011

import java.util.*;
import java.text.*;
public class CentimetersToInches {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter centimers: ");
double cm = in.nextDouble();
double totalInches = cm * INCH_PER_CM;
double feet = (int) (totalInches / INCHES_PER_FOOT);
double inches = totalInches - feet * INCHES_PER_FOOT;
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(cm + " cm = " + feet + " ft. "
+ df.format(inches) + " in.");
}
private static final double INCH_PER_CM = 1/2.54;
private static final int INCHES_PER_FOOT = 12;
}
1

$ java CentimetersToInches
Enter centimers:
7
7.0 centimeters = 0.0 ft. 2.76 in.

static keyword
Instance variables or methods in a class may be declared
static.
Static variables and methods are associated with the
class not an object of the class.
Static variables are like global variables. But, they exist
inside a class.
Only a single copy of a static variable exists. Unlike
other instance variables which are copied to each new
object.
3

The full name of a static variable includes the name of


its class.
To refer to a static varibale use className.staticVariable
CentimetersToInches.CM TO INCHES
You can use the short name (w/o the className.)
within a class. Some programmers prefer using className.staticVariable as a mnemonic even inside the class.
System.out is a static variable out in the System
class that represents standard output.

Static Methods
A static method is like a regular C function that is
defined inside a class.
Regular methods send messages to objects. There is
no receiver object for static methods. They operate on
a class.
Like static variables, the full name of a static method
is className.staticMethod() //For example Foo.bar()
refers to the class Foos static bar() method.
The Math class contains static methods, such as max(),
abs(), sin(), cos(), etc.. Their full names are Math.max(),
Math.sin(), and so on. Math.max()
4

A common error with static methods


Why wont this code compile?
public class Foo {
public int i;
public static int bar() {
i++;
return i;
}
}
$ javac Foo.java
Foo.java:5: non-static variable i cannot be
referenced from a static context
i++;

Need an object of a class to use the non-static variable.


i can only be accessed through an object
Foo foo = new Foo();
int a = foo.i;
Static variables can be accessed in static and non-static
methods. Non-static variables are only available to nonstatic methods.

final keyword
Instance variable, methods, and classes can be declared
final.
Final instance variables declares variable as a constant.
Set it and forget about it. Cannot change once set.
Final methods are methods that cannot be overridden.
No inherited class can redefine their meaning.
Final classes cannot be subclassed (i.e. inherited).

Control Flow
a lot like C
import java.util.*;
public class Middle {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("enter three numbers");
System.out.print("enter number one: ");
int first = in.nextInt();
System.out.print("enter number two: ");
int second = in.nextInt();
System.out.print("enter number three: ");
int third = in.nextInt();
7

int middle;
if ( first >= second && first >= third) {
middle = Math.max(second, third);
}
else if (second >= first && second >= third) {
middle = Math.max(first, third);
}
else {
middle = Math.max(second, third);
}
System.out.println("middle = " + middle);
}
}
$ java Middle

enter three numbers


enter number one: 8
enter number two: 18
enter number three: 7
middle = 8

if (condition) {
statement
} else {
statement
}
condition a boolean value (true or false). Like C the
relational operators are
<, , >, , ==, ! =
and the logical operators
&&, ||, !
8

Have to be careful with objects


What does this output?
public static void main(String[] args) {
String s1 = "foo";
String s2 = "foo";
if (s1 == s2) {
System.out.println(s1 + " equals " + s2);
}
else {
System.out.println(s1 + " does not equal " + s2);
}
}
}
9

$ java StringTest
foo equals foo
This is wrong!
This is an artifact of the java compiler. The compiler
finds all identical strings in a class and makes only one
copy. Identical strings point to each other.
The == operator is testing for object identity, not
equality. That is, do the objects point to the same
object.

This code has the same literal string but are not equal
using ==
public static void main(String[] args) {
String s1 = "foo";
String s2 = String.valueOf(new char [] {f,o,o} );
if (s1 == s2) {
System.out.println(s1 + " equals " + s2);
}
else {
System.out.println(s1 + " does not equal " + s2);
}
}
}
java StringTest
foo does not equal foo
10

Use equals method to compare strings for equality.


public class StringTest {
public static void main(String[] args) {
String s1 = "foo";
String s2 = String.valueOf(new char [] {f,o,o} );
if (s1.equals(s2)) {
System.out.println(s1 + " equals " + s2);
}
else {
System.out.println(s1 + " does not equal " + s2);
}
}
}
$ java StringTest
foo equals foo
11

For Loops
import java.util.*;
public class SumN {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Sum the numbers 1 to N");
System.out.print("enter N: ");
int n = in.nextInt();
int sum = 0;
for(int i = 1; i <= n; i++) {
sum += i;
}
System.out.println("sum of 1 to " + n + " is " + sum);
}
12

}
$ java SumN
Sum the numbers 1 to N
enter N: 100
sum of 1 to 100 is 5050

Like C, java has decrement () and increment (++)


operators as well as assignment operators +=, -=, *=,
/=.
for(initialization; condition; incrementor)
statement;
}
Can have multiple, comma-separated expressions in the
initialization and the incrementation sections.
for(int i = 0, int j = 100; i < j; i++, j--) {
...
}
13

Enhanced for loop


iterate over collections or arrays
for (varDeclartion : iterable)
statements;
public class PrintArray {
public static void main(String[] args) {
int[] foo = new int [] {10, 20, 20, 40};
for(int i : foo)
System.out.println(i);
}
}
14

$ java PrintArray
10
20
20
40

While loops
public class OneAtATime {
public static void main(String[] args) {
String s = "abcdef";
int i = 0;
while (i < s.length()) {
System.out.println(s.charAt(i));
i++;
}
}
}

15

$ java OneAtATime
a
b
c
d
e
f

16

Do loops

public class BottlesOfBeer {


public static void main(String[] args) {
int bottlesOfBeer = 6;
do {
if (bottlesOfBeer > 1)
System.out.println("there are " + bottlesOfBeer + " left"
else if (bottlesOfBeer == 1)
System.out.println("there is " + bottlesOfBeer + " left")
else
System.out.println("there is no more left");
} while (--bottlesOfBeer >= 0);
}
}
17

$ java BottlesOfBeer
there are 6 left
there are 5 left
there are 4 left
there are 3 left
there are 2 left
there is 1 left
there is no more left
do loops always execute at least once; while loops only
execute if condition is true

switch Statement
works on integer types
public class DaysOfWeek {
public static void main(String[] args) {
for (int i = 0; i < 7; i++) {
switch(i) {
case 0:
System.out.println("Sunday");
break;
case 1:
System.out.println("Monday");
break;
case 2:
18

System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
case 5:
case 6:
System.out.print("Thursday");
System.out.print(" or Friday");
System.out.println(" or Saturday");
break;
}
}
}

}
$ java DaysOfWeek
Sunday
Monday
Tuesday
Wednesday
Thursday or Friday or Saturday
Thursday or Friday or Saturday
Thursday or Friday or Saturday

Getting out of loops


use break
public class GiveMeABreak {
public static void main(String[] args) {
int i = 0;
while (true) { //infinite loop
i += 1;
if (i == 1000)
break;
}
System.out.println("i = " + i);
}
}
19

$ java GiveMeABreak
i = 1000
once break is encountered the code jumps to the end
of the for or while loop block and begins executing the
statements right after the block.

continue causes for and while loops to move to their


next iteration.
public class PrintOdds {
public static void main(String[] args) {
for(int i = 10; i >= 0; i--) {
if (i % 2 == 0)
continue;
System.out.println(i);
}
}
}

20

$ java PrintOdds
9
7
5
3
1

21

Arrays
two ways to declare them
int [] months; //preferred
int months []; //C - style
This just sets up a reference to the name of the array.
No storage allocated for the array.
Need to use new keyword to allocate space.
months = new [12];
or combine into one statement
22

int [] months

= new int [12];

Arrays are indexed starting with 0 and are initialized to


default values for their types. For objects, the elements
of an array of objects are references to objects, not to
actual instances of the objects. The default value for
an array of objects is null. Arrays of objects contain
only reference variables.
Can also declare arrays with C style braces
int [] months = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
No new keyword used here. The creation of the array
is implicit. Can use with objects as well
String [] names = {"Bob", "Bill", "Jane", "Mary"};

You might also like