-
How to properly compare two strings in Java?
The method
equals
checks whether 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 case?
Method
equalsIgnoreCase
- whether the 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?
Using the
Collections.sort()
.ArrayList
list = new ArrayList<>(); list.add("zas"); list.add("fas"); list.add("sd"); list.add("asdg"); Collections.sort(list); -
What encoding are strings stored in in Java?
Strings in java are stored in Unicode.
-
How to convert a 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 individual 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 expand a string backwards?
String s = "Bender"; StringBuilder s2 = new StringBuilder(s); s2.reverse(); //будет "redneB";
-
What happens when we write "A"+"b"+"C"?
Something like this:
new StringBuilder().append("A").append("b").append("C").toString();
-
What are
mutable
theimmutable
types?Objects that cannot be changed once they are created are called immutable or
immutable
.Objects that can be changed after they are created are called mutable or
mutable
. -
What does it give to a 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 line were changed, then we could access the object (a file for example) to which we have the right, then change the line with the name (accidentally or intentionally) and gain access to a different file.It is also
String
used in the file upload mechanism, and this is a fundamental aspect. And if the line were to change, 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, making the string very fast as a key for
hashmap
. -
Multithreading
immutable
makes string instances thread safe.
-
GO TO FULL VERSION