You are on page 1of 29

Version control

Sep 14 ● Added version control


● Changed display of outputs for test cases
● Reordered the 4 methods to output “Hello World!”
● Changed colour of test case outputs to green
● Changed colour of code to purple
● Added Java syntax list at the top of document
● Added Good practice list at top of document

Sep 15 ● Moved prime numbers to Computational Challenges

Sep 16 ● Added preamble (description, author, version) in classes


● Added Sublime Text
● Replaced itemisation with enumeration
● Moved recursion to Computational Challenges

Sep 17 ● Added data types

Colour scheme
purple Java code

blue Answer or hint

red Important comment

green Terminal output

Do until you know better...


The following are NOT good coding practices. However, always do it until you understand
why you should not always do it.
● Add the following lines of codes at the start of EVERY NEW classes:
import java.util.*;
import java.lang.*;
import java.io.*;
● Add a main method in EVERY NEW classes:
public static void main (String[] args)
● Start ALL your methods with:
public static

Java syntax
work in progress: this list will be continuously updated
- A semicolon terminates each instructions.
- Blocks of code are enclosed in curly brackets.
- The type of a variable has to be explicitly declared.
- Class names start with a capital letter (e.g. String).
- Extra spaces and carriage return are ignored (cf. good practices).

Good practices
work in progress: this list will be continuously updated
- Preamble: description, author, and version
- Indentation
- Comments
- Explicit variable names e.g. index instead of the letter i
- Camelcase for names of variables and methods e.g. printHelloWorld
- Capital letters and underscores for constant names e.g. MY_CONSTANT
- Test your programs
- Use the debugger

Terminology
work in progress: this list will be continuously updated
- Terminal: input/output
- Variable: declaration, types, assignment
- Method: return type, return statement, main method
- Control flow: conditionals (decision), loops, branching
- Conditional: if-statement, if-block, else-block, switch-case
- Loop: for-loop, while-loop, do-while-loop
- Branching:
- Layout: code-block, indentation, comment
- Data type: int float boolean
- Classes: String

[ optional ] BlueJ
Unless you are already extremely comfortable with an IDE (Integrated Development
Environment), I would recommend that you install BlueJ. This tutorial explains how to create
new projects and classes in BlueJ. This tutorial explains the basic workflow (compiling and
running) in BlueJ. This is all you need at this stage.

● Locate where your project folder is (so that you can find your .java files for
submission).

Hello world!
● Create a new project FirstProgrammes
● Add a new class HelloWorld and copy the code below.
HelloWorld

/**
* <Write a description here.>
* @author <firstname> <LASTNAME>
* @version <submission>.<modification>
* @date <yyyy>.<mm>.<dd>
*/

import java.util.*;
import java.lang.*;
import java.io.*;

public class HelloWorld


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

● Compile and run the main method of the HelloWorld class.


The code above shows how to write a “Hello World!” programme in Java. It is not a minimal
working example in the sense that some lines of code are not necessary for the programme
to work. However, to avoid getting into technicalities right now, I would suggest that you
always import the three standard libraries listed above and always include a main method in
your new classes. If you decide to reuse this code (e.g. by doing copy), make sure you
update the name of the class.

● Add a single-line comment to remind you to change the name of the class if you
decide to copy / paste this code snippet in the future.
Single-line comments start with // until the end of the line

● Add a multi-line comment to remind you to include a main method in your new
classes.
Multi-line comments start with /* and end with */

● Compile and run the main method of the HelloWorld class.


Comments are ignored so your programme should run the same as before.

[ optional ] Sublime Text


Sublime Text offers some very nice functionalities:
- syntax highlighting
- multiple selection: <cmd>+<D>
- code completion
- code folding: <cmd>+<0>
- code snippet: <trigger>+<tab>
- etc…

● Create a new snippet In Sublime Text: Tools\Developer\New Snippet...


● Copy the following code and personalise it: firstname and LASTNAME
● Save your new snippet as: HelloWorld.sublime-snippet

HelloWorld snippet

