0% found this document useful (0 votes)
9 views

c01 JSE Intro Synthax OOP MultiParadigm VMGit

Uploaded by

catanoiuandrei22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

c01 JSE Intro Synthax OOP MultiParadigm VMGit

Uploaded by

catanoiuandrei22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 149

Lecture 1

Java SE – Programming

presentation
Java Programming – Software App Development
Assoc. Prof. Cristian Toma Ph.D.

D.I.C.E/D.E.I.C – Department of Economic Informatics & Cybernetics


www.dice.ase.ro
[email protected] – Business Card
Agenda for Lecture 1 – Summary of JSE

1 2 3
JVM and Java
Fundamentals
Intro
Java OOP
analogy with
C++
Multi-paradigm
programming
intro & Git
sources from
Linux VM
1
JVM – Java Virtual Machine, Java SE – loops, methods, array

JVM & Java SE Fundamentals Intro


1.1 Java Virtual Machine Summary
Compilers & Interpreters Questions:

What is a virtual machine? How many types of JVM do you know?

What is the difference of stack based vs. registered based JVM and what are
features of JIT compiler?

Should have a virtual machine associated one or more state machines?


What are advantages and disadvantages of virtual machines – native compilers vs.
interpreters?

Hello World sample program in Oracle VM Box – MacOS, Linux, Windows and
RaspberryPi

Command line compiling with JDK 9.0 | 8.0 – all lectures samples are command line
based – and Eclipse OXYGEN projects in Linux Ubuntu 16 LTS. The sources are
full in Git and alternatively is a Docker image for the lectures in the command line.
Linux Ubuntu 16 VM download:
http://acs.ase.ro/java ~ 15 GB HDD, 2 CPU cores, 4 GB RAM / use Oracle VM
Box File->Import OVA file - All seminars will be in /home/stud/javase/labs directory
and the lectures are in /home/stud/javase/lectures : user=stud / pass=stud
1.1 Java Object Oriented Programming Summary

You had graduated from lectures of Java Fundamentals – let’s talk:

What is a class?

What is a package of classes in Java?

What is an object / instance?

How many bytes has an object inside JVM?

Why do we need clone, equals and hash methods?

Demo & memory model for the Certificate Java class


1.1 Java Overview Summary

http://support.novell.com/techcenter/articles/ana19970701.html

http://www.media-art-online.org/java/help/how-it-works.html
1.1 Java Virtual Machine Summary

http://en.wikipedia.org/wiki/Java_virtual_machine http://www.research.ibm.com/compsci/project_spotlight/plans oft/index.html


1.1 Java Creating, Compiling, and Running Programs
Create/Modify Source Code

Source code (developed by the programmer)


Saved on the disk
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!"); Source Code
}
} DEMO
Compile in command
Compile Source Code prompt HelloWorld +
Byte code (generated by the compiler for JVM i.e., javac Welcome.java show in GHex Ubuntu
to read and interpret, not for you to understand)
source and byte-code
… files in hex + Show
Method Welcome() If compilation errors
0 aload_0 stored on the disk
Project in Eclipse
… + copy byte-code on
Raspberry Pi and run
Bytecode
Method void main(java.lang.String[]) =>
0 getstatic #2 …
3 ldc #3 <String "Welcome to
Java!">
Write Once
5 invokevirtual #4 … Run Anywhere
8 return Run Byteode
i.e., java Welcome

Result
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson
Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/01slide.ppt If runtime errors or incorrect result
1.1 Java Trace a Program Execution

Enter main method

//This program prints Welcome to Java!


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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/01slide.ppt
1.1 Java Trace a Program Execution

Execute statement

//This program prints Welcome to Java!


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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/01slide.ppt
1.1 Java Trace a Program Execution

//This program prints Welcome to Java!


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

print a message to the


console

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/01slide.ppt
JSE – Java Standard Edition
1.1 Java SE JDK and JRE
JDK = JRE + Development / Compiling /
Debugging tools

JRE = JVM + Java Packages Classes(like util,


math, lang, awt etc) + Runtime libraries.

JVM = Class loader system + Runtime data area +


Execution Engine.
1.1 Java Development Kit 7/8 Diagram
1.1 Java Development Process

Examples of the JDKs Java SE implementations:


