Object methods

Figure 199. Object methods Slide presentation
Change an object's state.

Example: Scale a rectangle.

Get dependent values

Example: Calculate a rectangle's perimeter.

Combined

Scale a rectangle and calculate its new perimeter.


Figure 200. Scaling a rectangle Slide presentation

Figure 201. Scaling method implementation Slide presentation
public class Rectangle {
    int width, height;
    boolean hasSolidBorder;

    public void scale (int factor) {
        width *= factor;
        height *= factor;
    }
}
Scaling method implementation

Figure 202. Scaling method signature Slide presentation
void  scale (int factor ) {
...}

No value is being returned to caller.

A single value of type int is being provided as method argument.


Figure 203. Using the scale(...) method Slide presentation
Rectangle r = new Rectangle();
r.width = 33;
r.height = 22;

r.scale(2);

System.out.println("width=" + r.width);
System.out.println("height=" + r.height);
width=66
height=44

Figure 204. Method definition syntax Slide presentation
public  void  scale (int factor ) { 
   width *= factor; 
   height *= factor;
}
[access modifier]  return_type  methodName  ([arguments] ) {
   [statement(s)] 
}

Optional access control modifier either of public, protected or private.

The method's return type either of:

void

The method will not return a value on completion.

A data type e.g. int, double, ...

The method will return a value of the given type to its caller.

The method's name.

Arguments being required for execution.

Start of method's body.

The method's implementation.


Figure 205. A rectangle's perimeter Slide presentation

Figure 206. getPerimeter() method implementation Slide presentation
public class Rectangle {
    int width, height;
    boolean hasSolidBorder;

    public void scale (int factor) { ... }

    public int getPerimeter() {
        return 2 * (width + height);
    }
}
getPerimeter() method implementation

Figure 207. Using Rectangle.getPerimeter() Slide presentation
Rectangle r = new Rectangle();

r.width = 33;
r.height = 22;

System.out.println("Perimeter=" + r.getPerimeter());
Perimeter=110

exercise No. 89

Compile time error

Q:

Try to compile the following snippet:

public int getMinimum(int a, int b) {
  if (a < b) {
    return a;
  } 
}

You'll encounter a Missing return statement error. What's wrong here?

On contrary the following code compiles and executes perfectly well:

public class ReturnDemo {

  int minimum;

  public void getMinimum(int a, int b) {
    if (a < b) {
      minimum = a;
      return;
    }
  }
}

A:

The compiler effectively complains about a missing if related path: In case of b <= a no return value has been defined. There are two possible solutions:

  1. public int getMinimum(int a, int b) {
      if (a < b) {
        return a;
      } else {
        return b;
      }
    }
  2. Less readable but still producing an identical result:

    public int getMinimum(int a, int b) {
      if (a < b)
        return a;
      return b;
    }

On the other hand the return statement in ReturnDemo.getMinimum(...) is unnecessary. The following code produces exactly the same result. The method will terminate anyway when ending the method's body:

public class ReturnDemo {

  int minimum;

  public void getMinimum(int a, int b) {
    if (a < b) {
      minimum = a; // Same as before but no subsequent return statement
    }
  }
}

Albeit executing well the above code is flawed: Calling e.g. getMinimum(4, 3) does not assign any value to our instance variable minimum. Correction requires an else clause:

public class ReturnDemo {

  int minimum;

  public void getMinimum(int a, int b) {
    if (a < b) {
      minimum = a; // Same as before but no subsequent return statement
    } else {
      minimum = b;
    }
  }
}

exercise No. 90

Static code analysis

Q:

Consider the following snippet:

int count = (int) Math.sin(3);

if (count < 5)
    return;
    return;

System.out.println("Failed!");

This Java code resembles the Apple goto fail SSL bug's structural problem. Since Java does not (yet) offer goto statements we use return instead for terminating the current context.

Copy this code into your IDE and:

  1. Name and explain the resulting error. What is wrong? How do you correct this error?

  2. Explain the (int) Math.sin(3) term's purpose.

    Tip

    There is no real application logic in the given code. This example is meant to explain formal Java language features. What happens if you correct the compile time error and in addition replace the (int) Math.sin(3) term by simply setting int count = 3;?

  3. What is the underlying idea of these warning and error messages?

A:

  1. The System.out.println("Failed!") statement is being flagged as an »unreacheable statement« error. Like in the Apple goto fail SSL bug this is obscured by poor indentation. Using your IDE's auto indenting feature (Do it!) you get:

    int count = (int) Math.sin(3);
    
    if (count < 5)
        return;
    return; 
    
    System.out.println("Failed!");

    For the sake of clarity we add curly braces and a comment:

    int count = (int) Math.sin(3);
    
    if (count < 5){
        return;
    }
    
    return; // Does not depend on previous »if« statement
    
    System.out.println("Failed!");

    The second return statement will leave the given context unconditionally regardless of the preceding if (count < 5) and the count variable's value in particular. Thus the final System.out.println("Failed!") statement cannot be reached resulting in a compile time error.

    Removing the erroneous second return statement resolves the error leaving us with happily compiling code:

    int count = (int) Math.sin(3);
    
    if (count < 5)
        return;
    
    System.out.println("Failed!");

    Conclusion: The Apple goto fail SSL bug could not have been occurring in Java due to an inherent language feature.

  2. Replacing (int) Math.sin(3) leaves us with:

    int count = 3;
    
    if (count < 5) 
        return;
    
    System.out.println("Failed!");

    Compiler warning: Condition 'count < 5' is always 'true'.

    This warning is due to static compile time code analysis: On contrary to calculating Math.sin(3) the compiler is now »aware« of the variable count's value. Its value not being altered subsequently it could even be declared as final int count = 3. The return statement inside our if (count < 5) clause will thus always be executed.

  3. This mechanism keeps programmers from coding carelessly: Even the if (count < 5) statement is most likely an unintended bug.

Important

Conclusion: Watch out for compiler warning messages and do not ignore them!

In many cases compiler warnings reveal serious flaws. Correction on average will save you cumbersome time debugging your code.

Set your compiler / IDE's warnings to a yet tolerable higher level. In case of IntelliJ IDEA you may want to activate various settings in your project's Java section below Editor --> Inspections.