Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between char and Character in Java?

I need to know what is the difference between char and Character in Java because when I was making a java program, the char worked while the Character didn't work.

like image 469
Mido Avatar asked Jul 18 '14 10:07

Mido


People also ask

What is a character in Java?

The char keyword is a data type that is used to store a single character. A char value must be surrounded by single quotes, like 'A' or 'c'.

Can we use char in Java?

The Java programming language provides a wrapper class that "wraps" the char in a Character object for this purpose. An object of type Character contains a single field, whose type is char . This Character class also offers a number of useful class (that is, static) methods for manipulating characters.

What is the difference between the char and String data types?

The main difference between Character and String is that Character refers to a single letter, number, space, punctuation mark or a symbol that can be represented using a computer while String refers to a set of characters. In C programming, we can use char data type to store both character and string values.

Is a char a String in Java?

char is one character. String is zero or more characters. char is a primitive type.


2 Answers

char is a primitive type that represents a single 16 bit Unicode character while Character is a wrapper class that allows us to use char primitive concept in OOP-kind of way.

Example for char,

char ch = 'a';

Example of Character,

Character.toUpperCase(ch);

It converts 'a' to 'A'

like image 70
user3589907 Avatar answered Sep 19 '22 09:09

user3589907


From the JavaDoc:

The Character class wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char. In addition, this class provides several methods for determining a character's category (lowercase letter, digit, etc.) and for converting characters from uppercase to lowercase and vice versa.

Character information is based on the Unicode Standard, version 6.0.0.

So, char is a primitive type while Character is a class. You can use the Character to wrap char from static methods like Character.toUpperCase(char c) to use in a more "OOP way".

I imagine in your program there was an 'OOP' mistake(like init of a Character) rather than char vs Character mistake.

like image 45
dimzak Avatar answered Sep 21 '22 09:09

dimzak