Practical Coding in Java

Learn to write and validate your own code

Darren Kessner, PhD

(revised January 9, 2026)

Previous: Coding Exercises: Functions and Testing

2. Strings and Math

This chapter demonstrates the use of the String and Math classes in Java.

You can think of a String variable as representing a sequence of characters. In Java, what this really means is that a String variable is a reference to a String object, and it is the String object that actually represents the sequence of characters.

String s = "three";
String t = "four";

Strings have a member function length(). Note that the return value of a member function may differ for differenet objects.

s.length(); // returns 5
t.length(); // returns 4

The Math class is used in a different way. There is no need (or reason) to create Math objects. Instead, the Math class is a collection of useful mathematical functions and constants. Because these functions and constants are unique, they are defined to be static. Static methods and static variables are “shared” across the class, and are referenced using the class name.

Math.sin(0); // returns 0

Next: