COS240lec10a_TutorIntroJAVA.ppt

Download Report

Transcript COS240lec10a_TutorIntroJAVA.ppt

COS240 O-O Languages
AUBG, COS dept
Lecture 10a
Title:
Java as Conventional Prog Lan
(Tutorial Introduction)
Reference: COS240 Syllabus
8/4/2016
Assoc. Prof. Stoyan Bonev
1
Lecture Contents (new):
• Why Java (instead intro)
• Anatomy of a Java program
– Sample source text, the import directive, comments,
– Names – (identifiers, reserved words, modifiers),
– Classes - methods (statements, blocks of statements )
• Components of a Java program
–
–
–
–
–
–
–
Data – by category
Data – by type
Expressions (incl. operands & operators)
Statements
Routines (member functions - methods)
I/O facilities
Data collections – arrays, etc
• Demo programs - examples
8/4/2016
Assoc. Prof. Stoyan Bonev
2
Why Java?
8/4/2016
Assoc. Prof. Stoyan Bonev
3
Why Java?
The answer is that Java enables users to develop and deploy
applications on the Internet for servers, desktop computers, and
small hand-held devices. The future of computing is being
profoundly influenced by the Internet, and Java is the Internet
programming language.
Java
is a general purpose programming language.
Java
is the Internet programming language.
Java
programs may be applications or applets or servlets.
Applications are standalone programs, similar to .NET Console
and Windows applications.
Applets are similar to applications, but they do not run as
standalone programs.
- Instead, applets adhere to a set of conventions that lets
them run within a Java-compatible browser (client-side).
- You can only run an applet from an HTML page.
8/4/2016
Assoc. Prof. Stoyan Bonev
4
Preview to Java Language
• Basic syntax same as C++ (which was then copied by C#!).
• Classes are the building blocks of Java programs
• Pointers exist but in a simplified and hidden form.
– Object references
• Garbage Collection is used
– No need for destructors (but may have!).
– Memory leaks very unlikely .
– Not as many memory management issues (Memory is
still managed, but by the run time system instead of the
programmer.).
• Array index out of bounds causes a runtime error
– Java uses the term Exception for runtime errors
8/4/2016
Assoc. Prof. Stoyan Bonev
5
Anatomy of a Java program:
Sample source text
8/4/2016
Assoc. Prof. Stoyan Bonev
6
Syntax for simple Java program
import package;
public class class_name
{
public static void main(String[] args)
{
implementation of method
}
}
The first method that will be invoked when execution
commences must be called main().
Note the case of main() and String !
- C# has public static void Main(string[] args)
8/4/2016
Assoc. Prof. Stoyan Bonev
7
// Java
public class Hello {
public static void main(String[] args)
{
System.out.println("Hello world in Java");
}
}
// C#
public class Hello {
public static void Main(string[] args) {
System.Console.WriteLine("Hello world in C#");
System.Console.ReadLine();
}
}
8/4/2016
Assoc. Prof. Stoyan Bonev
8
Anatomy of a Java program:
the import directive
8/4/2016
Assoc. Prof. Stoyan Bonev
9
Import statement
A Java program is never entirely self-contained but
instead must execute in the “world” provided by the
Java runtime system.
Use of the import statement:
import java.lang.*;
This statement makes the methods in the library package
java.lang available to the class following it.
java.lang is just one package in the Java library or API.
8/4/2016
Assoc. Prof. Stoyan Bonev
10
Actually, importing java.lang is not required since it is
automatically available to all Java programs.
The package java.lang is important because it
contains the class System which itself contains I/O
methods like the methods below
System.out.print(...);
System.out.println(...);
System.in.read();
A Java package is similar to a C# namespace.
8/4/2016
Assoc. Prof. Stoyan Bonev
11
A Simple Java Program
Listing 1.1
//This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
8/4/2016
Assoc. Prof. Stoyan Bonev
12
Comments
Three types of comments in Java.
Line comment: A line comment is preceded by two
slashes (//) in a line.
Paragraph comment: A paragraph comment is
enclosed between /* and */ in one or multiple lines.
javadoc comment: javadoc comments begin
with /** and end with */. Used for documenting
classes, data, methods. They can be extracted
into HTML file using JDK's javadoc command.
8/4/2016
Assoc. Prof. Stoyan Bonev
13
Appropriate Comments
Include:
a summary at the beginning of the
program to explain what the program does,
its key features,
its supporting data structures, and
any unique techniques it uses.
Include:
your name,class section, instructor, date
8/4/2016
Assoc. Prof. Stoyan Bonev
14
Identifiers
• An identifier is a sequence of characters that
consist of letters, digits, underscores (_), and
dollar signs ($).
• An identifier must start with a letter, an
underscore (_), or a dollar sign ($). It cannot
start with a digit.
• An identifier cannot be a reserved word.
• An identifier cannot be true, false, or
null.
• An identifier can be of any length.
8/4/2016
Assoc. Prof. Stoyan Bonev
15
Naming Conventions
• Choose meaningful and descriptive names.
• Class names:
– Capitalize the first letter of each word in the name. For
example, the class name ComputeArea
• Constants:
– Capitalize all letters in constants, and use underscores to
connect words. For example: PI, MAX_VALUE
• Variables and method names:
– Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first word,
and capitalize the first letter of each subsequent word in
the name. For example, the variables radius, area
8/4/2016
Assoc. Prof. Stoyan Bonev
16
and the method computeArea
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 word class, it understands that the word
after class is the name for the class. Other
reserved words are public, static, void…
8/4/2016
Assoc. Prof. Stoyan Bonev
17
Modifiers
Java uses certain reserved words called
modifiers that specify the properties of the data,
methods, and classes and how they can be used.
Modifiers are public and static. Other modifiers
are private, final, abstract, protected.
A public datum, method, or class can be
accessed by other programs.
A private datum or method cannot be
accessed by other programs.
8/4/2016
Assoc. Prof. Stoyan Bonev
18
Classes
Classes are the building blocks of Java
programs.
The class is the essential Java construct. A
class is a template or blueprint for objects. To
program in Java, you must understand
classes and be able to write and use them.
For now, though, understand that a
program is defined by using one or more
classes.
8/4/2016
Assoc. Prof. Stoyan Bonev
19
Methods
What is System.out.println(“AUBG”)?
It is a method: a collection of statements that
performs a sequence of operations to display a
message on the console.
It is used by invoking a statement with a string
argument. The string argument is enclosed within
parentheses. In this case, the argument is “AUBG“.
You can call the same println method with
a different argument to print a different message.
8/4/2016
Assoc. Prof. Stoyan Bonev
20
main Method
The main method provides the control of program
flow. The Java interpreter executes the application
by invoking the main method.
The main method looks like this:
public static void main(String[] args) {
// Statements;
}
8/4/2016
Assoc. Prof. Stoyan Bonev
21
Statements
A statement represents an action or a sequence of
actions. The statement
System.out.println("Welcome to Java!");
is used to display the greeting "Welcome to Java!“.
Every statement in Java ends with a semicolon (;).
8/4/2016
Assoc. Prof. Stoyan Bonev
22
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!");
}
}
8/4/2016
Assoc. Prof. Stoyan Bonev
Class block
Method block
23
Block Styles
Use end-of-line style for braces.
Next-line
style
public class Test
{
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
8/4/2016
Assoc. Prof. Stoyan Bonev
End-of-line
style
24
Data within Program
• Data classification by category
(Java terminology):
–Literals
–Constants
–Variables
8/4/2016
Assoc. Prof. Stoyan Bonev
25
Declaring Variables
int x;
// Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a;
8/4/2016
// Declare a to be a
// character variable;
Assoc. Prof. Stoyan Bonev
26
Declaring and Initializing
in One Step
int x = 1;
double d = 1.4;
8/4/2016
Assoc. Prof. Stoyan Bonev
27
Constants
• Assigned value cannot be changed
•
– Similar to the const keyword in C/C++
• Variables declared with final
•
– must be initialized in the declaration
•
– can be initialized in a constructor, but must be
assigned a value in every constructor of the class
final datatype CONSTANTNAME = VALUE;
final double PI = 3.14159;
final int SIZE = 3;
8/4/2016
Assoc. Prof. Stoyan Bonev
28
• Data types
– 8 primitive types:
• boolean, byte, short, int, long, float, double, char
– Class types, either provided by Java, or made by
programmers (reference types)
• String, Object, Frame, Person, Animal, …
– Array types (also reference types)
• Variables
– dataType identifier [ = Expression]:
– Example variable declarations and initializations:
int[] intArray;
intArray = new int[2];
intArray[0] = 12;
intArray[1] = 6;
Person pArray = new Person[10];
Assoc. Prof. Stoyan Bonev
29
int x;
x=5;
boolean b = true;
Frame win = new Frame();
String x = “How are you?”;
8/4/2016
Object variables in Java are actually references to
objects, not the objects themselves!
- Object variables store the memory address of an
object of the proper type, not an object of the proper
type.
- Contrast this with primitive variables
8/4/2016
Assoc. Prof. Stoyan Bonev
30
(Non-)Pointers in Java
• All primitive variables are value variables. (Real,
actual).
– it is impossible to have an integer pointer or a
pointer to any variable of one of the primitive data
types
• All object variables are actually reference variables
(pointers, memory addresses) to objects.
– it is impossible to have anything but references to
objects. You can never have a plain object variable
8/4/2016
Assoc. Prof. Stoyan Bonev
31
Remember:
Reference Types
● Everything that is not a primitive type is a reference
type.
– objects, arrays, strings, interfaces, …
● A reference is a pointer, except that we are not allowed
to call it a pointer since Java "doesn't have pointers“!
– OK – it is an address.
– Actually, a pointer with very limited semantics,
there is not anything you can do with a reference except
dereference it.
8/4/2016
Assoc. Prof. Stoyan Bonev
32
Numerical Data Types
Name
Range
Storage Size
byte
–27 (-128) to 27–1 (127)
8-bit signed
short
–215 (-32768) to 215–1 (32767)
16-bit signed
int
–231 (-2147483648) to 231–1 (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
Positive range:
4.9E-324 to 1.7976931348623157E+308
64-bit IEEE 754
8/4/2016
Assoc. Prof. Stoyan Bonev
33
Number Literals
A literal is a constant value that
appears directly in the program. For
example, 34, 1,000,000, and 5.0 are literals
in the following statements:
int i = 34;
long x = 1000000;
double d = 5.0;
8/4/2016
Assoc. Prof. Stoyan Bonev
34
Integer Literals
An integer literal can be assigned to an integer
variable as long as it can fit into the variable. A
compilation error would occur if the literal were too
large for the variable to hold. For example, the
statement byte b = 1000; would cause a compilation
error, because 1000 cannot be stored in a variable of
the byte type.
An integer literal is assumed to be of the int type,
whose value is between -231 (-2147483648) to 231–1
(2147483647). To denote an integer literal of the long
type, append it with the letter L or l. L is preferred
because l (lowercase L) can easily be confused with
Assoc. Prof. Stoyan Bonev
35
1 8/4/2016
(the digit one).
Floating-Point Literals
Floating-point literals are written with a
decimal point. By default, a floating-point literal
is treated as a double type value. For
example, 5.0 is considered a double value, not
a float value. You can make a number a float
by appending the letter f or F, and make a
number a double by appending the letter d or
D. For example, you can use 100.2f or 100.2F
for a float number, and 100.2d or 100.2D for a
double number.
8/4/2016
Assoc. Prof. Stoyan Bonev
36
Scientific Notation
Floating-point literals can also be specified in
scientific notation, for example, 1.23456e+2,
same as 1.23456e2, is equivalent to
123.456, and 1.23456e-2 is equivalent to
0.0123456. E (or e) represents an exponent
and it can be either in lowercase or
uppercase.
8/4/2016
Assoc. Prof. Stoyan Bonev
37
Character Data Type
char letter = 'A'; (ASCII)
char numChar = '4'; (ASCII)
Four hexadecimal
digits.
char letter = '\u0041'; (Unicode)
char numChar = '\u0034'; (Unicode)
NOTE: The increment and decrement operators can also
be used on char variables to get the next or preceding
Unicode character. For example, the following statements
display character b.
char ch = 'a'; System.out.println(++ch);
8/4/2016
Assoc. Prof. Stoyan Bonev
38
Unicode Format
Java characters use Unicode, a 16-bit encoding scheme
established by the Unicode Consortium to support the
interchange, processing, and display of written texts in the
world’s diverse languages. Unicode takes two bytes,
preceded by \u, expressed in four hexadecimal numbers
that run from '\u0000' to '\uFFFF'. So, Unicode can
represent 65535 + 1 characters.
Unicode \u03b1 \u03b2 \u03b3 for three Greek
letters
8/4/2016
Assoc. Prof. Stoyan Bonev
39
Escape Sequences for Special
Characters
Description
Escape Sequence
Unicode
Backspace
\b
\u0008
Tab
\t
\u0009
Linefeed
\n
\u000A
Carriage return \r
\u000D
Backslash
\\
\u005C
Single Quote
\'
\u0027
Double Quote
\"
\u0022
8/4/2016
Assoc. Prof. Stoyan Bonev
40
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';
char c = 97; // Same as char c = (char)97;
8/4/2016
Assoc. Prof. Stoyan Bonev
41
The String Type
The char type only represents one character. To represent a
string of characters, use String data type. For example,
String message = "Welcome to Java";
String is actually a predefined class in the Java library just like
the System class and JOptionPane class. The String type is
not a primitive type. It is known as a reference type. Any Java
class can be used as a reference type for a variable.
For the time being, you just need to know
how to declare a String variable,
how to assign a string to the variable, and
how to concatenate strings.
8/4/2016
Assoc. Prof. Stoyan Bonev
42
String Concatenation
// 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
8/4/2016
Assoc. Prof. Stoyan Bonev
43
Expressions - operands
• Operands
– Literals
– Constants
– Variables – regular(scalar) or indexed
– Method call
– Sub expression like ( … )
8/4/2016
Assoc. Prof. Stoyan Bonev
44
Numeric Operators
Name
Meaning
Example
Result
+
Addition
34 + 1
35
-
Subtraction
34.0 – 0.1
33.9
*
Multiplication
300 * 30
9000
/
Division
1.0 / 2.0
0.5
%
Remainder
20 % 3
2
8/4/2016
Assoc. Prof. Stoyan Bonev
45
Integer Division
+, -, *, /, and %
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
5 % 2 yields 1 (the remainder of the division)
8/4/2016
Assoc. Prof. Stoyan Bonev
46
NOTE
Calculations involving floating-point numbers are
approximated because these numbers are not stored
with complete accuracy. For example,
System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
displays 0.5000000000000001, not 0.5, and
System.out.println(1.0 - 0.9);
displays 0.09999999999999998, not 0.1.
Integers are stored precisely. Therefore, calculations with
integers yield a precise integer result.
8/4/2016
Assoc. Prof. Stoyan Bonev
47
How to Evaluate an Expression
Though Java has its own way to evaluate an
expression behind the scene, the result of a Java
expression and its corresponding arithmetic
expression are the same. Therefore, you can safely
apply the arithmetic rule for evaluating a Java
expression.
3 + 4 * 4 + 5 * (4 + 3) - 1
3 + 4 * 4 + 5 * 7 – 1
3 + 16 + 5 * 7 – 1
(1) inside parentheses first
(2) multiplication
(3) multiplication
3 + 16 + 35 – 1
19 + 35 – 1
54 - 1
8/4/2016
Assoc. Prof. Stoyan Bonev
53
(4) addition
(5) addition
(6) subtraction
48
Shortcut Assignment
Operators
8/4/2016
Operator Example
Equivalent
+=
i += 8
i = i + 8
-=
f -= 8.0
f = f - 8.0
*=
i *= 8
i = i * 8
/=
i /= 8
i = i / 8
%=
i %= 8
i = i % 8
Assoc. Prof. Stoyan Bonev
49
Increment and
Decrement Operators
Operator
++var
Name
preincrement
var++
postincrement
--var
predecrement
var--
postdecrement
8/4/2016
Description
The expression (++var) increments var by 1 and
evaluates to the new value in var after the
increment.
The expression (var++) evaluates to the original
value in var and increments var by 1.
The expression (--var) decrements var by 1 and
evaluates to the new value in var after the
decrement.
The expression (var--) evaluates to the original
value in var and decrements var by 1.
Assoc. Prof. Stoyan Bonev
50
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;
8/4/2016
Assoc. Prof. Stoyan Bonev
51
Conversion Rules
When performing a binary operation involving
two operands of different types, Java
automatically converts the operand based on the
following rules:
1.
If one of the operands is double, the other is
converted into double.
2. Otherwise, if one of the operands is float, the
other is converted into float.
3. Otherwise, if one of the operands is long, the
other is converted into long.
4. Otherwise, both operands are converted into int.
8/4/2016
Assoc. Prof. Stoyan Bonev
52
Type Casting
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)
What is wrong? int x = 5 / 2.0;
range increases
byte, short, int, long, float, double
8/4/2016
Assoc. Prof. Stoyan Bonev
53
The boolean Type and Operators
Java provides six comparison operators (also
known as relational operators) The result of the
comparison is a Boolean value: true or false.
<
<=
>
>=
==
!=
boolean b = (1 > 2);
8/4/2016
Assoc. Prof. Stoyan Bonev
54
Logical Operators
Operator Name
!
not
&&
and
||
or
^
exclusive or
8/4/2016
Assoc. Prof. Stoyan Bonev
55
Conditional Operator
if (x > 0)
y=1
else
y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
(boolean-expression) ? expression1 : expression2
Ternary operator, Binary operator, Unary operator
8/4/2016
Assoc. Prof. Stoyan Bonev
56
Operator Precedence
•
•
•
•
•
•
•
•
•
•
•
•
var++, var-+, - (Unary plus and minus), ++var,--var
(type) Casting
! (Not)
*, /, % (Multiplication, division, and remainder)
+, - (Binary addition and subtraction)
<, <=, >, >= (Comparison)
==, !=; (Equality)
^ (Exclusive OR)
&& (Conditional AND) Short-circuit AND
|| (Conditional OR) Short-circuit OR
=, +=, -=, *=, /=, %= (Assignment operator)
8/4/2016
Assoc. Prof. Stoyan Bonev
57
Operator Precedence and Associativity
The expression in the parentheses is evaluated first.
(Parentheses can be nested, in which case the
expression in the inner parentheses is executed
first.) When evaluating an expression without
parentheses, the operators are applied according to
the precedence rule and the associativity rule.
If operators with the same precedence are next to
each other, their associativity determines the order
of evaluation. All binary operators except
assignment operators are left-associative.
8/4/2016
Assoc. Prof. Stoyan Bonev
58
Operator Associativity
When two operators with the same
precedence are evaluated, the associativity of
the operators determines the order of
evaluation. All binary operators except
assignment operators are left-associative.
a – b + c – d is equivalent to ((a – b) + c) – d
Assignment operators are right-associative.
Therefore, the expression
a = b += c = 5 is equivalent to a = (b += (c = 5))
8/4/2016
Assoc. Prof. Stoyan Bonev
59
Executable statements
•
•
•
•
Assignment statements
Decision/Selection statements
Iteration/Repetition statements
Input/Output
8/4/2016
Assoc. Prof. Stoyan Bonev
60
Assignment Statements
x = 1;
// Assign 1 to x;
radius = 1.0;
// Assign 1.0 to radius;
a = 'A';
// Assign 'A' to a;
8/4/2016
Assoc. Prof. Stoyan Bonev
61
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--;
8/4/2016
Assoc. Prof. Stoyan Bonev
62
Flow of control
if, if-else, if-else if
switch
for, while, do-while
break
continue
8/4/2016
Assoc. Prof. Stoyan Bonev
63
If-else
/**
* return the difference of x and y
*/
public static int abs(int x, int y){
if (x < y)
return y - x;
else if(x > y)
return x - y;
else
return 0;
}
8/4/2016
Assoc. Prof. Stoyan Bonev
64
One-way if Statements
if (boolean-expression) {
statement(s);
}
Boolean
Expression
false
false
(radius >= 0)
true
true
Statement(s)
8/4/2016
if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The
area"
+ " for the circle of radius "
+ radius + " is " + area);
}
(A)
area = radius * radius * PI;
System.out.println("The area for the circle of " +
"radius " + radius + " is " + area);
Assoc. Prof. Stoyan Bonev
(B)
65
Note
if i > 0 {
System.out.println("i is positive");
}
if (i > 0) {
System.out.println("i is positive");
}
(a) Wrong
(b) Correct
if (i > 0) {
System.out.println("i is positive");
}
Equivalent
if (i > 0)
System.out.println("i is positive");
(b)
(a)
8/4/2016
Assoc. Prof. Stoyan Bonev
66
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
true
Statement(s) for the true case
Boolean
Expression
false
Statement(s) for the false case
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
8/4/2016
Assoc. Prof. Stoyan Bonev
12
67
if...else Example
if (radius >= 0) {
area = radius * radius * 3.14159;
System.out.println("The area for the “
+ “circle of radius " + radius +
" is " + area);
}
else {
System.out.println("Negative input");
}
8/4/2016
Assoc. Prof. Stoyan Bonev
68
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);
}
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.
8/4/2016
Assoc. Prof. Stoyan Bonev
69
TIP
if (number % 2 == 0)
even = true;
else
even = false;
Equivalent
boolean even
= number % 2 == 0;
(b)
(a)
8/4/2016
Assoc. Prof. Stoyan Bonev
70
CAUTION
if (even == true)
System.out.println(
"It is even.");
Equivalent
if (even)
System.out.println(
"It is even.");
(b)
(a)
8/4/2016
Assoc. Prof. Stoyan Bonev
71
switch Statement Flow Chart
status is 0
Compute tax for single filers
break
Compute tax for married file jointly
break
Compute tax for married file separatly
break
Compute tax for head of household
break
status is 1
status is 2
status is 3
default
Default actions
Next Statement
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
8/4/2016
Assoc. Prof. Stoyan Bonev
44
72
Switch-case
switch ( N ) {
// (Assume N is an integer variable.)
case 1:
System.out.println("The number is 1.");
break;
case 2:
case 4:
case 8:
System.out.println("The number is 2, 4, or 8.");
System.out.println("(That's a power of 2!)");
break;
case 3:
case 6:
case 9:
System.out.println("The number is 3, 6, or 9.");
System.out.println("(That's a multiple of 3!)");
break;
case 5:
System.out.println("The number is 5.");
break;
default:
System.out.println("The number is 7 or is outside range 1 to 9.");
}
8/4/2016
Assoc. Prof. Stoyan Bonev
73
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(0);
}
8/4/2016
Assoc. Prof. Stoyan Bonev
74
Introducing while Loops
int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
8/4/2016
Assoc. Prof. Stoyan Bonev
75
do-while Loop
Statement(s)
(loop body)
true
do {
Loop
Continuation
Condition?
// Loop body;
false
Statement(s);
} while (loop-continuation-condition);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
8/4/2016
Assoc. Prof. Stoyan Bonev
1
76
for Loops
for (initial-action; loopcontinuation-condition;
action-after-each-iteration) {
// loop body;
Statement(s);
}
Initial-Action
Loop
Continuation
Condition?
int i;
for (i = 0; i < 100; i++) {
System.out.println(
"Welcome to Java!");
}
i=0
false
(i < 100)?
true
Statement(s)
(loop body)
true
System.out.println(
"Welcome to Java");
Action-After-Each-Iteration
i++
(A)
(B)
false
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
8/4/2016
Assoc. Prof. Stoyan Bonev
21
77
For-loop
For (int i=1, j=10; i < j; i++, j-=2)
System.out.println("i="+i+" j="+j);
i=1 j=10
i=2 j=8
i=3 j=6
for (int i = 0; i < 4; i++){
for( char letter = 'A'; letter <= 'A' + i; letter++)
System.out.print(letter);
System.out.println();
}
A
AB
ABC
ABCD
8/4/2016
Assoc. Prof. Stoyan Bonev
78
Note
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-eachiteration in a for loop can be a list of zero or more commaseparated statements. Therefore, the following two for
loops are correct. They are rarely used in practice,
however.
for (int i = 1; i < 100; System.out.println(i++));
for (int i = 0, j = 0; (i + j < 10); i++, j++) {
// Do something
}
8/4/2016
Assoc. Prof. Stoyan Bonev
79
Note
If the loop-continuation-condition in a for loop is omitted,
it is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct. Nevertheless, it is
better to use the equivalent loop in (b) to avoid confusion:
for ( ; ; ) {
// Do something
}
Equivalent
while (true) {
// Do something
}
(a)
8/4/2016
(b)
Assoc. Prof. Stoyan Bonev
80
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);
}
8/4/2016
Assoc. Prof. Stoyan Bonev
81
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
Logic Error
while (i < 10);
{
System.out.println("i is " + i);
i++;
}
In the case of the do loop, the following semicolon
is needed to end the loop.
int i=0;
do {
System.out.println("i is " + i);
i++;
Correct
} while (i<10);
8/4/2016
Assoc. Prof. Stoyan Bonev
82
The break statement
• Inside any loop, the break statement will immediately
get you out of the loop
– If you are in nested loops, break gets you out of the
innermost loop
• It doesn’t make any sense to break out of a loop
unconditionally - you should do it only as the result of
an if test
Example:
for (int i = 1; i <= 12; i++) {
if (badEgg(i)) break;
}
• break is not the normal way to leave a loop
8/4/2016
Assoc. Prof.but
Stoyandon’t
Bonev overuse it
– Use it when necessary,
83
The continue statement
• Inside any loop, the continue statement will start the
next pass through the loop
– In a while or do-while loop, the continue
statement will bring you to the test
– In a for loop, the continue statement will bring you
to the increment, then to the test
8/4/2016
Assoc. Prof. Stoyan Bonev
84
Solution
public static int sum(int i1, int i2) {
int sum = 0;
for (int i = i1; i <= i2; i++)
sum += i;
return sum;
}
public static void main(String[] args) {
System.out.println("Sum from 1 to 10 is " + sum(1, 10));
System.out.println("Sum from 20 to 30 is " + sum(20, 30));
System.out.println("Sum from 35 to 45 is " + sum(35, 45));
}
8/4/2016
Assoc. Prof. Stoyan Bonev
85
The general syntax for a method
modifers return_type method_name(parameters)
{
data declarations
sequence of statements
}
E.g.
public static void main(String[] args)
8/4/2016
Assoc. Prof. Stoyan Bonev
86
Methods – Declaration
•
Method declaration: two parts
1. Method header
•
•
consists of modifiers (optional), return type, method
name, parameter list and a throws clause (optional)
types of modifiers
–
–
visibility modifiers, e.g. public, private
abstract
»
–
static
»
»
»
–
8/4/2016
represent the whole class, not a specific object
may be invoked without creating an instance
can only access static fields and other static methods of the
same class
final
»
2.
the method body is empty. E.g.
abstract void sampleMethod( );
cannot be overridden in subclasses
Method body
Assoc. Prof. Stoyan Bonev
87
Methods – Parameter Values
• Primitive data type parameters are passed by value,
not by reference (i.e. by address).
public void method1 (int a) {
a = 6;
}
public void method2 ( ) {
int b = 3;
method1(b);
// now b = ?
// b = 3 still
}
• When the parameter is a reference type, it is the
reference, not the object itself, that is passed.
8/4/2016
Assoc. Prof. Stoyan Bonev
88
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
8/4/2016
Assoc. Prof. Stoyan Bonev
89
Method Signature
Method signature is the combination of the method name and the
parameter list.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
8/4/2016
Assoc. Prof. Stoyan Bonev
90
Formal Parameters
The variables defined in the method header are known as
formal parameters.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
8/4/2016
Assoc. Prof. Stoyan Bonev
91
Actual Parameters
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
8/4/2016
Assoc. Prof. Stoyan Bonev
92
Return Value Type
A method may return a value. The returnValueType is the data type
of the value the method returns. If the method does not return a
value, the returnValueType is the keyword void. For example, the
returnValueType in the main method is void.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
8/4/2016
Assoc. Prof. Stoyan Bonev
93
Calling Methods, cont.
pass the value of i
pass the value of j
8/4/2016
Assoc. Prof. Stoyan Bonev
94
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Suppose you invoke the method using
nPrintln(“Welcome to Java”, 5);
What is the output?
Suppose you invoke the method using
nPrintln(“Computer Science”, 15);
What is the output?
8/4/2016
Assoc. Prof. Stoyan Bonev
95
Pass by Value
.
8/4/2016
Assoc. Prof. Stoyan Bonev
96
Ambiguous Invocation
Sometimes there may be two or more
possible matches for an invocation of
a method, but the compiler cannot
determine the most specific match.
This is referred to as ambiguous
invocation. Ambiguous invocation is a
compilation error.
8/4/2016
Assoc. Prof. Stoyan Bonev
97
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
System.out.println(max(1, 2));
}
public static double max(int num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2) {
if (num1 > num2)
return num1;
else
return num2;
}
}
8/4/2016
Assoc. Prof. Stoyan Bonev
98
Scope of Local Variables
A local variable: a variable defined inside
a method.
Scope: the part of the program where the
variable can be referenced.
The scope of a local variable starts from
its declaration and continues to the end
of the block that contains the variable.
A local variable must be declared
before it can be used.
8/4/2016
Assoc. Prof. Stoyan Bonev
99
Scope of Local Variables, cont.
You can declare a local variable with the
same name multiple times in different
non-nesting blocks in a method, but you
cannot declare a local variable twice in
nested blocks.
8/4/2016
Assoc. Prof. Stoyan Bonev
100
Scope of Local Variables
A variable declared in the initial action part of a for
loop header has its scope in the entire loop. But a
variable declared inside a for loop body has its scope
limited in the loop body from its declaration and to the
end of the block that contains the variable.
The scope of i
The scope of j
8/4/2016
public static void method1() {
.
.
for (int i = 1; i < 10; i++) {
.
.
int j;
.
.
.
}
}
Assoc. Prof. Stoyan Bonev
101
Scope of Local Variables, cont.
It is fine to declare i in two
non-nesting blocks
public static void method1() {
int x = 1;
int y = 1;
It is wrong to declare i in
two nesting blocks
public static void method2() {
int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
x += i;
}
for (int i = 1; i < 10; i++) {
y += i;
}
for (int i = 1; i < 10; i++) {
sum += i;
}
}
}
8/4/2016
Assoc. Prof. Stoyan Bonev
102
JOptionPane Input
Two ways of obtaining input.
1. Using the Scanner class (console input)
needs
import java.util.Scanner;
2. Using JOptionPane input dialogs needs
import javax.swing.JOptionPane;
8/4/2016
Assoc. Prof. Stoyan Bonev
103
Reading Input from the Console
1. Create a Scanner object
Scanner input = new Scanner(System.in);
2. Use the methods next(), nextByte(), nextShort(),
nextInt(), nextLong(), nextFloat(), nextDouble(), or
nextBoolean() to obtain to a string, byte, short, int, long,
float, double, or boolean value. For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
8/4/2016
Assoc. Prof. Stoyan Bonev
104
public class CalculatingArea {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("This program calculates " +
"the area of a rectangle or a triangle");
System.out.print("Enter a and b (for rectangle) " +
"or a and h (for triangle): ");
int a = input.nextInt();
int b = input.nextInt();
System.out.print("Enter 1 for a rectangle or " +
"2 for a triangle: ");
int choice = input.nextInt();
double area = (double) (a * b) / choice;
System.out.println("The area of your figure is " + area);
}
}
8/4/2016
Assoc. Prof. Stoyan Bonev
105
Getting Input from Input Dialog
Boxes
String input = JOptionPane.showInputDialog(
"Enter an input");
8/4/2016
Assoc. Prof. Stoyan Bonev
106
Getting Input from Input Dialog
Boxes
String string = JOptionPane.showInputDialog(
null, “Prompting Message”, “Dialog Title”,
JOptionPane.QUESTION_MESSAGE);
8/4/2016
Assoc. Prof. Stoyan Bonev
107
Converting Strings to Integers
The input returned from the input dialog box is a
string. If you enter a numeric value such as 123, it
returns “123”. To obtain the input as a number, you
have to convert a string into a number.
To convert a string into an int value, you can use the
static parseInt method in the Integer class
as follows:
int intValue = Integer.parseInt(intString);
where
intStringAssoc.
is Prof.
a numeric
string as “123”.108
8/4/2016
Stoyan Bonev
Converting Strings to Doubles
To convert a string into a double value, you can use
the static parseDouble method in the Double class as
follows:
double doubleValue=Double.parseDouble(doubleString);
where doubleString is a numeric string such as
“123.45”.
8/4/2016
Assoc. Prof. Stoyan Bonev
109
Displaying Text in a Message Dialog Box
you can use the showMessageDialog
method in the JOptionPane class.
JOptionPane.showMessageDialog(null,
"Welcome to Java!",
"Display Message",
JOptionPane.INFORMATION_MESSAGE);
8/4/2016
Assoc. Prof. Stoyan Bonev
110
Two Ways to Invoke the
Method
There are several ways to use the showMessageDialog
method. For the time being, all you need to know are two
ways to invoke it.
One is to use a statement as shown in the example:
JOptionPane.showMessageDialog(null, x,
y, JOptionPane.INFORMATION_MESSAGE);
where x is a string for the text to be displayed, and y is a
string for the title of the message dialog box.
The other is to use a statement like this:
JOptionPane.showMessageDialog(null, x);
where x is a string for the text to be displayed.
8/4/2016
Assoc. Prof. Stoyan Bonev
111
(GUI) Confirmation Dialogs
int option = JOptionPane.showConfirmDialog
(null, "Continue");
8/4/2016
Assoc. Prof. Stoyan Bonev
112
String concatenation causes
converting all values to string
int age = 26; // int, no String
String text = "He is " + age + " years old.";
System.out.println(text);
String s = "Two: " + 1 + 1;
System.out.println(s); // Two: 11
String s = "Two: " + (1 + 1);
System.out.println(s); // Two: 2
8/4/2016
Assoc. Prof. Stoyan Bonev
113
Formatting Output
Use the printf statement.
System.out.printf(format, items);
Where format is a string that may consist of substrings and
format specifiers. A format specifier specifies how an item
should be displayed. An item may be a numeric value,
character, boolean value, or a string. Each specifier begins
with a percent sign.
8/4/2016
Assoc. Prof. Stoyan Bonev
114
Frequently-Used Specifiers
Specifier Output
Example
%b
a boolean value
true or false
%c
a character
'a'
%d
a decimal integer
200
%f
a floating-point number
45.460000
%e
a number in standard scientific notation
4.556000e+01
%s
a string
"Java is cool"
int count = 5;
items
double amount = 45.56;
System.out.printf("count is %d and amount is %f", count, amount);
display
8/4/2016
count is 5 and amount is 45.560000
Assoc. Prof. Stoyan Bonev
115
Thank You
for
Your attention!
Data Collections
• Arrays
• Records (C-like structs) – not
supported in Java
8/4/2016
Assoc. Prof. Stoyan Bonev
117
Arrays
Array: collection of group of data variables of same
type, sharing the same name for convenience
- Easy to search and manipulate
- Elements in an array are always numbered 0
through N-1, where N is the total number of elements,
called the size or length of array
- Position of an element in an array is called the
element index or subscript
- Array of values are arranged in consecutive
memory locations
8/4/2016
Assoc. Prof. Stoyan Bonev
118
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double[] myList = new double[10];
myList
reference
Array reference
variable
Array element at
index 5
8/4/2016
myList[0]
5.6
myList[1]
4.5
myList[2]
3.3
myList[3]
13.2
myList[4]
4
myList[5]
34.33
myList[6]
34
myList[7]
45.45
myList[8]
99.993
myList[9]
11123
Element value
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Assoc. Prof. Stoyan Bonev
5
119
Declaring Array Ref Variables
• datatype[] arrayRefVar;
Example:
double[] myList;
• datatype arrayRefVar[];
• // This style is allowed, but not preferred
Example:
double myList[];
8/4/2016
Assoc. Prof. Stoyan Bonev
120
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.
8/4/2016
Assoc. Prof. Stoyan Bonev
121
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];
8/4/2016
Assoc. Prof. Stoyan Bonev
122
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
8/4/2016
Assoc. Prof. Stoyan Bonev
123
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.
8/4/2016
Assoc. Prof. Stoyan Bonev
124
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. In the example
above, myList holds ten double values and
the indices are from 0 to 9.
Each element in the array is represented
using the following syntax, known as an
indexed variable:
arrayRefVar[index];
8/4/2016
Assoc. Prof. Stoyan Bonev
125
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];
8/4/2016
Assoc. Prof. Stoyan Bonev
126
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.
8/4/2016
Assoc. Prof. Stoyan Bonev
127
Declaring, creating, initializing
Using the Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
The above 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;
8/4/2016
Assoc. Prof. Stoyan Bonev
128
Enhanced for Loop (for-each loop)
JDK 1.5 introduced a new for loop that enables you to traverse the
complete array sequentially without using an index variable. For
example, the following code displays all elements in the array
myList:
for (double value: myList)
System.out.println(value);
In general, the syntax is
for (elementType value: arrayRefVar) {
// Process the value
}
Attention: You still have to use an index variable if you wish to
traverse the array in a different order or change the elements in the
8/4/2016array.
Assoc. Prof. Stoyan Bonev
129
Declaring and creating arrays
Similar to C#
• Example for array objects:
int[] myArray;
// declaration
• This declares myArray to be an array reference
variable
• It does not create an array — it only provides a place
to put a reference of an array, i.e. address of an array.
• Notice that the size is not part of the type
myArray = new int[10]; // creation
• The new int[10] creates the array of size 10
• Write as
int[] myArray = new int[10];
8/4/2016
Assoc. Prof. Stoyan Bonev
// combined
130
An array’s size is not part of its type
• When you declare an array, you declare its type; you
must not specify its size
– Example:
String[] names;
– or
String names[];//not recommended
• When you create the array, you allocate space; you
must specify its size
– Example: names = new String[50];
• This is true even when the two are combined.
Example:
String[] names = new String[50];
8/4/2016
Assoc. Prof. Stoyan Bonev
131
Arrays of objects
• Suppose you declare and create an array of objects:
– Person[] people = new Person[20];
• You have created an array named people, but you
have not yet given values to each element in that
array
• There is nothing wrong with this array, but
– it has 20 references to Persons in it
– all of these references are initially null
– you have not yet defined 20 Persons
– For example, people[12].name will give you a
nullPointerException if you do not define the
8/4/2016
Assoc. Prof. Stoyan Bonev
132
Persons.
Here’s one way to initialize an array of objects:
Person[] people = new Person[20];
for (int i = 0; i < people.length; i++)
{
people[i] = new Person(“John");
}
This approach has a slight drawback: all the array
elements have similar values!
Remember: index of array elements starts at 0 and
ends at (length – 1)
8/4/2016
Assoc. Prof. Stoyan Bonev
133
Resizing an array
The following is legal:
int[] myArray = new int[10];
...and later in the program,
myArray = new int[500];
// legal!
This is legal because the array’s size is not part of
its type, but part of its value
8/4/2016
Assoc. Prof. Stoyan Bonev
134
Length of an array
• Arrays are objects.
• Every array has an instance constant, length, that
tells how large the array is
• Example:
for (int i = 0; i < scores.length; i++)
System.out.println(scores[i]);
• Use of length is always preferred over using a
literal constant such as 10
• Arrays have a length variable,
• Strings have a length() method
8/4/2016
Assoc. Prof. Stoyan Bonev
135
• There is a special syntax for giving initial values to
the elements of arrays
– This syntax can be used in place of new
type[size]
– It can only be used in an array declaration
– The syntax is:
}
{ value, value, ..., value
• Examples:
int[] primes = {2,3,5,7,11,13,19};
String[] languages = { "Java","C","C++" };
8/4/2016
Assoc. Prof. Stoyan Bonev
136
Initializing arrays
• To initialize an array of Person:
Person[] people =
{ new Person(“Elena"),
new Person(“Ivan"),
new Person(“Katya"),
new Person(“Dimitar") };
• Notice that you do not specify the size of the array
8/4/2016
Assoc. Prof. Stoyan Bonev
137
Arrays - Recap
• Declare an array ref variable:
– int[] counts;
– String[] names;
– int[][] matrix; //this is an array of arrays
• Create an array and assign its reference to array ref
variable:
– counts = new int[5];
– names = new String[100];
– matrix = new int[5][10];
• Use:
– String months[] = {"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "July", "Aug", "Sep", "Oct",
"Nov", "Dec"};
8/4/2016
– for(int i = 0; i < months.length; i++)
System.out.println("month: " + months[i]);
Assoc. Prof. Stoyan Bonev
138
Array assignment
• Array assignment is object assignment:
• Object assignment does not copy values
Person p1; Person p2;
p1 = new Person(“Ivan");
p2 = p1;
// p1 and p2 refer to same person (“point to”)
• Array assignment does not copy values
int[] a1; int[] a2;
a1 = new int[10];
a2 = a1; // a1 and a2 refer to the same array
8/4/2016
Assoc. Prof. Stoyan Bonev
139
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;
Before the assignment
list2 = list1;
list1
After the assignment
list2 = list1;
Contents
of list1
list2
list1
list2
Contents
of list2
Garbage
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
8/4/2016
Contents
of list1
Assoc. Prof. Stoyan Bonev
Contents
of list2
45
140
Copying Arrays
Using a loop:
int[] srcArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[srcArray.length];
for (int i = 0; i < srcArrays.length; i++)
targetArray[i] = srcArray[i];
8/4/2016
Assoc. Prof. Stoyan Bonev
141
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
8/4/2016
Assoc. Prof. Stoyan Bonev
142
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.
8/4/2016
Assoc. Prof. Stoyan Bonev
143
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.
8/4/2016
Assoc. Prof. Stoyan Bonev
144
Simple Example
public class Test {
public static void main(String[] args) {
int x = 1; // x represents an int value
int[] y = new int[10]; // y is an array of int values
m(x, y); // Invoke m with arguments x and y
System.out.println("x is " + x);
System.out.println("y[0] is " + y[0]);
} // end of main
public static void m(int number, int[] numbers) {
number = 1001; // Assign a new value to number
numbers[0] = 5555; //Assign new value to numbers[0]
} // end of m
} // end of class Test
8/4/2016
Assoc. Prof. Stoyan Bonev
145
Returning an Array from a Method
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1;
i < list.length; i++, j--) {
result[j] = list[i];
}
list
return result;
}
result
int[] list1 = new int[]{1, 2, 3, 4, 5, 6};
int[] list2 = reverse(list1);
8/4/2016
Assoc. Prof. Stoyan Bonev
146
Arrays of arrays
Arrays of arrays
Or
Multi – Dimensional arrays
8/4/2016
Assoc. Prof. Stoyan Bonev
147
Arrays of arrays = Multidimensional arrays
• One-dimensional arrays are used to store
linear collections of elements, i.e. vector.
• Two-dimensional arrays are used to store a
matrix or a table.
• A two-dimensional array is one-dimensional
array in which each element is another onedimensional array. (look fwd after 7 slides)
• A multidimensional array is an array in which
each element is another array
8/4/2016
Assoc. Prof. Stoyan Bonev
148
Arrays of arrays = Multidimensional arrays
• A three-dimensional array consists of an array
of two-dimensional arrays, each of which is an
array of one-dimensional arrays.
int[][][] x = new int[2][2][5];
• x[0] and x[1] are two-dimensional arrays.
• x[0][0], x[0][1], x[1][0], x[1][1]
are one-dimensional arrays and each contains
5 elements
• x.length is 2
• x[0].length and x[1].length are 2
• x[0][0].length, x[0][1].length,
x[1][0].length,
x[1][1].length
are
5
8/4/2016
Assoc. Prof. Stoyan Bonev
149
Arrays of arrays
• The elements of an array can be arrays.
• Declaration: int[][] table;
• Definition: table = new int[10][15];
• Combined:
int[][] table = new int[10][15];
• The first index (10) is called the row index;
• The second index (15) is the column index
8/4/2016
Assoc. Prof. Stoyan Bonev
150
Example array of arrays
• int[][] table = new int[3][2];
or,
• int[][] table = { {1, 2}, {3, 6}, {7, 8} };
An array of three rows and two columns
• For example, table[1][1] contains 6
• table[2][1] contains 8, and
0
0 1
1 • table[1][2] is “array out of bounds”
2
1 3 6 • To “zero out this table”:
2 7 8
for (int i = 0; i < 3; i++)
for (int j = 0; j < 2; j++)
table[i][j] = 0;
8/4/2016
Assoc. Prof. Stoyan Bonev
151
Declaring Variables of 2-D Arrays and
Creating 2-D Arrays
// Declare array ref var
dataType[][] refVar;
// Create array & assign its reference to variable
refVar = new dataType[10][10];
// Combine declaration and creation in one stmt
dataType[][] refVar = new dataType[10][10];
// Alternative syntax, not recommended
dataType refVar[][] = new dataType[10][10];
8/4/2016
Assoc. Prof. Stoyan Bonev
152
Declaring Variables of 2-D Arrays
and Creating 2-D Arrays
// declare array ref var, create 2D array and assign its reference to array ref
var
// all three above activities in one step - statement
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);
// matrix.length – numr of rows or matrix capacity
// matrix[i].length – capacity of row nmr i
8/4/2016
Assoc. Prof. Stoyan Bonev
153
Two-dimensional Array Illustration
0 1
2
3
4
0 1
2
3
4
0
0
0
0
1
1
1
2
2
2
3
3
4
4
matrix = new int[5][5];
7
matrix[2][1] = 7;
3
1
2
2
3
4
5
6
7
8
9
10
11
12
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
matrix.length? 5
array.length? 4
matrix[0].length? 5
array[0].length? 3
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
8/4/2016
1
Assoc. Prof. Stoyan Bonev
6
154
Lengths of Two-dimensional
Arrays
int[][] x = new int[3][4];
x
x[0][0] x[0][1] x[0][2] x[0][3]
x[0].length is 4
x[1][0] x[1][1] x[1][2] x[1][3]
x[1].length is 4
x[2][0] x[2][1] x[2][2] x[2][3]
x[2].length is 4
x[0]
x[1]
x[2]
x.length is 3
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
8/4/2016
Assoc. Prof. Stoyan Bonev
8
155
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}
};
8/4/2016
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;
Assoc. Prof. Stoyan Bonev
156
Lengths of Two-dimensional
Arrays, cont.
int[][] array = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};
array.length
4
array[0].length
array[1].length
array[2].length
array[3].length
3
3
3
3
array[4].length
ArrayIndexOutOfBoundsException
8/4/2016
Assoc. Prof. Stoyan Bonev
157
Ragged Arrays
Each row in a two-dimensional array is itself an
array. So, the rows can have different lengths.
Such an array is known as a ragged array.
For example,
int[][] matrix = {
{1, 2, 3, 4, 5}, matrix.length is 5
matrix[0].length is 5
{2, 3, 4, 5},
matrix[1].length is 4
{3, 4, 5},
matrix[2].length is 3
{4, 5},
matrix[3].length is 2
matrix[4].length is 1
{5}
};
8/4/2016
Assoc. Prof. Stoyan Bonev
158
Associative Arrays
import java.util.Hashtable;
…
// associative array - special case – hashtable
Hashtable<String, String> ht = new
Hashtable<String, String>();
ht.put("Sofia", "BG");
ht.put("Berlin", "DE");
System.out.print(" " + ht.get("Sofia"));
8/4/2016
Assoc. Prof. Stoyan Bonev
159
Initializing arrays with input
values
java.util.Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and "
+
matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length;
column++) {
matrix[row][column] = input.nextInt();
}
}
8/4/2016
Assoc. Prof. Stoyan Bonev
160
Initializing arrays with random
values
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length;
column++) {
matrix[row][column] = (int)(Math.random() * 100);
}
}
8/4/2016
Assoc. Prof. Stoyan Bonev
161
Printing arrays
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length;
column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
8/4/2016
Assoc. Prof. Stoyan Bonev
162
Summing all elements
int total = 0;
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length;
column++) {
total += matrix[row][column];
}
}
8/4/2016
Assoc. Prof. Stoyan Bonev
163
Summing elements by column
for (int column = 0; column < matrix[0].length;
column++) {
int total = 0;
for (int row = 0; row < matrix.length; row++)
total += matrix[row][column];
System.out.println("Sum for column " + column + " is "
+ total);
}
8/4/2016
Assoc. Prof. Stoyan Bonev
164
Multidimensional Arrays
Occasionally, you will need to represent ndimensional 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 n-dimensional arrays for n
>= 3. For example, the following syntax declares
a three-dimensional array variable scores,
creates an array, and assigns its reference to
scores.
double[][][] scores = new double[10][5][2];
8/4/2016
Assoc. Prof. Stoyan Bonev
165
The ArrayList and Vector Classes
You can create an array to store objects. But the array’s size
is fixed once the array is created. Java provides the ArrayList
class that can be used to store an unlimited number of
objects.
java.util.ArrayList
+ArrayList()
Creates an empty list.
+add(o: Object) : void
Appends a new element o at the end of this list.
+add(index: int, o: Object) : void
Adds a new element o at the specified index in this list.
+clear(): void
Removes all the elements from this list.
+contains(o: Object): boolean
Returns true if this list contains the element o.
+get(index: int) : Object
Returns the element from this list at the specified index.
+indexOf(o: Object) : int
Returns the index of the first matching element in this list.
+isEmpty(): boolean
Returns true if this list contains no elements.
+lastIndexOf(o: Object) : int
Returns the index of the last matching element in this list.
+remove(o: Object): boolean
Removes the element o from this list.
+size(): int
Returns the number of elements in this list.
+remove(index: int) : Object
Removes the element at the specified index.
+set(index: int, o: Object) : ObjectAssoc.
SetsProf.
the element
at the specified index.
8/4/2016
Stoyan Bonev
166
Example
// Package Declaration
import java.lang.*; // not required
// Program start class
public class HelloWorld
{
// Main begins program execution
public static void main(string[] args)
{
// This is a single line comment
/* This is a
multiple
line comment */
System.out.println("Hello World!");
}
}
167
Example
public class HelloWorldApp {
public static void main(String[] args) {
// Display "Hello World!"
System.out.println("Hello World!");
}
}
168
Example
import java.io.*;
public class Testclass
{
public static void main( String args[] )
{
int count = 0;
while ( count < 10 )
{
System.out.println("counter is " + count );
count++;
}
}
}
169
Example
public class HelloWorld {
public static void main(String[] args) {
String name = "Java";
// See if an argument was passed from command line
if (args.length == 1)
name = args[0];
System.out.println("Hello, " + name + "!");
}
}
170
import java.util.*;
public class test11 {
public static void main(String[] args) {
System.out.println("Hello, it’s: ");
System.out.println(new Date());
}
}
171
Demo Programs
Demonstrate end-of-file controlled loop using
standard input from the keyboard and
standard output to the screen
Solution to implement in a version:
as console application
Problem:
To accumulate sum of stream of input integers
terminated by end-of-data (CTRL/Z) indicator
172
Demo Program – Source Code
// Java demo program, standard Input (keyboard) / Output (screen)
// Class Scanner (Import java.util.Scanner;)
// Methods next(), nextInt(), nextFloat(), nextDouble(), nextLine(), hasNext()
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int sum=0, arg;
Scanner cin = new Scanner(System.in);
while (cin.hasNext())
{
sum += cin.nextInt();
}
System.out.println("Final sum = " + sum);
}
}
173
Thank You
for
Your attention!