1. Free SDK and Commercial Support – Oracle OTN:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
2. Community Free SDK and Open Source – OpenJDK:
http://openjdk.java.net/
JDK Enhancement Proposals – JEP for Java Community: http://openjdk.java.net/jeps/0
1.2 Java Selections – Boolean Operators, if-else, switch statements

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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Comparison Operators
Operator Name
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal to
!= not equal to
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

if (radius >= 0) {
One-way if Statements area = radius * radius * PI;
System.out.println("The area"
if (boolean-expression) { + " for the circle of radius "
statement(s); + 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)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Note

if i > 0 { if (i > 0) {
System .out.pr intln( " i is po sitive "); Sys tem.out .printl n( "i is positi ve");
} }
(a) W ron g (b) C orre ct

i f (i > 0) { if (i > 0)
System .out.pr intln(" i is po sitive" ); Equ ivalent Syste m.out. println ("i is positiv e");
}

(a) (b)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

The Two-way if Statement


if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}

true false
Boolean
Expression

Statement(s) for the true case Statement(s) for the false case

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

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");
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace if-else statement


Suppose score is 70.0 The condition is false

if (score >= 90.0)


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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace if-else statement


Suppose score is 70.0 The condition is false

if (score >= 90.0)


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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace if-else statement


Suppose score is 70.0 The condition is true

if (score >= 90.0)


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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace if-else statement


Suppose score is 70.0 grade is C

if (score >= 90.0)


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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace if-else statement


Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Note
The else clause matches the most recent if clause in the
same block.
int i = 1; int i = 1;
int j = 2; int j = 2;
int k = 3; int k = 3;
Equivalent
if (i > j) if (i > j)
if (i > k) if (i > k)
System.out.println("A"); System.out.println("A");
else else
System.out.println("B"); System.out.println("B");
(a) (b)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Note, cont.
Nothing is printed from the preceding statement. To
force the else clause to match the first if clause, you
must add a pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j) {
if (i > k)
System.out.println("A");
}
else
System.out.println("B");
This statement prints B.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Common Errors
Adding a semicolon at the end of an if clause is a common
mistake.
Wrong
if (radius >= 0);
{
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

TIP
if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)

CAUTION
Equivalent if (even)
if (even == true)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Problem: Computing Taxes


The US federal personal income tax is calculated based on
the filing status and taxable income. There are four filing
statuses: single filers, married filing jointly, married filing
separately, and head of household. The tax rates for 2009
(2014?) are shown below.
Marginal Married Filing Jointly or
Single Married Filing Separately Head of Household
Tax Rate Qualified Widow(er)

10% $0 – $8,350 $0 – $16,700 $0 – $8,350 $0 – $11,950

15% $8,351– $33,950 $16,701 – $67,900 $8,351 – $33,950 $11,951 – $45,500

25% $33,951 – $82,250 $67,901 – $137,050 $33,951 – $68,525 $45,501 – $117,450

28% $82,251 – $171,550 $137,051 – $208,850 $68,525 – $104,425 $117,451 – $190,200

33% $171,551 – $372,950 $208,851 – $372,950 $104,426 – $186,475 $190,201 - $372,950

