Java methods

Some of the programming languages calls methods functions. Object oriented languages refer to the executable part of a class as a method. Java knows method types called return type methods which return any Java data types. Another type of methods is a void type method which don’t return any values or data. 

methods

Return methods

Java uses the return statement when returning data is required. The value returned should be the same type as the return type.

Sometimes you need a method to calculate and return the results based on known information. An example, we know that a minute is 60 seconds, an hour is 60 minutes and a day is 24 hours.

Example 1:

Write a method to convert a day to seconds. In the following program the method getSecondsInDay calculates the seconds in a day.

getSecondsInDay: name of the method
public : modifier.
int: return type

public class MyClass {

	public int getSecondsInDay(){
		int minute = 60; // seconds
		int hour = 60; // minutes
		int day = 24; // the initial value of day is 24
		day = minute * hour * day;
		return day;
	}
	public static void main(String[] args){
		MyClass mc = new MyClass();
		System.out.print("There are " + mc.getSecondsInDay() + " secons in a day");
	}
}

 

Void methods

Another types of methods are void methods, which do not return any data or value. Example is, a method that prints data to the standard output.

Example 2:

Here below is a method that prints the name “Emma” to the standard output.

public class MyClass {

	void method(){
		System.out.print("Emma");
	}
	public static void main(String[] args){
		MyClass mc = new MyClass();
		mc.method();
	}
}

Parameters

Parameters are similar to variables and each method may have zero or more parameters. In the previous example we did not need to pass any parameter to the methods, because we knew already what we need and the information were known, as a day is 24 hours and an hour is 60 minutes. We often calculate or need data based on other variables. If you write a method which calculates a net salary of a specific person based on his gross salary, you can use the following method.

 

Example 3:

Here below is a method which calculates a net salary based on a gross salary of $3000 and 30% tax rate. The result is always $2100.0.

public class CalculateTax {

	public double getNetSalary(){
		double netSalary = 3000 - (3000 * 30) / 100;
		return netSalary;
	}
	public static void main(String[] args){
		CalculateTax ct = new CalculateTax();
		System.out.println(ct.getNetSalary());
	}
}

 

Example 4:

If you want to make the method more useful, then you need to pass a “gross salary” as a parameter to the method. In that way, you can calculate any net salary based on gross salaries as shown below!

public class CalculateTax {

	public double getNetSalary(double grossSalary){
		double netSalary = grossSalary - (grossSalary * 30) / 100;
		return netSalary;
	}
}

 

There is still a problem with the above method, because it calculates the net salaries based on %30 tax rate.
The “exercise 2” below improves the method to calculate net salaries for different tax rates.

Example 5:

Another example, a product costs $120, but the shop owner decides to offer customers older than 70 years a discount of $15 and customers younger than 18 gets a discount of $20. To know how much the product cost we need first to know the age of the customers. A method only can calculate the product price based on the customer’s age. That is why we need to pass the age of the customer to the method. Then the method returns the price of the product based on the parameter age as shown below.

getProductPrice : name of the method
public : modifier.
double: return type which is the product price
int age : parameter of integer type

public class MethodClass {

	public double getProductPrice(int age){
		double productPrice;

		if(age < 18) {
			productPrice = 120 - 20;
			return productPrice;
		}
		else if(age >= 70) {
			productPrice = 120 - 15;
			return productPrice;
		}
		else {
			return 120;
		}
	}
}

 

If we pass the age 70 to the method getProductPrice, it will return the price of $85.0. However the same method returns the price of $80.0 for customers younger than 18 years. For everyone else the price of the product remains the full price of $120. We passed only one parameter to the method getProductPrice. Sometimes it is necessary to pass two or even more parameters to a method.

Exercise 1

Write a method to find the result of multiplying two numbers!

Question 1: What is written to the standard output when the following program is compiled and run?

Question 2: What is written to the standard output when the program is compiled and run by passing the two parameters 22, 148 to the method getResult instead of (233, 256)?

public class Calculation {

	public int getResult(int numberOne, int numberTwo){
		int result = numberOne * numberTwo;
		return result;
	}
	public static void main(String[] args){
		Calculation cal = new Calculation();
		System.out.println("result: " + cal.getResult(233,256));
	}
}

Answer Exercise 1:

Q1– When the code runs, the result “59648” is written to the standard output. That is because 233 x 256 = 59648;

Q2- The result “3256” is written to the standard output.

Exercise 2

The method getNeSalary  calculates the net salaries of employees if you pass to the method their gross salaries and the tax rate which they need to pay. It returns a double result which is net salary.

Answer the following questions!
a – When this code runs, what is written to the standard output?
b – What is written to the standard output for a gross salary of $4000 who pays a tax rate of 30%?
c – What is written to the standard output for a gross salary of $6400 who pays a tax rate of 35%?

public class CalculateTax {

	public double getNetSalary(double grossSalary, int taxRate){
		double netSalary = grossSalary - (grossSalary * taxRate) / 100;
		return netSalary;
	}
	public static void main(String[] args){
		CalculateTax ct = new CalculateTax();
		System.out.println(ct.getNetSalary(3000,20));
	}
}

Answer Exercise 2:

a. 2400.0, b. 2800.0, c. 4160.0

Please, leave your questions, feedback and suggestions in the comments below!
SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.


Sar Maroof is graduated from HBO Amsterdam “higher professional education” when he already had a bachelor of science degree in Physics.
He is a SUN certified JSP as well as EJB. He has experience with Java since 2001 and worked for several big as well as small companies and later as a freelancer.
He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           
 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!
Share on FacebookTweet about this on TwitterShare on RedditShare on LinkedIn

5 Comments

Add a Comment
  1. Why do I bother calilng up people when I can just read this!

  2. Thanks Sar for your helpful content! I tried already to solve your advanced quizzes on DZone,

    1. You are welcome!

      1. The purscahes I make are entirely based on these articles.

    2. Enlgthiening the world, one helpful article at a time.

Leave a Reply

Your email address will not be published. Required fields are marked *

Sarmaroof © 2017