https://www.golinuxcloud.com/java-interview-questions-answers-experienced-2/

75. What is the meaning of Immutable in the context of String class in Java?

  • An Immutable object cannot be modified or changed in Java. String is an Immutable class in Java.
  • Once a String object is created, it cannot be changed. When we assign the String to a new value, a new object is created

76. Why a String object is considered immutable in java?

  • Java language uses String for a variety of purposes. For this it has marked String Immutable.
  • There is a concept of String literal in Java.
  • Let say there are 2 String variables A and B that reference to a String object “TestData”. All these variables refer to same String literal. If one reference variable A changes the value of the String literal from “TestData” to “RealData”, then it will affect the other variable as well. Due to which String is considered Immutable. In this case, if one variable A changes the value to “RealData”, then a new String literal with “RealData” is created and A will point to new String literal. While B will keep pointing to “TestData”

77. How many objects does following code create?

Code:

String s1="HelloWorld";
String s2=" HelloWorld ";
String s3=" HelloWorld ";

The above code creates only one object. Since there is only one String Literal “HelloWorld” created, all the references point to same object.

78. How many objects does following code create?

Code:

String s = new String("HelloWorld");

The above code creates two objects. One object is created in String constant pool and the other is created on the heap in non-pool area.

79. What is String interning?字符串的驻留

  • String interning refers to the concept of using only one copy of a distinct String value that is Immutable.
  • It provides the advantage of making String processing efficient in Time as well as Space complexity. But it introduces extra time in creation of String.

http://www.cnblogs.com/artech/archive/2007/03/04/663728.html

80. What is the basic difference between a String and StringBuffer object?

String is an immutable object. Its value cannot change after creation. StringBuffer is a mutable object. We can keep appending or modifying the contents of a StringBuffer in Java.

https://en.wikipedia.org/wiki/String_interning

String interning

In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable.[1] Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.

The single copy of each string is called its intern and is typically looked up by a method of the string class, for example String.intern()[2] in Java. All compile-time constant strings in Java are automatically interned using this method.[3]

String interning is supported by some modern object-oriented programming languages, including Java, Python, PHP (since 5.4), Lua,[4] Ruby (with its symbols), Julia and .NET languages.[5] Lisp, Scheme, and Smalltalk are among the languages with a symbol type that are basically interned strings. The library of the Standard ML of New Jersey contains an atom type that does the same thing. Objective-C's selectors, which are mainly used as method names, are interned strings.

Objects other than strings can be interned. For example, in Java, when primitive values are boxed into a wrapper object, certain values (any boolean, any byte, any char from 0 to 127, and any short or int between −128 and 127) are interned, and any two boxing conversions of one of these values are guaranteed to result in the same object.[6]

History

Lisp introduced the notion of interned strings for its symbols. Historically, the data structure used as a string intern pool was called an oblist (when it was implemented as a linked list) or an obarray (when it was implemented as an array).

Modern Lisp dialects typically distinguish symbols from strings; interning a given string returns an existing symbol or creates a new one, whose name is that string. Symbols often have additional properties that strings do not (such as storage for associated values, or namespacing): the distinction is also useful to prevent accidentally comparing an interned string with a not-necessarily-interned string, which could lead to intermittent failures depending on usage patterns.

Motivation

String interning speeds up string comparisons, which are sometimes a performance bottleneck in applications (such as compilers and dynamic programming language runtimes) that rely heavily on associative arrays with string keys to look up the attributes and methods of an object. Without interning, comparing two distinct strings may involve examining every character of both.[Note 1] This is slow for several reasons: it is inherently O(n) in the length of the strings; it typically requires reads from several regions of memory, which take time; and the reads fill up the processor cache, meaning there is less cache available for other needs. With interned strings, a simple object identity test suffices after the original intern operation; this is typically implemented as a pointer equality test, normally just a single machine instruction with no memory reference at all.

String interning also reduces memory usage if there are many instances of the same string value; for instance, it is read from a network or from storage. Such strings may include magic numbers or network protocol information. For example, XML parsers may intern names of tags and attributes to save memory. Network transfer of objects over Java RMI serialization object streams can transfer strings that are interned more efficiently, as the String object's handle is used in place of duplicate objects upon serialization.[7]

Issues

Multithreading

One source of drawbacks is that string interning may be problematic when mixed with multithreading. In many systems, string interns are required to be global across all threads within an address space (or across any contexts which may share pointers), thus the intern pool(s) are global resources that should be synchronized for safe concurrent access. While this only affects string creation (where the intern pool must be checked and modified if necessary), and double-checked locking may be used on platforms where this is a safe optimization, the need for mutual exclusion when modifying the intern pool can be expensive.[8]

Contention can also be reduced by partitioning the string space into multiple pools, which can be synchronized independently of one another.

