0% found this document useful (0 votes)
21 views88 pages

CHAPTER 1 Java Review

The area for the circle of radius 20 is 1256.636 17

Uploaded by

dawitdabale09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views88 pages

CHAPTER 1 Java Review

The area for the circle of radius 20 is 1256.636 17

Uploaded by

dawitdabale09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 88

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 promises to remain a big part of that
future.
Java is a general purpose programming language.
Java is the Internet programming language.

1
Java, Web, and Beyond
• Java can be used to develop Web applications.
• Java Applets
• Java Web Applications
• Java can also be used to develop applications for
hand-held devices such as Palm and cell phones

2
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
3
JDK Editions
• Java Standard Edition (JSE)
• JSE can be used to develop client-side standalone applications
or applets.
• Java Enterprise Edition (JEE)
• JEE can be used to develop server-side applications such as
Java servlets and Java ServerPages.
• Java Micro Edition (JME).
• JME can be used to develop applications for mobile devices
such as cell phones.
• Popular Java IDE:
NetBeans Open Source by Sun
Eclipse Open Source by IBM
4
A Simple Java Program

//This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

5
Compiling Java Source Code
Java was designed to run object programs on any platform. With Java, you
write the program once, and compile the source program into a special type of
object code, known as bytecode.
The source program must be recompiled, however, because the object
program can only run on a specific machine. Nowadays computers are
networked to work together.
The bytecode can then run on any computer with a Java Virtual Machine, as
shown below. Java Virtual Machine is a software that interprets Java bytecode.
Java Bytecode

Java Virtual
Machine

Any
Computer

6
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 */. They are used for documenting
classes, data, and methods. They can be extracted
into an HTML file using JDK's javadoc command.
7
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, and void. Their
use will be introduced later in the book.

8
Modifiers
Java uses certain reserved words called modifiers
that specify the properties of the data, methods, and
classes and how they can be used.
Examples of modifiers are public and static. Other
modifiers are private, final, abstract, and protected.
A public datum, method, or class can be accessed by
other programs.
A private datum or method cannot be accessed by
other programs.

9
Statements
A statement represents an action or a sequence of actions.
The statement System.out.println("Welcome to Java!") is a
statement to display the greeting "Welcome to Java!" Every
statement in Java ends with a semicolon (;).
Block: A pair of braces in a program forms a block that groups
components of a program.

public class Test {


Class block
public static void main(String[] args) {
System.out.println("Welcome to Java!"); Method block
}
}

10
Classes
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.
The mystery of the class will continue to be unveiled
throughout this course.
For now, though, understand that a program is defined
by using one or more classes.

