Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Lecture 2: CS201 Review
Michael Hsu
CSULA
CS201 Main Topics
Anatomy of a Java Program
Data types
Methods
static vs instance
Arrays
Multi-dimensional arrays
HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Creating, Compiling, and Running
Programs
Compiling Java Source Code
"Write once, run anywhere" (WORA)
Remember machine code is platform dependent
Compiler compiles the code, can only run on that platform
The Java Virtual Machine(JVM)
What if we don’t compile for each different platform, but use a virtual machine ,
and compile for that machine instead? Genius!
The Java compiler compiles your program into bytecode
The bytecode can then be run on any JVM on any platform
Eclipse Tutorial
Follow the eclipse setup guide in the resources section on the course website
Key terms:
Workspace
Your working directory
it will contain multiple projects
When you want to move your eclipse files from file explorer, move the entire workspace folder.
Projects
This is where you will put your java files
You can have one workspace for all your courses, and have different projects for each course,
or have separate workspaces for each course and have separate projects for each
assignments
I recommend having a different workspace for each of your courses with separate projects for
each assignment of the course
Makes your life easier
Useful Eclipse Tips
Show Line Numbers:
Ctrl+ SPACE
Auto format and indentation
Ctrl + d
Autocomplete, auto fix
Ctrl + SHIFT + f
Window -> Preferences -> expand General -> expand Editors -> click on Text Editors
-> check show line numbers
Delete entire line
Right click on a variable then click refactor
You can rename your variables and Eclipse will update all the occurrences for you
Anatomy of a Java Program
Class name
Main method
Statements
Statement terminator
Reserved words
Comments
Blocks
Class Name
Every Java Program must have at least one class.
Each class has a name
Use upper camel case by convention
Capitalize the first character of each word
Examples: HelloWorld, WelcomeHome, ThisIsAnExample, Hello
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
The Main Method
A method is a set of code which is referred to by name and can be called
(invoked) at any point in a program simply by utilizing the method's name.
In order to run a class, the class must contain a special method named main.
The program is executed from the main method.
It has to look exactly like this:
public static void main(String[] args)
Remember, computers are stupid
Statement
A statement represents an action or a sequence of actions
The highlighted statement writes Hello World to standard output:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Notice the statement ends with a semicolon:
Every statement in Java ends with a semicolon(;).
Reserved Words
Reserved words or keywords are words that have a specific meaning to the
compiler and cannot be used for other purposes in the program. For example,
when the compiler sees the HelloWorld class, it understands that the word
after class is the name for the class.
In the example below, the reserved words are highlighted in red
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Blocks
A pair of braces ({ }) in a program forms a block that groups components of a
program:
public class Test {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
Class block
Method block
Special Symbols
Character Name
{}
()
[]
//
" "
;
Description
Opening and closing
braces
Opening and closing
parentheses
Opening and closing
brackets
Double slashes
Denotes a block to enclose statements.
Opening and closing
quotation marks
Semicolon
Enclosing a string (i.e., sequence of characters).
Used with methods.
Denotes an array.
Precedes a comment line.
Marks the end of a statement.
Escape Sequences
Escape Sequence
Description
\t
Insert a tab in the text at this point.
\b
Insert a backspace in the text at this point.
\n
Insert a newline in the text at this point.
\r
Insert a carriage return in the text at this point.
\f
Insert a formfeed in the text at this point.
\'
Insert a single quote character in the text at this point.
\"
Insert a double quote character in the text at this point.
\\
Insert a backslash character in the text at this point.
Programming Conventions
Why follow conventions?
Won’t make my eyes bleed
I look at all your assignments
I will take off points if you don’t.
Easier to read and maintain
Lots of APIs and frameworks rely on proper naming conventions
Comments Example
/* CS201
* Spring 2015
* Example 1
*/
public class HelloWorld {
//Write Hello, World to standard output
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Naming Conventions
Choose meaningful and descriptive names.
Length of name is no longer an issue, since most editors support autocomplete
Class names:
Upper Camel Case
Capitalize the first letter of each word in the name. For example, the class name
ComputeExpression.
Proper Indentation and Spacing
The machine doesn’t care whether you indent it or not. In fact, compressing
everything to one line saves a lot of space
Indentation and spacing is used so your code is readable.
Use Indentation to show different levels of the code block/structure
Generally two spaces per level, or you can use tabs
In fact, languages like python make it mandatory, or it won’t even compile
Use a plugin for your editor to automate the process.
I’m not too picky on the style, as long as it’s readable
Readable Code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Unreadable Code
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, World");
}
}
Conventions Grading Criteria
If you don’t follow conventions, I will take off up till 20% of your lab grade
depending on the offense.
Programming errors
Syntax Errors
Runtime Errors
Detected by the compiler, won’t compile at all
Causes the program to abort
Logic Errors
Produces incorrect result
Most difficult to debug
Syntax Error
public class Test {
publi static void main(String[] args) {
System.out.println("lol, you can't spell");
}
}
What is wrong with this code?
Runtime Errors
public class ShowRuntimeErrors {
public static void main(String[] args) {
System.out.println(1 / 0);
}
}
What is wrong with this code?
Logic Errors
public class CalculateAreaOfTriangle {
public static void main(String[] args) {
System.out.println("Base is 20, height is 10");
System.out.println("Area is: ");
System.out.println(20 + 10);
}
}
What is wrong with this code?
Reading Error Messages
Pay attention to the line number
Understand what type of error it is
Read your own code and find the problem.
At this stage, it is most likely a problem with your code or your environment setup,
Java is not the problem.
More Info
http://www.dummies.com/how-to/content/tackling-error-messages-in-javaprogramming.html
Variables and Constants
One of the basic building blocks of a program
Similar to variables and constants in math
Variables/constants, in the general sense, allocate memory for specific data
you’re using in a program
Example:
double radius = 0;
Allocates space to store a double, names it radius (think memory address), then
stores the value 0 at the memory address
We call the name of the variable an identifier
Declaring Variables
In Java, you must declare variables before you use them
int x;
// Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a;
// Declare a to be a
// character variable;
29
Assignment and Comparison
Statements
Note: a SINGLE equal sign is assignment in Java.
To compare variables, use ==
x = 1;
// Assign 1 to x;
radius = 1.0;
// Assign 1.0 to radius;
a = 'A';
// Assign 'A' to a;
1 == 1
// Is one equal to one?
30
Declaring and Initializing in One Step
int x = 1;
double d = 1.4;
31
Constants
final datatype CONSTANTNAME = VALUE;
final double PI = 3.14159;
final int SIZE = 3;
32
Naming Convention For
Variables/Constants
For variables, use lowerCamelCase
First word starts with lower case, the rest upper case
Choose meaningful, descriptive names, usually nouns.
Capitalize all letters in constants, and use underscores to connect words. For
example, the constant PI and MAX_VALUE
More examples of constant:
HEIGHT_OF_MICHAEL
ABOGADRO_CONSTANT
Again, if you don’t pick reasonable names/follow naming conventions, I will
take off points
Numerical Data Types
Name
Range
Storage Size
byte
–27 to 27 – 1 (-128 to 127)
8-bit signed
short
–215 to 215 – 1 (-32768 to 32767)
16-bit signed
int
–231 to 231 – 1 (-2147483648 to 2147483647)
32-bit signed
long
–263 to 263 – 1
(i.e., -9223372036854775808 to 9223372036854775807)
64-bit signed
float
Negative range:
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
32-bit IEEE 754
double
Negative range:
-1.7976931348623157E+308 to -4.9E-324
64-bit IEEE 754
Positive range:
4.9E-324 to 1.7976931348623157E+308
Floating Point Types
Include the types float and double
Uses scientific Notation in binary to store data
IEEE 754
These types store values with limited precision, essentially rounding to the
closest value they can hold
More Info
http://introcs.cs.princeton.edu/java/91float/
35
Floating Point Types Rounding Errors
Floating point arithmetic is not exact, as some numbers require infinite
amount of digits to be represented (like 1/10) in binary.
Do not rely on floating point types for accurate calculations
What if we’re calculating money? Use BigDecimal
Do not do test for equality between floating point nubmers
More Data Types
boolean
Either true or false
Comparisons evaluate to boolean values
100 > 2 true
2 == 2 true
char
Single character
Set literal value using single quotes:
char exampleChar = ‘B’
You can also use ASCII values:
char exampleChar = 66
Since the variable is of chart datatype, java knows that you are using the ASCII value to refer to the
character ‘B’
As a result, ‘b’ is different from ‘B’ since they have different ASCII values.
Primitive Data Types
Predefined by the language
basic types that build up other types
In later classes, you will use primitives to create your own data types
Only the values are copied when you reassign primitive type variables to each
other
More on this later
Includes all the numeric data types mentioned in previous slides, plus boolean and
char.
Strings
A sequence of zero or more characters
You already used them in the System.out.println statements
Set values using double quotes
The ‘S’ is capitalized
It is NOT a primitive type, but a class
Will be covered later
String helloWorld = “Hello, World”;
“”
null String/empty String
Using variables in String literals
To use variables in String literals, use the + operator:
int num1 = 2;
int num2 = 3;
System.out.println(num1+ " divided by "+num2+" in Java is " + 2/3);
Math Operations
Most of them are just like how you do it in math
int x = 1;
// declared an integer variable x, sets x to be 1
x = x + 1; // adds 1 to x
x = x * 2;
X = 2/3
x = 100.0/9.2; //Floating point division
Integer division: when all variables in the calculation are numeric nonfloating point types, the decimal portion is dropped.
// multiplies x by 2
//integer division
Example: 1/2 == 0, 20/6 == 3, 14/200 == 0
The modulus operator %
%
Performs integer division, and returns the remainder.
x =7%3
Divide 7 by 3, find the remainder, then assign value of the remainder to x
In this case x is 1
a%b
If a > b, then it returns the remainder of the division
If a < b, then it returns a
If a == b, then it returns 0
Testing even and odd
If x is even, then x % 2 == 0 evaluates to true
If x is odd, then x % 2 == 1, or you can use x % 2 != 0
Type Casting
Converting between data types
Implicit casting
double d = 3; (type widening)
Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is truncated)
char i = (char) 65; (ASCII code to char)
What is wrong?
int x = 5 / 2.0;
range increases
byte, short, int, long, float, double
43
Augmented Assignment Operators
44
Increment and
Decrement Operators
45
Increment and
Decrement Operators, cont.
int i = 10;
int newNum = 10 * i++;
Same effect as
int i = 10;
int newNum = 10 * (++i);
int newNum = 10 * i;
i = i + 1;
Same effect as
i = i + 1;
int newNum = 10 * i;
46
Assignment Expressions and
Assignment Statements
Prior to Java 2, all the expressions can be used as statements. Since Java 2,
only the following types of expressions can be statements:
variable op= expression; // Where op is +, -, *, /, or %
++variable;
variable++;
--variable;
variable--;
47
Expressions, Literals, and Statements
Literals:
Source code representation of a fixed value
Examples:
Expression:
Made up of variables, operators, that evaluates to a value
Java subexpressions are evaluated left to right
Examples:
1, 2, 0, -200, true, false, ‘A’
2*3*4
2%3
i+++I
K =10
Statements: sentences with semi-colon at the end
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html
Relational Operators
Java
Operator
Mathematics
Symbol
Name
Example
(radius is 5)
Result
<
<
less than
radius < 0
false
<=
≤
less than or equal to
radius <= 0
false
>
>
greater than
radius > 0
true
>=
≥
greater than or equal to
radius >= 0
true
==
=
equal to
radius == 0
false
!=
≠
not equal to
radius != 0
true
49
Control Flow Statements
Your source code is usually executed from top to bottom
In the order that they appear
Control Flow Statements
Breaks up your execution order
Conditionally execute particular blocks of code
Some categories:
Decision making
Looping
If-then, if-then-else, switch
for, while, do-while
Branching
Break, continue return
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html
if-then statements
Most basic of all control flow statements
A programmer's wife tells her: "Go to the store and get a loaf of bread. If they have
eggs, get a dozen."
The programmer comes home with 12 loaves of bread.
Tells your program to execute a certain section of code only if a particular test
evaluates to true
Syntax:
if(TEST){
//Do stuff in here is TEST evaluates to true
}
if-then example
Example:
boolean isThisClassCS201Section3 = true;
if(isThisClassCS201Section3){
System.out.println("My dog lectures better than the instructor");
System.out.println("JK, please don't give me a bad grade :)");
}
Eclipse tells you if the code block is “dead code”, never can be reached
if-then-else Statement
Provides a secondary path of execution when an “if” clause evaluates to false.
Example:
boolean isThisClassCS201Section3 = true;
if (isThisClassCS201Section3) {
System.out.println("My dog lectures better than the instructor");
} else {
System.out.println("I'm not gonna joke about the instructor cause he/she probably
can't take the joke");
}
You can also omit braces for the else clause if there is just one statement
if-else if - else
You can use else if, with or without a final else:
if(condition 1) {
// statements to execute if condition 1 is true
}
else if(condition 2) {
// statements to execute if condition 1 is false but condition 2 is true
}
// can use any number of else if blocks
else {
// statements to execute if condition none of the conditions are true
}
Nesting if-else statements
if(condition 1) {
// statements execute if condition 1 is true
if (condition 2){
// statements execute if condition 1 and condition 2 are both true
}
else {
// statements execute if condition 1 is true but condition 2 is false
}
}
else{
// statements execute if condition 1 is false
}
Common Errors
Adding a semicolon at the end of an if clause is a common mistake.
if (radius >= 0);
{
Wrong
area = radius*radius*PI;
System.out.println(
"The area for the circle of radius " +
radius + " is " + area);
}
Semi-colon marks the end of the statement, ending the if-statement. so the code block will
always execute.
This mistake is hard to find, because it is not a compilation error or a runtime error, it is a
logic error.
This error often occurs when you use the next-line block style.
56
A Note on Naming Conventions for
Boolean variables
The identifier of a boolean variable should be a phrase/sentence that is
either true or false
Examples:
isNumberEven
isOver9000
hasBeenNoticedBySenpai
Logical Operators
Operator
Name
Description
!
not
logical negation
&&
and
logical conjunction
||
or
logical disjunction
^
exclusive or
logical exclusion
58
Truth Table for Operator !
p
!p
Example (assume age = 24, weight = 140)
true false !(age > 18) is false, because (age > 18) is true.
false true
!(weight == 150)
is true, because (weight == 150) is false.
59
Truth Table for Operator &&
p1
p2
p1 && p2 Example (assume age = 24, weight = 140)
false
false false
(age <= 18) && (weight < 140) is false, because (age >
18) and (weight <= 140) are both false.
false
true
false
true
false
false
(age > 18) && (weight > 140) is false, because (weight
> 140) is false.
true
true
true
(age > 18) && (weight >= 140) is true, because both
(age > 18) and (weight >= 140) are true.
60
Truth Table for Operator ||
p1
p2
p1 || p2 Example (assume age = 24, weihgt = 140)
false false false
false true
true
(age > 34) || (weight <= 140) is true, because (age > 34)
is false, but (weight <= 140) is true.
true
false
true
(age > 14) || (weight >= 150) is false, because
(age > 14) is true.
true
true
true
61
Truth Table for Operator ^
p1
p2
p1 ^ p2 Example (assume age = 24, weight = 140)
false
false
false
(age > 34) ^ (weight > 140) is true, because (age > 34) is false
and (weight > 140) is false.
false
true
true
(age > 34) ^ (weight >= 140) is true, because (age > 34) is false
but (weight >= 140) is true.
true
false
true
(age > 14) ^ (weight > 140) is true, because (age > 14) is
true and (weight > 140) is false.
true
true
false
62
switch Statements
switch (status) {
case 0: compute taxes for single filers;
break;
case 1: compute taxes for married file jointly;
break;
case 2: compute taxes for married file separately;
break;
case 3: compute taxes for head of household;
break;
default: System.out.println("Errors: invalid status");
System.exit(1);
}
63
switch Statement Rules
The switch-expression
must yield a value of char,
byte, short, or int type and
must always be enclosed in
parentheses.
The value1, ..., and valueN must
have the same data type as the
value of the switch-expression.
The resulting statements in the
case statement are executed when
the value in the case statement
matches the value of the switchexpression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
64
switch Statement Rules
The keyword break is optional,
but it should be used at the end
of each case in order to
terminate the remainder of the
switch statement. If the break
statement is not present, the
next case statement will be
executed.
The default case, which is
optional, can be used to perform
actions when none of the
specified cases matches the
switch-expression.
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
…
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
When the value in a case statement matches the value
of the switch-expression, the statements starting from
this case are executed until either a break statement or
the end of the switch statement is reached.
65
Conditional Expressions
if (x > 0)
y=1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(boolean-expression) ? expression1 : expression2
66
java.util.Scanner
Lets you get input from keyboard (System.in) to make the programs more fun
Couple of things to notice
You have to import the scanner class because it is not under java.lang
You don’t need to import java.lang.Math cause the compiler does it for you
Import before you declare the class
Import statement:
import java.util.Scanner;
Difference between classes, object, and instance
java.util.Scanner is a class
A class is like a blueprint/template. To make copies of it that do different things, we need
to create an object
An object is an instance of its class
How to Use java.util.Scanner
1.
2.
import java.util.Scanner;
Create an instance of the Scanner class, a Scanner object:
Scanner scanner = new Scanner(System.in);
//We set up Scanner object with the name “scanner”
3. Do Stuff with it
4. Close it to free up resources:
scanner.close();
Scanner Input Methods
https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
Since most of the methods are instance methods, you have to create the
scanner object before you can use it
The main method is not an instance method because of the keyword “static”
For example, methods in String and Math are static methods
You can read an entire line, a String, a double, an int, etc.
Read the documentation and lecture code examples to learn more about
Scanner methods
Useful Scanner Methods
nextInt(): reads the next token as an int
next(): reads the next token as a string
nextLine(): reads the entire line, consumes end of line(carriage return)
nextDouble(): reads the next token as a double
nextBoolean(): reads in the next token as a boolean
What Exactly Are Methods?
We talked about the main method, we also used methods from Scanner
Methods:
A block of code that can be called using the identifier
It can do things without any input/output, like System.out.println()
You can pass in parameters as inputs
You can also specify the method return type, and return a value of that type using
the return keyword.
Example Method:
Return type
Method
Name/Identifier
Parameters
public double calculateTriangleArea(double base, double height) {
double area = base * height / 2;
return area;
}
Return a value with type
matching the return type
specified
Another Example Method:
Return type is void, so not
returning anything
public void calculateTriangleArea(double base, double height) {
System.out.println("I'm just printing out stuff");
}
Using Methods
Recall the differences between static and instance methods:
Static methods belong to the class
Has the “static” keyword between “public” and the return type
Using static methods:
CLASSNAME.STATIC_METHOD_NAME()
Example: Integer.parseInt(“23456”);
Instance methods belong to the objects that are instances of the class
Does not have the “static” keyword
Using instance methods:
Create an object first
OBJECT_NAME.METHOD_NAME()
Example: scanner.nextInt()
java.lang.Math
https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html
Unlike java.util.Scanner, you don’t need to import it cause it’s under
java.lang
Class constants:
PI
E
Class methods:
Trigonometric Methods
Exponent Methods
Rounding Methods
min, max, abs, and random Methods
The random Method (Not secure for
Cryptography)
Generates a random double value greater than or equal to
0.0 and less than 1.0 (0 <= Math.random() < 1.0).
Examples:
(int)(Math.random() * 10)
Returns a random integer
between 0 and 9.
50 + (int)(Math.random() * 50)
Returns a random integer
between 50 and 99.
In general,
a + Math.random() * b
Returns a random number between
a and a + b, excluding a + b.
76
Characters: Comparing and Testing
Characters
if (ch >= 'A' && ch <= 'Z')
System.out.println(ch + " is an uppercase letter");
else if (ch >= 'a' && ch <= 'z')
System.out.println(ch + " is a lowercase letter");
else if (ch >= '0' && ch <= '9')
System.out.println(ch + " is a numeric character");
77
Static Methods in the Character
Class
Method
Description
isDigit(ch)
Returns true if the specified character is a digit.
isLetter(ch)
Returns true if the specified character is a letter.
isLetterOfDigit(ch)
Returns true if the specified character is a letter or digit.
isLowerCase(ch)
Returns true if the specified character is a lowercase letter.
isUpperCase(ch)
Returns true if the specified character is an uppercase letter.
toLowerCase(ch)
Returns the lowercase of the specified character.
toUpperCase(ch)
Returns the uppercase of the specified character.
78
The String Type
The char type only represents one character. To represent
a string of characters, use the data type called String. For
example,
String message = "Welcome to Java";
String is not a primitive type like int, char, or double, but
a reference type like Scanner. You have to create a String
object before using it.
79
Different Ways of Creating Strings
String newString = new String(“This is a String literal”);
Shorthand:
String newString = “This is a String literal”;
String literals are interned, meaning the compiler caches the value and reuses it
Revisiting Variables and Objects
String testString = “This class is boring”;
Because String is not a primitive like int and double, testString is an object of
the class String, just like how Scanner works.
testString is a reference that points to a String object with the value “This
class is boring”
Remember, references are like memory addresses
Strings are immutable:
You cannot change a value of an existing String object. You can reassign the
variable/reference to a new String object, but the original one is still there.
More example in later slide
Null
A null value denotes that the variable points to nothing.
Variables whose data type is a reference type, like String or
Scanner, may exist without having any value:
String s = null;
//null is not the same as empty String
String s =“”;
A variable whose type is a primitive data type will be null if no
value is set, but can't be set to null
int x;
// ok
int x = null; //syntax error
82
Instance Methods for String Objects
Method
Description
length()
charAt(index)
Returns the number of characters in this string.
concat(s1)
toUpperCase()
Returns a new string that concatenates this string with string s1.
toLowerCase()
trim()
Returns a new string with all letters in lowercase.
Returns the character at the specified index from this string.
Returns a new string with all letters in uppercase.
Returns a new string with whitespace characters trimmed on both sides.
8
3
Simple Methods for String Objects
Strings are objects in Java. The methods in the preceding table can only be
invoked from a specific string instance.
For this reason, these methods are called instance methods. A non-instance
method is called a static method. A static method can be invoked without
using an object. All the methods defined in the Math class are static methods.
They are not tied to a specific object instance. The syntax to invoke an
instance method is
referenceVariable.methodName(arguments).
8
4
Getting String Length
String message = "Welcome to Java";
System.out.println("The length of " + message + " is "
+ message.length());
85
Getting Characters from a String
String message = "Welcome to Java";
System.out.println("The first character in message is "
+ message.charAt(0));
86
Converting Strings
"Welcome".toLowerCase() returns a new string,
welcome.
"Welcome".toUpperCase() returns a new string,
WELCOME.
" Welcome ".trim() returns a new string, Welcome.
87
String Concatenation
String s3 = s1.concat(s2); or String s3 = s1 + s2;
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";
// String Chapter is concatenated with number 2
String s = "Chapter" + 2; // s becomes Chapter2
// String Supplement is concatenated with character
B
String s1 = "Supplement" + 'B'; // s1 becomes
SupplementB
88
Reading a String from the Console
Scanner input = new Scanner(System.in);
System.out.print("Enter three words separated by
spaces: ");
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);
89
Comparing Strings
• When comparing two objects, if you use the ==, you are essentially
comparing whether the two variables point to the same object. You are not
actually comparing their actual values.
• To compare objects based on factors other than what they are pointing to,
use compareTo
Method
Description
equals(s1)
Returns true if this string is equal to string s1 .
equalsIgnoreCase(s1)
Returns true if this string is equal to string s1 ; it is case insensitive.
compareTo(s1)
Returns an integer greater than 0 , equal to 0 , or less than 0 to indicate whether
this string is greater than, equal to, or less than s1 .
compareToIgnoreCase(s1) Same as compareTo except that the comparison is case insensitive.
Returns true if this string starts with the specified prefix.
startsWith(prefix)
Returns true if this string ends with the specified suffix.
endsWith(suffix)
90
Obtaining Substrings
Method
Description
substring(beginIndex)
Returns this string’s substring that begins with the character at the specified
beginIndex and extends to the end of the string, as shown in Figure 4.2.
substring(beginIndex,
endIndex)
Returns this string’s substring that begins at the specified beginIndex and
extends to the character at index endIndex – 1, as shown in Figure 9.6.
Note that the character at endIndex is not part of the substring.
91
Finding a Character or a Substring
in a String
Method
Description
indexOf(ch)
Returns the index of the first occurrence of ch in the string. Returns -1 if not
matched.
indexOf(ch, fromIndex)
Returns the index of the first occurrence of ch after fromIndex in the string.
Returns -1 if not matched.
indexOf(s)
Returns the index of the first occurrence of string s in this string. Returns -1 if
not matched.
indexOf(s, fromIndex)
Returns the index of the first occurrence of string s in this string after
fromIndex. Returns -1 if not matched.
lastIndexOf(ch)
Returns the index of the last occurrence of ch in the string. Returns -1 if not
matched.
lastIndexOf(ch,
fromIndex)
lastIndexOf(s)
Returns the index of the last occurrence of ch before fromIndex in this
string. Returns -1 if not matched.
lastIndexOf(s,
fromIndex)
Returns the index of the last occurrence of string s before fromIndex.
Returns -1 if not matched.
Returns the index of the last occurrence of string s. Returns -1 if not matched.
92
Finding a Character or a Substring
in a String
int k = s.indexOf(' ');
String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);
93
Conversion between Strings and
Numbers
int intValue = Integer.parseInt(intString);
double doubleValue = Double.parseDouble(doubleString);
String s = number + "";
94
String Immutability Demonstration
String s = "example text";
s.substring(0, 4);
/*
* still printing "example text", substring
* returns a new string instead of modifying the
* existing one
*/
System.out.println(s);
String a = s.substring(0, 4);
System.out.println(a); // prints "example"
Loops
Control flow statements
While-loops
Do-while loops
For-loops
while Loop Flow Chart
while (loop-continuation-condition) {
// loop-body;
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java!");
Statement(s);
}
count++;
}
97
do-while Loop
• Runs the Loop body at least once
• Useful for asking user input
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
98
for Loops
for (initial-action; loopcontinuation-condition; actionafter-each-iteration) {
// loop body;
Statement(s);
}
int i;
for (i = 0; i < 100; i++) {
System.out.println(
"Welcome to Java!");
}
99
Caution
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic
Error
for (int i=0; i<10; i++);
{
System.out.println("i is " + i);
}
100
Which Loop to Use?
The three forms of loop statements, while, do-while, and for, are
expressively equivalent; that is, you can write a loop in any of these
three forms. For example, a while loop in (a) in the following figure
can always be converted into the following for loop in (b):
while (loop-continuation-condition) {
// Loop body
}
Equivalent
for ( ; loop-continuation-condition; ) {
// Loop body
}
(a)
(b)
A for loop in (a) in the following figure can generally be converted into the
following while loop in (b) except in certain special cases (see Review Question
3.19 for one of them):
for (initial-action;
loop-continuation-condition;
action-after-each-iteration) {
// Loop body;
}
(a)
Equivalent
initial-action;
while (loop-continuation-condition) {
// Loop body;
action-after-each-iteration;
}
(b)
101
Recommendations
Use the one that is most intuitive and comfortable for you.
In general, a for loop may be used if the number of repetitions is known, as,
for example, when you need to print a message 100 times.
A while loop may be used if the number of repetitions is not known, as in the
case of reading the numbers until the input is 0.
A do-while loop can be used to replace a while loop if the loop body has to be
executed before testing the continuation condition.
102
break
public class TestBreak {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
sum += number;
if (sum >= 100)
break;
}
System.out.println("The number is " + number);
System.out.println("The sum is " + sum);
}
}
103
continue
public class TestContinue {
public static void main(String[] args) {
int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 || number == 11)
continue;
sum += number;
}
System.out.println("The sum is " + sum);
}
}
104
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
105
Declaring Array Variables
datatype[] arrayRefVar;
Example:
double[] myList;
datatype arrayRefVar[]; // This style is
allowed, but not preferred
Example:
double myList[];
106
Creating Arrays
arrayRefVar = new datatype[arraySize];
Example:
myList = new double[10];
myList[0] references the first element in the array.
myList[9] references the last element in the array.
107
Declaring and Creating
in One Step
datatype[] arrayRefVar = new
datatype[arraySize];
double[] myList = new double[10];
datatype arrayRefVar[] = new
datatype[arraySize];
double myList[] = new double[10];
108
The Length of an Array
Once an array is created, its size is fixed. It
cannot be changed. You can find its size using
arrayRefVar.length
For example,
myList.length returns 10
109
Default Values
When an array is created, its elements are
assigned the default value of
0 for the numeric primitive data types,
'\u0000' for char types, and
false for boolean types.
110
Indexed Variables
The
array elements are accessed through the
index.
The
array indices are 0-based, i.e., it starts from 0
to arrayRefVar.length-1.
Each
element in the array is represented using the
following syntax, known as an indexed variable:
arrayRefVar[index];
111
Using Indexed Variables
After an array is created, an indexed
variable can be used in the same way as a
regular variable. For example, the
following code adds the value in myList[0]
and myList[1] to myList[2].
myList[2] = myList[0] + myList[1];
112
Array Initializers
Declaring,
creating, initializing in one
step:
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand syntax must be in one
statement.
113
Declaring, creating, initializing
Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;
114
Copying Arrays
Often, in a program, you need to duplicate an array or a part of
an array. In such cases you could attempt to use the assignment
statement (=), as follows:
list2 = list1;
115
Copying Arrays
Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[sourceArray.length];
for (int i = 0; i < sourceArrays.length; i++)
targetArray[i] = sourceArray[i];
116
The arraycopy Utility
arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);
Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);
117
Passing Arrays to Methods
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
Invoke the method
int[] list = {3, 1, 2, 6, 4, 2};
printArray(list);
Invoke the method
printArray(new int[]{3, 1, 2, 6, 4, 2});
Anonymous array
118
Anonymous Array
The statement
printArray(new int[]{3, 1, 2, 6, 4, 2});
creates an array using the following syntax:
new dataType[]{literal0, literal1, ..., literalk};
There is no explicit reference variable for the
array. Such array is called an anonymous
array.
119
Pass By Value
Java uses pass by value to pass arguments to a method.
There are important differences between passing a value
of variables of primitive data types and passing arrays.
For a parameter of a primitive type value, the actual
value is passed. Changing the value of the local
parameter inside the method does not affect the value
of the variable outside the method.
For a parameter of an array type, the value of the
parameter contains a reference to an array; this
reference is passed to the method. Any changes to the
array that occur inside the method body will affect the
original array that was passed as the argument.
120
The Arrays.sort Method
Since sorting is frequently used in programming, Java provides several
overloaded sort methods for sorting an array of int, double, char, short,
long, and float in the java.util.Arrays class. For example, the following
code sorts an array of numbers and an array of characters.
double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};
java.util.Arrays.sort(numbers);
char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};
java.util.Arrays.sort(chars);
Java 8 now provides Arrays.parallelSort(list) that utilizes the multicore
for fast sorting.
121
Command-Line Parameters
class TestMain {
public static void main(String[] args) {
...
}
}
java TestMain arg0 arg1 arg2 ... argn
122
Processing
Command-Line Parameters
In the main method, get the arguments
from args[0], args[1], ..., args[n],
which corresponds to arg0, arg1, ...,
argn in the command line.
123
Declare/Create Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;
// Create array and assign its reference to variable
refVar = new dataType[10][10];
// Combine declaration and creation in one statement
dataType[][] refVar = new dataType[10][10];
// Alternative syntax
dataType refVar[][] = new dataType[10][10];
124
Declaring Variables of Twodimensional Arrays and Creating Twodimensional Arrays
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 1000);
double[][] x;
125
Two-dimensional Array Illustration
matrix.length? 5
array.length? 4
matrix[0].length? 5
array[0].length? 3
126
Declaring, Creating, and Initializing Using
Shorthand Notations
You can also use an array initializer to declare, create
and initialize a two-dimensional array. For example,
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
Same as
int[][] array = new int[4][3];
array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
127
Lengths of Two-dimensional Arrays
int[][] x = new int[3][4];
128
Lengths of Two-dimensional Arrays, cont.
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
array.length
array[0].length
array[1].length
array[2].length
array[3].length
array[4].length
ArrayIndexOutOfBoundsException
129
Multidimensional Arrays
Occasionally, you will need to represent n-dimensional data structures. In Java,
you can create n-dimensional arrays for any integer n.
The way to declare two-dimensional array variables and create two-dimensional
arrays can be generalized to declare n-dimensional array variables and create ndimensional arrays for n >= 3.
130
Multidimensional Arrays
double[][][] scores = {
{{7.5, 20.5}, {9.0, 22.5}, {15, 33.5}, {13, 21.5}, {15, 2.5}},
{{4.5,
{{6.5,
{{6.5,
{{8.5,
{{9.5,
21.5},
30.5},
23.5},
26.5},
20.5},
Which student
{9.0,
{9.4,
{9.4,
{9.4,
{9.4,
22.5},
10.5},
32.5},
52.5},
42.5},
{15,
{11,
{13,
{13,
{13,
34.5},
33.5},
34.5},
36.5},
31.5},
Which exam
scores[ i ] [ j ] [ k ]
{12,
{11,
{11,
{13,
{12,
20.5},
23.5},
20.5},
24.5},
20.5},
{14,
{10,
{16,
{16,
{16,
9.5}},
2.5}},
7.5}},
2.5}},
6.5}}};
Multiple-choice or essay
131