简体   繁体   中英

How do I instantiate a char datatype in Java?

Input:

1
1.2
A

If line1 is integer then I return

new Integer(1);

If line2 is float then I return

new Float(1.2);

What should return for line 3 being a character?

There is a character wrapper for char primitive type. You can do new Character(char input)

If you need to get an instance of java.lang.Character from char , you have two ways:

Character c = Character.valueOf('A');

Or:

Character c = new Character('A');

Both ways are equivalent except the first way is more efficient because it uses caching for ASCII characters: Character.valueOf('A') == Character.valueOf('A') is always true.

If you need to convert String to Character , you can use the charAt method:

Character c = "A".charAt(0);

boolean -->Boolean;char --->Character;byte -->Byte;short -->Short;int -->Integer;long -->Long;float -->Float;double -->Double; So new Character('A'); should be what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM