310
Block IQ Marko Boon ([email protected]) Jacques Resing ([email protected])

Introduction to Programming in Java - TU/emarko/iq/part1-handouts.pdf · ... Fundamentals of programming 1.Introduction to Java ... write a program that computes the area of a circle,

  • Upload
    vohuong

  • View
    220

  • Download
    2

Embed Size (px)

Citation preview

Block IQ

Marko Boon ([email protected])Jacques Resing ([email protected])

2/310

Department of Mathematics and Computer Science Block IQ 1

Schedule (programming part):• Wednesday June 18, 13h30 – 16h30, MF 13

• Friday June 18, 9h00 – 12h00, MF 15 Will be rescheduled

• Friday June 27, 9h00 – 12h00, MF 11

• Wednesday July 2, 9h00 – 12h00, Zwarte Doos 1.03 (?)

• Thursday July 2, 9h00 – 12h00, Zwarte Doos 1.03 (?)

Block IQ 2014

3/310

Department of Mathematics and Computer Science Block IQ 1

Part I: Fundamentals of programming

1. Introduction to Java

2. Primitive Data Types and Operations

3. Control Statements

4. Methods

5. Arrays

4/310

Department of Mathematics and Computer Science Block IQ 1

The History of Java

• developed at Sun Microsystems

• originally called Oak, designed in 1991 for embedded systems

• redesigned in 1995 for Internet applications and renamed to Java

• nowadays used in many mobile phones

Java is not limited to web applications, but it has full programming featuresand it can be used to create stand alone applications. It was designed to beobject-oriented from the start.

Introduction to Java

5/310

Department of Mathematics and Computer Science Block IQ 1

Characteristics of Java

• simple

• object-oriented

• platform independent

• robust, reliable (exception handling)

• secure

• multithreaded

6/310

Department of Mathematics and Computer Science Block IQ 1

Installing Java

The Java Development Kit and Runtime Environment can be downloaded from:

http://www.oracle.com/technetwork/java/javase/

javase stands for Java 2 Platform, Standard Edition. It contains the javainterpreter and compiler, as well as many other tools.

Many graphical text editors have been written for development of Java pro-grams. We will use Netbeans, which can be downloaded from:

http://www.netbeans.org

Alternative:

• Eclipse

7/310

Department of Mathematics and Computer Science Block IQ 1

Creating, compiling and executing a Java program

R e s u l t

C o m p i l e S o u r c e C o d e

R u n B y t e c o d e

C r e a t e / M o d i f y S o u r c e C o d e

i f c o m p i l a t i o n e r r o r s

i f r u n t i m e e r r o r so r i n c o r r e c t r e s u l t

8/310

Department of Mathematics and Computer Science Block IQ 1

Create source code

Create a file Welcome.java:

// This program prints Welcome to Java!

public class Welcome {

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

}}

9/310

Department of Mathematics and Computer Science Block IQ 1

Compile source code

10/310

Department of Mathematics and Computer Science Block IQ 1

Compile source code

11/310

Department of Mathematics and Computer Science Block IQ 1

Compile source code

12/310

Department of Mathematics and Computer Science Block IQ 1

Run bytecode

13/310

Department of Mathematics and Computer Science Block IQ 1

Run bytecode

14/310

Department of Mathematics and Computer Science Block IQ 1

Anatomy of the Application Program

Components:

1. comments

2. reserved words

3. modifiers

4. statements

5. blocks

6. classes

7. methods

15/310

Department of Mathematics and Computer Science Block IQ 1

Comments

Comments are lines of text that are not interpreted by the compiler. They arenot programming statements. Comments help programmers and users com-municate and understand the program.

// This program prints Welcome to Java!

/* This is commentspread over morethan just one line

*/

16/310

Department of Mathematics and Computer Science Block IQ 1

Reserved words (keywords)

Reserved words, or keywords, are words that have a specific meaning to thecompiler and cannot be used for other purposes in the program.When the compiler sees the word class it understands that the word afterclass is the name for the class.

// This program prints Welcome to Java!

public class Welcome {

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

}}

All reserved words are printed in blue.

17/310

Department of Mathematics and Computer Science Block IQ 1

Modifiers

Modifiers are reserved words that specify the properties of the data, methods,classes and how they can be used. Examples: public, static, private, final,abstract and protected.Modifiers will be discussed in the part Object Oriented Programming.

18/310

Department of Mathematics and Computer Science Block IQ 1

Statements

A statement represents an action or a sequence of actions. The statement

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

is to display the welcome text. Every statement in Java ends with a semicolon( ; ).

19/310

Department of Mathematics and Computer Science Block IQ 1

Blocks

Blocks group the components of the program. Each block bgegins with anopen brace ( { ) and ends with a closing brace ( } ). Every class has a classblock that groups the data and methods of the class. Every method has amethod block that groups the statements in the method.Blocks can be nested, meaning that one block can be placed within another./ / T h i s p r o g r a m p r i n t s W e l c o m e t o J a v a !

p u b l i c c l a s s W e l c o m e {

p u b l i c s t a t i c v o i d m a i n ( S t r i n g [ ] a r g s ) { S y s t e m . o u t . p r i n t l n ( " W e l c o m e t o J a v a ! " ) ; }}

c l a s s b l o c k

m e t h o d b l o c k

20/310

Department of Mathematics and Computer Science Block IQ 1

Classes

The class is the essential Java construct. In Object Oriented Programming theywill be discussed in more detail. Every Java program has (at least) one class,and programs are contained inside a class definition enclosed in blocks.A class contains data and method declarations.The file name has to be equal to the class name (case sensitive!).

21/310

Department of Mathematics and Computer Science Block IQ 1

Methods

A method is a collection of statements that are grouped together to perform anoperation. Methods are part of classes. Predefined classes have predefinedmethods (e.g. System.out.println). If you are writing your own class, you canwrite your own methods (e.g. main).Methods may have one or more arguments (e.g. "Welcome to Java").In certain other languages methods are called procedures and functions.

The main method

One method is "special":

public static void main(String[])

This method defines where the program begins. The Java interpreter executesthe application by invoking this main method.The array of Strings contains the command-line arguments.

22/310

Department of Mathematics and Computer Science Block IQ 1

Example: write a program that computes the area of a circle, given the radius.

1. specify the value of the radius,

2. compute the area using the formula a = πr2,

3. display the area.

Primitive Data Types

23/310

Department of Mathematics and Computer Science Block IQ 1

Write the class declaration

24/310

Department of Mathematics and Computer Science Block IQ 1

Write the class declaration

public class AreaComputer {

}

25/310

Department of Mathematics and Computer Science Block IQ 1

Write the class declaration

/*** This class computes the area of a circle

* given a specified radius.

*/

public class AreaComputer {

}

26/310

Department of Mathematics and Computer Science Block IQ 1

Create the main method

/*** This class computes the area of a circle

* given a specified radius.

*/

public class AreaComputer {

}

27/310

Department of Mathematics and Computer Science Block IQ 1

Create the main method

/*** This class computes the area of a circle

* given a specified radius.

*/

public class AreaComputer {

public static void main(String[] args) {

}}

28/310

Department of Mathematics and Computer Science Block IQ 1

Create the main method

/*** This class computes the area of a circle

* given a specified radius.

*/

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {

}}

29/310

Department of Mathematics and Computer Science Block IQ 1

Create the main method

/*** This class computes the area of a circle

* given a specified radius.

*/

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {// Step 1: declare all variables that we need

}}

30/310

Department of Mathematics and Computer Science Block IQ 1

Create the main method

/*** This class computes the area of a circle

* given a specified radius.

*/

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {// Step 1: declare all variables that we need// Step 2 specify the radius and the constant PI

}}

31/310

Department of Mathematics and Computer Science Block IQ 1

Create the main method

/*** This class computes the area of a circle

* given a specified radius.

*/

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {// Step 1: declare all variables that we need// Step 2 specify the radius and the constant PI// Step 3: compute area

}}

32/310

Department of Mathematics and Computer Science Block IQ 1

Create the main method

/*** This class computes the area of a circle

* given a specified radius.

*/

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {// Step 1: declare all variables that we need// Step 2 specify the radius and the constant PI// Step 3: compute area// Step 4: display area

}}

33/310

Department of Mathematics and Computer Science Block IQ 1

Step 1: declare all variables that we need

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {

}}

34/310

Department of Mathematics and Computer Science Block IQ 1

Step 1: declare all variables that we need

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {double radius, area, PI;

}}

35/310

Department of Mathematics and Computer Science Block IQ 1

Step 2: specify the radius and the constant PI

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {double radius, area, PI;

}}

36/310

Department of Mathematics and Computer Science Block IQ 1

Step 2: specify the radius and the constant PI

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {double radius, area, PI;

radius = 5;

}}

37/310

Department of Mathematics and Computer Science Block IQ 1

Step 2: specify the radius and the constant PI

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {double radius, area, PI;

radius = 5;PI = 3.1415926536;

}}

38/310

Department of Mathematics and Computer Science Block IQ 1

Step 3: compute the area

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {double radius, area, PI;

radius = 5;PI = 3.1415926536;

}}

39/310

Department of Mathematics and Computer Science Block IQ 1

Step 3: compute the area

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {double radius, area, PI;

radius = 5;PI = 3.1415926536;

area = PI * radius * radius;

}}

40/310

Department of Mathematics and Computer Science Block IQ 1

Step 4: display the area

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {double radius, area, PI;

radius = 5;PI = 3.1415926536;

area = PI * radius * radius;

}}

41/310

Department of Mathematics and Computer Science Block IQ 1

Step 4: display the area

public class AreaComputer {

// main method: the program starts herepublic static void main(String[] args) {double radius, area, PI;

radius = 5;PI = 3.1415926536;

area = PI * radius * radius;

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

}}

