

A variable with a type and a name, that can be used inside the body of the method.īut here’s the important part: If a method takes a parameter, you must pass it something. And that something must be a value of the appropriate type. Q: What happens if the argument you want to pass is an object instead of a primitive?Ī: You’ll learn more about this in later chapters, but you already know the answer. And remember, you don’t stuff objects into variables the variable is a remote control- a reference to an object. So if you pass a reference to an object into a method, you’re passing a copy of the remote control.

Stay tuned, though, we’ll have lots more to say about this. Q: Can a method declare multiple return values? Or is there some way to return more than one value?Ī: Sort of. A method can declare only one return value.

if you want to return, say, three int values, then the declared return type can be an int array. Stuff those ints into the array, and pass it on back.

It’s a little more involved to return multiple values with different types we’ll be talking about that in a later chapter when we talk about ArrayList. Q: Do I have to return the exact type I declared?Ī: You can return anything that can be implicitly promoted to that type. So, you can pass a byte where an int is expected. The caller won’t care, because the byte fits just fine into the int the caller will use for assigning the result. You must use an explicit cast when the declared type is smaller than what you’re trying to return. Q: Do I have to do something with the return value of a method? Can I just ignore it?Ī: Java doesn’t require you to acknowledge a return value. You might want to call a method with a non-void return type, even though you don’t care about the return value. In this case, you’re calling the method for the work it does inside the method, rather than for what the method gives returns. In Java, you don’t have to assign or use the return value.Ĭlasses define what an object knows and what an object does.
