Java tip: Fields and methods in Java

Advanced techniques for working with fields and methods in your Java programs

1 2 Page 2
Page 2 of 2

Listing 4. Demonstrating Utilities's methods

class UtilDemo
{
   public static void main(String[] args)
   {
      double[] values = { 10.0, 20.0, 30.0, 40.0 };
      System.out.println(Utilities.average(values));
      System.out.println(Utilities.factorial(5));
      int[] numbers = { 25, 49, 33, 89 };
      System.out.println(Utilities.search(numbers, 33));
      System.out.println(Utilities.search(numbers, 34));
   }
}

If you compile Listing 6 as follows:

javac UtilDemo.java

and run the resulting application:

java UtilDemo

you should observe the following output:

25.0
120
2
-1

Conclusion

The tutorial Java 101: Classes and objects in Java presents a minimal set of features for working with classes and objects. This Java tip introduces additional concepts and techniques related to fields and methods--namely field constants, field-access rules, chaining instance method calls, pass-by-value arguments, recursion and the method-call stack, rules for calling methods, and utility classes. You can continue learning about this topic by downloading and experimenting with the example code for this Java tip, which includes examples from Java 101: Classes and objects in Java.

This story, "Java tip: Fields and methods in Java" was originally published by JavaWorld.

Copyright © 2019 IDG Communications, Inc.

1 2 Page 2
Page 2 of 2