42/310

Department of Mathematics and Computer Science Block IQ 1

Compile and run AreaComputer

43/310

Department of Mathematics and Computer Science Block IQ 1

IdentifiersJust as every entity in the real world has a name, so you need to choose namesfor the things you will refer to in your programs.Programming languages use special symbols called identifiers to name suchprogramming entities as variables, constants, methods, classes, and pack-ages.

Some rules for naming identifiers:

• an identifier is a sequence of characters that consists of letters, digits,underscores (_), and dollar signs ($).

• an identifier cannot start with a digit.

• an identifier cannot be a reserved word.

• an identifier cannot be true, false, or null.

Java is case-sensitive, so X and x are different identifiers.

44/310

Department of Mathematics and Computer Science Block IQ 1

VariablesVariables are used to store data input, data output, or intermediate data. Inthe example, radius and area are variables of double-precision, floating-pointtype (called double). The values of variables can be reassigned.

Declaring Variables

To use a variable, you declare it by telling the compiler the name of the variableas well as what type of data it represents.Syntax: datatype variableName;

int n;double radius;char c;String firstName;

You can declare multiple variables of the same data type in one line:

double radius, area, PI;

45/310

Department of Mathematics and Computer Science Block IQ 1

Assigning a value to a variable

Syntax: variable = expression;

An expression represents a computation involving values, variables, and op-erators that evaluates to a value.

n = 10;double x = 3.5;double y = x * 3;int m = x*2; // WRONG: possible loss of precisiondouble z = n * 3 + 2;String firstName = "Marko";String lastName = "Boon";String fullName = firstName + " " + lastName;n = n + 1;

As you can see, it is possible to declare and initialise a variable in one step.

46/310

Department of Mathematics and Computer Science Block IQ 1

Constants

The value of a variable may be changed during the execution of the program.It is possible to create permanent data that never change: constants.

final double PI = 3.14159;

By convention, constants are named in uppercase.

47/310

Department of Mathematics and Computer Science Block IQ 1

Numeric data typesName Rangebyte −128 to 127short −32768 to 32767int −231 (2147483647) to 231

− 1long −263 to 263

− 1

float −3.41038 to 3.41038 (6 to 7 significant digits of accuracy)double −1.710308 to 1.710308 (14 to 15 significant digits of accuracy)

For integers the most common type is int.For reals the most common type is double.

48/310

Department of Mathematics and Computer Science Block IQ 1

Numeric operators

Addition (+), subtraction (–), multiplication (*), division (/) and remainder (%).Examples:

int i1 = 34 + 1; // i1 becomes 35double d1 = 34.0 - 0.1; // d1 becomes 33.9long i2 = 300 * 30; // i2 becomes 9000double d2 = 1.0 / 2.0; // d2 becomes 0.5;int i3 = 7/3; // i3 becomes 2 (!)byte i4 = 7%3; // i4 becomes 1

49/310

Department of Mathematics and Computer Science Block IQ 1

Shortcut operatorsOperator Name Example Equivalent

+= addition assignment i+= 8 i = i + 8-= subtraction assignment f-= 8.0 f = f - 8.0

*= multiplication assignment i*= 8 i = i * 8/= division assignment i/= 8 i = i / 8%= remainder assignment i%= 8 i = i % 8

Two more shortcut operators:

i++; // i = i + 1i--; // i = i - 1

50/310

Department of Mathematics and Computer Science Block IQ 1

Accuracy

Calculations involving floating-point numbers are approximated becausethese numbers are not stored with complete accuracy. Example:

System.out.println(1 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);

Result: 0.5000000000000001

System.out.println(1 - 0.9);

Result: 0.09999999999999998

51/310

Department of Mathematics and Computer Science Block IQ 1

Numeric type conversions

You can always assign a value to a numeric variable whose type supports alarger range of values:

byte b = 120;int i = b;long l = i;

float f = 100.7f;double d = f;

The other way around is not allowed, even if the numeric value is within therange of the variable:

long l = 110;int i = l; // Possible loss of precision

double d = 100.7;float f = d; // Possible loss of precision

52/310

Department of Mathematics and Computer Science Block IQ 1

Numeric type conversions

You can cast a variable to another variable of a different data type, even witha smaller range:

long l = 110;int i = (int) l;

double d = 100.7;float f = (float) d;

Warning – this is allowed, but might not give the expected result:

double d = 100.7;int i = (int) d; // i = 100

int j = 270;byte b = (byte) j; // j = 14

Please note that casting does not change the variable being cast!

53/310

Department of Mathematics and Computer Science Block IQ 1

Character data type

char letter = ’A’;char numChar = ’4’;

Sequences of letters are stored in a String:

String message = "Welcome to Java!";

Please note that String is not a primitive data type, but a class. This meansthat is has got methods and properties.

54/310

Department of Mathematics and Computer Science Block IQ 1

String concatenation

You can concatenate Strings using the + operator. If you concatenate otherdata types to a String, they will be converted to a String automatically.

String message = "Welcome" + " to " + "Java!";int age = 62;System.out.println("I am " + age + " years old.");

You cannot concatenate characters using the + operator. The + operator castsa char to an int:

char b = ’B’;char c = ’C’;char d = (char) (c+1);int i = b + c + d; // i = 201char e = (char) i; // e = ÉString s = ’a’ + "b"; // s = "ab" !!!!

55/310

Department of Mathematics and Computer Science Block IQ 1

Converting Strings to numbers

A number can easily be converted to a String:

int n = 12;String nStr = ""+n;

Converting a String to a number is slightly more work:

String iStr = "-122";String dStr = "34.6";String qStr = "3+5";int i = Integer.parseInt(iStr);double d = Double.parseDouble(dStr);double q = Double.parseDouble(qStr); // ERROR

Integer and Double are classes, just like String. They will be discussed in moredetail later.

56/310

Department of Mathematics and Computer Science Block IQ 1

Special CharactersDescription Character Escape SequenceBackspace \bTab \tLinefeed \nCarriage return \rBackslash \\Single quote \’Double quote \"

System.out.println("Hello!\nMy name is \"Marko\".");

Hello!My name is "Marko".

57/310

Department of Mathematics and Computer Science Block IQ 1

Unicode Characters

Java characters use Unicode, a 16-bit encoding scheme established by theUnicode Consortium to support the interchange, processing, and display ofwritten texts in the world’s diverse languages (see www.unicode.org). Uni-code takes two bytes, preceded by \u, expressed in four hexadecimal num-bers that run from \u0000 to \uFFFF.

System.out.println("\u00A9 2004"); // CopyrightString alphaBeta = "\u03b1 \u03b2"; // Greek

58/310

Department of Mathematics and Computer Science Block IQ 1

The boolean data type

The boolean data type can have two values: true and false. Usually a booleanis the result of a logical comparison. The comparison operators are:

Operator Name Example Answer< less than 1 < 2 true<= less than or equal to 1 <= 2 true> greater than 1 > 2 false>= greater than or equal to 1 >= 2 false== equal to 1 == 2 false! = not equal to 1! = 2 true

Caution: do not confuse the equality comparison operator (==) to the assign-ment operator (=)!

Please note that booleans cannot be cast into a value of other types, like int.

59/310

Department of Mathematics and Computer Science Block IQ 1

Boolean operatorsOperator Name Description! not logical negation&& and logical conjunction|| or logical disjunctionˆ exclusive or logical exclusion

boolean a = true;boolean b = false;boolean c = true;System.out.println(!a); // falseSystem.out.println(a || b); // trueSystem.out.println(a || c); // trueSystem.out.println(a ^ c); // falseSystem.out.println(a && b); // falseSystem.out.println(a && !b); // true

60/310

Department of Mathematics and Computer Science Block IQ 1

Message and input dialogs

The class JOptionPane contains methods to show message and input dialogs.This class is part of the package javax.swing, so it needs to be imported man-ually. Packages, classes and especially user interfaces will be discussed later.Nevertheless dialogs are so convenient that we will show how to create easydialogs.

Message dialog:

JOptionPane.showMessageDialog(null, "Message","Title", JOptionPane.PLAIN_MESSAGE);

Input dialog:

String input = JOptionPane.showInputDialog(null,"Question", "Title", JOptionPane.QUESTION_MESSAGE);

61/310

Department of Mathematics and Computer Science Block IQ 1

Message and input dialogs – Exampleimport javax.swing.JOptionPane;

public class DialogsExample {

public static void main(String[] arg) {String radiusStr =JOptionPane.showInputDialog(null,"This program computes the area of a circle.\n"+ "Please specify the radius:", "Area Computer",JOptionPane.QUESTION_MESSAGE);double radius = Double.parseDouble(radiusStr);double area = 3.14159 * radius * radius;JOptionPane.showMessageDialog(null,"The area equals: "+area,"Area Computer", JOptionPane.PLAIN_MESSAGE);

System.exit(0);}

}

62/310

Department of Mathematics and Computer Science Block IQ 1

Message and input dialogs – Example

Two remarks:

1. the Java code to import the class JOptionPane from the packagejavax.swing is:

import javax.swing.JOptionPane;

2. Programs containing UI components have to be stopped manually usingthe following command:

System.exit(0);

The reason is that a new thread is started for the UI components. Threadswill be discussed later during the course.

63/310

Department of Mathematics and Computer Science Block IQ 1

Computing example

Problem: write a program that classifies a given amount of money into smallermonetary Euro units.

Solution:

1. prompt the user to enter the amount as a decimal number

2. convert the amount into cents

3. divide the cents by 200 to find the number of €2 coins. Obtain the remain-ing cents using the cents remainder 200.

4. divide the remaining cents by 100 to find the number of €1 coins. Obtainthe remaining cents using the cents remainder 100.