11
Methods
What is System.out.println?
It is a method: a collection of statements that performs
a sequence of operations to display a message on the
console.
It can be used even without fully understanding the
details of how it works.
It is used by invoking a statement with a string
argument. The string argument is enclosed within
parentheses.
In this case, the argument is "Welcome to Java!" You can
call the same println method with a different argument to
print a different message.
12
Trace a Program Execution
public class ComputeArea { allocate memory
for radius
/** Main method */
public static void main(String[] args) {
radius no value
double radius;
double area;

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
13
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
radius no value
double radius;
area no value
double area;

// Assign a radius
radius = 20; allocate memory
for area
// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
14
Trace a Program Execution
public class ComputeArea { assign 20 to radius
/** Main method */
public static void main(String[] args) {
radius 20
double radius;
double area; area no value

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
15
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
radius 20
double radius;
double area; area 1256.636

// Assign a radius
radius = 20;
compute area and assign
it to variable area
// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
16
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
radius 20
double radius;
double area; area 1256.636

// Assign a radius
radius = 20;

// Compute area print a message to the


area = radius * radius * 3.14159;
console

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
17
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();

18
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.

19
Variables
// Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ + area + " for
radius "+radius);

// Compute the second area


radius = 2.0;
area = radius * radius * 3.14159;
System.out.println("The area is “ + area + " for
radius "+radius);
20
Declaring Variables
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;
Assignment Statements:
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
21
Constants
final datatype CONSTANTNAME = VALUE;

final double PI = 3.14159;


final int SIZE = 3;

22
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 64-bit signed


(i.e., -9223372036854775808
to 9223372036854775807)
float Negative range: 32-bit IEEE 754
-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to
-4.9E-324
Positive range:
4.9E-324 to 1.7976931348623157E+308

23
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

Numeric Operators:
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
5 % 2 yields 1 (the remainder of the division)
24
Remainder Operator
Remainder is very useful in programming. For example, an even
number % 2 is always 0 and an odd number % 2 is always 1.
So you can use this property to determine whether a number is
even or odd.
Suppose today is Saturday and you and your friends are
going to meet in 10 days. What day is in 10 days? You can
find that day is Tuesday using the following expression:

Saturday is the 6th day in a week


A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days

25
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. 26
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;

27
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 1 (the
digit one).

28
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.

29
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.

30
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
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53

31
Shortcut Assignment Operators
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

32
Increment and Decrement Operators
Operator Name Description
++var preincrement The expression (++var) increments var by 1 and evaluates
to the new value in var after the increment.
var++ postincrement The expression (var++) evaluates to the original value
in var and increments var by 1.
--var predecrement The expression (--var) decrements var by 1 and evaluates
to the new value in var after the decrement.
var-- postdecrement The expression (var--) evaluates to the original value
in var and decrements var by 1.

int i = 10; Same effect as


int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as


int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;

33
Numeric Type Conversion
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;

34
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.

35
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

36
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';

char c = 97; // Same as char c = (char)97;

37
Escape Sequences for Special Characters
Description Escape Sequence Unicode
Backspace \b \u0008
Tab \t \u0009
Line feed \n \u000A
Carriage return \r \u000D
Backslash \\ \u005C
Single Quote \' \u0027
Double Quote \" \u0022

38
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 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.

39
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

40
Programming Style and
Documentation
• Appropriate Comments
• Naming Conventions
• Proper Indentation and Spacing
Lines
• Block Styles

41
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, and a


brief description at the beginning of the program.

42
Naming Conventions
• Choose meaningful and descriptive names.
• 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 and area, and the method computeArea.
• 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, the constant PI and MAX_VALUE

43
Proper Indentation and Spacing
• Indentation
• Indent two spaces.

• Spacing
• Use blank line to separate segments of the code.

44
Block Styles
Use end-of-line style for braces.

Next-line public class Test


style {
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}

End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}

45
JOptionPane Input
This book provides two ways of obtaining input.

1. Using the Scanner class (console input)


2. Using JOptionPane input dialogs
String input = JOptionPane.showInputDialog(
"Enter an input");

46
Getting Input from Input Dialog Boxes
String string = JOptionPane.showInputDialog(
null, “Prompting Message”, “Dialog Title”,
JOptionPane.QUESTION_MESSAGE);

47
Two Ways to Invoke the Method
There are several ways to use the showInputDialog method.
For the time being, you only need to know two ways to invoke
it.
One is to use a statement as shown in the example:
String string = JOptionPane.showInputDialog(null, x, y,
JOptionPane.QUESTION_MESSAGE); where x is a string for the
prompting message, and y is a string for the title of the
input dialog box.
The other is to use a statement like this:
JOptionPane.showInputDialog(x); where x is a string for the
prompting message.

48
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 intString is a


numeric string such as “123”.

49
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”.

50
The boolean Type and Operators
Often in a program you need to compare two values,
such as whether i is greater than j. Java provides six
comparison operators (also known as relational
operators) that can be used to compare two values.

The result of the comparison is a Boolean value: true


or false.

boolean b = (1 > 2);

51
Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to

52
One-way if Statements
if (radius >= 0) {
area = radius * radius * PI;
if (boolean-expression) { System.out.println("The area"
statement(s);
}
+ " for the circle of radius "
+ radius + " is " + area);
}
false false
Boolean (radius >= 0)
Expression

true true

Statement(s) area = radius * radius * PI;


System.out.println("The area for the circle of " +
"radius " + radius + " is " + area);

(A) (B)

53
The Two-way if Statement
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

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");
}

54
Multiple Alternative if Statements

if (score >= 90.0) if (score >= 90.0)


grade = 'A'; grade = 'A';
else else if (score >= 80.0)
if (score >= 80.0) Equivalent grade = 'B';
grade = 'B'; else if (score >= 70.0)
else grade = 'C';
if (score >= 70.0) else if (score >= 60.0)
grade = 'C'; grade = 'D';
else else
if (score >= 60.0) grade = 'F';
grade = 'D';
else
grade = 'F';

55
Logical Operators
Operator Name
! not
&& and
|| or
^ exclusive or

56
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression) {
byte, short, or int type and
must always be enclosed case value1: statement(s)1;
in parentheses. break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression.
case valueN: statement(s)N;
The resulting statements in the
case statement are executed when break;
the value in the case statement default: statement(s)-for-default;
matches the value of the switch- }
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.

57
switch Statement Rules
The keyword break is optional, switch (switch-expression) {
but it should be used at the end
of each case in order to terminate case value1: statement(s)1;
the remainder of the switch break;
statement. If the break statement
is not present, the next case case value2: statement(s)2;
statement will be executed. break;

case valueN: statement(s)N;
The default case, which is
break;
optional, can be used to perform default: statement(s)-for-default;
actions when none of the }
specified cases matches the
switch-expression. The case statements are executed in sequential
order, but the order of the cases (including the
default case) does not matter. However, it is good
programming style to follow the logical sequence of
the cases and place the default case at the end.
58
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
59
Conditional Operator
if (num % 2 == 0)
System.out.println(num + “is even”);
else
System.out.println(num + “is odd”);

System.out.println(
(num % 2 == 0)? num + “is even” :
num + “is odd”);

60
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 count is 5 and amount is 45.560000

61
Operator Precedence
1) var++, var--
2) +, - (Unary plus and minus), ++var,--var
3) (type) Casting
4) ! (Not)
5) *, /, % (Multiplication, division, and remainder)
6) +, - (Binary addition and subtraction)
7) <, <=, >, >= (Comparison)
8) ==, !=; (Equality)
9) ^ (Exclusive OR)
10) && (Conditional AND) Short-circuit AND
11) || (Conditional OR) Short-circuit OR
12) =, +=, -=, *=, /=, %= (Assignment operator)

