Download Java Primer II and more Lecture notes Java Programming in PDF only on Docsity!
Java Primer II
CMSC 202
Expressions
• An expression is a construct made up of
variables, operators, and method invocations,
that evaluates to a single value.
• For example:
int cadence = 0;
anArray[0] = 100;
System.out.println("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2;
System.out.println(x == y? "equal" :"not equal");
Statements
• Statements are roughly equivalent to sentences
in natural languages. A statement forms a
complete unit of execution.
• Two types of statements:
– Expression statements – end with a semicolon ‘;’
- Assignment expressions
- Any use of ++ or --
- Method invocations
- Object creation expressions
– Control Flow statements
- Selection & repetition structures
Comment Types
- End of line comment – ignores everything else on the line after the
“//”
- Multi-line comment — must open with “/” and close with “/”
- Javadoc comment — special version of multi-line comment that
starts with “/**”
- Used by Java’s documentation tool
// compute the volume
/*
- sort the array using
- selection sort */
/**
- Determines if the item is empty
- @return true if empty, false otherwise */
If-Then Statement
• The if-then statement is the most basic of all
the control flow statements.
if (x == 2) System.out.println("x is 2"); System.out.println("Finished");
if x == 2: print "x is 2" print "Finished"
Python Java
Notes about Java’s if-then :
- Conditional expression must be in parentheses
- Conditional expression must result in a boolean value
Multiple Statements
• What if our then case contains multiple
statements?
if(x == 2) System.out.println("even"); System.out.println("prime"); System.out.println("Done!");
if x == 2: print "even" print "prime" print "Done!"
Python Java
Notes:
- Unlike Python, spacing plays no role in Java’s
selection/repetition structures
- The Java code is syntactically fine – no compiler errors
- However, it is logically incorrect
Blocks
• A block is a group of zero or more statements
that are grouped together by delimiters.
• In Java, blocks are denoted by opening and
closing curly braces ‘{’ and ‘}’.
if(x == 2) { System.out.println("even"); System.out.println("prime"); } System.out.println("Done!");
Note:
- It is generally considered a good practice to include the curly
braces even for single line statements.
Variable Scope
• That set of code statements in which the variable
is known to the compiler.
• Where a variable it can be referenced in your
program
• Limited to the code block in which the variable is
defined
• For example:
if(age >= 18) { boolean adult = true; } /* couldn't use adult here */
If-Then-Else Statement
• The if-then-else statement looks much like it
does in Python (aside from the parentheses
and curly braces).
if(x % 2 == 1) { System.out.println("odd"); } else { System.out.println("even"); }
if x % 2 == 1: print "odd" else: print "even"
Python Java
If-Then-Else If-Then-Else Statement
• Again, very similar…
if(x < y) { System.out.println("x < y"); } else if (x > y) { System.out.println("x > y"); } else { System.out.println("x == y"); }
if x < y: print "x < y" elif x > y: print "x > y" else: print "x == y"
Python Java
Switch Statement
• Unlike if-then and if-then-else , the switch
statement allows for any number of possible
execution paths.
• Works with byte , short , char , and int primitive
data types.
– As well as enumerations (which we’ll cover later)
Switch Statement
int cardValue = /* get value from somewhere */; switch(cardValue) { case 1: System.out.println("Ace"); break; case 11: System.out.println("Jack"); break; case 12: System.out.println("Queen"); break; case 13: System.out.println("King"); break; default: System.out.println(cardValue); }
Notes:
- break statements are typically used to terminate each case.
- It is usually a good practice to include a default case.
Switch Statement
switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: System.out.println("31 days"); break; case 4: case 6: case 9: case 11: System.out.println("30 days"); break; case 2: System.out.println("28 or 29 days"); break; default: System.err.println("Invalid month!"); break; }
Note:
- Without a break statement, cases “fall through” to the next statement.
While Loops
• The while loop executes a block of statements
while a particular condition is true.
• Pretty much the same as Python…
int count = 0; while(count < 10) { System.out.println(count); count++; } System.out.println("Done!");
count = 0; while(count < 10): print count count += 1 print "Done!"
Python Java
Do-While Loops
• In addition to while loops, Java also provides a
do-while loop.
– The conditional expression is at the bottom of the
loop.
– Statements within the block are always executed
at least once.
– Note the trailing semicolon!
int count = 0; do { System.out.println(count); count++; } while(count < 10); System.out.println("Done!");
For Loop
• The for statement provides a compact way to iterate
over a range of values.
• The initialization expression initializes the loop – it is
executed once, as the loop begins.
• When the termination expression evaluates to false,
the loop terminates.
• The increment expression is invoked after each
iteration through the loop.
for (initialization; termination; increment) { /* ... statement(s) ... */ }
For Loop
• The equivalent loop written as a for loop
– Counting from start value (zero) up to (excluding)
some number (10)
for(int count = 0; count < 10; count++) { System.out.println(count); } System.out.println("Done!");
for count in range(0, 10): print count print "Done!"
Python
Java
For Loop
• Counting from 25 up to (excluding) 50 in steps
of 5
for(int count = 25; count < 50; count += 5){ System.out.println(count); } System.out.println("Done!");
for count in range(25, 50, 5): print count print "Done!"
Python
Java
For Loop
• Iterating over the contents of an array
String[] items = new String[]{"foo","bar","baz"}; for (int i = 0; i < items.length; i++) { System.out.printf("%d: %s%n", i, items[i]); }
items = ["foo", "bar", "baz"] for i in range(len(items)): print "%d: %s" % (i, items[i])
Python
Java
For Each Loop
• Java also has a second form of the for loop known
as a “for each” or “enhanced for” loop.
• This is much more like Python’s for-in loop.
• The general form is:
• For now, we’ll assume that the collection is an
array (though there are other objects it can be,
which we’ll discuss later in the semester).
for ( - : ) { /* ... do something with item ... */ }
For Each Loop
• Iterating over the contents of an array using a
for-each loop
String[] items = new String[]{"foo","bar","baz"}; for(String item : items) { System.out.println(item); }
items = ["foo", "bar", "baz"] for item in items: print item
Python
Java
Reading From the Console
• Java’s Scanner object reads in input that the user
enters on the command line.
• System.in is a reference to the standard input buffer.
• We can read values from the Scanner object using the
dot notation to invoke a number of functions.
- nextInt() — returns the next integer from the buffer
- nextFloat() — returns the next float from the buffer
- nextLine() — returns the entire line as a String
Scanner input = new Scanner(System.in);
Scanner Notes
• In order to use the Scanner class, you’ll need
to add the following line to the top of your
code…
• You should never declare more than one
Scanner object on a given input stream.
• The Scanner object will wait for a user to
type, and read all text entered up until the
user presses the “enter” key (including the
newline character).
import java.util.Scanner;
Reading from the Console
- Let’s assume the user has entered “128 10”.
- The first call to nextInt() reads the characters “ 128 ” leaving “ 10\n” in the input buffer.
- The second call to nextInt() reads the “ 10 ” and leaves the “\n” in the buffer.
‘ 1 ’ ‘ 2 ’ ‘ 8 ’ ‘ ’ ‘ 1 ’ ‘ 0 ’ ‘\n’ …
System.out.print("Enter 2 numbers to sum: "); Scanner input = new Scanner(System.in); int n1 = input.nextInt(); int n2 = input.nextInt(); System.out.printf("%d + %d = %d", n1, n2, n1 + n2);
Reading via UNIX Redirection
• The Scanner class also has a bunch of hasNextX()
methods to detect if there’s another data item of the
given type in the stream.
• For example, this is useful if we were reading an
unknown quantity of integers from a file that is
redirected into our program (as above).
% cat numbers 1 2 3 4 5 6 7 8 % java Sum < numbers Sum: 36 %
int sum = 0; Scanner input = new Scanner(System.in); while(input.hasNextInt()) { sum += input.nextInt(); } System.out.println("Sum: " + sum);