Difference between “char” and “String” in Java

2019-01-03 23:17发布

I am reading a book for Java that I am trying to learn, and I have a question. I can't understand what is the difference between the variable type char and String. For example, there is a difference between int and short, the bytes at the memory and the area of numbers that they have.

But what is the difference between char and String? except that char use (') and "String" (").

PS: It is my first "real" programming language. (At school I learned a fake-language for the purpose of the programming lesson.)

标签: java string char
15条回答
再贱就再见
2楼-- · 2019-01-03 23:52

I would recommend you to read through the Java tutorial documentation hosted on Oracle's website whenever you are in doubt about anything related to Java.

You can get a clear understanding of the concepts by going through the following tutorials:

查看更多
乱世女痞
3楼-- · 2019-01-03 23:55

A char simply contains a single alphabet and a string has a full word or number of words woth having a escape sequence inserted in the end automatically to tell the compiler that string has been ended here.(0)

查看更多
女痞
4楼-- · 2019-01-03 23:55

In terms of ASCII values you can say char is a single ASCII value ranging from 0-255. Whereas String is a collection of ASCII values. Try this code to learn better.

        char c='a';
        String s="a b c d e f g hijkl";
        int i=c;
        System.out.println(i);
        for(int count=0;count<s.length();count++){
            int temp=s.charAt(count);
            System.out.print(temp+" ");
        }

The output will be:

97

97 32 98 32 99 32 100 32 101 32 102 32 103 32 104 105 106 107 108

Since 97 is the ASCII value for small 'a'. 32 is the ASCII value for space. Hope this helps in-depth understanding of the concept.

查看更多
Explosion°爆炸
5楼-- · 2019-01-03 23:58

Well, char (or its wrapper class Character) means a single character, i.e. you can't write 'ab' whereas String is a text consisting of a number of characters and you can think of a string a an array of characters (in fact the String class has a member char[] value).

You could work with plain char arrays but that's quite tedious and thus the String class is there to provide a convenient way for working with texts.

查看更多
姐就是有狂的资本
6楼-- · 2019-01-03 23:58

In char only single character (should be in single quotes) can be used it could be alphabet or any number or even special character. below are the related examples for char

char a = '4';
char a = '$';
char a = 'B';

In String complete line can be used (should be in double quotes). below are the related examples for String

String a = "Hello World";
String a = "1234";
String a = "%%";
查看更多
看我几分像从前
7楼-- · 2019-01-04 00:00

A character is anything that you can type such as letters,digits,punctuations and spaces. Strings appears in variables.i.e they are text items in perls. A character consist of 16bits. While the lenght of a string is unlimited.

查看更多
登录 后发表回答