62
(GUI) Confirmation Dialogs
int option = JOptionPane.showConfirmDialog
(null, "Continue");

63
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s); count++;
} }

count = 0;

Loop
false false
Continuation (count < 100)?
Condition?

true true
Statement(s) System.out.println("Welcome to Java!");
(loop body) count++;

(A) (B)

64
do-while Loop
Statement(s)
(loop body)

true Loop
Continuation
do { Condition?
// Loop body;
false
Statement(s);
} while (loop-continuation-condition);

65
for Loops
for (initial-action; loop- int i;
continuation-condition; for (i = 0; i < 100; i++) {
action-after-each-iteration) { System.out.println(
// loop body; "Welcome to Java!");
Statement(s);
} }

Initial-Action i = 0

Loop
false false
Continuation (i < 100)?
Condition?
true true
Statement(s) System.out.println(
(loop body) "Welcome to Java");

Action-After-Each-Iteration i++

(A) (B)
66
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:
Remember: Nested loops, break and continue statements.

for ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }
(a) (b)

67
(GUI) Controlling a Loop with a
Confirmation Dialog
A sentinel-controlled loop can be implemented using a confirmation
dialog. The answers Yes or No to continue or terminate the loop. The
template of the loop may look as follows:

int option = 0;
while (option == JOptionPane.YES_OPTION) {
System.out.println("continue loop");
option = JOptionPane.showConfirmDialog(null, "Continue?");
}

