-
What is the correct way to compare two strings in Java?
The method
equals
checks if the strings match.boolean equals (Object o) String s = "cat"; boolean test1 = s.equals("cat");//true boolean test2 = s.equals("Cat");//false boolean test3 = s.equals("c"+"a"+"t");//true
-
How to correctly compare two strings in Java, ignoring letter case?
Method
equalsIgnoreCase
- whether strings match, ignoring letter case.boolean equalsIgnoreCase (String str) String s = "cat"; boolean test1 = s.equalsIgnoreCase("cat");//true boolean test2 = s.equalsIgnoreCase("Cat");//true boolean test3 = s.equalsIgnoreCase("cAT");//true
-
How to sort a list of strings alphabetically?
By using the method
Collections.sort()
.ArrayList
list = new ArrayList<>(); list.add("zas"); list.add("fas"); list.add("sd"); list.add("asdg"); Collections.sort(list); -
What is the encoding for strings in Java?
Strings in java are stored in Unicode.
-
How to convert string to Windows-1251 encoding?
String utf8 = "text"; byte[] bytes1251 = utf8.getBytes("windows-1251"); String win1251 = new String(bytes1251,"windows-1251");
-
How to split a string into separate words?
String[] split(String regex)
-
StringTokenizer:
String s = "Good news everyone!"; StringTokenizer tokenizer = new StringTokenizer(s,"ne"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); System.out.println(token); }
-
How to reverse a string backwards?
String s = "Bender"; StringBuilder s2 = new StringBuilder(s); s2.reverse(); //будет "redneB";
-
What happens when we write "A"+"b"+"C"?
Approximately the following:
new StringBuilder().append("A").append("b").append("C").toString();
-
What is
mutable
andimmutable
types?Objects that cannot be changed after they are created are called immutable or
immutable
.Objects that can be modified after creation are called mutable or
mutable
. -
What gives the type
String
that it was madeimmutable
?-
Safety.
String
widely used as a parameter for many Java classes, in particular for opening network connections, database connections, opening files, etc. And if the string changed, then we could access the object (file for example) to which we are entitled, then change the line with the name (accidentally or intentionally) and get access to another file.It is also
String
used in the file upload mechanism, and this is a fundamental aspect. And if the string changed, then the request to load " java.io.Writer " could be changed to " DiskErasingWriter ". -
hashcode
Because the string doesn't change, it caches its hashcode and doesn't calculate it every time we call it, which makes the string very fast as a key for
hashmap
. -
Multithreading
immutable
makes string instances thread-safe.
-
GO TO FULL VERSION