Learning Java
Custom Search

Previous Next

Other Modifiers

We will not cover all the other possible modifiers, only those included in this tutorial which follows.

Modifier Description
static The item is fixed in place.
If a variable in a class is static, then for each object created from that class, the static variable has the same value. Without the static keyword, each object has a separate copy of the variable where changing the value in one object does not affect the value of the variable in another.
When a method is static, then, as for variables, there is only one copy of this method for all objects created for the class. This enables this method to be used before any object is actually instantiated.
void This modifier states that this method will not return a value to the caller.
"type" These modifiers states that this method will return a value to the caller. The "type" represents a primitive type or a class name, and tells what type of data is being returned. The keyword return is used to return the value.

The following example illustrates the use of return values in methods. The class CalcTime has 2 methods,

    TravelTime which returns a value of type double.
    morePrint which does not return a value to the caller.

The class ReturnVal contains the main method. It instantiates the class CalcTime and executes its 2 methods.

class CalcTime {

	double distance;
	double driveTime;

    double TravelTime(String city) {

	if (city.equals("St.Louis")) {
	    distance = 350;
	    driveTime = distance / 63.2;
	} else 	if (city.equals("Chicago")) {
	    distance = 653;
	    driveTime = distance / 66.7;
	}

	return driveTime;
    }

    void morePrint() {
	System.out.println("distance is " + distance);
    }
}

class ReturnVal {

    public static void main(String args[]) {

	double t;

	CalcTime cal = new CalcTime();
	t = cal.TravelTime("Chicago");
	cal.morePrint();

	System.out.println("Travel time is " + t);
    }
}

Previous Next

Steps In Learning

Contact us

Copyright © 2008      N. Nelson      All Rights Reserved