35% $372,951+ $372,951+ $186,476+ $372,951+

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements
if (status == 0) { // Compute tax for single filers
import java.util.Scanner; if (income <= 8350)
tax = income * 0.10;
else if (income <= 33950)
public class ComputeTax {
tax = 8350 * 0.10 + (income - 8350) * 0.15;
public static void main(String[] else if (income <= 82250)
args) { tax = 8350 * 0.10 + (33950 - 8350) * 0.15 +
// Create a Scanner (income - 33950) * 0.25;
Scanner input = new else if (income <= 171550)
Scanner(System.in); tax = 8350 * 0.10 + (33950 - 8350) * 0.15 +
// Prompt the user to enter filing (82250 - 33950) * 0.25 + (income - 82250) * 0.28;
status else if (income <= 372950)
tax = 8350 * 0.10 + (33950 - 8350) * 0.15 +
System.out.print( (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 +
"(0-single filer, 1-married (income - 171550) * 0.35;
jointly,\n" + else
"2-married separately, 3-head of tax = 8350 * 0.10 + (33950 - 8350) * 0.15 +
household)\n" + (82250 - 33950) * 0.25 + (171550 - 82250) * 0.28 +
"Enter the filing status: "); (372950 - 171550) * 0.33 + (income - 372950) * 0.35;
}
int status = input.nextInt();
else if (status == 1) { // Compute tax for married file jointly
// Prompt the user to enter // Left as exercise
taxable income }
System.out.print("Enter the else if (status == 2) { // Compute tax for married separately
taxable income: "); // Left as exercise
double income = }
input.nextDouble(); else if (status == 3) { // Compute tax for head of household
// Compute tax // Left as exercise
}
double tax = 0; else {
System.out.println("Error: invalid status");
System.exit(0);
}

// Display the result


System.out.println("Tax is " + (int)(tax * 100) / 100.0);
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

ASSIGNMENT 01 - Problem: Computing Taxes, cont.


if (status == 0) {
// Compute tax for single filers
}
else if (status == 1) {
// Compute tax for married file jointly
}
else if (status == 2) {
// Compute tax for married file separately
}
else if (status == 3) {
// Compute tax for head of household
}
else {
// Display wrong status
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Logical Operators

Operator Name
! not
&& and
|| or
^ exclusive or

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Truth Table for Operator !


p !p Example (assume age = 24, gender = 'M')

true false !(age > 18) is false, because (age > 18) is true.
false true !(gender != 'F') is true, because (grade != 'F') is false.

p !p Example
true false !(1 > 2) is true, because (1 > 2) is false.
false true !(1 > 0) is false, because (1 > 0) is true.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Truth Table for Operator &&


p1 p2 p1 && p2 Example (assume age = 24, gender = 'F')

false false false (age > 18) && (gender == 'F') is true, because (age
false true false > 18) and (gender == 'F') are both true.

true false false (age > 18) && (gender != 'F') is false, because
(gender != 'F') is false.
true true true

p1 p2 p1 && p2 Example
false false false (3 > 2) && (5 >= 5) is true, because (3 >
false true false 2) and (5 >= 5) are both true.

true false false (3 > 2) && (5 > 5) is false, because (5 >


true true true 5) is false.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Truth Table for Operator ||


p1 p2 p1 || p2 Example (assume age = 24, gender = 'F')

false false false (age > 34) || (gender == 'F') is true, because (gender
false true true == 'F') is true.

true false true (age > 34) || (gender == 'M') is false, because (age >
true true true 34) and (gender == 'M') are both false.

p1 p2 p1 || p2 Example
false false false (2 > 3) || (5 > 5) is false, because (2 > 3)
false true true and (5 > 5) are both false.

true false true (3 > 2) || (5 > 5) is true, because (3 > 2)


true true true is true.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Truth Table for Operator ^


p1 p2 p1 ^ p2 Example (assume age = 24, gender = 'F')

false false false (age > 34) ^ (gender == 'F') is true, because (age
false true true > 34) is false but (gender == 'F') is true.

true false true (age > 34) || (gender == 'M') is false, because (age
> 34) and (gender == 'M') are both false.
true true false

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Examples
System.out.println("Is " + number + " divisible by 2 and 3? " +
((number % 2 == 0) && (number % 3 == 0)));

System.out.println("Is " + number + " divisible by 2 or 3? " +


((number % 2 == 0) || (number % 3 == 0)));

System.out.println("Is " + number +


" divisible by 2 or 3, but not both? " +
((number % 2 == 0) ^ (number % 3 == 0)));
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

The & and | Operators


If x is 1, what is x after this expression?
(x > 1) & (x++ < 10)

If x is 1, what is x after this expression?


(1 > x) && ( 1 > x++)

How about (1 == x) | (10 > x++)?


(1 == x) || (10 > x++)?

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

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);
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

switch Statement Flow Chart


status is 0
Compute tax for single filers break

status is 1
Compute tax for married file jointly break

status is 2
Compute tax for married file separatly break

status is 3
Compute tax for head of household break

default
Default actions

Next Statement

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

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 in case value1: statement(s)1;
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.
The resulting statements in the case valueN: statement(s)N;
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

switch Statement Rules


The keyword break is optional, switch (switch-expression) {
but it should be used at the end
case value1: statement(s)1;
of each case in order to terminate
the remainder of the switch break;
statement. If the break statement case value2: statement(s)2;
is not present, the next case
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace switch statement


Suppose ch is 'a':

switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace switch statement

ch is 'a':

switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace switch statement

Execute this line

switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace switch statement

Execute this line

switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace switch statement

Execute this line

switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace switch statement

Execute next statement

switch (ch) {
case 'a': System.out.println(ch);
case 'b': System.out.println(ch);
case 'c': System.out.println(ch);
}

Next statement;

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace switch statement


Suppose ch is 'a':

switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace switch statement


ch is 'a':

switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace switch statement


Execute this line

switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace switch statement


Execute this line

switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Trace switch statement


Execute next statement

switch (ch) {
case 'a': System.out.println(ch);
break;
case 'b': System.out.println(ch);
break;
case 'c': System.out.println(ch);
}

Next statement;

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Conditional Operator
(boolean-expression) ? exp1 : exp2
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”);

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

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.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements
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“
%02x a hex value 2F

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


Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

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)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

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))
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.2 Java Selections – Boolean Operators, if-else, switch statements