5. divide the remaining cents by 50 to find the number of €0.50 coins. Obtainthe remaining cents using the cents remainder 50.

6. repeat this for 20, 10, 5 and 2 cents.

7. the remaining cents are the Eurocent coins. Display the result.

64/310

Department of Mathematics and Computer Science Block IQ 1

Computing example: ChangeComputer.java

import javax.swing.JOptionPane;

/*** This class breaks down an amount.

*/

public class ChangeComputer {

/*** Main method.

*/

public static void main(String[] arg) {

}}

65/310

Department of Mathematics and Computer Science Block IQ 1

Computing example: ChangeComputer.java

public static void main(String[] arg) {

// Receive the amount entered from the keyboardString amountStr = JOptionPane.showInputDialog(

null, "Enter an amount:", "Example 2.4 input",JOptionPane.QUESTION_MESSAGE);

66/310

Department of Mathematics and Computer Science Block IQ 1

Computing example: ChangeComputer.java

public static void main(String[] arg) {

// Receive the amount entered from the keyboardString amountStr = JOptionPane.showInputDialog(

null, "Enter an amount:", "Example 2.4 input",JOptionPane.QUESTION_MESSAGE);

// Convert String to doubledouble amount = Double.parseDouble(amountStr);

67/310

Department of Mathematics and Computer Science Block IQ 1

Computing example: ChangeComputer.java

public static void main(String[] arg) {

// Receive the amount entered from the keyboardString amountStr = JOptionPane.showInputDialog(

null, "Enter an amount:", "Example 2.4 input",JOptionPane.QUESTION_MESSAGE);

// Convert String to doubledouble amount = Double.parseDouble(amountStr);

// multiply by 100 to obtain centsint remainingAmount = (int) (100*amount);

68/310

Department of Mathematics and Computer Science Block IQ 1

Computing example: ChangeComputer.java

// Find the remaining amount of two euro coinsint twoEuroCoins = remainingAmount / 200;

69/310

Department of Mathematics and Computer Science Block IQ 1

Computing example: ChangeComputer.java

// Find the remaining amount of two euro coinsint twoEuroCoins = remainingAmount / 200;remainingAmount = remainingAmount % 200;

70/310

Department of Mathematics and Computer Science Block IQ 1

Computing example: ChangeComputer.java

// Find the remaining amount of two euro coinsint twoEuroCoins = remainingAmount / 200;remainingAmount = remainingAmount % 200;

// Find the remaining amount of one euro coinsint oneEuroCoins = remainingAmount / 100;remainingAmount = remainingAmount % 100;

...

71/310

Department of Mathematics and Computer Science Block IQ 1

Computing example: ChangeComputer.java

String output = "Your amount " + amount+ " consists of:\n"+ twoEuroCoins + " two euro coins\n"+ oneEuroCoins + " one euro coins\n"+ fiftyCentCoins + " fifty cent coins\n"+ twentyCentCoins + " twenty cent coins\n"+ tenCentCoins + " ten cent coins\n"+ fiveCentCoins + " five cent coins\n"+ twoCentCoins + " two cent coins\n"+ oneCentCoins + " one cent coins";

}

72/310

Department of Mathematics and Computer Science Block IQ 1

Computing example: ChangeComputer.java

String output = "Your amount " + amount+ " consists of:\n"+ twoEuroCoins + " two euro coins\n"+ oneEuroCoins + " one euro coins\n"+ fiftyCentCoins + " fifty cent coins\n"+ twentyCentCoins + " twenty cent coins\n"+ tenCentCoins + " ten cent coins\n"+ fiveCentCoins + " five cent coins\n"+ twoCentCoins + " two cent coins\n"+ oneCentCoins + " one cent coins";

JOptionPane.showMessageDialog(null, output,"Example 2.4 output",JOptionPane.PLAIN_MESSAGE);

}

73/310

Department of Mathematics and Computer Science Block IQ 1

Computing example: ChangeComputer.java

String output = "Your amount " + amount+ " consists of:\n"+ twoEuroCoins + " two euro coins\n"+ oneEuroCoins + " one euro coins\n"+ fiftyCentCoins + " fifty cent coins\n"+ twentyCentCoins + " twenty cent coins\n"+ tenCentCoins + " ten cent coins\n"+ fiveCentCoins + " five cent coins\n"+ twoCentCoins + " two cent coins\n"+ oneCentCoins + " one cent coins";

JOptionPane.showMessageDialog(null, output,"Example 2.4 output",JOptionPane.PLAIN_MESSAGE);

System.exit(0);}

74/310

Department of Mathematics and Computer Science Block IQ 1

Programming style and documentation

It is important to have readable, well documented, structured source code.Otherwise it is not possible for other people to read, understand and/or use(parts of) your code.

1. document your classes and methods

2. use understandable names for identifiers (names of classes, variables andmethods)

3. make sure indentation and spacing in your source is consistent

75/310

Department of Mathematics and Computer Science Block IQ 1

Javadoc comments

Javadoc comments have a special format:

/** ... */

These comments should be provided:

• at the beginning of the program (or class) to explain what the programdoes.

• for every public property of a class (this will be discussed later)

• for every public method of a class

76/310

Department of Mathematics and Computer Science Block IQ 1

Javadoc comments

Javadoc comments may contain special commands (starting with the @character) to provide special information about author, version, functionparameters and return values.

Example:

/*** This program computes the area of a circle

* given the radius.

* Company: Technische Universiteit Eindhoven

* @author Marko Boon

* @version 1.0

*/

The javadoc tool uses these comments and these special commands to gen-erate documentation about all classes in HTML format.

77/310

Department of Mathematics and Computer Science Block IQ 1

Naming conventions

Use descriptive names with straightforward meanings for the variables, con-stants, classes and methods in your program. Names are case-sensitive.

Some conventions for Java:

• always use lowercase for variables and Methods. If a name consists ofseveral words, concatenate them into one, making the first word lower-case and capatilising the first letter of each subsequent word.

double amount = 3.0;int remainingAmount = (int) (100*amount);JOptionPane.showMessageDialog( ... );

• capitalise the first letter of each word in a class name.

public class AreaComputerJOptionPane

78/310

Department of Mathematics and Computer Science Block IQ 1

Naming conventions

• capitalise every letter in a constant, and use underscores between words.

final double PI = 3.141592;final int MAX_VALUE;JOptionPane.QUESTION_MESSAGE

79/310

Department of Mathematics and Computer Science Block IQ 1

Proper indentation and spacing

A consistent indentation style makes programs clear and easy to read. Inden-tation is used to illustrate the structural relationships between a program’scomponents or statements.

public class IndentationExample {

public static void main(String[] arg) {int age = 65;System.out.println("I’m " + age + " years old.");

}}

A single space should be added on both sides of a binary operator:

int b = 3 + 4 * (5 + (2 / a));

You should use single space lines to separate segments of the code to makeit easier to read.

80/310

Department of Mathematics and Computer Science Block IQ 1

Block styles

End-of-line style:

public class IndentationExample {

public static void main(String[] arg) {System.out.println("Hello World!");

}}

Next-line style:

public class IndentationExample{

public static void main(String[] arg){System.out.println("Hello World!");

}}

81/310

Department of Mathematics and Computer Science Block IQ 1

Programming errors

1. Syntax errors (or: compilation errors)

public class ShowSyntaxError {

public static void main(String[] args) {i = 30;System.out.println(i / 4);

}}

82/310

Department of Mathematics and Computer Science Block IQ 1

Programming errors

2. Runtime errors

public class ShowRuntimeError {

public static void main(String[] args) {System.out.println(30 / 0);

}}

83/310

Department of Mathematics and Computer Science Block IQ 1

Programming errors

3. Logic errors

public static void main(String[] args) {String tempCStr = JOptionPane.showInputDialog(

null,"Enter the temperature in degrees Celsius:","Celsius to Fahrenheit converter",JOptionPane.QUESTION_MESSAGE);

double tempC = Double.parseDouble(tempCStr);double tempF = tempC * (9 / 5) + 32;JOptionPane.showMessageDialog(null,

tempC + " \u00B0C is " + tempF + " \u00B0F","Celcius to Fahrenheit converter",JOptionPane.PLAIN_MESSAGE);

System.exit(0);}

84/310

Department of Mathematics and Computer Science Block IQ 1

Program control specifies the order in which statements are executed in a pro-gram. Until now all statements were executed in sequential order.

We will discuss:

• selection statements

• loop statements

Control statements

85/310

Department of Mathematics and Computer Science Block IQ 1

Selection statements

The simple if statement:

if (booleanExpression) {// this code will be executed if condition is true

}

The if . . . else statement:

if (booleanExpression) {// this code will be executed if condition is true

}else {// this code will be executed if condition is false

}

86/310

Department of Mathematics and Computer Science Block IQ 1

Simple if statement - examplepublic static void main(String[] arg) {String ageStr = JOptionPane.showInputDialog(

null, "What is your age?", "Question",JOptionPane.QUESTION_MESSAGE);

int age = Integer.parseInt(ageStr);String comment = "Perfect!";if (age < 18)

comment = "You are young.";if (age < 0)

comment = "This is an invalid age: "+age;if (age > 50)

comment = "You are old!";JOptionPane.showMessageDialog(null,

comment, "Answer", JOptionPane.PLAIN_MESSAGE);System.exit(0);

}}

87/310

Department of Mathematics and Computer Science Block IQ 1

Simple if statement - example

Multiple statements within the if-block:

if (age < 0) {age = -age;comment = "You entered a wrong number.\n" +

"I assume you meant: " + age;}

88/310

Department of Mathematics and Computer Science Block IQ 1

if ... else statement - example

int age = Integer.parseInt(ageStr);String comment;if (age < 0)

comment = "This is an invalid age: "+age;else if (age < 18)

