*** FOR ENQUIRES - PLEASE CALL (226) 777-2622 ***

What is a Java Method – With Example

What is a Java Method ?

A method is a block of code that only runs when it is called. You can pass data that are referred to as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions

Exercise Sample

import java.util.Scanner;

public class fruit_invoice {

	public static void main(String[] args) {
		
		/*
		Apples - $20/lb
		Oranges - $10/lb
		Grapes - $5/lb

		Ask customer how many pounds do they need 
		Ask user how he wants to pay
		Display total

		Method 1 - Calculate Total Price
		Method 2 - Provides the total with HST
		Method 3 - Provides the total with a discount of $10, with no HST
		*/
		
		float apple = 20; 
		float orange = 10;
		float grape = 5; 

		Scanner buy = new Scanner(System.in);
		System.out.print("How many lbs of Apples do you need ? ");
		int apple_lbs = buy.nextInt();
		float apple_price = apple * apple_lbs; 
		
		System.out.print("How many lbs of Oranges do you need ? ");
		int orange_lbs = buy.nextInt();
		float orange_price = orange * orange_lbs; 
		
		System.out.print("How many lbs of Grapes do you need ? ");
		int grape_lbs = buy.nextInt();
		float grape_price = grape * grape_lbs; 
		
		hst(apple_price,orange_price,grape_price);
		nohst(apple_price,orange_price,grape_price);
	}

	public static void hst(float apple, float orange, float grape) {
		
		float x_apple = apple*13/100;
		float x_orange = orange*13/100;
		float x_grape = grape*13/100;
		
		System.out.println("Total invoice with HST is :$" + (apple + orange + grape + x_apple + x_orange + x_grape));
	}
	
	public static void nohst(float apple, float orange, float grape) {
		
		System.out.println("Total invoice with HST is : $" + (apple + orange + grape -10));
	}
}

About Us

Resolve6 provides software QA training and Job placement services in Brampton, Mississauga for the past 2 decades. Check out our upcoming programs to know more.