68
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double[] myList = new double[10];

myList reference
myList[0] 5.6
myList[1] 4.5
Array reference myList[2] 3.3
variable
myList[3] 13.2

myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34

myList[7] 45.45

myList[8] 99.993

myList[9] 11123

69
Declaring Array Variables
• datatype[] arrayRefVar;
Example:
double[] myList;

• datatype arrayRefVar[]; // This style is


allowed, but not preferred
Example:
double myList[];

70
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.

71
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];

72
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;

73
Trace Program with Arrays

Declare array variable values, create an


array, and assign its reference to values
public class Test {
public static void main(String[] args) {
int[] values = new int[5];
After the array is created
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1]; 0 0

1 0
}
2 0
values[0] = values[1] + values[4]; 3 0
} 4 0

74
Initializing arrays with input values
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();

75
Printing arrays
for (int i = 0; i < myList.length; i++) {
System.out.print(myList[i] + " ");
}
//determines largest value;
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
76
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];

77
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);

78
Declaring Variables of Two-dimensional
Arrays and Creating Two-dimensional
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);

79
Method

Method signature is the combination of the method name and the


parameter list.
Define a method Invoke a method

return value method formal


modifier type name parameters
int z = max(x, y);
method
public static int max(int num1, int num2) {
header
actual parameters
int result; (arguments)
method
body parameter list
if (num1 > num2)
result = num1;
else
method
result = num2; signature

return result; return value


}

80
Example
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));
}
81
Ambiguous overloading 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;
}
}
82
The Math Class
• Class constants:
• PI
• E
• Class methods:
• Trigonometric Methods
• Exponent Methods
• Rounding Methods
• min, max, abs, and random Methods

83
Trigonometric Methods
• sin(double a) Examples:
• cos(double a)
Math.sin(0) returns 0.0
• tan(double a) Math.sin(Math.PI / 6)
• acos(double a) returns 0.5
Math.sin(Math.PI / 2)
• asin(double a) returns 1.0
• atan(double a) Math.cos(0) returns 1.0
Math.cos(Math.PI / 6)
returns 0.866
Math.cos(Math.PI / 2)
Radians returns 0
toRadians(90)
84
Exponent Methods
• exp(double a) Examples:
Returns e raised to the power of
a. Math.exp(1) returns 2.71
• log(double a) Math.log(2.71) returns 1.0
Returns the natural logarithm of a. Math.pow(2, 3) returns 8.0
• log10(double a) Math.pow(3, 2) returns 9.0
Returns the 10-based logarithm of Math.pow(3.5, 2.5) returns
a. 22.91765
Math.sqrt(4) returns 2.0
• pow(double a, double b)
Math.sqrt(10.5) returns 3.24
Returns a raised to the power of
b.
• sqrt(double a)
Returns the square root of a.

85
Rounding Methods
• double ceil(double x)
x rounded up to its nearest integer. This integer is returned as a
double value.
• double floor(double x)
x is rounded down to its nearest integer. This integer is returned as a
double value.
• double rint(double x)
x is rounded to its nearest integer. If x is equally close to two integers,
the even one is returned as a double.
• int round(float x)
Return (int)Math.floor(x+0.5).
• long round(double x)
Return (long)Math.floor(x+0.5).

86
min, max, and abs
• max(a, b)and min(a, b) Examples:
Returns the maximum or
minimum of two parameters.
Math.max(2, 3) returns 3
• abs(a)
Math.max(2.5, 3) returns 3.0
Returns the absolute value of the
parameter. Math.min(2.5, 3.6) returns 2.5
• random() Math.abs(-2) returns 2
Returns a random double value Math.abs(-2.1) returns 2.1
in the range [0.0, 1.0).

87
The random Method
Generates a random double value greater than or equal to 0.0 and
less than 1.0 (0 <= Math.random() < 1.0).

Examples:

Returns a random integer


(int)(Math.random() * 10)
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.

88

You might also like