Reclaiming unused interned strings

Many implementations of interned strings do not attempt to reclaim (manually or otherwise) strings that are no longer used. For applications where the number of interned strings is small or fixed, or which are short-lived, the loss of system resources may be tolerable. But for long-running systems where large numbers of string interns are created at runtime, the need to reclaim unused interns may arise. This task can be handled by a garbage collector, though for this to work correctly weak references to string interns must be stored in the intern pool.

String java的更多相关文章

  1. SpringBoot报错:nested exception is org.apache.ibatis.executor.ExecutorException: No constructor found in com.tuyrk.test.User matching [java.lang.Long, java.lang.String, java.lang.String]

    错误提示: Caused by: org.apache.ibatis.executor.ExecutorException: No constructor found in com.tuyrk._16 ...

  2. java.lang.String & java.lang.StringBuilder

    java.lang.String & java.lang.StringBuilder String 成员方法 作用 public charAr(int index) 返回给定位置的代码单元 p ...

  3. Failed to bind properties under 'logging.level' to java.util.Map<java.lang.String, java.lang.String>

    org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'log ...

  4. No converter found capable of converting from type [java.lang.String] to type [java.util.Map<java.lang.String, java.lang.String>]

    java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.conte ...

  5. String(Java版本)

    import java.io.UnsupportedEncodingException; public class Driver { public static void main(String[] ...

  6. String java问题随笔

    1.字符串加密 设计思想: 每个字符都能够转化为整数型,也能将整数型转化为字符类型,这样我们在加密时候由于向后推3个,所以可以将字符转换为整形,然后加3,之后在将运算完的变量转化为字符后输出,就可以实 ...

  7. Scanner、String(java基础知识十二)

    1.Scanner的概述和方法介绍 * A:Scanner的概述 * 是一个从键盘输入的类,有final修饰,不能被子类继承 * Scanner sc = new Scanner(System.in) ...

  8. leetcode 151. Reverse Words in a String --------- java

    Given an input string, reverse the string word by word. For example,Given s = "the sky is blue& ...

  9. leetcode 97 Interleaving String ----- java

    Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example,Given:s1 = ...

随机推荐

  1. AS负责人说不必用Kotlin重写,但OkHttp拿Kotlin重写了一遍,就发了OkHttp 4.0!

    虽然 Android Studio 的负责人 Jeffery 已经澄清,只是 Kotlin-First 而不是 Kotlin-Must,并不需要将 App 用 Kotlin 重写一遍.但是 OkHtt ...

  2. PHP之递归函数

    https://www.cnsecer.com/4146.html http://www.jb51.net/article/71424.htm //一列数字的规则如下:1,1,2,3,5,8,13,2 ...

  3. Python 获取脚本路径以及脚本所在文件夹路径

    import os script_path = os.path.realpath(__file__) script_dir = os.path.dirname(script_path)

  4. 洛谷P1829 [国家集训队]Crash的数字表格 / JZPTAB(莫比乌斯反演)

    传送门 式子好麻烦orz……大佬好腻害orz->这里 //minamoto #include<iostream> #include<cstdio> #define ll ...

  5. FISCO BCOS WorkShop | 区块链开发特训营,开课啦!

    FISCO BCOS是完全开源的联盟区块链底层技术平台,由金融区块链合作联盟(深圳)(简称金链盟)成立开源工作组通力打造.开源工作组成员包括博彦科技.华为.深证通.神州数码.四方精创.腾讯.微众银行. ...

  6. 00 | Two Sum

    Question Given an array of integers, return indices of the two numbers such that they add up to a sp ...

  7. Jmeter (二十六)逻辑控制器 之 Module Controller and Include Controller

    Module Controller ---模块控制器 测试计划设置“独立运行没每个线程组” 线程组2中使用Module Controller执行线程组1中的Sampler: 紧接着,将线程组1disa ...

  8. Django之ORM跨表操作

    Django之ORM表查询及添加记录 一.创建表 - 书籍模型: 书籍有书名和出版日期,一本书可能会有多个作者,一个作者也可以写多本书,所以作者和书籍的关系就是多对多的关联关系(many-to-man ...

  9. [Java]ArrayList、LinkedList、Vector、Stack的比较

    一.介绍 先回顾一下List的框架图 由图中的继承关系,可以知道,ArrayList.LinkedList.Vector.Stack都是List的四个实现类. AbstractList是一个抽象类,它 ...

  10. 寒假作业第二组E题题解

    注意看题,注意看题,注意看题.重要的事情三遍感觉都不够.不怕大家笑话,这道题RuntimeError 9次,我一直以为是哪里越界了,结果最后发现的时候,真是无语了,题目里说了,所有的integer都不 ...