Home  >  Article  >  Web Front-end  >  Introduction to the assignment of String type variables in Java_Basic knowledge

Introduction to the assignment of String type variables in Java_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:08:181810browse

Run the following code, what is the result?

package com.test;

public class Example {
  
  String str = new String("good");
  char[] ch = { 'a', 'b', 'c' };

  public static void main(String[] args) {
    Example ex = new Example();
    ex.change(ex.str, ex.ch);
    System.out.println(ex.str);
    System.out.println(ex.ch);
  }

  public void change(String str, char ch[]) {
    str = "test ok";
    ch[0] = 'g';
  }
  
}

The results are as follows:

good
gbc

Commentary:

String in Java is immutable, that is, immutable. Once initialized, the content pointed to by its reference is immutable (note: the content is immutable).

In other words, assuming that there is String str = "aa"; str = "bb"; in the code, the second statement does not change the content of the original storage address of "aa", but opens up another space. Used to store "bb"; at the same time, because "aa" that str originally pointed to is now unreachable, jvm will automatically recycle it through GC.

When calling a method, the String type and array are passed by reference. In the above code, str is passed as a parameter to the change(String str, char ch[]) method. The method parameter str points to the string pointed to by str in the class, but str = "test ok"; statement makes the method parameter str point to the newly allocated address, which stores "test ok", while the original str still points to "good". For arrays, in the change method, the method parameter ch points to the array pointed to by ch in the class, and the ch[0] = 'g'; statement changes the contents of the array pointed to by ch in the class

Let’s take a look at the following code again. What is the result of its operation?

package com.test;

public class Example {
  
  String str = new String("good");
  char[] ch = { 'a', 'b', 'c' };

  public static void main(String[] args) {
    Example ex = new Example();
    ex.change(ex.str, ex.ch);
    System.out.println(ex.str);
    System.out.println(ex.ch);
  }

  public void change(String str, char ch[]) {
    str = str.toUpperCase();
    ch = new char[]{ 'm', 'n' };
  }
  
}

The results are as follows:

good
abc

With the previous explanation, is this result expected? !

The above introduction to the assignment of String type variables in Java is all the content shared by the editor. I hope it can give you a reference, and I hope you will support Script Home.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn