Methods in the Main Class

Chapter 5
Jonas Lundberg, office B3024
Jonas.Lundberg@lnu.se
Slides and Java examples are available in Moodle
November 26, 2014

The Software Technology Group
Methods in the Main Class

1(20)

Chapter 5
I

Methods in the Main class

I

Construction your own methods

I

Rules and Terminology

I

Method Overloading

I

Best Practice

I

Arguments to the main Method

I

Call-by-Value vs Call-by-Reference

Reading Instructions: Chapter 5
Exercises: Assignment 3, Exercises 1-2.

The Software Technology Group
Methods in the Main Class

2(20)

Example: Using library methods
We have used methods defined in library classes many times
I

Ordinary (instance) method calls
String text = "Hello Java!";
int length = text.length();
char first = text.charAt(0);

// Object creation
// ==> length = 11
// ==> first = ’H’

I

Call pattern: variableName.methodName(. . .)
where variableName holds a reference to a specific String object.
⇒ methods are called on objects

I

Static method calls
double d = Math.sqrt(2.0);
char c = Character.toUpperCase(’a’);

I

// ==> d = 1.4142..
// ==> c = ’A’

Call pattern: className.methodName(. . .)
⇒ methods are called on classes

Introduction to Methods
Methods in the Main Class

The Software Technology Group
3(20)

Example: (MethodsInMain.java)
public static void main(String [] args) {
String [] str = {”Do”,”Re”,”Mi”,”Fa”,”So”,”La”};
str = reverseOrder( str );
// La,So,Fa,Mi,Re,Do
swapPosition( str ,1,3);
// La,Mi,Fa,So,Re,Do
for ( String s : str )
System.out. print (s+” ”);

// Print them all

}
private static String [] reverseOrder ( String [] in ) {
String [] out = new String[in . length ];
for ( int i = in. length−1; i>=0; i−−)
out[ in . length−1 − i] = in[ i ];
return out;
}
private static void swapPosition( String [] str , int p, int q) {
String tmp = str[p ];
str [p] = str [q ];
str [q] = tmp;
}
Introduction to Methods
Methods in the Main Class

The Software Technology Group
4(20)

Explaining (MethodsInMain.java)
I

The main method calls 2 methods (reverseOrder and swapPosition)

I

Both these methods are defined in the same class (MethodsInMain) as
the main method

I

Call within a class ⇒ no need to point out call target
⇒ no need for variableName.methodName(. . .) or
className.methodName(. . .)

I

public ⇒ public access ⇒ everyone can use it

I

private ⇒ can only be used by other methods inside the same class

I

Recommendation: use public when you expect other classes to call it,
otherwise private.

Introduction to Methods
Methods in the Main Class

The Software Technology Group
5(20)

Method Calls in Detail
public static void main(String [] args) {
String [] str = {”Do”,”Re”,”Mi”,”Fa”,”So”,”La”};
str = reverseOrder( str );
// str = [La,So,Fa,Mi,Re,Do]
...
}
private static String [] reverseOrder ( String [] in ) {
String [] out = new String[in . length ];
for ( int i = in. length−1; i>=0; i−−)
out[ in . length−1 − i] = in[ i ];
return out;
}
I When making call str = reverseOrder(str), execution halts in main and

continues in method reverseOrder
I The call argument str = [Do,Re,Mi,Fa,So,La] in the call

reverseOrder(str) is transfered to the method parameter in in method
reverseOrder(String[] in).
I Execution continues in reverseOrder(String[] in) until we reach return.
I return out ⇒ the result out = [La,So,Fa,Mi,Re,Do] is transfered back the
receiving variable str in the main method.
Introduction to Methods
Methods in the Main Class

The Software Technology Group
6(20)

Rules and Vocabulary
public static void main(String [] args) {
String [] str = {”Do”,”Re”,”Mi”,”Fa”,”So”,”La”};
str = reverseOrder( str );
// str = [La,So,Fa,Mi,Re,Do]
...
}
private static String [] reverseOrder ( String [] in ) {
...
return out;
}

