Transcript 1903 review
A Quick Review of Java Concepts (from ACS-1903)
Literals / constants
Data types and variables
Primitive types: int, double, boolean, char
Objects: of type String, Random, Scanner, …
Comparing primitive types vs objects
Expressions
Mixed mode expressions
Integer operations: division, modulo
1
A Quick Review of Java Concepts (from ACS-1903)
Input and Output
System.out.print(…) , System.out.println(…)
System.in
Scanner class
JOptionPane class
Import statements
Control structures
Sequence
Decision: if, switch
Iteration: for, enhanced for, while, do while
2
A Quick Review of Java Concepts (from ACS-1903)
Classes
Pre-defined:
String, Scanner, JOptionPane, Math,
Character, Random, Integer, ArrayList
You own classes:
structure
fields
methods
value-returning vs void
getters, setters
constructors
parameter lists/ argument lists
public vs private
overloading
Implementing associations between classes
3
Literals
Constants in Java are called literals
- int, double, char, boolean are primitive types
- String is a class and instances are objects
123
12.3
'a'
"James Gosling"
true
int
double
char
String
boolean
4
Variables
Variables
• Named location in memory
• Java is strongly typed
• You must declare the type of each variable … cannot
change this later
String firstName, lastName;
int studentNumber;
Common convention is
to name variables using
camel-case
5
Data types
Integer numeric types vary according to
amount of memory used
smallest/largest values
Integer class has fields MIN_VALUE and MAX_VALUE
6
Data types
Decimal numeric types vary according to
the amount of memory
smallest/largest values
7
Expressions
Operators for integer arithmetic expressions
Addition
Subtraction
Multiplication
Division
Modulo
no remainder
remainder when …
8
Autoincrement / Autodecrement
statements such as
n = n +1;
m = m-1;
can be written using autoincrement / autodecrement
n++;
m--;
and
++ n;
--m;
Called post- increment/decrement
Called pre- increment/decrement
9
Special assignment operators
Special operators that combine assignment with an operation
+= -+ *= /= %=
To sum a set of values
import java.util.Scanner;
Scanner kb = new Scanner (System.in);
System.out.println("enter 10 integer values"
+ " and press enter:");
int sum = 0;
// simple assignment
for (int i=0; i<10; i++){
sum += kb.nextInt();
// increment sum
}
System.out.println(sum);
10
Decimal arithmetic
Decimal expressions
do not use if exact calculations are needed (e.g. monetary calculations)
operators for arithmetic expressions
Addition
Subtraction
Multiplication
Division
10.0 / 4.0
Correction to 1903
notes, page 26
10/4 is 2 !!!!
10.0/4.0 is 2.5
11
boolean
boolean type has 2 values: true, false
Variables:
boolean xyz = true ;
boolean found ;
Operators && || !
a < b
a+5 >= q*3
a == b
a != b
found
a < b || b < c
found && i<100
i < 100 && j < 100
!found && i < 100
! found
12
char
char is used for single characters
Usual operators <
<= == !=
>
>=
char a, b, c;
a = '*';
b = 'q';
c = '1';
If (a == b) ……………
13
String
String literals are enclosed in double quotes
"this is a line of text“
"any character such as $ % etc can be included“
String Variables
e.g.
String firstName, lastName, address;
firstName = "Jones";
Most common operation is catenation:
fullName = lastName + ", "+ firstName;
line += word + ", ";
14
String
Memory for Strings is handled differently from primitive data types
Primitive
type
Object
15
String
What is the difference between the following?
if (firstName == lastName) …
and
if (firstName.equals(lastName))…
16
Evaluation of Expressions
If there is more than one operator at the
same priority the evaluation goes from
left to right.
Suppose c = 2.0;
/ and * have same priority… so:
( ( 9.0 / 5.0 ) * c ) + 32.0
1.8
3.6
35.6
17
Expressions
Priorities (and so order of evaluation) can be overridden with a
subexpression … operations enclosed in parentheses
A sub-expression is always evaluated before the expression in which
it is contained is evaluated. Of course the sub-expression is evaluated
according to the rules of expressions.
Consider C = 2.0
9.0 / 5.0 * c + 32.0
35.6
9.0 / (5.0 * c + 32.0 )
0.21
vs
18
Mixed Mode
A mixed-mode expression involves variables/constants of different types
Example: 9 / 5.0 * 2 + 32
If an operation involves two operands where one is an int and the other is
a double, then the int is converted automatically to its double
equivalent before the operation occurs.
9 / 5.0 * 2 + 32
1. The first operation is “/” … the 9 is converted to 9.0 and we have
9.0/5.0 * 2 + 32
And so we have
1.8 * 2 + 32
2. “*” is performed next … the 2 is converted to 2.0
1.8 * 2.0 + 32
And so we have
3.6 + 32
3. 32 becomes 32.0 and we have the final result of 35.6
19
Input and Output
Scanner
Input from standard input (console)
Input from a file
Parse tokens from a string
System.out
Display to standard output (console)
Two methods print() and println()
JOptionPane
An interactive form of input and output using pop-ups
20
Input Using the Scanner Class
•System - a pre-defined Java class that has an object named in.
•System.in -The standard input stream.
•Scanner – instances are used to obtain “tokens” from some source
A typical use of Scanner :
Scanner keyboard = new Scanner(System.in);
The keyboard object above is a Scanner object to be used to get user input from the
keyboard
The Scanner class is defined in the Java library named java.util
need an import statement for this
import java.util.Scanner;
21
Input Using the Scanner Class
22
Using a Scanner to count tokens on a line of input
import java.util.Scanner;
/**
* Count tokens on one line of input
* User enters CTL-D on Windows to indicate end of input (or CTL-Z on Mac or Unix)
*/
public class CountTokens
{
public static void main(String[] args){
// get line of text
Scanner kb = new Scanner(System.in);
System.out.println("Enter a line of text:\n");
String line = kb.nextLine();
// process the line
Scanner s = new Scanner(line);
int count=0;
while (s.hasNext()){
count++;
s.next();
}
System.out.println("Your line contained "+count+" words");
}
23
}
JOptionPane
input and output in the form of interactive dialog pop-ups
… programs need an import statement
To display information to the user we just use:
JOptionPane.showMessageDialog (null ,
);
A string goes here
The user sees a pop-up window and must click OK for the program to
continue …. showMessageDialog does not complete until the click.
24
JOptionPane
Example: to display information :
import javax.swing.JOptionPane;
public class UsingDialogBox
{
public static void main(String[] args)
{
double netPay, grossPay, deductions;
grossPay = 100.00;
deductions = 10.00;
// Calculate net pay
netPay = grossPay - deductions;
JOptionPane.showMessageDialog(null, "net pay is "+netPay);
}
}
25
JOptionPane
To get information from the user we just use
JOptionPane.showInputDialog(…)
A message string goes here
A string variable goes here
= JOptionPane . showInputDialog (
) ;
User sees a pop-up window displaying the message and with a box where
text is entered by the user.
User then clicks OK for the program to continue and then a value is assigned
to the variable on the left of the equals sign.
26
System.out
Used to continue a line displayed on the Terminal Window
What is the difference between?
System.out.println("start of display");
System.out.println("123");
and
System.out.print("start of display");
System.out.print("123");
27
System.out
println( )
causes the display to advance to a new line and then displays output.
print( )
does not advance to a new line
output begins at the end of the current line
Recall ‘\n’ will always advance to a new line
28
Control structures
Programmers use 3 basic structures
• Sequences compound statement
• Decisions if, switch
• Loops
while, do while, for, enhanced for
29
Control structures
compound statement :
Java statements delimited by curly braces
Opening brace
{
temp = x;
x = y;
y = temp;
}
A compound statement is
often used with if’s, while’s
etc.
… to provide a group of
statements to be executed
repeatedly or conditionally.
Closing brace
30
while
While statement
executes a statement as long as some expression is true
while ( logical expression )
statement
31
while
Example: use a loop to display the numbers from 0 to 9
Note the
indentation
/**
* Display the numbers from 0 to 9.
*/
public class Numbers0To9
{
public static void main(String[] args)
{
int count = 0;
System.out.println("Numbers");
while ( count < 10 ){
System.out.println(count);
count = count + 1;
}
System.out.println("*******");
}
}
BlueJ has a auto-layout command – under Edit
32
if
if ( logical expression)
statement1
else
statement2
The else clause is optional
33
if
Example: test a number for being positive or negative
import java.util.Scanner;
public class PositiveOrNot
{
public static void main(String[] args)
{
// Use a scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// Prompt the user for a number
System.out.println("Enter a number "
+"and then press Enter: ");
int number = keyboard.nextInt();
System.out.print("the number "+number+" is ");
// Display a message if number is positive or not
if (number > 0) {
System.out.println("positive");
}
else {
System.out.println("not positive");
}
}
}
34
for
for statement - commonly used where there is a need for a statement to be
executed a specific number of times.
This type of looping construct is sometimes called a counted loop.
Syntax:
for ( initialization; logical expression; increment )
statement
35
for
Example: roll a die 10 times
import java.util.Random;
/**
* Display 10 rolls of a 6-sided die.
*/
public class RollDie
{
public static void main(String[] args)
{
System.out.print("\n\n10 rolls: ");
Random g = new Random();
for (int i=0; i<10; i++)
System.out.print(g.nextInt(6)+1+" ");
}
}
36
do while
programming construct for executing a process at least once,
until some condition is true
37
do while
Example: display numbers 0 to 9
/**
* Display the numbers from 0 to 9.
*/
public class Numbers0To9UsingDoWhile
{
public static void main(String[] args)
{
int count = 0;
System.out.println("Numbers");
do{
System.out.println(count);
count = count + 1;
}
while ( count < 10 );
System.out.println("*******");
}
}
38
switch
programming construct for selecting one block of code for
execution based on a simple equality test
39
switch
40
switch
Example: given a letter grade translate to a numeric grade
41
switch
String grade;
double nGrade;
System.out.println("Enter letter grade:");
Scanner kb = new Scanner(System.in);
grade = kb.next();
switch (grade) {
case "A": nGrade = 4.0;
break;
case "B": nGrade = 3.0;
break;
case "C": nGrade = 2.0;
break;
case "D": nGrade = 1.0;
break;
default: nGrade = 0.0;
}
System.out.println(grade+" --> "+nGrade);
42
Some Important Classes
Math
Character
Integer
Often we just use these as utility
classes – no object is instantiated.
Methods used are static.
Random
Scanner
String
An object is instantiated … we may
need more than one random number
generator, more than one scanner, …
43
Math class
Math class is a utility class
•You cannot create an instance of Math
•Contains constants, π and e
Names of these are PI and E
Java convention is to name constants using capital letters
Math.PI, Math.E
44
Math class
Methods
pow(…)
Raise the first argument to the power
specified in second argument
e.g. Math.pow(x, 3)
abs(…)
Returns absolute value of its argument
max(…)
Returns the larger of two int or double
arguments
min(…)
Returns smaller …
…
45
Math class
Example - Finding the largest of 3 int values. Note the use of the
prefix Math.
import java.util.Scanner;
/**
* Prompt for 3 int values and report the largest
*/
public class FindMax
{
public static void main(String[] args){
Scanner kb = new Scanner(System.in);
System.out.println(
"Please enter 3 int values");
int i = kb.nextInt();
int j = kb.nextInt();
int k = kb.nextInt();
int mx = Math.max(i, Math.max(j,k));
System.out.println("largest is "+mx);
}
}
46
Integer class
Integer class is a utility class
•Many methods are static meaning you do not need an object of
type Integer.
•Contains constants, MAX_VALUE and MIN_VALUE
Java convention : name constants using capital letters.
47
Integer class
Methods
max(…)
Returns the larger of two int arguments
min(…)
Returns smaller …
parseInt(…)
Parses the string argument expecting
that argument to be a valid decimal
integer.
Correction: E.g. parseInt(" 23 ")
no spaces
Should be: E.g. parseInt("23")
…
to ensure there are no leading or trailing spaces
in a string one can use the trim() method
String xx = ...
xx = xx.trim();
int i = Integer.parseInt(xx);
48
Wrapper classes
There are wrapper classes corresponding to each primitive type
Called wrapper classes as you instantiate an object and wrap a
primitive value inside
Integer
Double
Boolean
Byte
Character
Float
Long
Short
e.g. int xx = …
Integer abc = new Integer (xx);
49
Character class
To use the utility methods of the Character class an instance is not
required
Character contains many useful utility methods
50
Character class
Example – validate a student number
import java.util.Scanner;
/**
* A string provided by the user is examined
* to determine whether or not it is numeric.
*/
public class ValidateStudentNumber
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter a number: ");
String number = kb.next();
// characters are examined one-by-one
boolean valid = true;
for (int i = 0; i < number.length(); i++){
char c = number.charAt(i);
if(! Character.isDigit(c)) valid = false;
}
if (valid) System.out.println("Valid");
else System.out.println("Invalid");
}
}
51
Random class
An instance of the Random class can be used to generate a stream of
random values
Usage:
1.Create a Random object
2.Use the object to get random values
nextInt()
returns a random integer
nextInt(max) returns a random value in [0, max )
nextDouble
returns a random value in [0.0, 1.0 )
nextBoolean() returns a random value from [true, false]
52
Random class
Example: code to display a random coin toss:
// two-sided coin: heads/tails
Random rand = new Random();
switch(rand.nextInt(2)) {
case 0:
System.out.println("Heads");
break;
case 1:
System.out.println("Tails");
break;}
Could have used nextBoolean() …………………
53
Scanner class
The Scanner class is useful when you need to parse some stream that
is said to contain tokens.
By default, a token is a sequence of characters; tokens are delimited
by whitespace.
We can create a Scanner object that is associated with one of:
– System.in
– a string
– a file
Examples
Scanner s = new Scanner(System.in);
Scanner s = new Scanner(str);
//str is of type String
Scanner s = new Scanner(f);
//f is of type File
54
Scanner class
Scanner methods
next()
get next token
nextBoolean()
get next …
nextInt()
get next …
nextDouble()
get next …
nextLine()
get next …
hasNext()
returns true if there is a token available
hasNextLine()
returns true if …
hasNextBoolean()
returns true if …
hasNextInt()
returns true if …
hasNextDouble()
returns true if …
55
Scanner class
Example – display the file README.TXT:
import …
/**
* Display contents of Readme.txt with line numbers
*/
public class DisplayReadme
{
public static void main(String[] args)
throws FileNotFoundException
{
Scanner f = new Scanner(
new File("Readme.txt"));
int i=1;
System.out.println(
"<<<< File Readme.txt >>>>");
while (f.hasNext()){
String line = f.nextLine();
System.out.println((i++)+" "+line);
}
System.out.println(
"<<<< end of listing >>>>");
}
}
56
A first data structure: the ArrayList class
An ArrayList can be visualized as a linear list of objects at index
positions
• for example 0, 1, 2, 3
[Joe, Jasper, Dick, Abigail]
ArrayList is a data structure that grows and shrinks gracefully
• you can add/remove objects as necessary
57
ArrayList class
ArrayList is a collection of objects
to hold data of a primitive data type (e.g. int) you need to use a
wrapper class (e.g. Integer, Double, Boolean, Character)
58
ArrayList class
ArrayList methods
Correction for
1903 notes
people.contains(“Jaime”);
59
ArrayList class
ArrayList methods
60
ArrayList class
Displaying a list
Always specify the type of objects to be held in an array list
ArrayList < String > people =new ArrayList () ;
// add some names
people . add ("Joe") ;
people . add ("Jasper") ;
people . add ("Dick") ;
whole list is displayed
people . add ("Abigail") ;
System.out.print(people);
[Joe, Jasper, Dick, Abigail ]
61
ArrayList class
The enhanced for
a variation on the for
used to iterate through all elements
cannot change anything
Example: iterate through an ArrayList
people
// add
people
people
people
people
=new ArrayList () ;
some names
. add ("Joe") ;
. add ("Jasper") ;
. add ("Dick") ;
. add ("Abigail") ;
for(String s : people) System.out.print(s+ "
simpler syntax
than for
");
62
Classes
Fields – what data values define/describe an instance?
Constructors – what values are assigned to fields when an
instance/object is created?
Methods – what does an instance know? What can an
instance do?
– getters
– setters
– equals
– toString
– … other
63
UML Diagram of a Class
Class name
fields
methods (including constructors)
64
Class Diagram for Student
show 1, 2, or 3
compartments/ info
as needed
getters
setters
65
Java Classes
Class: a template for objects
Objects:
instantiated/created via new
also called instances – so we can speak of instance fields and
methods
66
Methods
•value-returning vs non value-returning
– value-returning
must have return statement
e.g. getters
– void - no return statement
e.g. setters
•to provide a way to test for equality
equals()
•to provide a way to display an object
toString()
•public vs private
public - anyone can use
67
Java Classes
Parameter Lists / Arguments
A parameter list defines the type of data that will be passed in
to a method
Arguments appear in the call statement.
Arguments are copied into the parameters on entry, but there
is no copying on return.
Because addresses of objects are passed its possible to
modify an object in a called method
68
Java Classes
Methods are used for two purposes
To make a program more readable through decomposition
To reuse code instead of duplicating code
69
Java Classes
Associations: consider where a student may declare one major
and where a subject can have many majors
A student is majoring in a subject
A subject has majors (students)
70
Java Classes
See sample classes (Student and Subject) in 1903 Java notes
beginning on page 195
A student is majoring in a subject
A student will have at most one major
The student class has a private field & getter/setter
private Subject major;
A subject has majors (students)
A subject may have many majors
The Subject class has an ArrayList & getter/setter & addMajor(…)
private ArrayList<Student> majors;
71