Concepts / Static Variables and Methods

Static Variables and Methods

Functions return values that calling code can use.

  • Programming

A Call That Goes Nowhere

A beginner often assumes that once a function is called, its result is automatically useful. Calling a function is only the first half of the job. The function computes or retrieves a value and hands that value back to the code that called it, and the calling code has to decide what happens next. If nothing receives the value, the work the function did is simply lost.

What do you think happens?

If you call Math.sqrt(16) and print the result, what appears on the screen?

Reveal answer
Answer:

4.0

Math.sqrt computes the square root of 16 and returns it. The print statement receives that returned value and displays it. In Java, the square root is returned as a floating-point value, so it displays as 4.0.

What a Function Sends Back

A function returns a value. Think of a function call as producing a value that must be connected to the next job in the program. The call is not finished when the function's body finishes; the value still has to travel back to the line that made the call. From there it can go to one of two direct destinations: it can be displayed, or it can be assigned to a variable. The call can also take part in a larger numerical expression, because wherever a suitable numeric literal could be written, a function call that returns that kind of value can be written instead.

Math.sqrt(16) callcalling lineFunction bodycomputes the rootReturned value 4.0sent back to the callerAssignmentstored in a variablePrint statementdisplayed on screenLarger expressionused in a calculationpasses controlreturnsmay go tomay go tomay go to
How does a value travel from the function's body back to the calling line, and where can it go next: a variable, a print statement, or part of a bigger calculation?

Putting Returned Values to Work

java
Output
4.0
5.0
Notes on the code
  • Line 1 assigns the returned value to the variable root
  • Line 2 prints the value stored in root
  • Line 3 uses the call inside a larger expression, adding 1 to the returned value before printing
Worked example

Following one returned value through three uses

Trace what a program prints when it stores the square root of 9 in a variable, then uses that variable inside a bigger calculation.

  1. 1
    Make the call

    Math.sqrt(9) is evaluated. The function computes the square root of 9 and returns the value 3.0.

  2. 2
    Assign the value

    The returned value 3.0 is stored in the variable side.

  3. 3
    Use it in an expression

    The expression side * 2 is evaluated using the stored value, giving 6.0.

  4. 4
    Display the result

    The print statement receives 6.0 and displays it.

Result

The program prints 6.0. The function call supplied a value at the exact place where the expression needed one.

Mistakes with Discarded Return Values

Before
Math.sqrt(16);

The root is computed, but no variable or print statement receives it, so the value is discarded.

After
double root = Math.sqrt(16);

The returned value is stored in root, and later lines of the program can use it.

  • Common mistake

    Assuming that calling a function makes its result useful

    What it looks like

    Math.sqrt(25); followed by a line that prints a value without the root

    Why it fails

    The returned value only reaches the program if the calling code directs it somewhere.

    Do this instead

    Assign the returned value to a variable or use it in a print statement or expression.

  • Common mistake

    Expecting a print statement to show a value that was never returned to it

Calling Static Methods from Math

java
Notes on the code
  • Math is the class name, and it appears before the dot
  • sqrt is a static method; the arguments in parentheses supply the input
  • PI and E are static variables holding mathematical constants
  • No Math object is created anywhere in this code

The name before the dot identifies the class that supplies the member. Math.sqrt is a static method that performs a calculation and returns a value. Math.PI and Math.E are static variables that contain mathematical constants. The shared Math prefix shows their relationship to the class, while the member after the dot identifies the particular variable or method. Because these members belong to the class itself, you call them through the class name and do not need to create a Math object first.

Instance Variables Belong to Each Object

Definition

An object created from a class is an instance of that class, and the variables it contains are called instance variables. The word instance names the object, so an instance variable is simply a variable that lives inside one particular object.

The key fact is where these variables live. Instance variables are part of the object, not part of the class. The class describes which variables an object will have, but the values belong to each individual object. This is why two objects created from the same class can hold different data at the same time.

java
Notes on the code
  • The class PlayerData describes two instance variables, name and age
  • first and second are two separate objects built from the same class
  • Each object holds its own name and age values
nameAnaage14nameBenage15
Which named values does each object hold separately, and how do two objects built from the same class keep their own copies of the instance variables?

Instance Methods and Logical Membership

The same idea extends to behavior. The methods, meaning the subroutines, that an object contains are called instance methods. These are the non-static methods, and they become part of objects created from the class. Because an instance method is logically part of the object, you can think of the object as carrying its behavior along with its data: it contains both its instance variables and its instance methods in the logical sense. The source notes that the examples in its discussion do not include methods, but that methods work similarly to variables.

A common picture treats the class as a cookie cutter and every object as a full, independent copy of everything the class describes, including its behavior. Under that picture, three objects created from a class with an instance method would seem to have three separate copies of the method's code in memory. This picture breaks down for methods.

Static Versus Instance: Where Methods Live

Not every method belongs to objects. The source contrasts two kinds. Static methods are part of the class and are associated with the class, not with objects. Non-static methods, which are the instance methods, become part of objects created from the class. Keeping this contrast in mind prevents a common confusion about where a method lives. Math.sqrt is the static case: you call it on the class name. An instance method is called on an object that was created from its class.

Lives inthe classCalled onthe class name, such asMathExampleMath.sqrt(16)Logically part ofeach object made from theclassCalled onan object of the classExamplea call on an objectvariable
Where does each kind of method live, on the class itself or inside each object created from it, and how does a call on the class differ from a call on an object?

Practice Tracing Two Objects

EASY

Using the PlayerData code from the earlier section, what does second.age hold after the code runs, and does changing first.age change second.age? Explain using the idea that instance variables belong to each object.

Hints
  • Look at the value assigned to second.age in the code, not the value assigned to first.age.
  • Ask whether the two objects share one age variable or each have their own.

Key Takeaways

  • A function returns a value, and the calling code must direct that value into a print statement, an assignment, or a larger expression; a call whose result is ignored loses that value.
  • Static members such as Math.sqrt, Math.PI, and Math.E belong to the class, so you call them through the class name without creating a Math object.
  • An object created from a class is an instance of that class, and its variables are instance variables whose values belong to that one object, so two objects can hold different data.
  • Instance methods are non-static methods that logically become part of each object, but the compiled code is defined once by the class and is not literally copied into each object.
  • Static methods are associated with the class, while instance methods are associated with the objects created from it.