0

I am quite new in programming. I have a misunderstanding with Strings in Java. As I know that Strings in java immutable. That means it can not be changed, but I have seen lot's of examples of readings file string by string and currentString always was changed in every iterations. Please help me to understand why it's possible and write. Example from URL Java read large text file with separator

BufferedReader br = null;
try {
    String sCurrentLine;
    br = new BufferedReader(new FileReader("C:\\testing.txt"));//file name with path
    while ((sCurrentLine = br.readLine()) != null) {
           String[] strArr = sCurrentLine.split("\\+");
           for(String str:strArr){
                System.out.println(str);
                  }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
Community
  • 1
  • 1
qmalt
  • 23
  • 1
  • 7
  • By immutable, they mean the instances of the strings themselves cannot be changed. When you reassign the variable, you're assigning a different string instance to it, the old value isn't changed. – Rogue Jan 24 '17 at 10:50

3 Answers3

0

In your code sCurrentLine is not an object but is a reference to an an object. Each time the line is iterated, it is referenced to a new String object, so in fact the value of sCurrentLine doesn't change, but the reference of it changes to a new String object at each iteration which of course contains the different values.

Please refer to this post which explains immutability of strings a lot better.

Community
  • 1
  • 1
px06
  • 2,256
  • 1
  • 27
  • 47
0

In Java String objects are immutable your understanding is correct.

String s = new String("ABC");

String S - > s is reference variable its just a pointer this can be reused only constrain is when u point to other object u ll loose the reference of previous.

"ABC" or new String("ABC") is object in java this is immutable.

In ur program String str is reused as reference variable but the actual objects which will be garbage collect after writing to file as it will dereferenced ion next loop.

Hope u understood.

Akshay
  • 177
  • 1
  • 3
  • 14
0

You are confused with variable and reference. The String objects are immutable. It means String object, to which your variable refers to, cannot be changed. Though, you can reassign variable to new String objects.

Ravi.Kumar
  • 761
  • 2
  • 12
  • 34