Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

Can anyone help me how I can able to return any data type in Java? I am using the below code to return the datatype:

public static void askln(String text, String type){

     System.out.println(text);

     if(type.equals("int"))

          return getInt();

     if(type.equals("char"))

          return getChar();

     if(type.equals("String")) 

          return getString();

     if(type.equals("double"))

         return getDouble();

     if(type.equals("float"))

         return getFloat();

     if(type.equals("long")) 

         return getLong();

}

It is giving an error. Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

You can use a generic parameter to return the value, so your signature will be something like this:

public static <T> T askln(String text, Class<T> type)

I hope this will help.

Want to become a Java Expert? Join Java Course now!!

Want to know more about Java? Watch this video on Java Tutorial for Beginners | Java Programming:

Related questions

Browse Categories

...