Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set the value of a String in Java without using a constructor?

Tags:

java

string

How-Do/Can I set the value of a String object in Java (without creating a new String object)?

like image 313
Crazy Chenz Avatar asked Aug 02 '10 12:08

Crazy Chenz


People also ask

How do you assign a value to a string?

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.

Do you need to initialize a 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 .

Do we need to initialize string in java?

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.


2 Answers

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.

like image 155
Mark Byers Avatar answered Oct 06 '22 23:10

Mark Byers


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

like image 31
Jose Diaz Avatar answered Oct 07 '22 01:10

Jose Diaz