Example
Applying the operator precedence and associativity rule, the
expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows:

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) subtraction
19 > 34
(6) greater than
false
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/03slide.ppt
1.3 Java Loops – for, while, … statements

Problem: System.out.println("Welcome to Java!");


System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100 …
times …

System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
Solution: System.out.println("Welcome to Java!");

int count = 0;
while (count < 100) {
System.out.println("Welcome to Java");
count++;
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

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++;
} }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace while Loop


Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace while Loop, cont.


(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace while Loop, cont.


Print Welcome to Java

int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace while Loop, cont.


Increase count by 1
count is 1 now
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace while Loop, cont.


(count < 2) is still true since count
is 1
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace while Loop, cont.


Print Welcome to Java

int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace while Loop, cont.


Increase count by 1
count is 2 now
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace while Loop, cont.


(count < 2) is false since count is 2
now
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace while Loop


The loop exits. Execute the next
statement after the loop.

int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Caution
Don’t use floating-point values for equality checking in a loop control. Since
floating-point values are approximations for some values, using them could result in
imprecise counter values and inaccurate results. Consider the following code for
computing 1 + 0.9 + 0.8 + ... + 0.1:

double item = 1; double sum = 0;


while (item != 0) { // No guarantee item will be 0
sum += item;
item -= 0.1;
}
System.out.println(sum);

Variable item starts with 1 and is reduced by 0.1 every time the loop body is
executed. The loop should terminate when item becomes 0. However, there is no
guarantee that item will be exactly 0, because the floating-point arithmetic is
approximated. This loop seems OK on the surface, but it is actually an infinite loop.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

do-while Loop

Statement(s)
(loop body)

true Loop
Continuation
Condition?
do {
// 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:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

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 true true


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

false Action-After-Each-Iteration false


i++

for Loops
(A) (B)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace for Loop


Declare i
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace for Loop, cont.


Execute initializer
int i; i is now 0
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace for Loop, cont.


(i < 2) is true
int i; since i is 0
for (i = 0; i < 2; i++) {
System.out.println( "Welcome to Java!");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace for Loop, cont.


Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace for Loop, cont.


(i < 2) is still true
int i; since i is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace for Loop, cont.


Print Welcome to Java 2nd time
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace for Loop, cont.


Execute adjustment statement
int i; i now is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace for Loop, cont.


(i < 2) is false
int i; since i is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Trace for Loop, cont.


Exit the loop. Execute the next
int i; statement after the loop
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Note
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-each-
iteration in a for loop can be a list of zero or more comma-
separated 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
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

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 ( ; ; ) { Equivalent while (true) {


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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

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);
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

Similarly, the following loop is also wrong:


int i=0;
while (i < 10); Logic Error Caution, cont.
{
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);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

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) { Equivalent for ( ; loop-continuation-condition; )


// Loop body // 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:

for (initial-action; initial-action;


loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.3 Java Loops – for, while, … statements

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.
ASSIGNMENT 02 - Problem: Write a program that uses nested for
loops to print a multiplication table – nested loops.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807:
http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/04slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Problem
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Problem
int sum = 0;
for (int i = 1; i <= 10; i++)
sum += i;
System.out.println("Sum from 1 to 10 is " + sum);

sum = 0;
for (int i = 20; i <= 30; i++)
sum += i;
System.out.println("Sum from 20 to 30 is " + sum);

sum = 0;
for (int i = 35; i <= 45; i++)
sum += i;
System.out.println("Sum from 35 to 45 is " + sum);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

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));
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
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


}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Calling Methods
pass the value of i
pass the value of j

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Method Invocation


i is now 5

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Method Invocation


j is now 2

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Method Invocation


invoke max(i, j)

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Method Invocation


invoke max(i, j)
Pass the value of i to num1
Pass the value of j to num2

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Method Invocation


declare variable result

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Method Invocation


(num1 > num2) is true since num1
is 5 and num2 is 2

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Method Invocation


result is now 5

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Method Invocation


return result, which is 5

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Method Invocation


return max(i, j) and assign the
return value to k

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Method Invocation


Execute the print statement

public static void main(String[] args) { public static int max(int num1, int num2) {
int i = 5; int result;
int j = 2;
int k = max(i, j); if (num1 > num2)
result = num1;
System.out.println( else
"The maximum between " + i + result = num2;
" and " + j + " is " + k);
} return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

CAUTION
A return statement is required for a value-returning method. The method
shown below in (a) is logically correct, but it has a compilation error because
the Java compiler thinks it possible that this method does not return any value.

public static int sign(int n) { public static int sign(int n) {


if (n > 0) Should be if (n > 0)
return 1; return 1;
else if (n == 0) else if (n == 0)
return 0; return 0;
else if (n < 0) else
return –1; return –1;
} }
(a) (b)

To fix this problem, delete if (n < 0) in (a), so that the compiler will
see a return statement to be reached regardless of how the if
statement is evaluated.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Call Stacks

Space required for Space required for


the max method the max method
result: 5
num2: 2 num2: 2
num1: 5 num1: 5

Space required for Space required for Space required for Space required for
the main method the main method the main method the main method
k: k: k: k: 5 Stack is empty
j: 2 j: 2 j: 2 j: 2
i: 5 i: 5 i: 5 i: 5

(a) The main (b) The max (c) The max method (d) The max method is (e) The main
method is invoked. method is invoked. is being executed. finished and the return method is finished.
value is sent to k.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Call Stack


i is declared and initialized

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);

System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}

public static int max(int num1, int num2) {


int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;

return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Call Stack


j is declared and initialized

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);

System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
}

