Bright Java Tutorial

is brought to you by DoITBright LLC

Java

Method Parameters and Return Type

We will now get to familiarize on the variety of ways a method can be declared in a class in terms of what kind of parameters it accepts, if it does accept a parameter and what kind of parameter it returns, if it does return a parameter. Lets look at the code below.

  package com.example.core;

  public class MoreOnMethods {

	/**
	 * This is the main method of a core Java class. 
	 * When you run your code as an application,
	 * it will look for this method. 
	 */
	public static void main(String[] args) {
	  MoreOnMethods obj = new MoreOnMethods();
	  obj.noAcceptNoReturn();
	  String aString = obj.noAcceptReturnParam();
	  System.out.println(aString);
	  obj.acceptParamNoReturn(1);
	  long aLong = obj.acceptParamReturnsParam("Hi there!");
	  System.out.println(aLong);
	  obj.multipleParam("xyz", 5);
	}
	
	/**
	 * This method does not accept any parameter and does 
	 * not return a parameter. The 'void' is a Java keyword 
	 * for not returning anything.
	 */
	public void noAcceptNoReturn() {
	  System.out.println("Hello!");
	}
	
	/**
	 * This method does not accept any parameter and
	 * returns a String parameter.
	 */
	public String noAcceptReturnParam() {
	  return "Hello again!";
	}
	
	/**
	 * This method accepts int as parameter
	 * and returns nothing.
	 */
	public void acceptParamNoReturn(int param) {
	  System.out.println("The param value is " + param);
	}
	
	/**
	 * Accepts a String as parameter and returns a long.
	 * 
	 * @param param String
	 * @return long
	 */
	public long acceptParamReturnsParam(String param) {
	  System.out.println("The value of param is " + param);
	  return 123;
	}
	
	/**
	 * Accepting multiple parameters. In this example 
	 * return type is void. You may choose to return 
	 * something if you wish.
	 * 
	 * In Java, the name of the method and the number 
	 * and type of the accepted parameters are called 
	 * method signature. It does not inlcude the return 
	 * type and the exceptions it throws.
	 * 
	 * Exception will be discussed in the future.
	 */
	public void multipleParam(String param1, int param2) {
	  System.out.println("The value of param1 is " + param1 
	    + " and the value of param2 is " + param2);
	}
}
                            



Back    Next