Method Calls:
I A call has zero or more arguments and will receive zero or one result
I Consider it as if we are assigning the argument str to the method
parameter in, and that we are assigning the return value (out) to the
receiving variable str.
Method Parameters and Return Types:
I A method has zero or more parameters and will return zero or one result
I Number of arguments must (of course) match the number of parameters.
Rules and Vocabulary
Methods in the Main Class

The Software Technology Group
7(20)

Signature and Types
public static void main(String [] args) {
String [] str = {”Do”,”Re”,”Mi”,”Fa”,”So”,”La”};
str = reverseOrder( str );
// str = [La,So,Fa,Mi,Re,Do]
...
}
private static String [] reverseOrder ( String [] in )
// Method Signature
{
...
// Method Body
return out;
}
I

A method has a signature and a body

I

Each parameter comes with a type (String[]) and a name (in)

I

The signature also defines a return type (String[])

I

The type of the call argument str must match the parameter type

I

The returned value (out) must match the return type

Rules and Vocabulary
Methods in the Main Class

The Software Technology Group
8(20)

More Method Examples (RandomArrays.java)
public static void main(String [] args) {
int [] arr = getRandomArray(3,100);
if (areAllEven( arr ))
System.out. println (”All elements are even: ”+Arrays.toString( arr ));
}
private static int [] getRandomArray(int arraySize, int maxValue) {
Random rand = new Random();
int [] result = new int[ arraySize ];
// Empty result array
for ( int i =0; i<arraySize; i ++)
result [ i ] = rand.nextInt(maxValue);
// Add random values
return result ;
}
private static boolean areAllEven( int [] array ) {
for ( int n : array )
if (n%2 == 1)
// if odd, interupt iteration
return false ;
// and return false
return true ;
// Every element is even!
}
Rules and Vocabulary
Methods in the Main Class

The Software Technology Group
9(20)

Methods Returning void
private static void printArray ( int [] intArray ) {
StringBuilder buf = new StringBuilder ();
buf.append(”[”);
for ( int n : intArray )
buf.append(” ” + n);
buf.append(” ]”);
System.out. println ( buf. toString () );
}
I

The method prints the content of an integer array

I

It does not return any value

I

Return value void ⇒ method does not return anything

Rules and Vocabulary
Methods in the Main Class

The Software Technology Group
10(20)

Many Return Statements
return_type not equal to void ⇒ at least one return statement
public static boolean isPrime(int n) {
if (n <= 0)
return false;
else if (n == 1)
return true;
else {
for (int i=2;i<n;i++) {
if ( n%i == 0)
return false;
}
}
return true;
}

public static int sum(int n) {
int sum = 0;
for (int i=1;i<=n;i++) {
sum = sum + i;
}
return sum;
}
public static int div(int a, int b) {
if (b != 0)
return a/b;
} // An incorrect method!
// Each possible execution path
// must end with a return statement

I In general: return Expr where Expr is an expression of correct type
I return ⇒ the method execution is terminated
I Each possible execution path must end with a return (of correct type)

or with an exception. (Exceptions are handled in an upcoming lecture.)
Rules and Vocabulary
Methods in the Main Class

The Software Technology Group
11(20)

Overloading Methods
StringBuilder buf = new StringBuilder ();
buf.append(”Hello”);
// Append string
buf.append(345);
// Append int
buf.append(’X’);
// Append char
System.out. println (buf. toString ()); // Hello345X
I

We append different types of values (String,int,char) to the
StringBuilder.

I

We say that the method append is overloaded.

I

⇒ many methods with same name but different parameter types

I

From the StringBuilder API documentation:
I

append(char c), append(String str), append(int n)

And many more methods.
I

Many methods with same name only differing in return type is not allowed.

