Results 1 to 2 of 2
  1. #1
    NirelG is offline Member
    Join Date
    Mar 2017
    Rep Power

    Default Question regarding "String"

    Hi all,

    For my surprise, I understood from the java documentation that "String" is not a primitive data type.
    Although its hard for me to understand this I have also a question regarding something else that was written there:

    "String objects are immutable, which means that once created, their values cannot be changed. "

    I tried to understand this line both from their documentation and online, yet found no explanation.

    I mean I can write:
    Java Code:
    public class MyClass{
    	public static void main(String[] args) {
            String a = "a";
            a = "b";
    The output of course is "b".

    So what does line means?
    If anyone can explain me please what this line means it would be highly appreciated.
    Also why String is not considered a primitive data type although from my side (the programmer) i can use it the same way as int or any other primitive data type?


  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Northern Virginia, United States
    Rep Power

    Default Re: Question regarding "String"

    First, String is not a primitive type because it is a really a class. Internally, it uses a char[] array (which is primitive). It is a special
    class though in that the compiler will automatically create an instance of it when you assign a string in literals.


    Java Code:
    String a = "abcd";
    And String is not mutable because if you do this,

    Java Code:
    a will still have the original string. the replace command returns a new String that has been altered as desired. So you have
    to do this.
    Java Code:
    a = a.replace('a', 'd');
    Now a has a new String object with the desired replacement.

    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 0
    Last Post: 12-07-2012, 08:29 AM
  2. Replies: 3
    Last Post: 10-30-2012, 03:06 PM
  3. Replies: 1
    Last Post: 05-07-2012, 05:35 PM
  4. Replies: 14
    Last Post: 04-08-2011, 06:01 PM
  5. Replies: 0
    Last Post: 04-02-2009, 07:02 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts