Last Updated : 12 Jul, 2025
The
toString()method of
java.util.Optional classin Java is used to get the string representation of this Optional instance.
Syntax:public String toString()Parameters:
This method accepts nothing.
Return value:This method returns the
stringrepresentation of this Optional instance. Below programs illustrate toString() method:
Program 1: Java
// Java program to demonstrate
// Optional.toString() method
import java.util.*;
public class GFG {
public static void main(String[] args)
{
// create a Optional
Optional<Integer> op
= Optional.of(452146);
// get value using toString
String value = op.toString();
// print value
System.out.println("String Representation: "
+ value);
}
}
Output:
String Representation: Optional[452146]Program 2: Java
// Java program to demonstrate
// Optional.toString() method
import java.util.Optional;
public class GFG {
public static void main(String[] args)
{
// create a Optional
Optional<Integer> op
= Optional.empty();
// get value using toString
String value = op.toString();
// print value
System.out.println("String Representation: "
+ value);
}
}
Output:
String Representation: Optional.emptyReferences: https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#toString--
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4