comment = "You are young.";else if (age > 50)

comment = "You are old!";else

comment = "Perfect!";JOptionPane.showMessageDialog(null,

comment, "Answer", JOptionPane.PLAIN_MESSAGE);System.exit(0);

89/310

Department of Mathematics and Computer Science Block IQ 1

Nested if statements - example

String catsStr = JOptionPane.showInputDialog(null, "How many cats do you have?", "Question",JOptionPane.QUESTION_MESSAGE);

int nrOfCats = Integer.parseInt(catsStr);String answer;if (nrOfCats > 0) {String plantStr = JOptionPane.showInputDialog(null, "How many plants have they destroyed?","Question",JOptionPane.QUESTION_MESSAGE);

int nrOfPlants = Integer.parseInt(plantStr);if (nrOfPlants > 5) answer = "Aren’t they cute?";else answer = "Just wait...";

}elseanswer = "Too bad...";

90/310

Department of Mathematics and Computer Science Block IQ 1

More complex conditions - examples

if (nrOfCats > 0 && nrOfDogs == 0) {answer = "I like you!";

}else {answer = "Too bad...";

}

if (denom != 0 && num/denom > 1)...

This statement will not throw a DivisionByZeroException.

91/310

Department of Mathematics and Computer Science Block IQ 1

Loop statements

Loops are structures that control repeated executions of a block of state-ments. The statements that should be repeated are called loop body.The loop is being executed as long as a boolean expression called theloop-continuation-condition is true.

Example 1: calculate S = 1+ 2+ . . .+ 19+ 20.

// initialisationint S = 0;S = S + 1;S = S + 2;S = S + 3;...S = S + 20;System.out.println("S = " + S);

92/310

Department of Mathematics and Computer Science Block IQ 1

The while loop

while (loop-continuation-condition) {// loop body;

}

n e x t s t a t e m e n t ( s )

s t a t e m e n t ( s )

l o o pc o n t i n u a t i o nc o n d i t i o n ?

T r u e

F a l s e

93/310

Department of Mathematics and Computer Science Block IQ 1

The while loop

Example 1: calculate S = 1+ 2+ . . .+ 19+ 20.

94/310

Department of Mathematics and Computer Science Block IQ 1

The while loop

Example 1: calculate S = 1+ 2+ . . .+ 19+ 20.

// initialisationint S = 0;

95/310

Department of Mathematics and Computer Science Block IQ 1

The while loop

Example 1: calculate S = 1+ 2+ . . .+ 19+ 20.

// initialisationint S = 0;// create a counterint counter = 1;

96/310

Department of Mathematics and Computer Science Block IQ 1

The while loop

Example 1: calculate S = 1+ 2+ . . .+ 19+ 20.

// initialisationint S = 0;// create a counterint counter = 1;while (counter <= 20) {

}

97/310

Department of Mathematics and Computer Science Block IQ 1

The while loop

Example 1: calculate S = 1+ 2+ . . .+ 19+ 20.

// initialisationint S = 0;// create a counterint counter = 1;while (counter <= 20) {S = S + counter;

}

98/310

Department of Mathematics and Computer Science Block IQ 1

The while loop

Example 1: calculate S = 1+ 2+ . . .+ 19+ 20.

// initialisationint S = 0;// create a counterint counter = 1;while (counter <= 20) {S = S + counter;counter = counter + 1;

}

99/310

Department of Mathematics and Computer Science Block IQ 1

The while loop

Example 1: calculate S = 1+ 2+ . . .+ 19+ 20.

// initialisationint S = 0;// create a counterint counter = 1;while (counter <= 20) {S = S + counter;counter = counter + 1;

}System.out.println("S = "+S);

100/310

Department of Mathematics and Computer Science Block IQ 1

The while loop

Example 1: calculate S = 1+ 2+ . . .+ 19+ 20.

// initialisationint S = 0;// create a counterint counter = 1;while (counter <= 20) {S = S + counter;counter = counter + 1;

}System.out.println("S = "+S);

Warning: please note that S and counter are initialised outside the loop. Seethe section on The scope of Local Variables for more information.

101/310

Department of Mathematics and Computer Science Block IQ 1

The do-while loop

do {// loop body;

}while (loop-continuation-condition);

N e x t s t a t e m e n t ( s )

T r u e

F a l s e

l o o pc o n t i n u a t i o nc o n d i t i o n ?

S t a t e m e n t ( s )

102/310

Department of Mathematics and Computer Science Block IQ 1

The do-while loop

Example 1: calculate S = 1+ 2+ . . .+ 19+ 20.

// initialisationint S = 0;// create a counterint counter = 1;do {S = S + counter;counter = counter + 1;

}while (counter <= 20);System.out.println("S = "+S);

Difference: the statement(s) in the loop body will be executed at least once!

103/310

Department of Mathematics and Computer Science Block IQ 1

The for loop

for (initialisation; loop-continuation-condition;action-after-each-iteration) {

// loop body;}

n e x t s t a t e m e n t ( s )

s t a t e m e n t ( s )l o o p b o d y

l o o pc o n t i n u a t i o nc o n d i t i o n ?

T r u e

F a l s e

a c t i o n a f t e re a c h i t e r a t i o n

i n i t i a l a c t i o n

104/310

Department of Mathematics and Computer Science Block IQ 1

The for loop

Example 1: calculate S = 1+ 2+ . . .+ 19+ 20.

// initialisationint S = 0;for (int counter = 1; counter <= 20; counter++) {S = S + counter;

}System.out.println("S = "+S);

If there is only one statement in the loop body, the braces can be omitted.

105/310

Department of Mathematics and Computer Science Block IQ 1

Example 1: calculate∑N

k=0 αk given numbers α and N .

public class LoopExample1 {

public static void main(String[] arg) {

}}

106/310

Department of Mathematics and Computer Science Block IQ 1

Example 1: calculate∑N

k=0 αk given numbers α and N .

public class LoopExample1 {

public static void main(String[] arg) {double alpha = 0.6;int N = 20;

}}

107/310

Department of Mathematics and Computer Science Block IQ 1

Example 1: calculate∑N

k=0 αk given numbers α and N .

public class LoopExample1 {

public static void main(String[] arg) {double alpha = 0.6;int N = 20;double sum = 0.0;

}}

108/310

Department of Mathematics and Computer Science Block IQ 1

Example 1: calculate∑N

k=0 αk given numbers α and N .

public class LoopExample1 {

public static void main(String[] arg) {double alpha = 0.6;int N = 20;double sum = 0.0;// initialisation: powerAlphaK = alpha^0double powerAlphaK = 1.0;

}}

109/310

Department of Mathematics and Computer Science Block IQ 1

Example 1: calculate∑N

k=0 αk given numbers α and N .

public class LoopExample1 {

public static void main(String[] arg) {double alpha = 0.6;int N = 20;double sum = 0.0;// initialisation: powerAlphaK = alpha^0double powerAlphaK = 1.0;for (int k = 0; k <= N; k++) {

}

}}

110/310

Department of Mathematics and Computer Science Block IQ 1

Example 1: calculate∑N

k=0 αk given numbers α and N .

public class LoopExample1 {

public static void main(String[] arg) {double alpha = 0.6;int N = 20;double sum = 0.0;// initialisation: powerAlphaK = alpha^0double powerAlphaK = 1.0;for (int k = 0; k <= N; k++) {

// precondition: powerAlphaK = alpha^ksum += powerAlphaK;

}

}}

111/310

Department of Mathematics and Computer Science Block IQ 1

Example 1: calculate∑N

k=0 αk given numbers α and N .

public class LoopExample1 {

public static void main(String[] arg) {double alpha = 0.6;int N = 20;double sum = 0.0;// initialisation: powerAlphaK = alpha^0double powerAlphaK = 1.0;for (int k = 0; k <= N; k++) {

// precondition: powerAlphaK = alpha^ksum += powerAlphaK;powerAlphaK *= alpha;

}

}}

112/310

Department of Mathematics and Computer Science Block IQ 1

Example 1: calculate∑N

k=0 αk given numbers α and N .

public class LoopExample1 {

public static void main(String[] arg) {double alpha = 0.6;int N = 20;double sum = 0.0;// initialisation: powerAlphaK = alpha^0double powerAlphaK = 1.0;for (int k = 0; k <= N; k++) {

// precondition: powerAlphaK = alpha^ksum += powerAlphaK;powerAlphaK *= alpha;

}System.out.println("Sum = "+sum);

}}

113/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

114/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 1: initialisation

115/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 1: initialisation

final double ABSOLUTE_PRECISION = 1E-5;final double RELATIVE_PRECISION = 1E-4;final double MAX_ITERATIONS = 1E2;

116/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 1: initialisation

final double ABSOLUTE_PRECISION = 1E-5;final double RELATIVE_PRECISION = 1E-4;final double MAX_ITERATIONS = 1E2;

double alpha = 0.6;double sum = 0.0;double powerAlphaK = 1.0;

117/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 1: initialisation

final double ABSOLUTE_PRECISION = 1E-5;final double RELATIVE_PRECISION = 1E-4;final double MAX_ITERATIONS = 1E2;

double alpha = 0.6;double sum = 0.0;double powerAlphaK = 1.0;

double oldSum = 0.0;double absPrec = 0.0;double relPrec = 0.0;int n = 0;

118/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 2: the main loop

do {

}while (

);

119/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 2: the main loop

do {oldSum = sum;

}while (

);

120/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 2: the main loop

do {oldSum = sum;sum += powerAlphaK;

}while (

);

121/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 2: the main loop

do {oldSum = sum;sum += powerAlphaK;powerAlphaK *= alpha;

}while (

);

122/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 2: the main loop

do {oldSum = sum;sum += powerAlphaK;powerAlphaK *= alpha;absPrec = sum - oldSum;

}while (

);