<snippet>
<content><![CDATA[
/**
* <write a description here>
* @author <firstname> <LASTNAME>
* @version <submission>.<modification>
* @date <yyyy>.<mm>.<dd>
*/

import java.util.*;
import java.lang.*;
import java.io.*;

public class <ClassName>


{
public static void main (String[] args)
{
System.out.println("Hello World!");
}
}
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the
snippet -->
<tabTrigger>helloworld</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will
trigger -->
<scope>source.java</scope>
</snippet>

Data types
For the moment, we will focus on the 3 primitive data types int double boolean and the
class String. Note that String starts with a capital letter because it is a Java convention
for classes (objects).

● Add a new class named DataTypes and copy the code below. Make sure to
personalise the preamble.
DataTypes

/**
* <Write a description here.>
* @author <firstname> <LASTNAME>
* @version <submission>.<modification>
* @date <yyyy>.<mm>.<dd>
*/

import java.util.*;
import java.lang.*;
import java.io.*;

public class DataTypes


{
public static void main(String[] args)
{
int one = 1;
int two = 2;
double root2 = Math.sqrt(2);
boolean bool0 = false;
boolean bool1 = true;
boolean test1 = (one==3/2);
boolean test2 = (two==2.0);
boolean test3 = ((int)root2==1);
boolean test4 = (root2==(float)root2);
System.out.println(test1);
System.out.println(test2);
System.out.println(test3);
System.out.println(test4);
}
}

● Use the information in this article to add a multi-line comment in your DataTypes
class to describe each primitive data types supported by Java.
○ byte
○ short
○ int
○ long
○ float
○ double
○ boolean
○ char

● Compile and run the main method of your DataTypes class. Explain the outputs.
The value of test1 is true because operations on int return int
The value of test2 is true because of implicit data type conversion
The value of test3 is true because of explicit data type conversion
The value of test4 is false because double is more precise than float

● Find how many more decimal places root2 has compared to (float)root2.
Add the following instructions in your main method.
System.out.println(root2);
System.out.println((float)root2);

● Compare and contrast the following sources about data type conversion:
○ primitive type casting
○ conversion and promotion

Terminal IO
● Add a new class named Terminal and copy the code below. Make sure to
personalise your preamble.

Terminal

/**
* <Write a description here.>
* @author <firstname> <LASTNAME>
* @version <submission>.<modification>
* @date <yyyy>.<mm>.<dd>
*/

import java.util.*;
import java.lang.*;
import java.io.*;

public class Terminal


{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();
System.out.print("Choose an integer: ");
int integer = input.nextInt();
System.out.print("Choose another number: ");
double floatingPoint = input.nextDouble();
System.out.printf(
"Hello %s! You chose %d and %f\n"
,name
,integer
,floatingPoint
);
}
}

● Describe the difference between the method println and the method print.
The method println adds a carriage return at the end of the current output so that the next
output starts on a new line

● Compile the class Terminal and run its main method; enter the following on the
terminal and describe what happens.
○ Two integers separated by a space instead of one for the question “Choose
an integer” (2nd question on the terminal)
The 1st integer is used as the answer of the 2nd question and the 2nd integers is used as
the answer for the 3rd question.
○ A sentence for “Enter your name” (1st question on the terminal). Compare
and contrast this behaviour with the one observed in the previous experiment.
The whole line (including spaces) is read until a carriage return symbol is found.
○ An integer for the last question
The integer is still outputted as a float (i.e. with a decimal point).
Java automatically converts int into float when it expects an object of type float.
○ A decimal number (e.g. 1.2) instead of an integer for the question “Choose an
integer” (2nd question on the terminal)
A runtime error is triggered: java.util.InputMismatchException
Java does not convert float into int even if an object of type int is expected.

● List some features of Java syntax. Make sure to keep your list up-to-date with any
new features you encounter.
cf. list at the top of document

Conditionals
● Add a new class Conditionals and copy the code below.

Conditionals

/**
* <Write a description here.>
* @author <firstname> <LASTNAME>
* @version <submission>.<modification>
* @date <yyyy>.<mm>.<dd>
*/
import java.util.*;
import java.lang.*;
import java.io.*;

public class Conditionals


{
public static void main (String[] args)
{
int myNumber = 1;
if (myNumber%2==0)
{
System.out.println("The number is even.");
} else
{
System.out.println("The number is odd.");
}
}
}

● Compile and run the main method of the class Conditionals class. Change one
character in your programme so that the outputs become “The number is even.”
Change the value of myNumber to any even number of your choice.

● List some good practices when writing code. Make sure you keep your list up-to-date.
cf. list at the top of document

● Modify the programme above so that it only uses one println instruction.
Create a String variable called message that is instantiated to "The number is ".
String message = “The number is ”;
Replace the first println statement (in the if-block) by:
message += “even.”;
Replace the second println statement (in the else-block) by:
message += “odd.”;
Add the following line of code at the end of the main method:
System.out.println(message);

● Explain the advantages and limitations of only using one println instruction.
The code might be easier to maintain. However, it might become harder to understand. This
reinforces the importance of good coding practices. This is a delicate balance to achieve.

● Add a conditional to check if myNumber is NOT negative.


SOLUTION 1: use an if-statement with the following condition:
!(myNumber<0)
SOLUTION 2: use an if-statement with the following condition:
myNumber>=0
NOT negative is equivalent to positive OR zero.
● Add a conditional to check if myNumber is between 1 (included) and 9 (included)
Use an if-statement with the following condition:
(myNumber>0) && (myNumber<10)

● Add a conditional to check if myNumber is a multiple of 3 or a multiple of 5.


Use an if-statement with the following condition:
(myNumber%3==0) || (myNumber%5==0)

Loops
● Add a new class called Loops and copy the code below. Make sure to personalise
your preamble.

Loops

/**
* <Write a description here.>
* @author <firstname> <LASTNAME>
* @version <submission>.<modification>
* @date <yyyy>.<mm>.<dd>
*/

import java.util.*;
import java.lang.*;
import java.io.*;

public class Loops


{
public static void main (String[] args)
{
//version 0
for (int count=1; count<=10; count++)
{
System.out.println("Hello World!");
}
//version 1
for (int count=0; count<10; count++)
{
System.out.println("Hello World!");
}
//version 2
for (int count=0; count<10; count=count+1)
{
System.out.println("Hello World!");
}
//version 3
int countWhileDo=0;
while (countWhileDo<10)
{
System.out.println("Hello World!");
countWhileDo++;
}
//version 4
int countDoWhile=0;
do
{
System.out.println("Hello World!");
countDoWhile++;
}
while (countDoWhile<10);
}
}

● Compile and run the main method of the Loops class. All 4 loops output “Hello
World!” 10 times to the terminal. Compare and contrast the syntax of each loop.
Version 0 seems more natural; it starts at 1 and goes up to 10 (included)
Version 1 is preferred when dealing with arrays (cf. section on arrays)
Version 2 replaces the shorthand index++ by its definition index=index+1
Version 3 uses a while-do-loop (also called while-loop)
Version 4 uses a do-while-loop
The context of your programme will dictate which type of loops to use.

● Comment (use <F8> in BlueJ) the instruction countWhileDo++ in the while-do-loop


(version 3) or the instruction countDoWhile++ in the do-while-loop (version 4).
Compile and run the main method of the class Loop. Describe what happens.
Without this instruction, the while-do-loop does not stop. It is very important that you add
instructions to your while-loops to update the loop-counter because this error is not caught
automatically; your programme might run indefinitely (infinite loop).
To stop your programme in BlueJ, open the Debugger window (<ctrl>+<D> on a PC and
<cmd>+<D> on a Mac) then click the Terminate button.

The expressions in a for-loop are optional; an infinite loop can be created as simply as
follows: for(;;){}. There are many ways to make infinite loops.

● Copy / paste the following method into your Loop class.

Infinite loops

public static void infinite()


{
//for(;1>0;){}
//while(1>0){}
//do{}while(1>0);
//for(;true;){}
//while(true){}
//do{}while(true);
int n=1;
//for(;n>0;){}
//while(n>0){}
//do{}while(n>0);
System.out.println();
}

● Uncomment each line of code one at a time and compile your programme. Hence,
compare and contrast the following pieces of code.

int n=1;
//for(;true;){} //for(;1>0;){} //for(;n>0;){}
//while(true){} //while(1>0){} //while(n>0){}
//do{}while(true); //do{}while(1>0); //do{}while(n>0);

If you uncomment any of the lines in the first two columns, it will trigger a compilation error
(unreachable statement) because the compiler can identify that the System.out.println
will never be executed. However, the code in the last column does not trigger such
compilation error because the compiler cannot recognise if a boolean expression that
involves at least one variable is always true (deciding if there is any valuation that makes a
boolean expression true is a very difficult theoretical problem cf. tautology). This is another
common way to unexpectedly create an infinite loop.

● Modify your programme so that each loop outputs “Hello World!” to the terminal 20
times. Suggest a modification to your programme that will allow to change the
number of times “Hello World!” is outputted to the terminal by only changing one
parameter.
Replace the numeral 10 by the variable numberOfTimes and add the following line of code
as the first statement in the main method:
int numberOfTimes = 10;
Note that you need to declare the type of a variable in Java even if the value you assign to
your variable implicitly defines a type.
In the example above, the variable numberOfTimes is of type int (integer) that has to be
declared even though the numeral 10 is of type int too.

It is good practice to keep the main method as simple as possible. To do so, you can move
blocks of codes outside of the main method by creating additional methods.

● Replace the code in your Loops class by the code below and copy each loop
statement into its corresponding new method.

Loops (bis repetita)


/**
* <Write a description here.>
* @author <firstname> <LASTNAME>
* @version <submission>.<modification>
* @date <yyyy>.<mm>.<dd>
*/

import java.util.*;
import java.lang.*;
import java.io.*;

public class Loops


{
public static void main (String[] args)
{
//Hello World!
int numberOfTimes = 10;
System.out.println("version 0");
v0_printHelloWorld(numberOfTimes);
System.out.println("version 1");
v1_printHelloWorld(numberOfTimes);
System.out.println("version 2");
v2_printHelloWorld(numberOfTimes);
System.out.println("version 3");
v3_printHelloWorld(numberOfTimes);
System.out.println("version 4");
v4_printHelloWorld(numberOfTimes);
System.out.println();
}
public static void v0_printHelloWorld(int numberOfTimes)
{
//the code for version 0 goes here
}
public static void v1_printHelloWorld(int numberOfTimes)
{
//the code for version 1 goes here
}
public static void v2_printHelloWorld(int numberOfTimes)
{
//the code for version 2 goes here
}
public static void v3_printHelloWorld(int numberOfTimes)
{
//the code for version 3 goes here
}
public static void v4_printHelloWorld(int numberOfTimes)
{
//the code for version 4 goes here
}
}

● Change the value of numberOfTimes to 0. Compile and run your programme.


Describe what happens. Compare and contrast the syntax of a do-while-loop and a
while-do-loop.
The do-while-loop (version 4) outputs “Hello World!” to the terminal. The do-block of a do-
while-loop is always executed at least once irrespective the while-condition because the do-
while-loop evaluates its while-condition after the do-block.

● Write a java method that outputs the integers from 0 to a given number. The
signature of your method should be:
public static void printIntegersTo(int limit)
The following instructions:
printIntegersTo(10);
should output to the terminal:
0 1 2 3 4 5 6 7 8 9 10

● Write 4 java methods that outputs the even integers from 0 to a given number. Each
of your method should illustrate a different aspect of loops in Java. Compare and
contrast your different methods.
Use number%2==0 in a if-statement to check if number is even.
Replace index++ by index=index+2 in the for-loop.
Use 2*index<=limit in a while-do-loop.
Use 2*index<=limit in a do-while-loop.
The signature of your methods should be:
public static void v1_printEvenIntegersTo(int limit)
public static void v2_printEvenIntegersTo(int limit)
public static void v3_printEvenIntegersTo(int limit)
public static void v4_printEvenIntegersTo(int limit)
The following instructions:
v1_printEvenIntegersTo(20);
v2_printEvenIntegersTo(20);
v3_printEvenIntegersTo(20);
v4_printEvenIntegersTo(20);
should output to the terminal:
0 2 4 6 8 10 12 14 16 18 20
0 2 4 6 8 10 12 14 16 18 20
0 2 4 6 8 10 12 14 16 18 20
0 2 4 6 8 10 12 14 16 18 20

●Write a java method that outputs the multiples of 3 and 5 from 0 to a given number.
The signature of your method should be:
public static void printMultiplesOf3And5To(int limit)
The following instructions:
printMultiplesOf3And5To(20);
should output to the terminal:
0 15

● Write a java method that outputs the multiples of 3 or 5 from 0 to a given number.
The signature of your method should be:
public static void printMultiplesOf3Or5To(int limit)
The following instructions:
printMultiplesOf3Or5To(20);
should output to the terminal:
0 3 5 6 9 10 12 15 18 20

● Write a java method that outputs the squares from 0 to a given number. The
signature of your method should be:
public static void printSquaresTo(int limit)
The following instructions:
printSquaresTo(10);
should output to the terminal:
0149

● Add the below method to your Loops class.

Accumulators

public static int getSumOfIntegersTo(int limit)


{
int sum = 0;
for (int number=0; number<=limit; number++)
{
sum += number;
}
return sum;
}

● Add a for-loop in the main method that outputs the sum of integers:
○ From 0 to 1
○ From 0 to 2
○ From 0 to 3
○ From 0 to 4
○ From 0 to 5
○ From 0 to 6
○ From 0 to 7
○ From 0 to 8
○ From 0 to 9
○ From 0 to 10
Use the getSumOfIntegersTo method in conjunction with the println instructions. The
output to the terminal should be:
1
3
6
10
15
21
28
36
45
55
By using simple pieces of code, we can build more complex programmes. This is a paradigm
we will be using throughout this course.

● Write a java method that returns the sum of even integers from 0 to a given number.
The signature of your java methods should be:
public static int getSumOfEvenIntegersTo(int limit)
The following instructions:
System.out.println(getSumOfEvenIntegersTo(10));
should output to the terminal:
30

● Write a java method that returns the sum of multiples of 3 and 5 from 0 to a given
number. The signature of your java methods should be:
public static int getSumOfMultiplesOf3And5To(int limit)
The following instructions:
System.out.println(getSumOfMultiplesOf3And5To(20));
should output to the terminal:
15

● Write a java method that returns the sum of multiples of 3 or 5 from 0 to a given
number. The signature of your java methods should be:
public static int getSumOfMultiplesOf3Or5To(int limit)
The following instructions:
System.out.println(getSumOfMultiplesOf3Or5To(10));
should output to the terminal:
33

● Write a java method that returns the sum of square numbers from 0 to a given
number. The signature of your java methods should be:
public static int getSumOfSquaresTo(int limit)
The following instructions:
System.out.println(getSumOfSquaresTo(10));
should output to the terminal:
14

● Write a java method that outputs (on the same line) the cubes from 1 to a given
number. The signature of your method should be:
public static void printCubesTo(int limit)
The following instructions:
printCubesTo(10);
should output to the terminal:
018

● Write a java method that returns the sum of cubes from 1 to a given number. The
signature of your method should be:
public static int getSumOfCubesTo(int limit)
The following instructions:
System.out.println(getSumOfCubesTo(10));
should output to the terminal:
9

Arrays
The code below demonstrates some basic operations with arrays in Java. Note that the
index of the first element of an array is 0; hence, the index of the last element of an array is
equal to its length minus 1; for example, in the programme below, myFirstArray.length
returns the numeral 9 (i.e. the array has 9 elements) which means that myFirstArray[8]
is the last element (i.e. 8 is the index of the last element).

● Add a new class called Arrays and copy the code below. Make sure to personalise
your preamble.

Arrays

/**
* <Write a description here.>
* @author <firstname> <LASTNAME>
* @version <submission>.<modification>
* @date <yyyy>.<mm>.<dd>
*/

import java.util.*;
import java.lang.*;
import java.io.*;

public class Arrays


{
public static void main(String[] args)
{
int[] myFirstArray = {1,2,3,4,5,6,7,8,9};
System.out.println(myFirstArray[0]);//output 1st element
System.out.println(myFirstArray[1]);//output 2nd element
System.out.println(myFirstArray[2]);//output 3rd element
System.out.println(myFirstArray[3]);//output 4th element
System.out.println(myFirstArray[4]);//output 5th element
System.out.println(myFirstArray[5]);//output 6th element
System.out.println(myFirstArray[6]);//output 7th element
System.out.println(myFirstArray[7]);//output 8th element
System.out.println(myFirstArray[8]);//output 9th element
System.out.println(myFirstArray.length);//output length
// System.out.println(myFirstArray);
}
}

● Create a new array named mySecondArray whose elements are {1,1,1,1,2,3}.


int[] mySecondArray = {1,1,1,1,2,3};
The following instructions:
System.out.println(mySecondArray.length);
should output to the terminal:
6

● Create a new array named emptyArray that does not contain any element.
int[] emptyArray = {};
The following instructions:
System.out.println(emptyArray.length);
should output to the terminal:
0

It is good practice to also test your methods on exceptional cases (such as empty arrays) so
that you can check if all possible behaviours are properly handled.

● Remove the last // in the main method. Describe what happens.


You get the physical address of the array in memory. If you want to print the elements of an
array you need to loop through its elements one by one.


Write a java method that outputs the elements of an array on the same line. Use
System.out.print instead of System.out.println and make sure you add a
space in between outputs so that you can read the elements of your array easily. The
signature of your method should be:
public static void printArray(int[] arrayOfIntegers)
The following instructions:
printArray(new int[] {1,2,3,4,5,6,7,8,9});
should output to the terminal:
123456789


Write a java method that returns the sum of the elements of an array (your method
should return 0 if the array given is empty). The signature of your method should be:
public static int getSum(int[] arrayOfIntegers)
The following instructions:
System.out.println(getSum(new int[] {1,2,3,4,5,6,7,8,9}));
should output to the terminal:
45

●Write a java method that returns the product of the elements of an array (your
method should return 1 if the array given is empty). The signature of your method
should be:
public static int getProduct(int[] arrayOfIntegers)
The following instructions:
System.out.println(getProduct(new int[] {1,2,3,4,5,6,7,8,9}));
should output to the terminal:
362880


Write a java method that returns the number of elements in an array that are equal to
a given value. The signature of your method should be:
public static int count(int value, int[] inArray)
The following instructions:
System.out.println(count(1,new int[] {1,1,1,1,2,3}));
should output to the terminal:
4


Write a java method that returns the maximum value of an array (your method should
return Integer.MIN_VALUE - this is the smallest value an integer can take - if the
array given is empty). The signature of your method should be:
public static int getMaximum(int[] arrayOfIntegers)
The following instructions:
System.out.println(getMaximum(new int[] {1,1,1,1,2,3}));
should output to the terminal:
3


Write a java method that returns the index of the first element of the array that is
equal to the maximum value of the array (your method should return -1 if the array
given is empty). The signature of your method should be:
public static int getFirstIndexOfMaximum(int[] arrayOfIntegers)
The following instructions:
System.out.println(getFirstIndexOfMaximum(new int[] {1,1,1,1,2,3}));
should output to the terminal:
5


Write a java method that returns the minimum value of an array (your method should
return Integer.MAX_VALUE if the array given is empty). The signature of your
method should be:
public static int getMinimum(int[] arrayOfIntegers)
The following instructions:
System.out.println(getMinimum(new int[] {1,1,1,1,2,3}));
should output to the terminal:
1
● Write a java method that returns the index of the first element of the array that is
equal to the minimum value of the array (your method should return -1 if the array
given is empty). The signature of your method should be:
public static int getFirstIndexOfMinimum(int[] arrayOfIntegers)
The following instructions:
System.out.println(getFirstIndexOfMinimum(new int[] {1,1,1,1,2,3}));
should output to the terminal:
0

● Write a java method that returns true if a given value is found in an array and
false otherwise (your method should return false if the array given is empty). The
signature of the method should be:
public static boolean isElement(int element, int[] ofArray)
The following instructions:
System.out.println(isElement(0,new int[] {1,2,3}));
System.out.println(isElement(1,new int[] {1,2,3}));
should output to the terminal:
false
true

● Write a java method that returns the index of the first element that is equal to a given
value (your method should return -1 if the value given is not found). The signature of
the method should be:
public static int getFirstIndex(int ofValue, int[] inArray)
The following instructions:
System.out.println(getFirstIndex(1,new int[] {1,1,1}));
System.out.println(getFirstIndex(0,new int[] {1,1,1}));
should output to the terminal:
0
-1

● The code below illustrate how to return an array as a value of a method. Add the
method getIntegersTo to your Arrays class.

Arrays (bis repetita)

public static int[] getIntegersTo(int limit)


{
int numberOfElements = limit + 1;
int[] arrayOfIntegers = new int[numberOfElements];
for(int index=0; index<numberOfElements; index++)
{
arrayOfIntegers[index] = index;
}
return arrayOfIntegers;
}
● Use the method getIntegersTo to create a new variable myThirdArray that
contains the integers from 0 to 100 included.
int[] myThirdArray = getIntegersTo(100);

● Use a println instructions to output the last element of myThirdArray.


System.out.println(myThirdArray[100]);//outputs 100

● Describe and explain what happens when you use the following instructions:
myThirdArray[101]=101;
This triggers the runtime error java.lang.ArrayIndexOutOfBoundsException (the
programme compiles but does not run).
The size of an array is fixed and cannot be changed.

● Write a java method that compares two arrays; two arrays are equal when: (i) they
have the same length; and (ii) corresponding elements (i.e. elements at the same
index) are equal. The signature of your method should be:
public static boolean isEqual(int[] array1, int[] array2)
The following instructions:
System.out.println(isEqual(new int[] {0,1},new int[] {0,1,2}));
should output to the terminal:
false

● Write a java method that returns a new array whose elements are in reverse order.
The signature of your method should be:
public static int[] reverse(int[] arrayOfIntegers)
The following instructions:
printArray(reverse(new int[] {1,2,3,4}));
should output to the terminal:
4321

● Write a java method that returns a new array with an additional element at the end.
The signature of your method should be:
public static int[] addTail(int newElement, int[] toArray)
The following instructions:
printArray(addTail(0,new int[] {1,2,3,4}));
should output to the terminal:
12340

● Write a java method that returns a new array with an additional element at the start.
The signature of your method should be:
public static int[] addHead(int newElement, int[] toArray)
The following instructions:
printArray(addHead(0,new int[] {1,2,3,4}));
should output to the terminal:
01234
● Write a java method that returns the number of elements of an array that are lower
than or equal to a given limit. Elements of same value should only be counted once.
The signature of your method should be:
public static int countOnceValuesLessThan(
int limit, int[] inArray)
The following instructions:
System.out.println(countOnceValuesLessThan(
3,new int[] {1,2,2,3,4}));
should output to the terminal:
3

● Write a java method that returns a new array whose elements are the elements of a
given array that are at the indices given (assume that the indices given have no
duplicates and are all within the range of possible indices for the given array). The
order of the elements in the new array should match the order of the indices given.
The signature of your method should be:
public static int[] keepNewOrder(int[] indices, int[] inArray)
The following instructions:
printArray(keepNewOrder(new int[] {1,0},new int[] {2,3,4,5,6}));
should output to the terminal:
32

● Write a java method that returns a new array whose elements are the elements of a
given array that are at the indices given (assume that the indices given have no
duplicates and are all within the range of possible indices for the given array). The
order of the elements in the new array should match the order of the elements in the
given array. The signature of your method should be:
public static int[] keepOldOrder(int[] indices, int[] inArray)
The following instructions:
printArray(keepOldOrder(new int[] {1,0},new int[] {0,1,2,3,4}));
should output to the terminal:
01

● The first method below shows how to use a switch statement to choose which
method to use. The second method below shows how to use polymorphism to define
a default value for an argument; this is called a wrapper method. Copy / paste the
code below into your Array class and uncomment the line that you think is the most
natural for the method keep(). Justify your answer.

Example of switch statement

public static int[] keep(


int[] indices,
int[] inArray,
String order
)
{
switch (order)
{
case "new":
return keepNewOrder(indices,inArray);
case "old":
return keepOldOrder(indices,inArray);
default:
return inArray;
}
}
public static int[] keep(int[] indices, int[] inArray)
{
//return keepNewOrder(indices, inArray);
//return keepOldOrder(indices, inArray);
}

● Write a java method that returns a new array whose elements are the elements of a
given array that are not at the indices given (assume that the indices given have no
duplicates and are all within the range of possible indices for the given array). The
signature of your method should be:
public static int[] remove(int[] indices, int[] inArray)
The following instructions:
printArray(remove(new int[] {0,1},new int[] {0,1,2,3,4}));
should output to the terminal:
234

● Write a java method that returns a new array whose elements are the indices at
which to find a given value (your method should return an empty array if the value is
not found). The signature of your method should be:
public static int[] find(int value, int[] inArray)
The following instructions:
printArray(find(1,new int[] {1,1,1,2,3,4}));
System.out.println(find(0,new int[] {1,2,3,4}).length);
should output to the terminal:
012
0

● Write a java method that returns a new array without any elements that are equal to
the value given. The signature of your method should be:
public static int[] trim(int value, int[] inArray)
The following instructions:
printArray(trim(1,new int[] {1,1,1,2,3,4}));
should output to the terminal:
234
● Write a java method that returns a new array that combines two arrays. The
signature of your method should be:
public static int[] append(int[] elements, int[] toArray)
The following instructions
printArray(append(new int[] {1,2},new int[] {3,4}));
should output to the terminal:
1234

● Write a java method that returns an array whose elements are the even integers from
0 to a given number (included). The signature of your method should be:
public static int[] getEvenIntegersTo(int limit)
The following instructions:
printArray(getEvenIntegersTo(10));
should output to the terminal:
0 2 4 6 8 10

● Write a java method that returns an array whose elements are the squares from 0 to
a given number. The signature of your method should be:
public static int[] getSquaresTo(int limit)
The following instructions:
printArray(getSquaresTo(20));
should output to the terminal:
0 1 4 9 16

● Write a java method that returns an array whose elements are the multiples of 3 and
5 from 0 to a given number. The signature of your method should be:
public static int[] getMultiplesOf3And5To(int limit)
The following instructions:
printArray(getMutiplesOf3And5To(20));
should output to the terminal:
0 15

● Write a java method that returns an array whose elements are the multiples of 3 or 5
from 0 to a given number. The signature of your method should be:
public static int[] getMultiplesOf3Or5To(int limit)
The following instructions:
printArray(getMutiplesOf3Or5To(20));
should output to the terminal:
0 3 5 6 9 10 12 15 18 20

Branching [work in progress]

Branching
/**
* <Write a description here.>
* @author <firstname> <LASTNAME>
* @version <submission>.<modification>
* @date <yyyy>.<mm>.<dd>
*/

import java.util.*;
import java.lang.*;
import java.io.*;

public class Branching


{
public static void main (String[] args)
{
}
}

More information can be found here.


● break
● continue
● return

Debugger [work in progress]


● Add a new class Debugger and copy the code below.

Debugger

/**
* <Write a description here.>
* @author <firstname> <LASTNAME>
* @version <submission>.<modification>
* @date <yyyy>.<mm>.<dd>
*/

import java.util.*;
import java.lang.*;
import java.io.*;

public class Debugger


{
public static main (String[] args)
{
int maximum = 10;
System.out.println("*** testing for Fibonacci");
for(int index=1;index<maximum; index++)
{
System.out.format("%d ",fibonacciRecursive(index));
}
System.out.println();
for(int index=1;index<maximum; index++)
{
System.out.format("%d ",fibonacciIterative(index));
}
System.out.println();
}
public static int fibonacciRecursive(int rank)
{
switch (rank)
{
case 1:
return 1;
case 2:
return 1;
default:
return fibonacci(rank-1) + fibonacci(rank-2);
}
}
public static int fibonacciIterative(int rank)
{
int term0 = 0;
int term1 = 1;
int term2 = 1;
int index = 0;
do
{
term2 = term0 + term1;
term1 = term2;
term0 = term1;
index++;
}
while (index<rank);
return term2;
}

● Compile and run the main method. Use the debugger to investigate why
fibonacciIterative does not return the same value as
fibonacciRecursive.

Algorithms
● Create a new class named Algorithms and copy / paste the code below. Once you
wrote the new methods described below, you can uncomment the code in the main
method to check that your method work (test cases).
Algorithms

/**
* <Write a description here.>
* @author <firstname> <LASTNAME>
* @version <submission>.<modification>
* @date <yyyy>.<mm>.<dd>
*/

import java.util.*;
import java.lang.*;
import java.io.*;

public class Algorithms


{
public static void main(String[] args)
{
// int[] myArray = new int[] {4,5,2,3,0,1};
// int[] myArrayIncreasing = new int[] {0,1,2,3,4,5};
// int[] myArrayDecreasing = new int[] {5,4,3,2,1,0};

// System.out.println("Sequential search:
"+toString(myArray));
// for (int index=0; index<=myArray.length; index++)
// {
// System.out.printf(" %d can be found at %d\n"
// ,index
// ,sequentialSearch(index,myArray)
// );
// }
// System.out.println("Bubble sort increasing");
// System.out.println(" input before
"+toString(myArrayDecreasing));
// System.out.println(" input sorted
"+toString(bubbleSortIncreasing(myArrayDecreasing)));
// System.out.println(" input after
"+toString(myArrayDecreasing));
// System.out.println("Bubble sort decreasing");
// System.out.println(" input before
"+toString(myArrayIncreasing));
// System.out.println(" input sorted
"+toString(bubbleSortDecreasing(myArrayIncreasing)));
// System.out.println(" input after
"+toString(myArrayIncreasing));
// System.out.println("Selection sort increasing");
// System.out.println(" input before
"+toString(myArrayDecreasing));
// System.out.println(" input sorted
"+toString(selectionSortIncreasing(myArrayDecreasing)));
// System.out.println(" input after
"+toString(myArrayDecreasing));
// System.out.println("Selection sort decreasing");
// System.out.println(" input after
"+toString(myArrayIncreasing));
// System.out.println(" input sorted
"+toString(selectionSortDecreasing(myArrayIncreasing)));
// System.out.println(" input after
"+toString(myArrayIncreasing));

// System.out.println("Binary search:
"+toString(myArrayIncreasing));
// for (int index=0; index<=myArrayIncreasing.length;
index++)
// {
// System.out.printf(" %d can be found at %d\n"
// ,index
//
,binarySearchIncreasing(index,myArrayIncreasing)
// );
// }
// System.out.println("Binary search:
"+toString(myArrayDecreasing));
// for (int index=0; index<=myArrayDecreasing.length;
index++)
// {
// System.out.printf(" %d can be found at %d\n"
// ,index
//
,binarySearchDecreasing(index,myArrayDecreasing)
// );
// }
}
}

