- Java OOP: Class Methods Tutorial
- What is a method
- How to define a method in Java
- How to use (invoke/call) a method in Java
- Are values returned by static method are static in java?
- Example
- 2.1 Static Methods
- Using and defining static methods.
- Properties of static methods.
- Implementing mathematical functions.
- Using static methods to organize code.
- Passing arguments and returning values.
- Superposition of sound waves.
- Exercises
- Creative Exercises
- Web Exercises
Java OOP: Class Methods Tutorial
In this Java tutorial we learn how to group sections of program functionality into smaller reusable units called methods.
We cover how to define and use non-static and static methods, how to add parameters and how to return values, along with control, from them. We also cover the ‘this’ construct and how it refers to the calling object as well as how to construct objects with initial values.
Lastly, we quickly discuss and link to the Lambdas lesson and do a quick little challenge.
- What is a method
- How to define a method in Java
- How to use (invoke/call) a method in Java
- How to add parameters to a method in Java
- How to return a value from a method in Java
- Static methods in Java
- Lambda expressions (anonymous methods) in Java
- Mini challenge
- The ‘this’ construct in Java
- How to construct an object with values in Java
- Summary: Points to remember
What is a method
Methods allow us to group sections of our code into a smaller, reusable units.
As an example, let’s consider some simple logic.
The simple logic in the example above will check if a number is even or odd.
Our application may require this evaluation multiple times throughout the code. We don’t want to repeat ourselves and retype this logic each time we want to check a number.
Instead, we want to separate the logic into a unit that we can more easily use over and over, anywhere in our code. These units are called methods.
How to define a method in Java
A method definition consists of the following parts.
- An access modifier
- A return type
- A name
- Parameters (optional)
- A body with one or more statements
- A returned value (optional)
In Java, methods can only be defined in classes, we cannot define standalone methods.
We’ll start with the most basic method and add features as we go.
In the example above, we create a class called ‘Logger’ with a method inside called ‘logMessage’. All it does is print some text to the console.
Typically we would create each class in its own file, but to keep things simple, we just defined the ‘Logger’ class below the ‘Program’ class.
Let’s break down the method definition step by step.
- For the access modifier, we used public to allow access to the function from any other class. We cover access modifiers in detail in the OOP: Encapsulation & Access Modifiers lesson .
- For the return type, we used void. When a function doesn’t return a value, we always specify the return type as void.
- Our method has no parameters so we left the parameter list empty. The parentheses must always be included even if the method doesn’t have any parameters.
- In the function body we just print some text to the console.
- Because our function doesn’t return anything, we can omit the return keyword.
Now if we go ahead and run the script, nothing happens. That’s because we’ve defined the method, but we haven’t used anywhere it yet.
How to use (invoke/call) a method in Java
To use a method, we need to tell the compiler that we want the method to execute the code in its body once. We do this by invoking the method, otherwise known as calling it.
To call a method we write its name, its parameter list and terminate the statement with a semicolon.
But, because the method is inside a class, we need to instantiate an object and call the method through dot notation. Like we did with parameters.
Are values returned by static method are static in java?
Whenever you return values from a static method they are either static nor instance by default, they are just values.
The user invoking the method can use them as he wants. i.e. you can retrieve the values and declare them static.
But, since you cannot declare variables of a method static if you need to declare the vales returned by a method static you need to invoke it in the class outside the methods.
Example
Assume we have a class with name Demo as −
class Demo < int data = 20; public Demo(int data)< this.data = data; >public int getData() < return this.data; >>
In the following Java example, we have two methods getObject() and getInt() returning an object and an integer respectively.
We are invoking these methods twice in the class and within a method. In the class we have declared the values returned by them as static.
And in the method we are using them (values returned by the methods) as local variables (obviously non-static).
public class StaticExample < static int data = StaticExample.getInt(); static Demo obj = StaticExample.getObject(); public static Demo getObject()< Demo obj = new Demo(300); return obj; >public static int getInt() < return 20; >public static void main(String args[]) < System.out.println(StaticExample.data); System.out.println(StaticExample.obj.data); StaticExample obj = new StaticExample(); System.out.println(obj.getInt()); Demo demo = obj.getObject(); System.out.println(demo.data); >>
2.1 Static Methods
The Java construct for implementing functions is known as the static method.
Using and defining static methods.
The use of static methods is easy to understand. For example, when you write Math.abs(a-b) in a program, the effect is as if you were to replace that code with the return value that is produced by Java’s Math.abs() method method when passed the expression a-b as an argument.
-
Flow-of-control.Harmonic.java comprises two static methods: harmonic() to compute harmonic numbers and and main() to interact with user.
Properties of static methods.
Implementing mathematical functions.
We now consider two important functions that play an important role in science, engineering, and finance. The Gaussian (normal) distribution function is characterized by the familiar bell-shaped curve and defined by the formula:
- Closed form. In the simplest situation, we have a closed-form mathematical equation defining our function in terms of functions that are implemented in the Math library. This is the case for \(\phi(x)\).
- No closed form. Otherwise, we may need a more complicated algorithm to compute function values. This situation is the case for \(\Phi(z)\), for which no closed-form expression exists. For small (respectively large) z, the value is extremely close to 0 (respectively 1); so the code directly returns 0 (respectively 1); otherwise the following Taylor series approximation is an effective basis for evaluating the function:
Using static methods to organize code.
- Given n, compute a random coupon value.
- Given n, do the coupon collection experiment.
- Get n from the command line, and then compute and print the result.
Passing arguments and returning values.
- Pass by value. You can use parameter variables anywhere in the code in the body of the function in the same way you use local variables. The only difference between a parameter variable and a local variable is that Java evaluates the argument provided by the calling code and initializes the parameter variable with the resulting value. This approach is known as pass by value.
- Arrays as arguments. When a static method takes an array as an argument, it implements a function that operates on an arbitrary number of values of the same type.
- Side effects with arrays. It is often the case that the purpose of a static method that takes an array as argument is to produce a side effect (change values of array elements).
- Arrays as return values. A static method can also provide an array as a return value.
Superposition of sound waves.
Notes like concert A have a pure sound that is not very musical, because the sounds that you are accustomed to hearing have many other components. Most musical instruments produce harmonics (the same note in different octaves and not as loud), or you might play chords (multiple notes at the same time). To combine multiple sounds, we use superposition: simply add the waves together and rescale to make sure that all values stay between −1 and 1.
PlayThatTuneDeluxe.java is a version of PlayThatTune that encapsulates the sound wave calculation and adds harmonics.
Exercises
- Write a static method max3() that takes three int arguments and returns the value of the largest one. Add an overloaded function that does the same thing with three double values.
public static int max3(int a, int b, int c) < int max = a; if (b >max) max = b; if (c > max) max = c; return max; > public static double max3(double a, double b, double c) < double max = a; if (b >max) max = b; if (c > max) max = c; return max; >
public static boolean majority(boolean a, boolean b, boolean c)
public static void cube(int i)
Creative Exercises
- Black–Scholes option valuation. The Black–Scholes formula supplies the theoretical value of a European call option on a stock that pays no dividends, given the current stock price s, the exercise price x, the continuously compounded risk-free interest rate r, the volatility σ, and the time (in years) to maturity t. The value is given by the formula
February 2009 S M Tu W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
Web Exercises
- Diamond tile. Write a program DiamondTile.java that takes a command-line argument N and creates an N-by-N tile of diamonds. Include static methods diamond() and filledDiamond().
- Hexagonal tile. Write a program HexTile.java that takes a command-line argument N and creates an N-by-N tile of hexagons. Include static methods hexagon() and filledHexagon().
- Inverse Gaussian cumulative distribution. Suppose SAT math scores are normally distributed with mean 500 and standard deviation. Estimate how high student must score in order to be among the top 10%. To do this you need to find the value z for which Φ(z, 500, 100) = 0.9. Hint: use binary search.
- SAT scores. A prominent northeastern university receives 20,000 student applications. Assume that the SAT scores of these individuals is normally distributed with mean 1200 and standard deviation 100. Suppose the university decides to admit the 5,000 students with the best SAT scores. Estimate the lowest score that will still be admitted.
- Voting machines. Suppose that in a population of 100 million voters, 51% vote for candidate A and 49% vote for candidate B. However, the voting machines are prone to make mistakes, and 5% of the time they produce the wrong answer. Assuming the errors are made independently and at random, is a 5% error rate enough to invalidate the results of a close election? What error rate can be tolerated?
- Gambler’s histogram. Write a program RandomWalk.java that takes one command line parameter M and simulates a gambler starting with M who places exactly M one dollar bets.
- Produce a histogram of the amount of money the gambler ends up with by running this experiment N times.
- The amount of money the gambler ends up with follows a binomial distribution with mean M and variance N/4. The distribution can be approximated by a normal distribution with the same mean and variance. Produce a histogram for the fraction of time you’d expect the gambler to end up with the amount in each histogram bin.
public boolean areCollinear(int x1, int y1, int x2, int y2, int x3, int y3)
The integral has no closed form solution in terms of elementary functions so we resort to approximations. When z is nonnegative, the Chebyshev fitting estimate below is accurate to 7 significant digits:
If z is negative, use the identity erf(z) = -erf(-z). A particularly efficient way to implement it is via a judicious use of parentheses known as Horner’s method. Consider simpler (but less accurate) approximation from Algorithm 26.2.17 in Abromowitz and Stegun, Handbook of Mathematical.
erf(x) = 1 - (a_1 t + a_2 t^2 + a_3 t^3) e^(-x^2) t = 1 / (1 + px) p = 0.47047 a_1 = 0.3480242 a_2 = -0.0958798 a_3 = 0.7478556 assuming x >= 0
- if x is 7 or 11, you win instantly
- if x is 2, 3, or 12, you lose instantly
- otherwise, repeatedly roll two dice until their sum is either x or 7
- if their sum is x, you win
- if their sum is 7, you lose
public static boolean isPrime(long N) < if (N < 2) return false; for (long i = 2; i*i return true; >
- Write a method fv that computes the amount of money you will have if you invest C dollars today at the compound interest rate of r per period, in T periods. The formula for the future value is given by C*(1 + r)^T.
- Write a method pv that computes the amount of money that would have to be invested now, at the compound interest rate r per period, to obtain a cash flow of C in T periods. The formula for the present value is given by C/(1 + r)^T.
public static long factorial(int n)
public static void negate(int a) < a = -a; >public static int main(String[] args)
public static int min(int a, int b, int c, int d) < // if a is the smallest return it if (a public static int min(int a, int b, int c, int d) < int min = a; if (b < min) min = b; if (c < min) min = c; if (d < min) min = d; return min; >public static int min(int a, int b, int c, int d) < if (a < b && a < c && a < d) return a; if (b < c && b < d) return b; if (c < d) return c; return d; >public static int min(int a, int b, int c, int d) < if (a if (c if (b else if (c public static int min(int a, int b) < if (a public static int min(int a, int b, int c, int d)Answer: you can’t hope to test it on every conceivable input since there are 2 128 different possible inputs. Instead, test it on all 4! = 24 cases depending on whether a