123/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 2: the main loop

do {oldSum = sum;sum += powerAlphaK;powerAlphaK *= alpha;absPrec = sum - oldSum;relPrec = absPrec / sum;

}while (

);

124/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 2: the main loop

do {oldSum = sum;sum += powerAlphaK;powerAlphaK *= alpha;absPrec = sum - oldSum;relPrec = absPrec / sum;n++;

}while (

);

125/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 2: the main loop

do {oldSum = sum;sum += powerAlphaK;powerAlphaK *= alpha;absPrec = sum - oldSum;relPrec = absPrec / sum;n++;

}while (absPrec > ABSOLUTE_PRECISION

);

126/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 2: the main loop

do {oldSum = sum;sum += powerAlphaK;powerAlphaK *= alpha;absPrec = sum - oldSum;relPrec = absPrec / sum;n++;

}while (absPrec > ABSOLUTE_PRECISION

&& relPrec > RELATIVE_PRECISION);

127/310

Department of Mathematics and Computer Science Block IQ 1

Example 2: calculate∑∞

k=0 αk with absolute precision 10−5, relative precision

10−4 and a maximum of 102 iterations.

Step 2: the main loop

do {oldSum = sum;sum += powerAlphaK;powerAlphaK *= alpha;absPrec = sum - oldSum;relPrec = absPrec / sum;n++;

}while (absPrec > ABSOLUTE_PRECISION

&& relPrec > RELATIVE_PRECISION&& n < MAX_ITERATIONS);

128/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

129/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

String msg = " Multiplication Table\n\n";

System.out.println(msg);

130/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

String msg = " Multiplication Table\n\n";// create the title row

System.out.println(msg);

131/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

String msg = " Multiplication Table\n\n";// create the title rowmsg += " ";for (int i = 1; i <= 9; i++)

msg += " "+i;

System.out.println(msg);

132/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

String msg = " Multiplication Table\n\n";// create the title rowmsg += " ";for (int i = 1; i <= 9; i++)

msg += " "+i;msg += "\n------------------------------\n";

System.out.println(msg);

133/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

String msg = " Multiplication Table\n\n";// create the title rowmsg += " ";for (int i = 1; i <= 9; i++)

msg += " "+i;msg += "\n------------------------------\n";

// create the table

....

System.out.println(msg);

134/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

// create the table

135/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

// create the tablefor (int row = 1; row <= 9; row++) {

}

136/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

// create the tablefor (int row = 1; row <= 9; row++) {

// create the title columnmsg += row+" |";

}

137/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

// create the tablefor (int row = 1; row <= 9; row++) {

// create the title columnmsg += row+" |";// create the columnsfor (int col = 1; col <= 9; col++) {

}

}

138/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

// create the tablefor (int row = 1; row <= 9; row++) {

// create the title columnmsg += row+" |";// create the columnsfor (int col = 1; col <= 9; col++) {int product = row * col;

}

}

139/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

// create the tablefor (int row = 1; row <= 9; row++) {

// create the title columnmsg += row+" |";// create the columnsfor (int col = 1; col <= 9; col++) {int product = row * col;

msg += " " + product;

}

}

140/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

// create the tablefor (int row = 1; row <= 9; row++) {

// create the title columnmsg += row+" |";// create the columnsfor (int col = 1; col <= 9; col++) {int product = row * col;if (product < 10)

msg += " " + product;

}

}

141/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

// create the tablefor (int row = 1; row <= 9; row++) {

// create the title columnmsg += row+" |";// create the columnsfor (int col = 1; col <= 9; col++) {int product = row * col;if (product < 10)

msg += " " + product;else

msg += " " + product;}

}

142/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

// create the tablefor (int row = 1; row <= 9; row++) {

// create the title columnmsg += row+" |";// create the columnsfor (int col = 1; col <= 9; col++) {int product = row * col;if (product < 10)

msg += " " + product;else

msg += " " + product;}msg += "\n";

}

143/310

Department of Mathematics and Computer Science Block IQ 1

Nested for loops – Example: multiplication table

144/310

Department of Mathematics and Computer Science Block IQ 1

A method is a collection of statements that are grouped together to performan operation. Methods that have a return value are called functions. Methodswithout a return value are called procedures. Methods may have parameters.These parameters will be treated as local variables in the method body.

Methods

145/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method without arguments and return type.

public class MethodTest1 {

public static void main(String[] arg) {

}}

146/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method without arguments and return type.

public class MethodTest1 {

public static void printName() {

}

public static void main(String[] arg) {

}}

147/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method without arguments and return type.

public class MethodTest1 {

public static void printName() {System.out.println("My name is Marko Boon.");System.out.println("I am 65 years old.");

}

public static void main(String[] arg) {

}}

148/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method without arguments and return type.

public class MethodTest1 {

public static void printName() {System.out.println("My name is Marko Boon.");System.out.println("I am 65 years old.");

}

public static void main(String[] arg) {printName();

}}

149/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method with arguments, but no return type.

public class MethodTest2 {

public static void main(String[] arg) {

}}

150/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method with arguments, but no return type.

public class MethodTest2 {

public static void printName(String name, int age) {

}

public static void main(String[] arg) {

}}

151/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method with arguments, but no return type.

public class MethodTest2 {

public static void printName(String name, int age) {System.out.println("My name is " + name);System.out.println("I am " + age + " years old.");

}

public static void main(String[] arg) {

}}

152/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method with arguments, but no return type.

public class MethodTest2 {

public static void printName(String name, int age) {System.out.println("My name is " + name);System.out.println("I am " + age + " years old.");

}

public static void main(String[] arg) {printName("Marko Boon", 65);

}}

153/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method with arguments, but no return type.

public class MethodTest2 {

public static void printName(String name, int age) {System.out.println("My name is " + name);System.out.println("I am " + age + " years old.");

}

public static void main(String[] arg) {printName("Marko Boon", 65);printName("Mick Jagger", 98);

}}

154/310

Department of Mathematics and Computer Science Block IQ 1

MethodsExample: method with arguments and return type.

public class MethodTest3 {

public static void main(String[] arg) {

}}

155/310

Department of Mathematics and Computer Science Block IQ 1

MethodsExample: method with arguments and return type.

public class MethodTest3 {

public static boolean isPrime(int number) {...

}

public static void main(String[] arg) {

}}

156/310

Department of Mathematics and Computer Science Block IQ 1

MethodsExample: method with arguments and return type.

public class MethodTest3 {

public static boolean isPrime(int number) {...

}

public static void main(String[] arg) {int numberOfPrimesFound = 0;

}}

157/310

Department of Mathematics and Computer Science Block IQ 1

MethodsExample: method with arguments and return type.

public class MethodTest3 {

public static boolean isPrime(int number) {...

}

public static void main(String[] arg) {int numberOfPrimesFound = 0;for (int i = 2; numberOfPrimesFound < 50; i++) {

}}

}

158/310

Department of Mathematics and Computer Science Block IQ 1

MethodsExample: method with arguments and return type.

public class MethodTest3 {

public static boolean isPrime(int number) {...

}

public static void main(String[] arg) {int numberOfPrimesFound = 0;for (int i = 2; numberOfPrimesFound < 50; i++) {

if (isPrime(i)) {

}}

}}

159/310

Department of Mathematics and Computer Science Block IQ 1

MethodsExample: method with arguments and return type.

public class MethodTest3 {

public static boolean isPrime(int number) {...

}

public static void main(String[] arg) {int numberOfPrimesFound = 0;for (int i = 2; numberOfPrimesFound < 50; i++) {

if (isPrime(i)) {System.out.println(i+" ");

}}

}}

160/310

Department of Mathematics and Computer Science Block IQ 1

MethodsExample: method with arguments and return type.

public class MethodTest3 {

public static boolean isPrime(int number) {...

}

public static void main(String[] arg) {int numberOfPrimesFound = 0;for (int i = 2; numberOfPrimesFound < 50; i++) {

if (isPrime(i)) {System.out.println(i+" ");numberOfPrimesFound++;

}}

}}

161/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method with arguments and return type.

public static boolean isPrime(int number) {

}

162/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method with arguments and return type.

public static boolean isPrime(int number) {boolean prime = true;

}

163/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method with arguments and return type.

public static boolean isPrime(int number) {boolean prime = true;for (int i = 2; i < number; i++) {

}

}

164/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method with arguments and return type.

public static boolean isPrime(int number) {boolean prime = true;for (int i = 2; i < number; i++) {

if (number % i == 0) prime = false;}

}

165/310

Department of Mathematics and Computer Science Block IQ 1

Methods

Example: method with arguments and return type.

public static boolean isPrime(int number) {boolean prime = true;for (int i = 2; i < number; i++) {

if (number % i == 0) prime = false;}return prime;

}

166/310

Department of Mathematics and Computer Science Block IQ 1

Methods – passing parameters

Java uses pass by value when you invoke a method with parameters. Thismeans that a copy of the value of the actual parameter is passed to themethod. The actual variable outside the method is not affected.

public class PassByValue {

public static void changeValue(int n) {n = 5;System.out.println("inside method: "+n);

}public static void main(String[] arg) {int n = 3;System.out.println("Before calling method: "+n);changeValue(n);System.out.println("After calling method: "+n);

}}

167/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

You can create different methods with the same name, but with different pa-rameters.

public static void main(String[] arg) {

}

168/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

You can create different methods with the same name, but with different pa-rameters.

public static int max(int n1, int n2) {...

}

public static void main(String[] arg) {

}

169/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

You can create different methods with the same name, but with different pa-rameters.

public static int max(int n1, int n2) {...

}

public static int max(int n1, int n2, int n3) {...

}

public static void main(String[] arg) {

}

170/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

