Object methods

Figure 216. Object methods Slide presentation Create comment in forum
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 217. Scaling a rectangle Slide presentation Create comment in forum

Figure 218. Scaling method implementation Slide presentation Create comment in forum
public class Rectangle {
    int width, height;
    boolean hasSolidBorder;

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

Figure 219. Scaling method signature Slide presentation Create comment in forum
void  scale (int factor ) {
...}

No value is being returned to caller.

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


Figure 220. Using the scale(...) method Slide presentation Create comment in forum
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 221. Method definition syntax Slide presentation Create comment in forum
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 222. A rectangle's perimeter Slide presentation Create comment in forum

Figure 223. getPerimeter() method implementation Slide presentation Create comment in forum
public class Rectangle {
    int width, height;
    boolean hasSolidBorder;

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

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

Figure 224. Using Rectangle.getPerimeter() Slide presentation Create comment in forum
Rectangle r = new Rectangle();

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

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

exercise No. 86

Compile time error Create comment in forum

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. 87

Static code analysis Create comment in forum

Q:

Consider the following snippet:

int count = 3;

count++;

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. Explain the resulting error. What is wrong? How do you correct this error?

  2. Explain the count++ statement'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 purge the count++ statement?

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

A:

  1. Like in the Apple goto fail SSL bug the code is poorly indented. Using your IDE's auto indenting feature (Do it!) you get:

    int count = 3;
    count++;
    
    if (count < 5)
        return;
    return;
    
    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 being unreachable results in a compile time error.

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

    int count = 3;
    count++;
    
    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. Removing count++ 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: The count variable's value is not being altered throughout its scope. It could actually be declared as final int count = 3 disallowing since no subsequent assignments occur. Thus the return inside the if (count < 5) clause will always be executed.

    Note

    Despite its simplicity having the count++ statement in place defeats the compiler's ability to discover our variable count's value now being 4 is still smaller than 5.

  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.