All posts by admin

5 Minutes of Java (13. Method Overloading vs Method Overriding)

Method overloading and method overriding are two completely different concepts. To distinguish the two, we need to first understand method signature.

Method signature consists of both method name and parameter list, if two methods have the same name and the same parameter list, then they have the same method signature.

public class SampleClass{

  public void drawA() {}

  public void drawA(int i) {}

  public int drawB() {}

  public void drawB() {}

  public void drawC(int m) {System.out.println(m);}

  public void drawC(int n) {System.out.println(n);}
}

From the example given above, two drawA methods have the same method name but different parameter list (one has no parameter, the other has one of type int), so they have different method signatures. However,  two drawB methods have the same method signature since they have the same method method and parameter list though they have different return types (one returns int and the other returns nothing). Similarly, two drawC methods also have the same method signature though the variable names used for parameters are different (one uses m and the other uses n). Java does not allow two methods of the same signature defined within the same class, so in our case, drawB and drawC would give compilation errors.

Now we can go on to talk about method overloading and overriding. Method overloading happens when we have two or more methods with the same name but different parameter lists within a class. In our earlier example, method overloading occurs for two drawA methods.

For method overriding, we must have at least one superclass and one subclass. It occurs when one method in the subclass has the same signature as one method inherited from its superclass.

public class Parent {
  public void show() {
    System.out.println("Parent class");
  }
}
public class Child extends Parent{
  public void show() {
    System.out.println("Child class - method overriding");
  }
}

In the example given above, the show method in the superclass is overridden in the subclass.

In this case, if we call show method in Child class, it would display “Child class -method overriding”, if we want to call show method in its superclass, we need to call super.show().

To summarize,

  Within same class? Same name? Same parameter list?
Overloading Yes* Yes No
Overriding No (one in subclass, one in superclass) Yes Yes

*Note: method overloading could also happen in subclass when it inherits a method with the same name but different parameter list from its superclass, like the example given below.

public class Parent {
 public void show() {
 System.out.println("Parent class");
 }
}
public class Child extends Parent{
 public void show(int i) {
 System.out.println("Child class - method overloading");
 }
}

For more details on method overloading and method overriding, you can look at this link: method overriding vs overloading

5 Minutes of Java (12. ArrayList with FOR Loop)

There are many common questions related to use of FOR loop in going through elements in ArrayList. Let’s give an example:

Question: We have an ArrayList stockList containing Stock objects. Calculate the sum of prices of all the elements and display the sum.

Following the steps given in the slides, we need to

  1. Declare a variable to sum up all values and initialise it to 0
  2. Go through each value and add it to the variable
  3. Print out the variable after the FOR loop

Step 1:

For step 1, think about what data type we should use for the variable, it should be the same as the values we need to sum up. In this case, price is of type double, so the sum should be of type double as well.

double sum = 0;

Step 2:

Step 2.1 To go through the ArrayList, we need to use a FOR loop. A common structure is like this:

for (int a = 0; a < arrayListVariable.size(); a++) {
   //Statements
}

So to apply it to our example,

for (int a = 0; a < stockList.size(); a++) {
   //Statements
}

Inside the FOR loop, think about how to get the price of each element and add them together.

Step 2.2  To get the element, from there, you try to get the desired field (in our case price) of the element. Still remember how to get an element of an ArrayList? we use arrayListVariable.get(i) where i refers to the position of the element. So in this case, we use stockList.get(a)

Step 2.3 To get the price of the element, we look at the getter methods available, which one should we use? Obviously getPrice().

Step 2.4 To add to the variable we use to sum up the all values, we should add it to the variable, and assign the total prices to the variable again.

common structure:

sum = sum + value of one element

Now we combine everything for step 2

for (int a = 0; a < stockList.size(); a++) {
   sum = sum + stockList.get(a).getPrice();
}

Step 3:

At the end, we should print out the sum to the screen. To display the value, always think about what is the data type of the value, it is a reference type (Car object, Employee object, String, etc) or primitive types (int, double) . For primitive type and String, we usually use System.out.println directly, whereas for others, we need to look for the method available for the object class to find out the method to use (some common names are display(), show(), showInfo(), printInfo() )

In our case, the data type of sum is double, so we should use System.out.println().

System.out.println("the sum of prices of all elements is "+ sum);

Putting All Together:

double sum = 0; 
for (int a = 0; a < stockList.size(); a++) 
{
    sum = sum + stockList.get(a).getPrice(); 
}
System.out.println("the sum of prices of all elements is "+ sum);

