Difference between String and character in Java

In this post, we will discuss the difference between string and character in Java.


 

1. A char is a single character which is 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

A String, on the other hand, consists of sequence of characters (zero or more characters). It is worth pointing out that a String object is backed by an array of chars underneath.

 
2. A char is a primitive data type while a String is a class in Java. Please note that there also exists an object Wrapper type Character for primitive char.

 
3. A char literal needs to be enclosed in the single quotes, while a String literal needs to be enclosed in the double quotes.

 
4. The standard approach to convert a char to a String in Java is to use String.valueOf(char) method which returns the string representation of specified char argument.

We can convert a String containing exactly one character to its equivalent primitive char value in Java. The idea is to call the charAt(int) method on the specified String to retrieve character value present at the first index.

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of