Library contents

Java String.valueOf

Convert a primitive, an object or character-array data into a String using the selected overload.

A simple example

String.valueOf

  1. Start with The integer 2
  2. Do this Convert to text
  3. Result "2"
The result is a character string that you can join to other text.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(String.valueOf(2));
    }
}
Output
2

Syntax

Java syntax
public static String valueOf(Object obj)
JDK 21 method signatures (9)
public static String valueOf(Object obj)
public static String valueOf(char[] data)
public static String valueOf(char[] data, int offset, int count)
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Print the count of remaining seats

The booking screen keeps a numeric count internally and prints it beside a text label. Convert at display time so the same count remains available for arithmetic when another booking is made.

From the programint seats = 12
ResultSeats: 12
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        int seats = 12;
        System.out.println("Seats: " + String.valueOf(seats));
    }
}
Output
Seats: 12

The integer overload produces decimal digits suitable for the label.

Advertisements

Understand a missing optional note

An optional field may be absent when a receipt or notice is displayed. Decide what that missing value should look like on the screen before treating the converted text as a user-supplied note.

Result[null]
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        Object note = null;
        System.out.println("[" + String.valueOf(note) + "]");
    }
}
Output
[null]

A null Object becomes four printable letters. Replace it deliberately if a blank display is preferable.

Print the first entry tag

A coat-check desk numbers the first ticket one. The ticket printer includes the number as ordinary decimal text after a prefix. What does the completed label say?

GivenPrefix “Ticket ” + 1
Worked resultTicket 1

What to watch for

Calling valueOf on a null Object returns the text null. A null char array selects a different overload and throws.

Documentation for String.valueOf