public static int max(int num1, int num2) { j: 2


int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;

return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Call Stack


Declare k

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);

System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
} Space required for the
main method
k:
public static int max(int num1, int num2) { j: 2
int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;

return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Call Stack


Invoke max(i, j)

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);

System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
} Space required for the
main method
k:
public static int max(int num1, int num2) { j: 2
int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;

return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Call Stack


pass the values of i and j to num1
and num2

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);

System.out.println(
"The maximum between " + i +
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) { main method
int result;
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;

return result; The max method is


} invoked.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Call Stack


pass the values of i and j to num1
and num2

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);

System.out.println(
"The maximum between " + i + result:
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) { main method
int result;
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;

return result; The max method is


} invoked.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Call Stack


(num1 > num2) is true

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);

System.out.println(
"The maximum between " + i + result:
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) { main method
int result;
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;

return result; The max method is


} invoked.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Call Stack


Assign num1 to result

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
Space required for the
System.out.println( max method
"The maximum between " + i + result: 5
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) { main method
int result;
k:
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;

return result; The max method is


} invoked.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Call Stack


Return result and assign it to k

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);
Space required for the
System.out.println( max method
"The maximum between " + i + result: 5
" and " + j + " is " + k); num2: 2
} num1: 5
Space required for the
public static int max(int num1, int num2) { main method
int result;
k:5
if (num1 > num2) j: 2
result = num1; i: 5
else
result = num2;

return result; The max method is


} invoked.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trace Call Stack


Execute print statement

