String concatenation: Final string value does not equal to the latest value

I have a simple question about string concatenation. Following is the code. I want to ask why s6 = "abcde" and not "akcde"? I have change the s2 value to "k".

Public Class Form1
    Public s1 As String = "a"
    Public s2 As String = "b"
    Public s3 As String = "c"
    Public s4 As String = "d"
    Public s5 As String = "e"
    Public s6 As String = ""
    Public s7 As String = "k"

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        s6 = s1 & s2 & s3 & s4 & s5
        s2 = s7
        MessageBox.Show(s6) 's6 = abcde

    End Sub
End Class

Answers


because when you assign the value to s6 - a new string based on the concatenation of the s1 - s5 is created - changing s2 afterwards has no effect on the value in s6


when you store value in s6 it gets stored as "abcde" and then AFTER THAT you change the value of s2, so s6 is not affected because it is not present in expression "s2=s7"

because the compiler only gets s2 and s7 so it works on that the compiler is not made to check every variable when you change any one variable.....


When you do this:

s6 = s1 & s2 & s3 & s4 & s5

s6 contains abcde, a new string that resulted from the concatenation.

You then change the value of the variable s2 - this does not change s6.


When 2 strings are concatenated, a new string is generated, since string are immutable. Even when you modify a string, a new string is generated. To prove it, just try

s1 = "foo"
s2 = s1
s1 = s1 + "bar" 's2 == 'foo'

Rule of thumb: don't think to string variables as reference to strings, but as value objects, exactly as int or bool variables.


you are just doing your assign and concatenate in the wrong order, change to this;

Public Class Form1
    Public s1 As String = "a"
    Public s2 As String = "b"
    Public s3 As String = "c"
    Public s4 As String = "d"
    Public s5 As String = "e"
    Public s6 As String = ""
    Public s7 As String = "k"

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        s2 = s7
        s6 = s1 & s2 & s3 & s4 & s5
        MessageBox.Show(s6) 's6 = abcde

    End Sub
End Class

Need Your Help

UIScrollView isn't working with Auto-layout and Segue

uiscrollview segue autolayout viewdidload viewdidappear

in the ViewController (principal), i have a UiSrcollView called scroller. It works well when i start the app. But, if i use a segue (to pass to another view controller) the uiscrollview stop to works

Why does writeBytes discard each character's high eight bits?

java

I wanted to use DataOutputStream#writeBytes, but was running into errors. Description of writeBytes(String) from the Java Documentation: