String java

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]

Contents

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.

原文地址:https://www.cnblogs.com/longchang/p/10649673.html

时间: 2024-12-22 16:42:26

String java的相关文章

Reverse Words in a String (JAVA)

Given an input string, reverse the string word by word. For example,Given s = "the sky is blue",return "blue is sky the". 1 public class Solution { 2 public String reverseWords(String s) { 3 if(s.equals(""))return s; 4 String

String java问题随笔

1.字符串加密 设计思想: 每个字符都能够转化为整数型,也能将整数型转化为字符类型,这样我们在加密时候由于向后推3个,所以可以将字符转换为整形,然后加3,之后在将运算完的变量转化为字符后输出,就可以实现字符串加密. 程序流程图: 输入字符串->将字符串分解为字符->字符转换为整形->整形加3->转化为字符->输出. 源代码:import java.util.*; public class zifu { public static void main(String args[]

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

1.Scanner的概述和方法介绍 * A:Scanner的概述 * 是一个从键盘输入的类,有final修饰,不能被子类继承 * Scanner sc = new Scanner(System.in); * String str = sc.nextLine(); * B:Scanner的构造方法原理 * Scanner(InputStream source) * System类下有一个静态的字段: * public static final InputStream in; 标准的输入流,对应着键

int string java 呼转

int -> String int i=12345; String s=""; 第一种方法:s=i+""; 第二种方法:s=String.valueOf(i); 这两种方法有什么区别呢?作用是不是一样的呢?是不是在任何下都能互换呢? String -> int s="12345"; int i; 第一种方法:i=Integer.parseInt(s); 第二种方法:i=Integer.valueOf(s).intValue(); 这两

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",return "blue is sky the". Update (2015-02-12):For C programmers: Try to solve it in-place in O(1) space. 倒序字符串. 注意使用BufferString,因为如果使用Stri

【Leetcode】Reverse Words in a String JAVA实现

一.题目描述 Given an input string, reverse the string word by word. For example,Given s = "the sky is blue",return "blue is sky the". 二.分析 要注意几点:1.当字符串的头部或者尾部存在空格时,最后都将被消除 2.当两个子字符串之间的空格的个数大于1时,只要保留一个 解题思路:1.首先,将整个字符串进行反转 2.然后,使用split函数对字符串

344. Reverse String Java Solutions

Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh". Subscribe to see which companies asked this question 1 public class Solution { 2 public String reverseString(Str

leetcode344 Reverse String Java

自己写法,不过不被leetcode接受,提示Time Limit Exceeded~~~ public String reverseString(String s) { String res = ""; Stack<Character> stack = new Stack<>(); char[] ch = s.toCharArray(); int count = 0; for(char c : ch) { count++; stack.push(c); } fo

345. Reverse Vowels of a String Java Solutions

Write a function that takes a string as input and reverse only the vowels of a string. Example 1: Given s = "hello", return "holle". Example 2: Given s = "leetcode", return "leotcede". Subscribe to see which compani