public static void main(String[] args) {


int i = 5;
int j = 2;
int k = max(i, j);

System.out.println(
"The maximum between " + i +
" and " + j + " is " + k);
} Space required for the
main method
k:5
public static int max(int num1, int num2) { j: 2
int result; i: 5

if (num1 > num2)


result = num1; The main method
else is invoked.
result = num2;

return result;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

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?
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Passing parameters by value

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Call Stacks – Passing parameters by value

The values of num1 and num2 are


passed to n1 and n2. Executing swap
does not affect num1 and num2.

Space required for the


swap method
temp:
n2: 2
n1: 1
Space required for the Space required for the Space required for the
main method main method main method Stack is empty
num2: 2 num2: 2 num2: 2
num1: 1 num1: 1 num1: 1

The main method The swap method The swap method The main method
is invoked is invoked is finished is finished

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters
Overloading methods - 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;
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Method Abstraction
A programmer can think of the method body as a black box that contains the
detailed implementation for the method.
Optional arguments Optional return
for Input value

Method Header
Black Box
Method body

Benefits of using methods:


§ Write a method once and reuse it anywhere.
§ Information hiding. Hide the implementation from the user.
§ Reduce complexity.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

The Math Class


Case study:
§ Class constants:
• PI
• E
§ Class methods:
• Trigonometric Methods
• Exponent Methods
• Rounding Methods
• min, max, abs, and random Methods
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

Trigonometric Methods
• sin(double a) Examples:

• cos(double a) Math.sin(0) returns 0.0


Math.sin(Math.PI / 6) returns 0.5
• tan(double a)
Math.sin(Math.PI / 2) returns 1.0
• acos(double a) Math.cos(0) returns 1.0
Math.cos(Math.PI / 6) returns
• asin(double a) 0.866
Math.cos(Math.PI / 2) returns 0
• atan(double a)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

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
Math.pow(3, 2) returns 9.0
• log10(double a)
Math.pow(3.5, 2.5) returns
Returns the 10-based logarithm of 22.91765
a.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
1.4 Java Methods – defining, signature, formal / actual parameters

min, max, and abs


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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807: http://akyokus.com/courses/Fall2011/ise204/Lectures/Liang8e/05slide.ppt
Section Conclusion
Fact: Java is natural
In few samples it is simple to remember:
selections, loops, methods – it is like in
C/C++ syntax.
2
Java OOP

Java OOP & JSE


2. Summary of Java SE - OOP
Analogy with C++ and it will be reloaded in next lecture (C02)

What is a class?

What is a package of classes in Java?

What is an object / instance?

How many bytes has an object inside JVM?

Why do we need clone, equals and hash methods?

Demo & memory model for the Certificate Java class


2. Summary of Java SE - OOP
Polymorphism – “the ability to have multiple forms” is obtaining through:
§ The overriding (not overloading; overloading is a form of polymorphism) of
the methods from a Java class
§ “Pure” form of polymorphism has to have the following conditions:
§ Inheritance mechanism – “extends is the key word”
§ Virtual Methods – “in Java by default”
§ Overriding the virtual methods
§ Using the pointer / references to the objects – “in Java by default”

Interface – “contract between objects of the class that implements the interface and
another objects of another classes that interact with objects from the
implementation class” – has the following features:
§ static fields
§ Static and non-static methods prototypes – declaration but NOT
implementation
§ The implementation class use the “implements” keyword
§ It is possible to have interface as type – declare objects with type interface
but you must call the constructor methods from a real Java class
2. Summary of Java SE - OOP

Abstract Class – “a class that have at least one method abstract” – has
the following features:
§ At least one abstract method – keyword “abstract”
§ May contain standard static and non-static fully implemented methods
§ You may declare objects from an abstract class but you can NOT
instantiate them, you should use constructor method from a real Java
class

Pay attention @: Objects vs. vectors / arrays of objects + null pointer


exception

DEMO

Compile in command prompt & Eclipse – Shallow Copy vs. Deep Copy Example.
Section Conclusions
Object Oriented Programming in Java – class,
object, object’s deep vs. shallow copy, interface,
interface as type, abstract class, inheritance,
polymorphism.

Class is used to encapsulate attributes (fields |


features | characteristics) and methods
(behavior | ‘interface’) in order to produce
instances / objects.

Object is a instance of a class with certain values


Object Oriented Programming for attributes and with same methods class for
for easy Java sharing all the generated instances.

In OOP there are two major relationships: “has a”


(composition) and “is a” (inheritance)
3
Share knowledge, Empowering Minds

Multi-paradigm Programming Intro


3.1 Multi-paradigm programming
Some paradigms are concerned mainly with implications for the execution model of the language, such as
allowing side effects, or whether the sequence of operations is defined by the execution model. Other
paradigms are concerned mainly with the way that code is organized, such as grouping a code into units
along with the state that is modified by the code. Yet others are concerned mainly with the style of syntax
and grammar.
Common programming paradigms include:
imperative which allows side effects,
functional which disallows side effects,
declarative which does not state the order in which operations execute,
object-oriented which groups code together with the state the code modifies,
procedural which groups code into functions,
logic which has a particular style of execution model coupled to a particular style of syntax and grammar,
and
symbolic programming which has a particular style of syntax and grammar.[1][2][3]
For example, languages that fall into the imperative paradigm have two main features: they state the order
in which operations occur, with constructs that explicitly control that order, and they allow side effects, in
which state can be modified at one point in time, within one unit of code, and then later read at a different
point in time inside a different unit of code. The communication between the units of code is not explicit.
Meanwhile, in object-oriented programming, code is organized into objects that contain state that is only
modified by the code that is part of the object. Most object-oriented languages are also imperative
languages. In contrast, languages that fit the declarative paradigm do not state the order in which to
execute operations. Instead, they supply a number of operations that are available in the system, along with
the conditions under which each is allowed to execute.
Copyright: https://en.m.wikipedia.org/wiki/Programming_paradigm
3.1 Multi-paradigm programming
Just as software engineering (as a process) is defined by differing methodologies, so the programming languages (as models
of computation) are defined by differing paradigms. Some languages are designed to support one paradigm
(Smalltalk supports object-oriented programming, Haskell supports functional programming), while other programming
languages support multiple paradigms (such as Object Pascal, C++, Java, C#, Scala, Visual Basic, Common
Lisp, Scheme, Perl, PHP, Python, Ruby, Oz, and F#). For example, programs written in C++, Object Pascal or PHP can be
purely procedural, purely object-oriented, or can contain elements of both or other paradigms. Software designers and
programmers decide how to use those paradigm elements.
In object-oriented programming, programs are treated as a set of interacting objects. In functional programming, programs
are treated as a sequence of stateless function evaluations. When programming computers or systems with many
processors, in process-oriented programming, programs are treated as sets of concurrent processes acting on logically
shared data structures.
Many programming paradigms are as well known for the techniques they forbid as for those they enable. For instance, pure
functional programming disallows use of side-effects, while structured programming disallows use of the goto statement.
Partly for this reason, new paradigms are often regarded as doctrinaire or overly rigid by those accustomed to earlier
styles. [5] Yet, avoiding certain techniques can make it easier to understand program behavior, and to prove theorems about
program correctness.
Programming paradigms can also be compared with programming models which allow invoking an execution model by
using only an API. Programming models can also be classified into paradigms, based on features of the execution model.
For parallel computing, using a programming model instead of a language is common. The reason is that details of the
parallel hardware leak into the abstractions used to program the hardware. This causes the programmer to have to map
patterns in the algorithm onto patterns in the execution model (which have been inserted due to leakage of hardware into
the abstraction). As a consequence, no one parallel programming language maps well to all computation problems. It is thus
more convenient to use a base sequential language and insert API calls to parallel execution models, via a programming
model. Such parallel programming models can be classified according to abstractions that reflect the hardware, such as
shared memory, distributed memory with message passing, notions of place visible in the code, and so forth. These can be
considered flavors of programming paradigm that apply to only parallel languages and programming models.
Copyright: https://en.m.wikipedia.org/wiki/Programming_paradigm
3.1 Multi-paradigm programming
A concise reference for the programming paradigms listed here – copyright Wiki:
•Concurrent programming – have language constructs for concurrency, these may involve multi-threading,
support for distributed computing, message passing, shared resources (including shared memory), or futures
• Actor programming – concurrent computation with actors that make local decisions in response to
the environment (capable of selfish or competitive behavior)
•Constraint programming – relations between variables are expressed as constraints (or constraint networks),
directing allowable solutions (uses constraint satisfaction or simplex algorithm)
•Dataflow programming – forced recalculation of formulas when data values change (e.g. spreadsheets)
•Declarative programming – describes actions (e.g. HTML describes a page but not how to actually display
it)
•Distributed programming – have support for multiple autonomous computers that communicate via
computer networks
•Functional programming – uses evaluation of mathematical functions and avoids state and mutable data
•Generic programming – uses algorithms written in terms of to-be-specified-later types that are then
instantiated as needed for specific types provided as parameters
•Imperative programming – explicit statements that change a program state
•Logic programming – uses explicit mathematical logic for programming
•Metaprogramming – writing programs that write or manipulate other programs (or themselves) as their data,
or that do part of the work at compile time that would otherwise be done at runtime
• Template metaprogramming – metaprogramming methods in which templates are used by a
compiler to generate temporary source code, which is merged by the compiler with the rest of the
source code and then compiled
• Reflective programming – metaprogramming methods in which a program modifies or extends itself
Copyright: https://en.m.wikipedia.org/wiki/Comparison_ of_multi-paradigm_ programming_languages
3.1 Multi-paradigm programming
•Object-oriented programming – uses data structures consisting of data fields and
methods together with their interactions (objects) to design programs
• Class-based – object-oriented programming in which inheritance is achieved by
defining classes of objects, versus the objects themselves
• Prototype-based – object-oriented programming that avoids classes and
implements inheritance via cloning of instances
•Pipeline programming – a simple syntax change to add syntax to nest function calls to
language originally designed with none
•Rule-based programming – a network of rules of thumb that comprise a knowledge
base and can be used for expert systems and problem deduction & resolution
•Visual programming – manipulating program elements graphically rather than by
specifying them textually (e.g. Simulink or Scratch from MIT); also
termed diagrammatic programming

Copyright: https://en.m.wikipedia.org/wiki/Comparison_ of_multi-paradigm_ programming_languages


3.1 Multi-paradigm programming

Copyright: https://en.m.wikipedia.org/wiki/Comparison_ of_multi-paradigm_ programming_languages


3.1 Multi-paradigm programming

Copyright: https://en.m.wikipedia.org/wiki/Programming_paradigm
3.2 JVM Languages
This list of JVM Languages comprises notable computer programming languages that
are used to produce computer software that runs on the Java virtual machine (JVM).
Some of these languages are interpreted by a Java program, and some are compiled
to Java bytecode and JIT-compiled during execution as regular Java programs to
improve performance.
The JVM was initially designed to support only the programming language Java.
However, as time passed, ever more languages were adapted or designed to run on
the Java platform.
JVM based High-profile programming languages
Apart from the Java language, the most common or well-known other JVM languages
are:
• Clojure, a functional Lisp dialect
• *** Apache Groovy, a dynamic programming and scripting language (Jenkins)
• JRuby, an implementation of Ruby
• Jython, an implementation of Python
• *** Kotlin, a statically-typed language from JetBrains, the developers of IntelliJ IDEA
(Android Mobile Apps)
• *** Scala, a statically-typed object-oriented and functional programming language
(Cloud – IaaS / PaaS / CaaS over IaaS, HA/HPC scalable computing, Big Data,
DataMining, Collective Intelligence….)
Copyright: https://en.wikipedia.org/wik i/List_of_JVM_languages
3.2 JVM Languages
JVM implementations of existing languages
Language Java implementations Language Java implementations
Ada JGNAT JIProlog
Prolog
Arden Syntax Arden2ByteCode TuProlog
COBOL Micro Focus Visual COBOL Python Jython
ColdFusion Adobe ColdFusion
R Renjin
Markup Railo
Language (CF Lucee Rexx NetRexx
ML) Open BlueDragon JRuby
Common Lisp Armed Bear Common Lisp Ruby
Mirah
Cypher Neo4j
Bigloo
Rhino Kawa
JavaScript Scheme
Nashorn
SISC
Mercury Mercury (Java grade) JScheme
Oberon Component Pascal
Tcl Jacl
MIDletPascal
Pascal Visual Basic Jabaco
Oxygene
Perl 6 Rakudo Perl 6
PHP Quercus
Copyright: https://en.wikipedia.org/wik i/List_of_JVM_languages
3.3 Repositories: Git from Linux VM
Mandatory steps to get the lectures and the labs: (Optional full Git presentation
@ISM – Cyber-Security Master – www.ism.ase.ro by Cristian Toma & Casian Andrei @ Oracle):
1. Download & install the Linux Ubuntu 16.04 LTS VM OVA appliance from Google drive:

2. In Ubuntu Linux VM download the Git repo with the sources for the lecture & labs:
https://github.com/critoma/javase | http://acs.ase.ro/java

Optional – set your e-mail and Git global username if you want to contribute:
git config --global user.email [email protected]
git config --global user.name "critoma"

Mandatory – clone or pull the latest Git repo updates OR Download-ZIP (web):
git clone https://github.com/critoma/javase.git
git pull
?
Questions & Answers!
What’s
Thanks!Your Message?

Java Application Development


End of Lecture 1 – summary of Java SE

You might also like