How-Do/Can I set the value of a String object in Java (without creating a new String object)?
String assignment is performed using the = operator and copies the actual bytes of the string from the source operand up to and including the null byte to the variable on the left-hand side, which must be of type string. You can create a new variable of type string by assigning it an expression of type string.
out. println(monthString); In order to use a local variable in java it must be initialized to something even if that something is setting it equal to null .
String declaration refers to declaring a String without assigning any value explicitly. In most of the use cases, the only declaration of the String requires not initialization.
There are no "set" methods on String
. Strings are immutable in Java. To change the value of a String
variable you need to assign a different string to the variable. You can't change the existing string.
(without creating a new String object)
Assigning doesn't create a new object - it copies the reference. Note that even if you write something like this:
s = "hello";
it won't create a new string object each time it is run. The string object will come from the string pool.
Actually there is no way to do that in Java, the String objects are immutable by default.
In fact, that's one of the reason why using the "+"
concatenation operator like "str1" + "str2"
is terribly inefficient, because what it does is copy every string in order to produce a third one.
Depending on your need you should consider using StringBuilder
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With