● Write a Java method that outputs the elements of an array on the same line and
ensures that the next output will be on a new line. The signature of your method
should be:
public static void print(int[] array)
The following instructions:
print(int[] new {1,2,3,4,5});
print(int[] new {5,4,3,2,1});
should output to the terminal:
12345
54321
● Write a Java method that returns a string that concatenates the elements of a given
array (insert a space between each element). The signature of your method should
be:
public static String toString(int[] array)
The following instructions:
System.out.println(toString(int[] new {1,2,3,4,5}));
should output to the terminal:
12345

● Write a Java method that returns a new array that is an exact copy of a given array.
The signature of your method should be:
public static int[] copy(int[] array)
The following instructions:
print(copy(int[] new {1,2,3,4,5}));
should output to the terminal:
12345

● Describe and implement sequential search in java; your method should return the
first index at which to find a given value in an array (your method should return -1 if
the value is not found). The signature of your method should be:
public static int sequentialSearch(int value, int[] inArray)
The following instructions:
System.out.println(sequentialSearch(3,new int[] {3,1,2}));
System.out.println(sequentialSearch(4,new int[] {3,1,2}));
should output to the terminal:
0
-1

● Describe and implement binary search in java; your method should return the first
index at which to find a given value in a sorted array (your method should return -1 if
the value is not found). The signature of your method should be:
public static int binarySearchIncreasing(int value, int[] inArray)
public static int binarySearchDecreasing(int value, int[] inArray)
The following instructions:
System.out.println(binarySearchIncreasing(0,new int[] {0,1,2,3}));
System.out.println(binarySearchDecreasing(4,new int[] {3,2,1,0}));
should output to the terminal:
0
-1