You can create different methods with the same name, but with different pa-rameters.

public static int max(int n1, int n2) {...

}

public static int max(int n1, int n2, int n3) {...

}

public static void main(String[] arg) {int n = max(4, 6);

}

171/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

You can create different methods with the same name, but with different pa-rameters.

public static int max(int n1, int n2) {...

}

public static int max(int n1, int n2, int n3) {...

}

public static void main(String[] arg) {int n = max(4, 6);int m = max(7, -3, 3);

}

172/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

You can create different methods with the same name, but with different pa-rameters.

public static int max(int n1, int n2) {...

}

public static int max(int n1, int n2, int n3) {...

}

public static void main(String[] arg) {int n = max(4, 6);int m = max(7, -3, 3);System.out.println("n = "+n+", m = "+m);

}

173/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

public static int max(int n1, int n2) {

}

174/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

public static int max(int n1, int n2) {if (n1 > n2) return n1;

}

175/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

public static int max(int n1, int n2) {if (n1 > n2) return n1;else return n2;

}

176/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

public static int max(int n1, int n2) {if (n1 > n2) return n1;else return n2;

}

public static int max(int n1, int n2, int n3) {

}

177/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

public static int max(int n1, int n2) {if (n1 > n2) return n1;else return n2;

}

public static int max(int n1, int n2, int n3) {if (n1 > n2) {

}

}

178/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

public static int max(int n1, int n2) {if (n1 > n2) return n1;else return n2;

}

public static int max(int n1, int n2, int n3) {if (n1 > n2) {

if (n1 > n3) return n1;else return n3;

}

}

179/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

public static int max(int n1, int n2) {if (n1 > n2) return n1;else return n2;

}

public static int max(int n1, int n2, int n3) {if (n1 > n2) {

if (n1 > n3) return n1;else return n3;

}else {

}}

180/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

public static int max(int n1, int n2) {if (n1 > n2) return n1;else return n2;

}

public static int max(int n1, int n2, int n3) {if (n1 > n2) {

if (n1 > n3) return n1;else return n3;

}else {

if (n2 > n3) return n2;else return n3;

}}

181/310

Department of Mathematics and Computer Science Block IQ 1

Method overloading

Smarter implementation:

public static int max(int n1, int n2) {if (n1 > n2) return n1;else return n2;

}

public static int max(int n1, int n2, int n3) {return max(n1, max(n2, n3));

}

182/310

Department of Mathematics and Computer Science Block IQ 1

Recursion

Recursion is the powerful mathematical concept of a function calling itself.Example: factorial.

0! = 1n! = n × (n − 1)! (n > 0)

public static int factorial(int n) {if (n < 0) return 0;else if (n == 0) return 1;else return n * factorial(n - 1);

}

183/310

Department of Mathematics and Computer Science Block IQ 1

Recursion

Of course n! can be computed without using recursion:

int factorial = 1;for (int i = 2; i <= n; i++) {factorial *= i;

}

This is always more efficient!But sometimes the solution using recursion is much easier.

Example: Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . .)

f (0) = 0f (1) = 1f (n) = f (n − 2)+ f (n − 1) (n ≥ 2)

184/310

Department of Mathematics and Computer Science Block IQ 1

Recursion

public class RecursionExample2 {

public static int fibonacci(int n) {if (n < 0) return 0;else if (n == 0 || n == 1) return n;else return fibonacci(n - 2) + fibonacci(n - 1);

}

public static void main(String[] arg) {System.out.println("Fibonacci numbers:");for (int i = 0; i <= 25; i++) {

System.out.print(fibonacci(i)+" ");}

}}

185/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

Problem: move a specified number of disks of a distinct size from one towerto another while observing the following rules:

• there are n disks labelled 1, 2, . . . , n and three towers labelled A, B and C

• no disk can be on top of a smaller disk at any time

• all the disks are initially placed on tower A and should be moved to B

• only one disk can be moved at a time, and it must be the top disk of onetower.

A B C

186/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

Problem: move a specified number of disks of a distinct size from one towerto another while observing the following rules:

• there are n disks labelled 1, 2, . . . , n and three towers labelled A, B and C

• no disk can be on top of a smaller disk at any time

• all the disks are initially placed on tower A and should be moved to B

• only one disk can be moved at a time, and it must be the top disk of onetower.

A B C

187/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

Problem: move a specified number of disks of a distinct size from one towerto another while observing the following rules:

• there are n disks labelled 1, 2, . . . , n and three towers labelled A, B and C

• no disk can be on top of a smaller disk at any time

• all the disks are initially placed on tower A and should be moved to B

• only one disk can be moved at a time, and it must be the top disk of onetower.

A B C

188/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

Problem: move a specified number of disks of a distinct size from one towerto another while observing the following rules:

• there are n disks labelled 1, 2, . . . , n and three towers labelled A, B and C

• no disk can be on top of a smaller disk at any time

• all the disks are initially placed on tower A and should be moved to B

• only one disk can be moved at a time, and it must be the top disk of onetower.

A B C

189/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

Problem: move a specified number of disks of a distinct size from one towerto another while observing the following rules:

• there are n disks labelled 1, 2, . . . , n and three towers labelled A, B and C

• no disk can be on top of a smaller disk at any time

• all the disks are initially placed on tower A and should be moved to B

• only one disk can be moved at a time, and it must be the top disk of onetower.

A B C

190/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

Problem: move a specified number of disks of a distinct size from one towerto another while observing the following rules:

• there are n disks labelled 1, 2, . . . , n and three towers labelled A, B and C

• no disk can be on top of a smaller disk at any time

• all the disks are initially placed on tower A and should be moved to B

• only one disk can be moved at a time, and it must be the top disk of onetower.

A B C

191/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

Problem: move a specified number of disks of a distinct size from one towerto another while observing the following rules:

• there are n disks labelled 1, 2, . . . , n and three towers labelled A, B and C

• no disk can be on top of a smaller disk at any time

• all the disks are initially placed on tower A and should be moved to B

• only one disk can be moved at a time, and it must be the top disk of onetower.

A B C

192/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

Problem: move a specified number of disks of a distinct size from one towerto another while observing the following rules:

• there are n disks labelled 1, 2, . . . , n and three towers labelled A, B and C

• no disk can be on top of a smaller disk at any time

• all the disks are initially placed on tower A and should be moved to B

• only one disk can be moved at a time, and it must be the top disk of onetower.

A B C

193/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

Recursion:

• suppose you solved the problem for n − 1 disks

• then move the first n − 1 disks to C

• then move disk n to B

• finally move the n − 1 disks back to B

Now we have to find one n for which the problem can be solved easily. This isn = 1, because one disk can simply be moved to the desired tower.

194/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static void main(String[] arg) {

}

195/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

...}public static void main(String[] arg) {

}

196/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

...}public static void main(String[] arg) {String nStr = JOptionPane.showInputDialog(null,"Please enter the number of disks:","The Tower of Hanoi",JOptionPane.QUESTION_MESSAGE);

}

197/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

...}public static void main(String[] arg) {String nStr = JOptionPane.showInputDialog(null,"Please enter the number of disks:","The Tower of Hanoi",JOptionPane.QUESTION_MESSAGE);

int n = Integer.parseInt(nStr);

}

198/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

...}public static void main(String[] arg) {String nStr = JOptionPane.showInputDialog(null,"Please enter the number of disks:","The Tower of Hanoi",JOptionPane.QUESTION_MESSAGE);

int n = Integer.parseInt(nStr);String solution = moveDisks(n, ’A’, ’B’, ’C’);

}

199/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

...}public static void main(String[] arg) {String nStr = JOptionPane.showInputDialog(null,"Please enter the number of disks:","The Tower of Hanoi",JOptionPane.QUESTION_MESSAGE);

int n = Integer.parseInt(nStr);String solution = moveDisks(n, ’A’, ’B’, ’C’);JOptionPane.showMessageDialog(null,"Solution:\n" + solution,"The Tower of Hanoi", JOptionPane.PLAIN_MESSAGE);

}

200/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

...}public static void main(String[] arg) {String nStr = JOptionPane.showInputDialog(null,"Please enter the number of disks:","The Tower of Hanoi",JOptionPane.QUESTION_MESSAGE);

int n = Integer.parseInt(nStr);String solution = moveDisks(n, ’A’, ’B’, ’C’);JOptionPane.showMessageDialog(null,"Solution:\n" + solution,"The Tower of Hanoi", JOptionPane.PLAIN_MESSAGE);

System.exit(0);}

201/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

}

202/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

if (n <= 0) return "No disks to move.\n";

}

203/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

if (n <= 0) return "No disks to move.\n";else if (n == 1) return "Move disk 1 from "

+ fromTower + " to " + toTower + "\n";

}

204/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

if (n <= 0) return "No disks to move.\n";else if (n == 1) return "Move disk 1 from "

+ fromTower + " to " + toTower + "\n";else {

}}

205/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

if (n <= 0) return "No disks to move.\n";else if (n == 1) return "Move disk 1 from "

+ fromTower + " to " + toTower + "\n";else {String s =

moveDisks(n - 1, fromTower, auxTower, toTower);

}}

206/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

if (n <= 0) return "No disks to move.\n";else if (n == 1) return "Move disk 1 from "

+ fromTower + " to " + toTower + "\n";else {String s =

moveDisks(n - 1, fromTower, auxTower, toTower);s += "Move disk " + n + " from " + fromTower

+ " to " + toTower + "\n";

}}

207/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

if (n <= 0) return "No disks to move.\n";else if (n == 1) return "Move disk 1 from "

+ fromTower + " to " + toTower + "\n";else {String s =

moveDisks(n - 1, fromTower, auxTower, toTower);s += "Move disk " + n + " from " + fromTower

+ " to " + toTower + "\n";s += moveDisks(n - 1, auxTower, toTower,

fromTower);

}}

