In Java, Why String is non-primitive data type?

后端 未结 10 2120
闹比i
闹比i 2021-01-01 03:10

In Java, we can directly use String to declare a string variable name and specify its value. We do not have to define the string as an array by using new keywor

10条回答
  •  轮回少年
    2021-01-01 03:26

    I think you are confusing 'primitive' and 'literal'. A primitive is a datatype that is not an object. A literal is a convenient way of describing the bit pattern for a datatype. For instance -1 describes the bit pattern 0xFFFFFFFF for an int,and 'a' describes the unicode code point for a lower case A in 16 bits (0x0061). Literals aren't restricted to describing primitive datatypes. You can describe an array. For instance, int[] a = {1, 2, 3};.

    A string literal is just a way of describing an immutable array of characters with some methods attached. The literal is syntactic sugar for describing something that would otherwise be very complicated. For example:

    String s = "ab";
    

    Is much simpler than:

    char[] c = new char[2];
    c[0] = 'a';
    c[1] = 'b';
    String s = new String(c);
    

提交回复
热议问题