Rules and Vocabulary
Methods in the Main Class

The Software Technology Group
12(20)

Best Practice
I Methods are named in the same way as variables. That is, camal casing

⇒ starts with a lower case letter and words are separated by upper case letters.
I Try to make your methods reusable ⇒ they should do one thing, and they

should do it in a good way. Example: The method sortAndPrintArray(...)
should be split into method sortArray(...) and printArray(...) since it is
much more likely that each one of the shorter methods can be reused later on
I Methods can be very short:
public static boolean isValidMonthNumber(int month) {
return month > 0 && month < 13;
}
Advantages: Makes the code easier to understand,
we are defining what we mean by a valid month at one place only.
I Do not modify parameter variables
public static boolean convertToSeconds(int hours, int min, int sec) {
sec = hours*3600 + min*60 + sec;
// update parameter sec ==>
return sec;
// OK but considered bad practice
}
Programmers reading the code get confused since they consider method input as
constants.
Best Practice
Methods in the Main Class

The Software Technology Group
13(20)

Best Practice (2)
When to use methods?
I When your program (the main method) starts to get too long
⇒ divide into smaller parts ⇒ divide into methods
I When you repeat the same type of computations (1-4 lines) many times
⇒ make a method of the computation and call it many times.
Advantages: Shorter code and easier to update method (than multiple
occurences of similar code) when error in computation discovered.
I Methods ⇒ name given computations ⇒ makes program easier to understand
public static boolean isValidMonthNumber(int month) {
return month > 0 && month < 13;
}
Usage:

Alternative without methods

int n = ...
if ( isValidMonthNumber(n) ) {
...
}

int n = ...
if (n > 0 && n < 13) {
...
}

The code using isValidMonthNumber(n) is easier to understand. We do not
have to figure out the purpose of the boolean expression n > 0 && n < 13.
Best Practice
Methods in the Main Class

The Software Technology Group
14(20)

Tasks: Provide a Suitable Signture
I

Compute the sum 1 + 2 + 3 + 4 + ... + N

I

Compare if two integer arrays contain the same values

I

Convert all upper to lower case in a string

I

Print a double array and use only two decimals for each element

Best Practice
Methods in the Main Class

The Software Technology Group
15(20)

Tasks: Provide a Suitable Signture
I

Compute the sum 1 + 2 + 3 + 4 + ... + N
int sumUpToN(int maxValue)

I

Compare if two integer arrays contain the same values

I

Convert all upper to lower case in a string

I

Print a double array and use only two decimals for each element

Best Practice
Methods in the Main Class

The Software Technology Group
15(20)

Tasks: Provide a Suitable Signture
I

Compute the sum 1 + 2 + 3 + 4 + ... + N
int sumUpToN(int maxValue)

I

Compare if two integer arrays contain the same values
boolean areEqual(int[] first, int[] second)

I

Convert all upper to lower case in a string

I

Print a double array and use only two decimals for each element

Best Practice
Methods in the Main Class

The Software Technology Group
15(20)

Tasks: Provide a Suitable Signture
I

Compute the sum 1 + 2 + 3 + 4 + ... + N
int sumUpToN(int maxValue)

I

Compare if two integer arrays contain the same values
boolean areEqual(int[] first, int[] second)

I

Convert all upper to lower case in a string
String convertToUpper(String inputString)

I

Print a double array and use only two decimals for each element

Best Practice
Methods in the Main Class

The Software Technology Group
15(20)

Tasks: Provide a Suitable Signture
I

Compute the sum 1 + 2 + 3 + 4 + ... + N
int sumUpToN(int maxValue)

I

Compare if two integer arrays contain the same values
boolean areEqual(int[] first, int[] second)

I

Convert all upper to lower case in a string
String convertToUpper(String inputString)

I

Print a double array and use only two decimals for each element
String toString(double[] doubleArray, String decimalPattern)
... and print using System.out.println( toString(arr) )