208/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

public static String moveDisks(int n, char fromTower,char toTower, char auxTower) {

if (n <= 0) return "No disks to move.\n";else if (n == 1) return "Move disk 1 from "

+ fromTower + " to " + toTower + "\n";else {String s =

moveDisks(n - 1, fromTower, auxTower, toTower);s += "Move disk " + n + " from " + fromTower

+ " to " + toTower + "\n";s += moveDisks(n - 1, auxTower, toTower,

fromTower);return s;

}}

209/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

210/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

211/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

212/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

213/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

214/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

215/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

216/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

217/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

218/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

219/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

220/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

221/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

222/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

223/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

224/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

225/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

226/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

227/310

Department of Mathematics and Computer Science Block IQ 1

Recursion – Example: The Tower of Hanoi

A B C

228/310

Department of Mathematics and Computer Science Block IQ 1

An array is an object which stores a collection of data of the same type. Youcan retrieve data from this collection by specifying the position (or index)where the item is stored. The first index is 0!

As an example we are going to create an array called a that can hold 5 integervalues. Then we are going to store the following numbers in it: 3, 4, 5, 6 and7.

Arrays

229/310

Department of Mathematics and Computer Science Block IQ 1

Step 1: declare the array

230/310

Department of Mathematics and Computer Science Block IQ 1

Step 1: declare the array

int[] a;

a

231/310

Department of Mathematics and Computer Science Block IQ 1

Step 2: initialise (construct) the array

int[] a;

a

232/310

Department of Mathematics and Computer Science Block IQ 1

Step 2: initialise (construct) the array

int[] a;a = new int[5];

a0 1 2 3 4

233/310

Department of Mathematics and Computer Science Block IQ 1

Step 3: fill the array

int[] a;a = new int[5];

a0 1 2 3 4

234/310

Department of Mathematics and Computer Science Block IQ 1

Step 3: fill the array

int[] a;a = new int[5];a[0] = 3;

a

30 1 2 3 4

235/310

Department of Mathematics and Computer Science Block IQ 1

Step 3: fill the array

int[] a;a = new int[5];a[0] = 3;a[1] = 4;a[2] = 5;a[3] = 6;a[4] = 7;

a

3 4 5 60 1 2 3 4

7

236/310

Department of Mathematics and Computer Science Block IQ 1

Arrays

• an array is an Object, no primitive type

• this means that an array that is declared but not constructed has the valuenull

• this also means that an array variable does not actually contain that array,but a reference to the array

• arrays have a property length that returns the capacity (or size) of the array

• you cannot store items in an array before it is constructed (to specify thesize)

• an alternative array declaration, compatible with C++, is:

dataType arrayName[];

237/310

Department of Mathematics and Computer Science Block IQ 1

Step 3: fill the array

Another way to fill the array is to use the alternative constructor.

int[] a = {3, 4, 5, 6, 7};

Most popular approach is to use the for-loop when possible:

int[] a = new int[5];for (int i = 0; i < a.length; i++)a[i] = 3 + i;

It is easy to compute the sum of the elements:

int sum = 0;for (int i = 0; i < a.length; i++)sum += a[i];

238/310

Department of Mathematics and Computer Science Block IQ 1

Array example

239/310

Department of Mathematics and Computer Science Block IQ 1

Array example

String size = JOptionPane.showInputDialog(null,"How many numbers do you want to enter?","Array Example", JOptionPane.QUESTION_MESSAGE);

240/310

Department of Mathematics and Computer Science Block IQ 1

Array example

String size = JOptionPane.showInputDialog(null,"How many numbers do you want to enter?","Array Example", JOptionPane.QUESTION_MESSAGE);

int n = Integer.parseInt(size);

241/310

Department of Mathematics and Computer Science Block IQ 1

Array example

String size = JOptionPane.showInputDialog(null,"How many numbers do you want to enter?","Array Example", JOptionPane.QUESTION_MESSAGE);

int n = Integer.parseInt(size);double[] numbers = new double[n];

242/310

Department of Mathematics and Computer Science Block IQ 1

Array example

String size = JOptionPane.showInputDialog(null,"How many numbers do you want to enter?","Array Example", JOptionPane.QUESTION_MESSAGE);

int n = Integer.parseInt(size);double[] numbers = new double[n];for (int i = 0; i < numbers.length; i++) {

}

243/310

Department of Mathematics and Computer Science Block IQ 1

Array example

String size = JOptionPane.showInputDialog(null,"How many numbers do you want to enter?","Array Example", JOptionPane.QUESTION_MESSAGE);

int n = Integer.parseInt(size);double[] numbers = new double[n];for (int i = 0; i < numbers.length; i++) {String nr = JOptionPane.showInputDialog(null,

"Please enter number "+(i+1),"Array Example", JOptionPane.QUESTION_MESSAGE);

}

244/310

Department of Mathematics and Computer Science Block IQ 1

Array example

String size = JOptionPane.showInputDialog(null,"How many numbers do you want to enter?","Array Example", JOptionPane.QUESTION_MESSAGE);

int n = Integer.parseInt(size);double[] numbers = new double[n];for (int i = 0; i < numbers.length; i++) {String nr = JOptionPane.showInputDialog(null,

"Please enter number "+(i+1),"Array Example", JOptionPane.QUESTION_MESSAGE);

numbers[i] = Double.parseDouble(nr);}

245/310

Department of Mathematics and Computer Science Block IQ 1

Array example

// find largest number

246/310

Department of Mathematics and Computer Science Block IQ 1

Array example

// find largest numberdouble max = -99999;

247/310

Department of Mathematics and Computer Science Block IQ 1

Array example

// find largest numberdouble max = -99999;String output = "The numbers you entered: ";

248/310

Department of Mathematics and Computer Science Block IQ 1

Array example

// find largest numberdouble max = -99999;String output = "The numbers you entered: ";for (int i = 0; i < numbers.length; i++) {

}

249/310

Department of Mathematics and Computer Science Block IQ 1

Array example

// find largest numberdouble max = -99999;String output = "The numbers you entered: ";for (int i = 0; i < numbers.length; i++) {

if (numbers[i] > max) max = numbers[i];

}

250/310

Department of Mathematics and Computer Science Block IQ 1

Array example

// find largest numberdouble max = -99999;String output = "The numbers you entered: ";for (int i = 0; i < numbers.length; i++) {

if (numbers[i] > max) max = numbers[i];output += numbers[i] + " ";

}

251/310

Department of Mathematics and Computer Science Block IQ 1

Array example

// find largest numberdouble max = -99999;String output = "The numbers you entered: ";for (int i = 0; i < numbers.length; i++) {

if (numbers[i] > max) max = numbers[i];output += numbers[i] + " ";

}output += "\nThe largest number is: "+max;

252/310

Department of Mathematics and Computer Science Block IQ 1

Array example

// find largest numberdouble max = -99999;String output = "The numbers you entered: ";for (int i = 0; i < numbers.length; i++) {

if (numbers[i] > max) max = numbers[i];output += numbers[i] + " ";

}output += "\nThe largest number is: "+max;

JOptionPane.showMessageDialog(null,output, "Array Example",JOptionPane.PLAIN_MESSAGE);

253/310

Department of Mathematics and Computer Science Block IQ 1

Array example

// find largest numberdouble max = -99999;String output = "The numbers you entered: ";for (int i = 0; i < numbers.length; i++) {

if (numbers[i] > max) max = numbers[i];output += numbers[i] + " ";

}output += "\nThe largest number is: "+max;

JOptionPane.showMessageDialog(null,output, "Array Example",JOptionPane.PLAIN_MESSAGE);

System.exit(0);

254/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

public static double[] sortArray(double[] numbers) {

}

255/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

Step 1: Create a copy of the original array.

public static double[] sortArray(double[] numbers) {double[] sorted = new double[numbers.length];

}

256/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

Step 1: Create a copy of the original array.

public static double[] sortArray(double[] numbers) {double[] sorted = new double[numbers.length];for (int i = 0; i < sorted.length; i++)sorted[i] = numbers[i];

}

257/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

Step 2: create a loop that runs through the elements

public static double[] sortArray(double[] numbers) {double[] sorted = new double[numbers.length];for (int i = 0; i < sorted.length; i++)sorted[i] = numbers[i];

for (int i = 0; i < sorted.length; i++) {

}

}

258/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

Step 3: create another loop that find the smallest number behind ipublic static double[] sortArray(double[] numbers) {double[] sorted = new double[numbers.length];for (int i = 0; i < sorted.length; i++)sorted[i] = numbers[i];

for (int i = 0; i < sorted.length; i++) {for (int j = i + 1; j < sorted.length; j++) {

}}

}

259/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

Step 4: if element at position j is smaller, swap with i .

public static double[] sortArray(double[] numbers) {double[] sorted = new double[numbers.length];for (int i = 0; i < sorted.length; i++)sorted[i] = numbers[i];

for (int i = 0; i < sorted.length; i++) {for (int j = i + 1; j < sorted.length; j++) {

if (sorted[j] < sorted[i]) {

}}

}

}

260/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

Step 4: if element at position j is smaller, swap with i .

public static double[] sortArray(double[] numbers) {double[] sorted = new double[numbers.length];for (int i = 0; i < sorted.length; i++)sorted[i] = numbers[i];

for (int i = 0; i < sorted.length; i++) {for (int j = i + 1; j < sorted.length; j++) {

if (sorted[j] < sorted[i]) {double tmp = sorted[j];

}}

}

}

261/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

Step 4: if element at position j is smaller, swap with i .

