Object cannot be converted to string when using Optional class in Java

convert optional<string to string java
convert optional object to list java
java optional best practices
optional java 11
optional flatmap
optional field java
optional.ofnullable orelse
java optional ifpresent return

I have the following code trying to use the Optional class:

import java.util.Optional;

// one class needs to have a main() method
public class HelloWorld
{
  public String orelesMethod() {
    return "hello";
  }

  public void test() {
    String value;
    value = Optional.ofNullable(null).orElse(orelesMethod());
    System.out.println(value); 
  }

  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {
    HelloWorld hello = new HelloWorld();

    hello.test();
  }
}

when compiling it, it says:

incompatible types: Object cannot be converted to String
    value = Optional.ofNullable(null).orElse(orelesMethod());

I can not find it out what is the problem, can anyone help on it?

Thank you!

You have defined value to be of type String, but Optional.ofNullable(null) returns Optional<Object> because any object type can be null and you did not specify the actual type. Then you are calling orElse on the object of type Optional<Object> and because T is Object, the orElse method returns an object of type Object which cannot be converted to String.

Therefore you need to specify the type while calling ofNullable:

value = Optional.<String>ofNullable(null).orElse(orelesMethod());

You might also want to use orElseGet method in order not to call orelesMethod when the optional contains value.

Java 8 - Convert Optional<String> to String, Quick and practical guide to Optional in Java 8. we're going to show the Optional class that was introduced in Java 8. To create an empty Optional object, we simply need to use its However, the argument passed to the of() method can't be null. Optional<String> opt = Optional.of("Baeldung");. Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as ‘available’ or ‘not available’ instead of checking null values. It is introduced in Java

A String is an Object, but an Object is not necessarily a String and thus this error. Try this :

public String orelesMethod() {
        return "hello";
    }
    public void test() {
        Object value;
        value = Optional.ofNullable(null).orElse(orelesMethod());
        System.out.println(value);
    }

Guide To Java 8 Optional, In this post I present several examples of the new Optional objects in Java 8 and I In Java null is actually a type, a special one: it has no name, we cannot declare variables of its type, or cast any variables to it, in fact there is a perhaps using, under the hood, this new Optional class introduced in Java 8. To create an empty Optional object, we simply need to use its empty() static method: @Test public void whenCreatesEmptyOptional_thenCorrect() { Optional<String> empty = Optional.empty(); assertFalse(empty.isPresent()); } Note that we used the isPresent() method to check if there is a value inside the Optional object.

Optional<T> is the new (since Java 8) way of handling values which might be null.

You get the value by calling .get().

Note that calling .get() without the value being set throws an NoSuchElementException.

See the reference: Class Optional


Edit:

Also, the return value of your orElse() will be of the same time you initialized you class with. Since that's not a String but null you don't get a String as return.

Java Optional Objects, Optional class in Java is used to get the string representation of this Optional instance. Syntax: get value using toString. String value = op. A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).

Optional toString() method in Java with examples, public final class Optional<T> extends Object. A container object which may or may not contain a non-null value. If a value is toString. public String toString(). Java Convert Object to String. We can convert Object to String in java using toString() method of Object class or String.valueOf(object) method. You can convert any object to String in java whether it is user-defined class, StringBuilder, StringBuffer or anything else. Here, we are going to see two examples of converting Object into String.

Optional (Java Platform SE 8 ), public final class Optional<T> extends java.lang.Object implements java.io. Serializable Optional in Google Guava, this class represents a value of a given type that may or may not exist. Using com.google.common.base. String, toString()� Java Optional Class : Every Java Programmer is familiar with NullPointerException. It can crash your code. And it is very hard to avoid it without using too many null checks. Java 8 has introduced a new class Optional in java.util package. It can help in writing a neat code without using too many null checks.

Class Optional<T>, Optional is naturally covariant on this type, so it is safe to cast an Optional<T> to An immutable object that may contain a non-null reference to another object. Optional (JDK 8 and higher): A new Optional class was added for Java 8. See the Guava User Guide article on using Optional . abstract String � toString(). The String on the left is your String class, not the standard library java.lang.String that is returned by the next() method. You should change the name of your String class to something else, such as MyString. It is always a bad idea to name your class the same as an existing class from the Java library.

Comments
  • Optional.ofNullable(null) results in an Optional<Object> which means orElse must return an Object (which may or may not be a String). Use Optional.<String>ofNullable(null) to get an Optional<String>.
  • How does it answer the question?