Tutorials

Numbers and Strings in Modern Java Programming

In our guide to primitive data types, you've seen how data types can be initialized with literals. While primitives offer simplicity, object wrappers like Number and String add functionality in Java, especially in modern editions.

This guide explores how Number and String classes, alongside supporting classes like Math and PrintStream, provide enhanced control and performance when dealing with numeric and string operations. We'll explore when and why you should utilize these wrappers.

Key Takeaways

  • Wrapper classes provide object representations for primitive types, adding useful methods for manipulation.
  • Autoboxing and unboxing simplify interacting with wrapper classes, automatically converting primitives where necessary.
  • The Math, PrintStream, and DecimalFormat classes complement Number and String, offering extensive functionality for formatting and calculations.

Why use a wrapper class?

The Number and String classes act as wrappers for primitive types. Sometimes an object representation is necessary, such as when methods require an object parameter. These wrappers offer additional methods like toString(), adding convenience for common operations.

The Java compiler handles conversions between types via autoboxing, reducing boilerplate when using these classes.

The Number Class

Numeric wrapper classes under the abstract Number class include:

  • Byte
  • Double
  • Float
  • Integer
  • Short
  • Long

These wrappers convert and compare numeric values effectively via methods like:

public class MainClass {
    public static void main(String[] args) {
        Integer myInt = 25;
        System.out.println(myInt.floatValue()); // prints 25.0
        System.out.println(myInt.longValue());  // prints 25
        System.out.println(myInt.compareTo(25)); // prints 0
        System.out.println(myInt.equals(26));   // prints false
    }
}

The compareTo() and equals() methods provide enhancements absent from primitives.

Formatting Numeric Output

PrintStream methods format() and printf() help format numeric output:

public class MainClass {
    public static void main(String[] args) {
        int myAge = 25;
        String myName = "Sam";
        System.out.format("My name is %s and I'm %d years old.", myName, myAge);
    }
}

These methods use format strings, where %s and %d are placeholders for strings and integers.

Formatting Decimals

The DecimalFormat class forms a concise solution for decimal precision control:

import java.text.*; 
public class MainClass {
    public static void main(String[] args) {
        DecimalFormat currency = new DecimalFormat("$###.##");
        System.out.println(currency.format(123.456)); // prints $123.46
    }
}

Note the auto-rounding function when formatting exceeds specified decimal places.

Using Math

The Math class enables complex calculations with simplicity:

public class MainClass {
    public static void main(String[] args) {
        System.out.println(Math.min(22.33, 44.54)); // prints 22.33
    }
}

It provides static methods like sqrt(), abs(), min(), and max(), covering an array of common calculations.

The String Class

The immutable String class simplifies manipulation with methods like length() and concat():

public class MainClass {
    public static void main(String[] args) {
        String helloWorld = "Hello world";
        System.out.println(helloWorld.concat("!").length()); // prints 12
    }
}

Methods return new strings, reflecting immutability and optimizing memory usage.

Manipulating Strings

A suite of methods supports flexible string operations:

public class MainClass {
    public static void main(String[] args) {
        String myString = "Hello world";
        System.out.println(myString.toUpperCase());  // prints HELLO WORLD
        System.out.println(myString.replace("l", "z")); // prints Hezzo worzd
    }
}

Remember, operations result in new strings, crucial for performance in tight loops or large projects.

Autoboxing

Java's compiler automatically handles converting between primitive types and their object wrappers, a process known as autoboxing (or unboxing when reversing).

Autoboxing lets you easily assign literal values:

Integer myInt = 4;

This simplifies code and reduces manual type management.

FAQ

What's the difference between autoboxing and explicit conversion?

Autoboxing is automatic, handled by the Java compiler, whereas explicit conversion requires manual conversion logic or methods.

Are String wrapper classes better than String objects for performance?

String wrapper classes like StringBuilder or StringBuffer offer better performance with mutable operations, thanks to less memory overhead.

How do I choose between Number classes?

Choose based on required precision and size; for instance, use Integer for whole numbers, Double for fractional values requiring more precision.

Mastering the tech interviewWhat everyone is doing wrong in tech interviews