● Describe and implement selection sort in java; your methods should return a new
array that is sorted in increasing or in decreasing order. The signature of your
methods should be:
public static int[] selectionSortIncreasing(int[] inArray)
public static int[] selectionSortDecreasing(int[] inArray)
The following instructions:
print(selectionSortIncreasing(new int[] {3,1,4,2}));
print(selectionSortDecreasing(new int[] {3,1,4,2}));
should output to the terminal:
1234
4321

● Describe and implement bubble sort in java; your methods should return a new array
that is sorted in increasing or in decreasing order. The signature of your methods
should be:
public static int[] bubbleSortIncreasing(int[] inArray)
public static int[] bubbleSortDecreasing(int[] inArray)
The following instructions:
print(bubbleSortIncreasing(new int[] {3,1,4,2}));
print(bubbleSortDecreasing(new int[] {3,1,4,2}));
should output to the terminal:
1234
4321

● Compare and contrast the increasing and decreasing versions of your Java methods.
The increasing and decreasing versions are essentially the same. If we could pass how to
compare elements as an argument both methods could be collapsed into a single method.

● maximum / minimum (cf. arrays)


● append (cf. arrays)
● keep (cf. arrays)
● remove (cf. arrays)
● find (cf. arrays)

Iterators [work in progress]

Error handling [work in progress]

Files IO [work in progress]

Graphics [work in progress]

JFrames [work in progress]

SQL [work in progress]

You might also like