String s;
/*code*/
s = "foo";
Is a whole new object being created, since the empty string can't change?
This:
String s;
doesn't create an "empty string", it's simply an uninitialised variable.
This:
s = "foo";
sets that variable to refer to a String object. It's the object that's immutable, not the variable.
You need to understand the difference between variables and objects.
Consider this code:
String x = "hello";
for (int i = 0; i < 10; i++) {
x = x + i;
}
This will end up creating 11 string objects, but there are only two variables involved (x and i). At any point, the value of i is an integer (0-10) and the value of x is a reference to a String. (It could be null too, but it happens not to be in this example.)
It's important to understand that x is not an object, nor is the value of x an object.
If it helps to think of it in physical terms, consider a piece of paper with my home address on it:
The piece of paper is like the variable - it's "somewhere a value can be stored".
The address written on the piece of paper is like the reference - it's a way of finding an object
The house itself is like the object.
Neither the piece of paper nor the address is the house itself. If you rub the address out on the paper and write a different address instead, that doesn't make any changes to my house - just like changing the value of x doesn't make any changes to the string objects themselves in my sample code.
s isn't currently assigned to anything at all.
But if you had -- if you had defined String s = ""; and then s = "foo";, then the empty string isn't changed, but the variable s is changed to refer to the string "foo" instead of the empty string.
Related
class Main {
public static void main(String[] args) {
String s1 = "xy";
String s2 = s1;
s1 = s1 + s2 + "z";
System.out.println(s1);
System.out.println(s2);
}
}
When I ran the code i was expecting to get something like this, because the value of s1=s2 :
xyxyz
xyxyz
But the actual output is:
xyxyz
xy
I am unsure why i don't get the same answer? Is it because the line of code changing s1 to the value "xyxyz" was ran after making s1=s2?
Java Strings are immutable. When you reassign s1, you create a new String which s1 now references. s2 is still referencing the original string.
Essentially when you do s1 = s2, you are not tying the two into one object, but rather that their values are the same for the time being (this is somewhat simplified). If you were to change the values of either one, it would not affect the values of the other.
Imagine having a .txt file. You type whatever you want to type in it, and then copy and paste it. Afterwards, you go back in the original file and continue typing. The text in the duplicate file hasn't changed, although the text in the original has. This is mostly comparable to what is happening here.
String s2 = s1; is an assignment, not a designation of eternal equality.
That line means, “when the program executes this line, set the value of the s2 variable to be the same as the value the s1 variable contains at the moment it executes.”
Any later changes to the variable s1 will not affect s2. The assignment was a momentary transfer of information, nothing more.
Im having a trouble in java. Im creating a HRRN scheduling. I want to print the integer that I input into a textfield area. Please help me to solve this problem. Thankyou!
private void AWTActionPerformed(java.awt.event.ActionEvent evt) {
int firstprocess=1;
if (bt1.getText().equals("")){
double tempbt1 = Double.parseDouble(bt1.getText());
awttotalprocess = (firstprocess + (tempbt1));
AWTCLICK = 0;
jtf_awt.setText(String.valueOf(awttotalprocess+"ms"));
}
I want to print the awttotalprocess into jtf_awt.
Bracketing issue:
jtf_awt.setText(String.valueOf(awttotalprocess)+"ms");
Many classes come with what's called a .toString() method that prints a pre-specified output when joined with a string. You can concatenate or join a string and a variable -in this case an integer- like this:
int i = 50;
String join() {
return "I'm a string, next is a number: " + 50;
}
Keep in mind that int and Integer are different in that the first is a primitive data type, and the second is the object. This isn't an issue for you in this code but in the future if you try to concatenate a string with an object it may end up printing out the memory address as written in the .toString() default method and would require you to #override the method to specify your own string output. The primitive data types are "easier" to combine and don't require such .toString() overriding or .valueOf() shenanigans.
if (eyeColor == green)
{
System.out.println ("If your eyes are green I recommend buying .... ");
....
}
error says
variable green might not have been initialized
I can't display my whole code since it is for school, but I am just wondering how can I initialized it if the eyeColor from the user input (using scanner) is green?
Not sure what is the type of green but this is how you declare method local variables:
Object green = null;
or
Object green = SOME_DEFAULT_VALUE_BETTER_THAN_NULL;
Initialise eyeColor before you compare it.
If it is a string, simply initialise it as an empty string:
String eyeColor;
eyeColor = "";
Before you perform any checks to see what eyeColor has been specified, you may also want to check to make sure that is is NOT still ""..
Assuming that your variable eyeColor is the input from the user. You could use the following
if("green".equals(eyeColor))
Since green is a string, and it will never change (it is always green), you can just use the string. It is also worth noting that in Java, you need to use .equals() when comparing string values, not '=='.
I would also suggest using .toLowerCase(), so that the comparison is no longer case sensitive. An example check is shown in the code below:
public static void main(String args[]) throws IOException {
String eyeColor = "Green";
if("green".equals(eyeColor.toLowerCase())){
System.out.println ("If your eyes are green I recommend buying .... ");
}
}
I'd like to know, in detail, how the Enhanced For Loop works in Java (assuming i do get how the basic usage of this loop is and how it works in general).
Given the following code:
String[] a = {"dog", "cat", "turtle"};
for (String s : a) {
out.println("String: " + s);
s = in.readLine("New String? ");
}
It doesn't actually modify the original list 'a'.
Why not? How memory Management works? Isn't 's' a reference to the same memory cell of 'a[i]'?
I read on the oracle documentation that enhanced for loops can't be used to remove elements from the original array, it makes sense. Is it the same for modifying values?
Thanks in advance
Isn't 's' a reference to the same memory cell of 'a[i]'?
Originally, yes. But then in.readLine produces a reference to a new String object, which you then use to overwrite s. But only s is overwritten, not the underlying string, nor the reference in the array.
s is a local variable that points to the String instance. It is not associated with a[i], they just happen to have the same value initially.
You can only write
for (int i = 0; i < a.length; i++) {
out.println("String: " + a[i]);
a[i] = in.readLine("New String? ");
}
You can't use for-each loops to modify the original collection or array.
Think in s like an address to an object. The thing here is that s is pointing out to a certain value of the array when using the for loop. When you reassing s inside the loop is just happen that s points out to another value but the original value of the array is not modified as you are only changing the address s is pointing to.
String[] a = {"dog", "cat", "turtle"};
for (String s : a) {
//s --> "dog"
out.println("String: " + s);
s = in.readLine("New String? ");
//s --> the new string the user inputs
}
For every iteration String s initially references to corresponding String object in String a[]. But it is then referenced to another String object that is returned by in.readLine().
private String kNow(String state, String guess) {
for (int i = 0; i < word.length(); i++) {
if (guess.equals(word.charAt(i))) {
state.charAt(i) = word.charAt(i);
}
}
return state;
}
state.charAt(i) part points the problem in the title.
How can I solve the problem, if my approach is not completely wrong.
The reason this doesn't work is because charAt(int x) is a method of the String class - namely it is a function, and you can't assign a function a value in Java.
If you want to loop through a string character by character, I might be tempted to do this:
Char[] GuessAsChar = guess.toCharArray();
Then operate on GuessAsChar instead. There are, depending on your needs, possibly better (as in neater) ways to approach searching for character equivalence in strings.
Not exactly sure what the intention is for guess.equals(word.charAt(i)) as that statement will always evaluate to false since a String never can equal a char, but you want to convert your String to a StringBuilder
private String kNow(String state, String guess) {
final StringBuilder mutable = new StringBuilder(state);
for (int i = 0; i < word.length(); i++) {
if (guess.equals(word.charAt(i))) {
mutable.setCharAt(i, word.charAt(i));
}
}
return mutable.toString();
}
Strings in Java are immutable: you can't change string after it's created. It might be better to use byte[] or char[] or collection for state.
Strings are immutable in Java. This means that you cannot change a string object once you have created it. You can however create a new string and then reassign it to the variable.
state = state.substring(0, i) + word.charAt(i) + state.substring(i + 1);
However in this situation I think it would be better to use a mutable type for state such as a character array (char[]). This allows you to modify individual characters directly.
A second problem with your code is that guess should presumably be a char, not a string. Currently your if statement will always return false because an object of type string will never be equal to an object of type char.