Java Strings
Let us learn about Java Strings.
Java Strings
String: String is a sequence of characters in Java. Syntax of String declaration is below -
String str = "Tester";
Char ch[] = {"T","e", "s", "t", "e", "r"};
String.valueOf(ch); // prints string Tester
Different String Methods
- Int compareTo() - used to compare 2 strings lexicographically.
- boolean equals()
- String concat()
- boolean equalsIgnoreCase()
- char charAt()
- boolean contains()
- toUpperCase()
- toLowerCase()
- trim()
- substring()
- boolean endsWith()
- boolean startsWith()
- int length()
- replace()
Parsing in String
- int num = Integer.parseInt(str); Converts String to Int
- int num = Integer.ValueOf(str); Converts String to Int
- String.valueOf(); Converts Int to String
- Integer.toString(); Converts Int to String
In Java, Strings are immutable, which means they cannot be changed or modified.
StringBuilder vs StringBuffer
- Object created for StringBuffer cannot be accessed by multiple threads simultaneously.
- It is Synchronized
- Whereas StringBuilder is non synchronized and can be accessed by multiple thread simultaneously.
Some practical examples to get started
Can you guess the output of above program?
Output:
rin
String
string
2nd Program -
3rd Program(Most Important) -
5th Program to understand String FormatsWrite output of below program
// Main.java
public class Main
{
public static void main(String args[])
{
String s1 = "abc";
String s2 = s1;
s1 += "d";
System.out.println(s1 + " " + s2 + " " + (s1 == s2));
StringBuffer sb1 = new StringBuffer("abc");
StringBuffer sb2 = sb1;
sb1.append("d");
System.out.println(sb1 + " " + sb2 + " " + (sb1 == sb2));
}
} //end class
Output - abcd abc false
abcd abcd true
Explanation - So string s2 and s1 both pointing to the same string abc. And, after making the changes the string s1 points to abcd and s2 points to abc, hence false. While in string buffer, both sb1 and sb2 both point to the same object. Since string buffer are mutable, making changes in one string also make changes to the other string. So both string still pointing to the same object after making the changes to the object (here sb2).
// Main.java
public class Main
{
public static void main(String args[])
{
short s = 0;
int x = 07;
int y = 08;
int z = 112345;
s += z;
System.out.println("" + x + y + s);
}
} //end class
Output - Compile error
Explanation - Those other two are red herrings however as the code will never compile due to line 8.
Any number beginning with zero is treated as an octal number (which is 0-7).
Comments
Post a Comment