Practice Question: Find out the Stock object with the max price in the ArrayList stockList, and display the object.

Hint: Think about the steps you need to do in order to solve the question,  some standard steps can be found here.

Solution:

Stock maxStock = stockList.get(0);  //initialize maxStock to be the first element of the ArrayList 
for (int a = 0; a < stockList.size(); a++) 
{
    if(maxStock.getPrice()< stockList.get(a).getPrice()) //compare the price of maxStock with the current element
    { 
        maxStock = stockList.get(a); //if the current element has higher price, update the maxStock to be the element
    }; 
}
maxStock.display(); //display the object, since it is of type Stock, cannot use System.out.println(), instead, should look into the class diagram to find out the correct method to use

5 Minutes of Java (11. Array vs ArrayList)

Standard Java Array has a fixed length. So after it is created, it cannot grow or shrink,  which means that you must decide in advance how many elements an array should hold.

ArrayList has a variable size, therefore you need not specify its size at the point of the creation. Therefore it is more friendly to use than the array.

Declaration and Creation

Array:
dataType[] arrayRefVar = new dataType[arraySize];

Example:

String[] arrayA = new String[5];

Alternatively you can create arrays as follows if you know the values to put in:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

Example:

String[] arrayB = {"Bentley", "Wilson", "Palmer", null, null};
ArrayList:
ArrayList<dataType> arrayListRefVar = new ArrayList<dataType>();

<dataType> decides what can be stored inside the ArrayList.

Example:

ArrayList<String> listA = new ArrayList<String>();

 Common Operations:

Operation
Array
ArrayList
Get size
arrayA.length
listA.size()
get the element at position i
arrayA[i]
listA.get(i)
Replace the element at position i
arrayA[i] = “newValue”;
listA.set(i,”newValue”);
Delete the element at position i
arrayA[i] = null;
listA.remove(i);
Append an element to the end
NA
listA.add(“newValue”);
Insert an element at position i
NA
listA.add(i,”newValue”);

5 Minutes of Java (10. Convert a FOR loop to a WHILE loop)

Converting a WHILE loop to a FOR loop may not be that straightforward, but converting a FOR loop to a WHILE loop is always easy.

First, let’s have a comparison of the structures of FOR loop and WHILE loop:

FOR Loop Structure:

for(Initialization; Conditional Test; Update)
{
   Statements //inside the loop body
}
//statements after for loop

WHILE Loop Structure:

While (Conditional Test)
{
   Statements; //inside the loop block/body
}

We can see that both FOR loop and WHILE loop have Conditional Test inside the (). but FOR loop has two more items, Initialisation and Update. Where to place it in WHILE loop?

According to the post on FOR loop,

  • The initialization statement is executed only once before the loop starts, so we place it before the WHILE loop
  • The update statement is executed after the loop body is executed, so we place it at the end of the WHILE loop body
Initialisation; //from the FOR loop
While (Conditional Test)
{
   Statements; //inside the loop block/body
   Update; //from the FOR loop
}

That’s it!

Example:

for (int i = 0; i < 8; i++) {
   System.out.println(i);
}
System.out.println("done");

WHILE Loop version:

int i = 0; //initialisation
while (i < 8) {
   System.out.println(i);
   i++; //update
}
System.out.println("done");

 

 

5 Minutes of Java (9. Write a For loop for a given output)

One common question we often encounter is to write a for loop for a given output.

Output example:

number 1
number 2
number 3
number 4
number 5
number 6

We will follow a 5-step process to come out with a For loop.

Step 1: write a program without using while/for loop

System.out.println(“number 1”);
System.out.println(“number 2”);
System.out.println(“number 3”);
System.out.println(“number 4”);
System.out.println(“number 5”);
System.out.println(“number 6”);

Step 2: Identify the constant part and the variable part

constant and variable

System.out.println(“number 1”);
System.out.println(“number 2”);
System.out.println(“number 3”);
System.out.println(“number 4”);
System.out.println(“number 5”);
System.out.println(“number 6”);

 

Step 3:  Use a variable to replace the variable part

System.out.println("number "+n);

Step 4: Identify the starting number, the ending number and the step/update

  • start: 1
  • end: 6
  • step/update: +1 (add 1 every time)

Step 5:  Construct a for loop

for(int n=1; n <= 6; n++)
{
   System.out.println(“number “+n);
}

Let’s recap the 5-step process again:

  • Write a program without using for loop
  • Identify the constant part and the variable part
  • Use a variable to replace the variable part
  • Identify the starting number, the ending number and the step/update
  • Construct a for loop

