Which one of the following methods converts all Java objects into String objects?
A Brief Summary of the String ClassA Java Show
Java
Method SummaryThe commonly-used method in the int length() boolean isEmpty() boolean isBlank() boolean equals(String another) boolean equalsIgnoreCase(String another) int compareTo(String another) int compareToIgnoreCase(String another) boolean startsWith(String another) boolean startsWith(String another, int fromIdx) boolean endsWith(String another) int indexOf(String key) int indexOf(String key, int fromIdx) int indexOf(int char) int indexOf(int char, int fromIdx) int lastIndexOf(String key) int lastIndexOf(String key, int fromIdx) int lastIndexOf(int char) int lastIndexOf(int char, int fromIdx) char charAt(int idx) String substring(int fromIdx) String substring(int fromIdx, int toIdx) String toLowerCase() String toUpperCase() String concat(String another) String trim() String strip() String stripLeading() String stripTrailing() String repeat(int count) String indent(int n) char[] toCharArray() void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) boolean contains(CharSequence cs) boolean contentEquals(CharSequence cs) boolean contentEquals(StringBuffer sb) static String join(CharSequence delimiter, CharSequence... elements) static String join(CharSequence delimiter, Iterable Examplesstatic method String.format() (JDK 5)The String.format("%.1f", 1.234);
System.out.printf("%.1f", 1.234); [TODO] More examples New MethodsJDK 9 new methods
JDK 9 new methods
JDK 11 new methods
JDK 12 new methods
JDK 13 new methods
String is Really Special!Strings receive special treatment in Java, because they are used frequently in a program. Hence, efficiency (in terms of computation and storage) is crucial. The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the method stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces. For performance reason, Java's
String Literal vs. String ObjectAs mentioned, there are two ways to construct a string: implicit construction by assigning a string literal or explicitly creating a String s1 = "Hello"; String s2 = "Hello"; String s3 = s1; String s4 = new String("Hello"); String s5 = new String("Hello"); Java has provided a special mechanism for keeping the You can use the method s1 == s1; s1 == s2; s1 == s3; s1.equals(s3); s1 == s4; s1.equals(s4); s4 == s5; s4.equals(s5); Important Notes:
String is ImmutableSince string literals with the same contents share storage in the common pool, Java's Because String str = "Hello"; for (int i = 1; i < 1000; ++i) { str = str + i; } If the contents of a String.intern()[TODO] StringBuffer & StringBuilderAs explained earlier, JDK provides two classes to support mutable strings:
java.lang.StringBufferRead the JDK API specification for StringBuffer() StringBuffer(int size) StringBuffer(String s) int length() StringBuffer append(type arg) StringBuffer insert(int offset, arg) StringBuffer delete(int fromIdx, int toIdx) StringBuffer deleteCharAt(int idx) void setLength(int newSize) void setCharAt(int idx, char newChar) StringBuffer replace(int fromIdx, int toIdx, String s) StringBuffer reverse() char charAt(int idx) String substring(int fromIdx) String substring(int fromIdx, int toIdx) String toString() int indexOf(String key) int indexOf(String key, int fromIdx) int lastIndexOf(String key) int lastIndexOf(String key, int fromIdx) Take note that To create a string from parts, It is more efficient to use int year = 2010, month = 10, day = 10; int hour = 10, minute = 10, second = 10; String dateStr = new StringBuilder() .append(year).append("-").append(month).append("-").append(day).append(" ") .append(hour).append(":").append(minute).append(":").append(second).toString(); System.out.println(dateStr); String anotherDataStr = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second; System.out.println(anotherDataStr); JDK compiler, in fact, uses both String msg = "a" + "b" + "c"; will be compiled into the following codes for better efficiency: String msg = new StringBuffer().append("a").append("b").append("c").toString(); Two objects are created during the process, an intermediate Rule of Thumb: java.lang.StringBuilder (JDK 5)JDK 5 introduced a new
Benchmarking String/StringBuffer/StringBuilder The
following program compare the times taken to reverse a long string via a
Elapsed Time is 332100 usec (Build String) Elapsed Time is 346639 usec (Using String to reverse) Elapsed Time is 2028 usec (Using StringBuffer to reverse) Elapsed Time is 847 usec (Using StringBuffer's reverse() method) Elapsed Time is 1092 usec (Using StringBuilder to reverse) Elapsed Time is 836 usec (Using StringBuidler's reverse() method) Observe java.util.StringTokenizer (Obsoleted by regex)Very often, you need to break a line of texts into tokens delimited by white spaces. The For example, the following program reverses the words in a String. import java.util.StringTokenizer; public class StringTokenizerTest { public static void main(String[] args) { String str = "Monday Tuesday Wednesday Thursday Friday Saturday Sunday"; String strReverse; StringBuilder sb = new StringBuilder(); StringTokenizer st = new StringTokenizer(str); while (st.hasMoreTokens()) { sb.insert(0, st.nextToken()); if (st.hasMoreTokens()) { sb.insert(0, " "); } } strReverse = sb.toString(); System.out.println(strReverse); } } StringTokenizer(String s) StrintTokenizer(String s, String delimiterChars) boolean hasNextToken() String nextToken() For example, StringTokenizer tokenizer = new StringTokenizer(aString); while (tokenizer.hasNextToken()) { String token = tokenizer.nextToken(); ..... } The JDK documentation stated that " For example, the following program uses the public class StringSplitTest { public static void main(String[] args) { String str = "Monday Tuesday Wednesday Thursday Friday Saturday Sunday"; String[] tokens = str.split("\\s"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < tokens.length; ++i) { sb.insert(0, tokens[i]); if (i < tokens.length - 1) { sb.insert(0, " "); } } String strReverse = sb.toString(); System.out.println(strReverse); } } Regular Expression (Regex), Patterns & Matches (JDK 4)Read "Regular Expression in Java". Super-Interface CharSequence for String, StringBuffer and StringBuilder (since JDK 4)The interface It defines the common behavior via these abstract charAt(int index) -> char abstract length() -> int abstract subSequence(int fromIdx, int toIdx) -> CharSequence abstract toString() -> String JDK 8 added two default chars() -> IntStream default codePoints() -> IntStream JDK 11 added one static compare(CharSequence cs1, CharSequence cs2) -> int LINK TO JAVA REFERENCES & RESOURCES Which of the following methods will create String in Java Mcq?Java String is created by using the keyword “new”. Example: String s=new String(“Welcome”); Hence the correct answer is Both I and II.
In which of the following is toString () method defined?toString() is defined in java. lang. Object.
Which of these methods can be used to convert all characters in a String into a character array Mcq?We can easily convert a string array into a character array using the toCharArray() method.
What are the String methods in Java?All String Methods. |