Search code examples
javastringswingjoptionpane

JOptionPane getValue method


I recently started studying Java in college. And in my online test, which is allowed to search, I had a doubt about the method getValue available in the class JOptionPane. Is it true that this method returns an object of class String? If not, why? What kind of object this method returns? Please answer me. Thank you.


Solution

  • It depends on the JOptionPane and the value that was put there to be selected. If the program gives the user the choice between several Strings like (choose: "dog", "cat"...) then you can expect a String when calling the getValue() method.

    But be careful, actually the getValue() only returns an object from the class Object and not a String. Object is the mother of all classes, and a JOptionPane can hold anything you want (String, Integer, Images other JOptionPanes...) so the method getValue() can't really be sure of what kind of class it is returning. That's why it is returning an object of the class Object.

    If you are sure that the JOptionPane contains a String then you could use it like this:

       String myString = (String) myJOptionPane.getValue();
    

    if you are not 100% sure, test the result first:

       if( myJOptionPane.getValue() instanceOf String){
           String myString = (String) myJOptionPane.getValue();
       }
    

    Now if you are wondering why your question got voted down: you may want to google those questions first. The first way to look is in this Java Docs. For example here is the description of the JOptionPane.getValue(). Don't get confused about the complex looking docs. They will give you the correct answer to everything you want to know about how methods and classes work.