5 Minutes of Java (8. For loop)

For Loop Structure:

for(Initialization; Conditional Test; Update)
{
   Statements //inside the loop body
}
//statements after for loop

meaning:

  • The initialization statement is executed before the loop starts, and it is executed only once. It is commonly used to initialize the loop variable.
  • Conditional test is evaluated, if it is true, loop body will be executed. If it is false, the for loop is terminated, and the statement after the for loop will be run.
  • Update statement is executed after the loop body is executed. It is usually used to increment or decrement the loop variable.

Example:

for (int i = 0; i < 8; i++) {
   System.out.println(i);
}
System.out.println("done");

Output:

0
1
2
3
4
5
6
7
done

Common use of for loop:

  • When the number of iterations is known from the outset.

 

5 Minutes of Java (7. While loop)

While Loop Structure:

While (Conditional Test)
{
   Statements; //inside the loop block/body
}

Meaning:  While conditional test result is true, keep looping (statements inside the loop block/body will be executed/run)

Example:

int cupsOfRice = 0;
while(cupsOfRice<4)
{
 System.out.println("I am eating");
 cupsOfRice++; //cupOfRice = cupOfRice + 1;
}
System.out.println("I am full");

Output:

I am eating
I am eating
I am eating
I am eating
I am full

Common uses of While Loop:

  • When the number of iterations is not known from the outset.
  • When an infinite loop is enforced, until the condition becomes false.

Example:

int num = Helper.readInt("Enter a number between 1 to 10> ");
while (num < 1 || num > 10) {
   num = Helper.readInt("Invalid Numer, 1 to 10 please > ");
}
System.out.println("You entered " + num);

In this example, we are not sure how many times a user would enter a invalid number, so we use while loop. As long as the user enters a invalid number, the program will keep asking the user to enter a new number again.

5 Minutes of Java (6. Using equals() or ==)

Using == for comparision

In python, to compare whether two variables have the same value, we will write the following code:

if (a == b):

print “a is equal to b”

This works whether the data type of the variables is String or number.

In Java, you can still use == to compare whether two numbers have the same value:
int a = 3;
int b = 3;
if (a == b){

 System.out.println(“a and b has the same value”);

}

However, you should use the equals() method to compare String in Java. In the code segment shown below, if you enter “hello” for both inputs, only the following result will be displayed: “Using equals() for comparison: a is equal to b”.

String a = Helper.readString("Enter first String");
String b = Helper.readString("Enter second String");

if(a==b){
 System.out.println("Using == for comparison: a is equal to b");
}

if(a.equals(b)){
 System.out.println("Using equals() for comparison: a is equal to b");
}

In summary,

  • to compare numbers in Java, use ==
  • to compare Strings in Java, use equals()

5 Minutes of Java (5. Decision Making with if/else statement)

Decision making is done using the if/else statement. See example below on the code to determine whether a person passed a test:

int score = 59;

if (score >= 50){
    System.out.println("You passed the test.");
}
else{
    System.out.println("Try harder next time.");
}

To handle more than 2 conditions, you will use the else if statement. This is similar to elif in python.

int score = 65;
char grade = 'F';

if (score > 70){
   grade = 'A';
}
else if (score >= 50){
   grade = 'C';
}
else{
    grade = 'F';
}

System.out.println("Your grade is " +  grade);

5 Minutes of Java (4. Java Methods)

In Python, you define function to create a block of re-usable code. In Java, this is done using method. You must create your method within the Java class.   There can be more than one method in each Java class.

The code below shows you the syntax of a Java method:

modifier returnValueDataType methodName(list of parameters) {
  // Method body;
}

The code below shows you how to create a method addNumber with the following attributes in a class MyNumber:

public class MyNumber{
    public double addNumber(double x, double y){
        return x + y;
    }
}
  1. public — Method modifier. It tells the compiler how to call the method. Always use public for now, you will learn more about this later on.
  2. double — The data type of the value returned by the method. In this example, x + y which is of double data type, will be returned.
  3. addNumber — Name of the method.
  4. double x, double y — The parameters that are passed to the method. In this example, there are 2 parameters: x and y. Both x and y have double data type.
  5. return x + y — The method body. The result of (x + y) is the value to be returned by the method. The data type must match those stated at point 2.

Take a look at another method given below:

public class MyName{
    public void sayHello(String name){
        System.out.println("Hello " + name);
    }
}
  1. void — This means that the method will not return any value. Take note that there is no “return …” in the method body.
  2. System.out.println(…) — The method body. It calls a method to print out the value in its parameter for the user to see.