Java 101 — Returns and Arguments
First we are going to build a calling class called Rectangle with a method called showArea.
public class Rectangle
{
public int length;
public int width; public int showArea()
{
int area = length * width;
//Return the result
return area;
}
}
Now that we are returning a value area, we have to make our main class able to capture it.
public class testRectangle
{
public static void main (String [] args)
{
Rectangle myObj = new Rectangle();
//Set the values of the rectangle
myObj.length = 45;
mObj.width = 28;
//We make a local variable to store the return
int area = myObj.showArea();
//Output
System.out.println("The area is "+ area);
}
}
We are able to capture the return value from our calling class and set it to the local variable called area.
We are also able to pass variables into our methods not only return variables.
Arguments
We create a calling class called Pirate
import javax.swing.JOptionPane; public class Pirate
{
public void pirateSpeak(String mySentence)
{
mySentence = mySentence + " you scurvy dog!");
myOutput.showMessageDialog(null, mySentence);
}
}
Our function pirateSpeak accepts a String called mySentence.
Inside the function we concatenate the String by adding “you scury dog”.
Our main class.
import javax.swing.JOptionPane; public class PirateGame
{
public static void main (String [] args)
{
Pirate myPirate = new Pirate();
myPirate.pirateSpeak("Hello,");
// This will output:
// Hello, you scurvy dog!
}
}
It is a very powerful feature and once we write more complicated code everything will start making sense.