Ok, just 2 lines of code. I understand the first line. What's the meaning of the second line and when and why do i have to use this line?
char c = 'x';
Character C = new Character(c);
Please answer to all of the questions..(What's,when,why)
Ok, just 2 lines of code. I understand the first line. What's the meaning of the second line and when and why do i have to use this line?
char c = 'x';
Character C = new Character(c);
Please answer to all of the questions..(What's,when,why)
char
is a primitive type. Character
is the wrapper to the primitive type, as you can see in the Java documentation
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
is a wrapper of the primitive type char
. It allows you to use the primitive char
in a more object-oriented way.
Java provides a Class for every primitive type (int, char, long, float, byte, short, boolean and double) The ideia is to have this Class instead of the primitive type to operate where you need an Object
.
Object a = new Integer(1);
Object b = new Character(c);
See an ArrayList
, for example:
You cannot do:
ArrayList<boolean> list = new ArrayList<boolean>;
But you can do:
ArrayList<Boolean> list = new ArrayList<Boolean>;
list.add(new Boolean(true));
This is the Wrapper Class of the primary type char. As this is an Object you can use it like every other Object, for Example some Collection use Objects, or a Character could also be null, whereas a char can not.
The first line create a primitive char
where as the second creates a Character
object. You don't have to use one or the other. It depends on what you are doing with your code. Generally java will un-box primitives as needed.
That is called a boxed primitive, and they're useful when, for example, you want to put primitives into a Collection
. Since a collection has to hold objects, you can't just declare a Collection<char>
, so you need to use a Collection<Character>
.