Immutability of Strings in Java

Consider the following example. String str = new String(); str = “Hello”; System.out.println(str); //Prints Hello str = “Help!”; System.out.println(str); //Prints Help! Now, in Java, String objects are immutable. Then how come the object str can be assigned value “Help!”. Isn’t this contradicting the immutability of strings in Java? Can anybody please explain me the exact … Read more

What’s the best name for a non-mutating “add” method on an immutable collection? [closed]

Closed. This question is opinion-based. It is not currently accepting answers. Closed last month. Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions. Sorry for the waffly title – if I could come up with a concise title, … Read more

Why is immutability so important (or needed) in JavaScript?

I am currently working on React JS and React Native frameworks. On the half way road I came across Immutability or the Immutable-JS library, when I was reading about Facebook’s Flux and Redux implementation. The question is, why is immutability so important? What is wrong in mutating objects? Doesn’t it make things simple? Giving an … Read more

What is the difference between shallow copy, deepcopy and normal assignment operation?

import copy a = “deepak” b = 1, 2, 3, 4 c = [1, 2, 3, 4] d = {1: 10, 2: 20, 3: 30} a1 = copy.copy(a) b1 = copy.copy(b) c1 = copy.copy(c) d1 = copy.copy(d) print(“immutable – id(a)==id(a1)”, id(a) == id(a1)) print(“immutable – id(b)==id(b1)”, id(b) == id(b1)) print(“mutable – id(c)==id(c1)”, id(c) == id(c1)) … Read more

Const in JavaScript: when to use it and is it necessary?

I’ve recently come across the const keyword in JavaScript. From what I can tell, it is used to create immutable variables, and I’ve tested to ensure that it cannot be redefined (in Node.js): const x = ‘const’; const x = ‘not-const’; // Will give an error: ‘constant ‘x’ has already been defined’ I realise that … Read more

Is a Java string really immutable?

We all know that String is immutable in Java, but check the following code: String s1 = “Hello World”; String s2 = “Hello World”; String s3 = s1.substring(6); System.out.println(s1); // Hello World System.out.println(s2); // Hello World System.out.println(s3); // World Field field = String.class.getDeclaredField(“value”); field.setAccessible(true); char[] value = (char[])field.get(s1); value[6] = ‘J’; value[7] = ‘a’; value[8] … Read more

Remove specific characters from a string in Python

I’m trying to remove specific characters from a string using Python. This is the code I’m using right now. Unfortunately it appears to do nothing to the string. for char in line: if char in ” ?.!/;:”: line.replace(char,”) How do I do this properly? 26 s 26 Strings in Python are immutable (can’t be changed). … Read more