public static double[] sortArray(double[] numbers) {double[] sorted = new double[numbers.length];for (int i = 0; i < sorted.length; i++)sorted[i] = numbers[i];

for (int i = 0; i < sorted.length; i++) {for (int j = i + 1; j < sorted.length; j++) {

if (sorted[j] < sorted[i]) {double tmp = sorted[j];sorted[j] = sorted[i];

}}

}

}

262/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

Step 4: if element at position j is smaller, swap with i .

public static double[] sortArray(double[] numbers) {double[] sorted = new double[numbers.length];for (int i = 0; i < sorted.length; i++)sorted[i] = numbers[i];

for (int i = 0; i < sorted.length; i++) {for (int j = i + 1; j < sorted.length; j++) {

if (sorted[j] < sorted[i]) {double tmp = sorted[j];sorted[j] = sorted[i];sorted[i] = tmp;

}}

}

}

263/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

Step 5: return the sorted array.

public static double[] sortArray(double[] numbers) {double[] sorted = new double[numbers.length];for (int i = 0; i < sorted.length; i++)sorted[i] = numbers[i];

for (int i = 0; i < sorted.length; i++) {for (int j = i + 1; j < sorted.length; j++) {

if (sorted[j] < sorted[i]) {double tmp = sorted[j];sorted[j] = sorted[i];sorted[i] = tmp;

}}

}return sorted;

}

264/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 45 60 1 2 3 47

265/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 45 60 1 2 3 47

i

266/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 45 60 1 2 3 47

i j

267/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 45 60 1 2 3 4

7

i j

268/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 45 60 1 2 3 4

7

i j

269/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 45 60 1 2 3 4

7

i j

270/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 45 60 1 2 3 4

7

i j

271/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 45 60 1 2 3 4

7

i j

272/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 45 60 1 2 3 4

7

i j

273/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 45 60 1 2 3 4

7

i j

274/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 45 60 1 2 3 4

7

i j

275/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 4 560 1 2 3 4

7

i j

276/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 4 560 1 2 3 4

7

i j

277/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 4 560 1 2 3 4

7

i j

278/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 4 560 1 2 3 4

7

i j

279/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 4 5 60 1 2 3 4

7

i j

280/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 4 5 60 1 2 3 4

7

i j

281/310

Department of Mathematics and Computer Science Block IQ 1

Array example 3 – Sorting an array

3 4 5 60 1 2 3 4

7

i j

282/310

Department of Mathematics and Computer Science Block IQ 1

References to arrays

Creating an array actually creates a reference to an array. This means thatmethods actually can modify array entries. So be careful when you think youare using Reference by value in a method. Suppose we have the following tomethods:

public static void changeArray1(double[] numbers) {numbers = new double[] {1, 2, 4};

}

public static void changeArray2(double[] numbers) {numbers[0] = 1;numbers[1] = 2;numbers[2] = 4;

}

Do these methods change the original array?

283/310

Department of Mathematics and Computer Science Block IQ 1

References to arrays

public static void printArray(double[] array) {for (int i = 0; i < array.length; i++)

System.out.print(array[i]+" ");System.out.println();

}

public static void main(String[] arg) {double[] array = {5, 6, 7};printArray(array);changeArray1(array);printArray(array);changeArray2(array);printArray(array);

}

284/310

Department of Mathematics and Computer Science Block IQ 1

References to arrays

285/310

Department of Mathematics and Computer Science Block IQ 1

References to arrays

public static void changeArray1(double[] numbers) {numbers = new double[] {1, 2, 4};

}

a r r a y

75 60 1 2

286/310

Department of Mathematics and Computer Science Block IQ 1

References to arrays

public static void changeArray1(double[] numbers) {numbers = new double[] {1, 2, 4};

}

a r r a y

75 60 1 2

n u m b e r s

287/310

Department of Mathematics and Computer Science Block IQ 1

References to arrays

public static void changeArray1(double[] numbers) {numbers = new double[] {1, 2, 4};

}

a r r a y

75 60 1 2

n u m b e r s

41 20 1 2

288/310

Department of Mathematics and Computer Science Block IQ 1

References to arrays

public static void changeArray2(double[] numbers) {numbers[0] = 1;numbers[1] = 2;numbers[2] = 4;

}

a r r a y

75 60 1 2

n u m b e r s

289/310

Department of Mathematics and Computer Science Block IQ 1

References to arrays

public static void changeArray2(double[] numbers) {numbers[0] = 1;numbers[1] = 2;numbers[2] = 4;

}

a r r a y

71 60 1 2

n u m b e r s

290/310

Department of Mathematics and Computer Science Block IQ 1

References to arrays

public static void changeArray2(double[] numbers) {numbers[0] = 1;numbers[1] = 2;numbers[2] = 4;

}

a r r a y

71 20 1 2

n u m b e r s

291/310

Department of Mathematics and Computer Science Block IQ 1

References to arrays

public static void changeArray2(double[] numbers) {numbers[0] = 1;numbers[1] = 2;numbers[2] = 4;

}

a r r a y

41 20 1 2

n u m b e r s

292/310

Department of Mathematics and Computer Science Block IQ 1

References to arrays

• since an array variable is actually only a reference to an array, “pass byvalue” only creates a new local array variable that references to the samearray. This means that you can actually replace the items in an array (butnot the array size!)

• to prevent mistakes, always create a copy of the array at the beginning ofa method:

public static void changeArray2(double[] numbers){double numbersCopy = new double[numbers.length];for (int i = 0; i < numbersCopy.length; i++)numbersCopy[i] = numbers[i];

...}

Whatever you do to numbersCopy will not affect the original array num-bers.

293/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

Until now we only created one-dimensional arrays. It is also possible to createmultidimensional arrays.

294/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays – Example

295/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays – Example

int[][] matrix;

Declaration: matrix is a two-dimensional array of integers. At this point matrixequals null, which is the value of an Object that has been declared, but hasnot been initialised (constructed) yet.

296/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays – Example

int[][] matrix;matrix = new int[3][5];

m a t r i x0 1 2 3 4

0

1

2

297/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays – Example

int[][] matrix;matrix = new int[3][5];matrix[2][0] = 7;

m a t r i x0 1 2 3 4

7

0

1

2

298/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays – Example

int[][] matrix;matrix = new int[3][5];matrix[2][0] = 7;for (int i = 0; i < matrix.length; i++)for (int j = 0; j < matrix[i].length; j++)matrix[i][j] = i * matrix[i].length + j;

m a t r i x

0 1 2 30 1 2 3 4

45 6 7 8 91 0 1 1 1 2 1 3 1 4

0

1

2

299/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

In Java a multidimensional array is in fact an array of arrays. To obtain thelengths of multidimensional arrays we have to determine the size of each di-mension:

double[][][] a = new double[7][10][14];int d1 = a.length; // d1 = 7int d2 = a[0].length; // d2 = 10int d3 = a[1].length; // d3 = 10int d4 = a[0][1].length; // d3 = 14

300/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

This makes it possible to create ragged arrays: an array with rows of unequallengths:

double[][] triangle = {{1, 2, 3, 4},{5, 6, 7},{8, 9},{10}};

301/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

This makes it possible to create ragged arrays: an array with rows of unequallengths:

double[][] triangle = {{1, 2, 3, 4},{5, 6, 7},{8, 9},{10}};

int d1 = triangle.length; // d1 = 4int d2 = triangle[0].length; // d2 = 4int d3 = triangle[1].length; // d3 = 3int d4 = triangle[2].length; // d4 = 2int d5 = triangle[3].length; // d5 = 1

302/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

Alternative constructor for ragged arrays:

303/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

Alternative constructor for ragged arrays:

double[][] triangle = new double[4][];

304/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

Alternative constructor for ragged arrays:

double[][] triangle = new double[4][];triangle[0] = new double[4];triangle[1] = new double[3];triangle[2] = new double[2];triangle[3] = new double[1];

305/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

Alternative constructor for ragged arrays:

double[][] triangle = new double[4][];triangle[0] = new double[4];triangle[1] = new double[3];triangle[2] = new double[2];triangle[3] = new double[1];int n = 1;

306/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

Alternative constructor for ragged arrays:

double[][] triangle = new double[4][];triangle[0] = new double[4];triangle[1] = new double[3];triangle[2] = new double[2];triangle[3] = new double[1];int n = 1;for (int i = 0; i < triangle.length; i++) {

}

307/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

Alternative constructor for ragged arrays:

double[][] triangle = new double[4][];triangle[0] = new double[4];triangle[1] = new double[3];triangle[2] = new double[2];triangle[3] = new double[1];int n = 1;for (int i = 0; i < triangle.length; i++) {for (int j = 0; j < triangle[i].length; j++) {

}}

308/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

Alternative constructor for ragged arrays:

double[][] triangle = new double[4][];triangle[0] = new double[4];triangle[1] = new double[3];triangle[2] = new double[2];triangle[3] = new double[1];int n = 1;for (int i = 0; i < triangle.length; i++) {for (int j = 0; j < triangle[i].length; j++) {triangle[i][j] = n;

}}

309/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

Alternative constructor for ragged arrays:

double[][] triangle = new double[4][];triangle[0] = new double[4];triangle[1] = new double[3];triangle[2] = new double[2];triangle[3] = new double[1];int n = 1;for (int i = 0; i < triangle.length; i++) {for (int j = 0; j < triangle[i].length; j++) {triangle[i][j] = n;n++;

}}

310/310

Department of Mathematics and Computer Science Block IQ 1

Multidimensional arrays

Alternative constructor for ragged arrays:

double[][] triangle = new double[4][];triangle[0] = new double[4];triangle[1] = new double[3];triangle[2] = new double[2];triangle[3] = new double[1];int n = 1;for (int i = 0; i < triangle.length; i++) {for (int j = 0; j < triangle[i].length; j++) {triangle[i][j] = n;n++;

}}printMatrix(triangle);