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. 30个物联网传感器小实验:三行代码点亮LED灯

    30个物联网传感器小实验:三行代码点亮LED灯 三行代码点亮LED灯 LED灯闪烁 LED灯调亮度 LED淡入淡出 不写一行代码点亮LED灯 全彩RGB灯 面包板 30个物联网传感器小实验:三行代码点 ...

  2. 洛谷P1228 地毯填补问题

    P1228 地毯填补问题 题目描述 相传在一个古老的阿拉伯国家里,有一座宫殿.宫殿里有个四四方方的格子迷宫,国王选择驸马的方法非常特殊,也非常简单:公主就站在其中一个方格子上,只要谁能用地毯将除公主站 ...

  3. 洛谷P3608 [USACO17JAN]Balanced Photo平衡的照片

    P3608 [USACO17JAN]Balanced Photo平衡的照片 题目描述 Farmer John is arranging his NN cows in a line to take a ...

  4. linux vim 配置 go 开发环境

    安装vim-go 插件 vim 暂时对golang 还不支持语法高亮,如果用户希望使用vim 开发golang 程序,还需要给vim 安装对应的插件 首先需要安装一个vim-pathogen vim插 ...

  5. P5346 【XR-1】柯南家族

    题目地址:P5346 [XR-1]柯南家族 Q:官方题解会咕么? A:不会!(大雾 题解环节 首先,我们假设已经求出了 \(n\) 个人聪明程度的排名. \(op = 1\) 是可以 \(O(1)\) ...

  6. Java程序动态编译Java源文件

    最近接触到公司一个项目,需要将生成的源码动态编译,记录下学习过程. 先贴出官网推荐写法: JavaCompiler.CompilationTask getTask(Writer out,        ...

  7. 字符串split函数

    https://www.cnblogs.com/hjhsysu/p/5700347.html 函数:split() Python中有split()和os.path.split()两个函数,具体作用如下 ...

  8. POJ3694 Network 边双缩点+LCA+并查集

    辣鸡错误:把dfs和ldfs搞混...QAQ 题意:给定一个无向图,然后查询q次,求每次查询就在图上增加一条边,求剩余割边的个数. 先把边双缩点,然后预处理出LCA的倍增数组: 然后加边时,从u往上跳 ...

  9. NET Core Web发布包

    给ASP.NET Core Web发布包做减法 https://www.cnblogs.com/sheng-jie/p/9122582.html 1.引言 紧接上篇:ASP.NET Core Web ...

  10. 050 Pow(x, n)

    实现 pow(x, n).示例 1:输入: 2.00000, 10输出: 1024.00000示例 2:输入: 2.10000, 3输出: 9.26100详见:https://leetcode.com ...