Is a string containing a single character same as a char? [closed]

怎甘沉沦 提交于 2020-06-29 04:46:12

问题


Is a string containing a single character same as a char ? It seems java treats a single character string as a string itself, but I am not sure.


回答1:


No. Infact String can contain nothing at all. Example : String s="" is still a String.




回答2:


A char is a primitive type, while a String is a an object. Primitive types don't have methods associated, while a String object does. If your string object is a single letter, the array storing it would have a single char, but all these string methods would still work on it. String Methods. Without a Character wrapper, the single char would not have any methods associated with it.




回答3:


No, "c" is a string while 'c' is a char, the quotations determine the type




回答4:


They are different.

You can find this out very easily - simply try to assign one to the other:

String s = 'c';
char s = "s";

Both will generate 'incompatible types' compile errors.

Furthermore, they are fundamentally different things. A char is a primitive type, a string is a reference type. A char value is the single character itself represented as a 2-byte number, a String value is a reference to (essentially) an array of characters elsewhere in memory.




回答5:


You see when you declare a String it starts with capital S which means it is a class from java.lang package While a char is a data type which can hold any single character and not a class.




回答6:


A String containing a single character is not the same as a char. They both can be declared using quotes (single quotes for chars and double quotes for Strings), but they are very different.

A char is a primitive data type just like int, boolean, long, etc; while a String is an Object.[1][2]

At a high level, a way to think about it is that a String is an Object that allows you to operate on a sequence of chars.

When thinking about variables, it may be helpful to think about it in two parts, the type and value.

The type of a variable is specified when it is declared and given a name. In this case, our types would be char and String.

The value is what we assign to the variable with the equals sign.

While two variables, in spirit, may represent the same value, if their types are different they cannot be considered the same.

[1] http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

[2] http://docs.oracle.com/javase/7/docs/api/java/lang/String.html



来源:https://stackoverflow.com/questions/28241493/is-a-string-containing-a-single-character-same-as-a-char

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!