Skip to content

Method Variables

Estimated time to read: 2 minutes

Overview

Methods can create variables for their exclusive use.

  • These variables can only be seen by the code in the method block.

Method variables are defined inside of the method block.

  • Variables may be defined anywhere in the block.
  • Variables are only available to code below where they are defined.
  • Usually declared at the very top of the method block

Method Parameters are a type of Method Variables, they are provided as variables into the method.

Local Method Variables

public void setTirePressures(int ... pressures){
 int i;
 i = 10
}

After the above code has been executed, i and its value no longer exist in the stack.

Nested Local Method Variables

Building upon that, it is possible to have code blocks within other methods.

public void setTirePressures(int ... pressures){
 int i;
 i = 10;

 {
  int j;
 }

}

In the above code, once the inner block (where j is located) exists, the variable and its value are destroyed. The variable j is not accessible anywhere else, even though it is nested within another code block.

Example

The variable, maximumSpeed in the example below is accessible only to the code in the setSpeed() method. It can not be accessed by any other blocks within the class or anywhere else in the runtime.

public class Car(){

 private int speed;
 private int gasoline;
 private boolean engineState;

 public void setSpeed(int newSpeed {
  int maximumSpeed = 65;
  if(newSpeed <= maximumSpeed) {
   speed = newSpeed;
  }
  else{
   speed = maximumSpeed;
  }
 }
}

Ternary Operators in Methods

Taking the setSpeed() method below, this can be improved by using ternary operators.

 public void setSpeed(int newSpeed {
  int maximumSpeed = 65;
  if(newSpeed <= maximumSpeed) {
   speed = newSpeed;
  }
  else{
   speed = maximumSpeed;
  }
 public void setSpeed(int newSpeed) {
  int maximumSpeed = 65;
  speed = newSpeed <= maxSpeed ? newSpeed : maxSpeed;
  // Speed is set to newSpeed is less than or equal to maxSpeed, if so, set value to newSpeed else maxSpeed.
 }

variable equals condition value1 if value1 is less than or equal to value2 value2 then set variable to value1 else value2 end
speed = newSpeed <= maxSpeed ? newSpeed : maxSpeed ;