Best Practice
Methods in the Main Class

The Software Technology Group
15(20)

Tasks: Provide a Suitable Signture
I

Compute the sum 1 + 2 + 3 + 4 + ... + N
int sumUpToN(int maxValue)

I

Compare if two integer arrays contain the same values
boolean areEqual(int[] first, int[] second)

I

Convert all upper to lower case in a string
String convertToUpper(String inputString)

I

Print a double array and use only two decimals for each element
String toString(double[] doubleArray, String decimalPattern)
... and print using System.out.println( toString(arr) )

The final example: A good implementation of a flexible method
toString(double[] doubleArray, String decimalPattern) is a good candidate for
reuse.
Best Practice
Methods in the Main Class

The Software Technology Group
15(20)

Arguments to main(String[] args)
public class ArgsMain {
public static void main(String [] args) {
System.out. println (”Number of argument: ”+args.length); // Number of arguments
for ( int i =0;i<args.length ; i ++)
System.out. println ( i +”.\t”+args[i ]);
// Print argument
}
}
I

args in the method main is the input to the program

I

String[] args ⇒ the arguments are always strings.
Can be transformed to integer or doubles using the wrapper classes.

I

How to use:
1. Eclipse: Run --> Run Configurations --> arguments
2. Command prompt: java chap7.ArgsMain My three arguments

Try to run my program ArgsMain.java when you get home.
Best Practice
Methods in the Main Class

The Software Technology Group
16(20)

Old Exam Exercise
Considering the following program:
public class AddX {
public static void addTwo(int n) {n = n+2;}
public static void addOne(int[] arr ) {
for ( int i =0;i<arr.length ; i ++)
arr [ i ] = arr[ i ]+1;
}
public static void main(String [] args) {
int a = 5;
addTwo(a);
System.out. println (a );
// Print−out 1
int [] arr = new int []{5,10,15};
addOne(arr);
System.out. println ( arr [1]); // Print−out 2
}
}
What is printed in the two cases? Motivate your answer.
Call-by-X
Methods in the Main Class

The Software Technology Group
17(20)

Two Types of Parameters
I Java separates: 1) Primitive types, and 2) Reference types
I They are treated differently in calls
I Method calls using primitive types

int a = 5;
addTwo(a);

public void addTwo(int n) { // n is assigned a copy
n = n + 2;
// of the argument value a.
}
// Changes in n do NOT
System.out.println(a);
// affect the call
// Print-out 5
// argument a
I A copy of the value is given to method addTwo
I ⇒ The parameter n is independent of a
I ⇒ Changes inside the method do not affect the calling method.
I It is called call-by-value.

Call-by-X
Methods in the Main Class

The Software Technology Group
18(20)

Call-by-Reference and Aliasing
I Calls using reference types

int[] arr = new int[] {5,10,15};
addOne(arr);
System.out.println(arr[1]);
// Print-out 11

public void addOne(int[] n) {
for (int i=0;i<n.length;i++)
n[i] = n[i]+1;
}
// n is assigned a reference to the same
// object referenced by the argument arr.
// Both are referencing the same object
// ==> changes do affect the argument
// used in the code.

I A reference (an object address) is given to the method addOne
I ⇒ The parameter n referenes the same object as argument arr
I ⇒ Changes inside the method do affect the calling method.
I It is called call-by-reference.

To have many active references at a single object is called aliasing. It is a bit
dangerous since changes using one of this references can give unexpected results at
other parts of the program.
Call-by-X
Methods in the Main Class

The Software Technology Group
19(20)

Upcoming Assignments

I

Deadline Assignment 2: 2014-11-30

I

Assignment 3 is now available

I

Deadline Assignment 3: 2014-12-14

I

Assignment 3 is considered to slightly more difficult and slightly
more time consuming than Assignment 2 ⇒ start working now!

Course infomation
Methods in the Main Class

The Software Technology Group
20(20)