Java - Working With Strings
StringBuffer
String is an immutable sequence of characters. StringBuffer is mutable sequence of characters. StringBuffer is modifiable variant of String object. StringBuffer is thread-safe and hence multiple threads can try accessing the string without causing conflicts. StringBuffer has append and insert for all primitive datatypes and Objects. It also has delete methods to remove one or more characters at specified positions.
StringBuffer - Example
public class StringBufferExample {
public static void main(String a[]){
StringBuffer sbuffer= new StringBuffer(
"Time is an resource with no limits. ");
System.out.println( "Orginal String: "+ sbuffer);
sbuffer.append( "Earth rotates and revolves. ");
System.out.println( "After Append: "+sbuffer);
sbuffer.insert( sbuffer.lastIndexOf(" ")+1,
"Moon rotates around the Earth.");
System.out.println( "After insert: " +sbuffer);
int lastIndex=sbuffer.lastIndexOf("Earth.");
System.out.println("Last Index of 'Earth': " +lastIndex);
sbuffer.delete(sbuffer.lastIndexOf("Earth."), lastIndex+5);
System.out.println("After deletion: " +sbuffer);
int lastIndexThe= sbuffer.lastIndexOf( "the");
sbuffer.replace(lastIndexThe, lastIndexThe+4, "Jupiter");
System.out.println("After replace: " +sbuffer);
}
}
public class StringBufferExample {
public static void main(String a[]){
StringBuffer sbuffer= new StringBuffer( "Time is an resource with no limits. ");
System.out.println( "Orginal String: " +sbuffer);
sbuffer.append( "Earth rotates and revolves. ");
System.out.println( "After Append: " +sbuffer);
sbuffer.insert( sbuffer.lastIndexOf(" ")+1, "Moon rotates around the Earth.");
System.out.println("After insert: " +sbuffer);
int lastIndex= sbuffer.lastIndexOf( "Earth.");
System.out.println( "Last Index of 'Earth': " +lastIndex);
sbuffer.delete(sbuffer.lastIndexOf( "Earth."), lastIndex+5);
System.out.println("After deletion: "+ sbuffer);
int lastIndexThe= sbuffer.lastIndexOf("the");
sbuffer.replace( lastIndexThe, lastIndexThe+4, "Jupiter");
System.out.println( "After replace: " +sbuffer);
}
}
StringBuffer - Output
Orginal String: Time is an resource with no limits. After Append: Time is an resource with no limits. Earth rotates and revolves. After insert: Time is an resource with no limits. Earth rotates and revolves. Moon rotates around the Earth. Last Index of 'Earth': 88 After deletion: Time is an resource with no limits. Earth rotates and revolves. Moon rotates around the . After replace: Time is an resource with no limits. Earth rotates and revolves. Moon rotates around Jupiter.
StringBuilder
StringBuilder is mutable sequence of characters.
Example
public class StringBuilderExample {
public static void main(String a[]){
StringBuilder sb = new StringBuilder();
sb.append( "Cool String. Good String. Some String. It does not matter. ");
sb.append( "Pestering");
System.out.println( sb);
System.out.println( "After Append:\n" +sb);
sb.insert(5, true);
sb.insert(16, "-nice-");
sb.insert(35,'!');
System.out.println( "After insert:\n" +sb);
sb.delete(53, 58);
System.out.println( "After delete:\n" +sb);
sb.deleteCharAt(21);
System.out.println( "After deleteCharAt:\n" +sb);
System.out.println( "Position of not: " +sb.indexOf("not"));
StringBuilder secondSB = new StringBuilder("Super Simple");
System.out.println( "Before reverse"+secondSB);
secondSB.reverse();
System.out.println( "After reverse"+secondSB);
}
}
StringBuffer - Output
Cool String. Good String. Some String. It does not matter. Pestering After Append: Cool String. Good String. Some String. It does not matter. Pestering After insert: Cool true String-nice-. Good String!. Some String. It does not matter. Pestering After delete: Cool true String-nice-. Good String!. Some String. It not matter. Pestering After deleteCharAt: Cool true String-nice. Good String!. Some String. It not matter. Pestering Position of not: 53 Before reverse: Super Simple After reverse: elpmiS repuS
StringTokenizer
StringTokenizer is mutable sequence of characters.
StringBuffer - Example
import java.util.StringTokenizer;
public class StringTokenizerExample {
public static void main(String a[]){
String str= "Good,Bad,Ugly,Nice,Yellow";
StringTokenizer tokenizer= new StringTokenizer(str,",");
System.out.println( "Original String:\n"+str);
System.out.println(
"\nAfter Splitting using String Tokenizer:");
while( tokenizer.hasMoreTokens()){
System.out.println( tokenizer.nextToken());
}
}
}
StringBuffer - Output
Original String: Good,Bad,Ugly,Nice,Yellow After Splitting using String Tokenizer: Good Bad Ugly Nice Yellow
Scanner
Scanner can scan primitives as well as Strings using Regular expresssions. Scanner can use keyboard input, File, or String as its source of input
Example
import java.util.Scanner;
public class ScannerExample {
public static void main(String a[]){
String input = "Where there is a will, there is a way.";
Scanner s = new Scanner(input)
.useDelimiter( "\\s*is|,");
System.out.println( s.next());
System.out.println( s.next());
System.out.println( s.next());
System.out.println( s.next());
s.close();
}
}
Scanner - Output
Where there a will there a way.
String.split()
String.split() -Example
public class StringSplitExample {
public static void main(String a[]){
String s= "Hello, I am Good!";
String arr[]= s.split(" ",4);
for(int i=0; i<arr.length; i++){
System.out.println( arr[i]);
}
}
}
String.split() - Output
Hello, I am Good!
Reversing a String
Reversing a String - Example
public class StringReverse {
public static void main(String a[]){
StringBuffer sb= new StringBuffer( "Day is Good");
System.out.println( "Original String:");
System.out.println( sb);
System.out.println( "String in Reverse:");
sb.reverse();
System.out.println( sb);
}
}
Output
Original String: Day is Good String in Reverse: dooG si yaD
Finding the position of a character of a string
indexOf and lastIndexOf
Example
public class StringIndexOfAndLastIndexOf {
public static void main(String a[]){
String newString = new String("It was nice knowing you!");
System.out.println("indexOf('n') method returned: "
+ newString.indexOf('n'));
System.out.println("indexOf('o') method returned: "
+ newString.indexOf('o'));
System.out.println("lastIndexOf('o') method returned: "
+ newString.lastIndexOf('o'));
}
}
Output
indexOf('n') method returned: 7 indexOf('o') method returned: 14 lastIndexOf('o') method returned: 21
Working with substrings
Finding whether string contains a specific substring and finding the location of a substringstring.contains(), substring() and trim() method
Example
public class StringContainsAndSubstringAndTrim {
public static void main(String a[]){
String newString
= "It was nice knowing you!";
System.out.println(
"contains() method returned: "
+ newString.contains("nice"));
System.out.println(
"substring() method returned: "
+ newString.substring(7));
String anotherString
= " Good Morning! Welcome ";
System.out.println(
"Original String:" +anotherString + ".");
System.out.println(
"Trimmed String:" +anotherString.trim() + ".");
}
}
Output
contains() method returned: true substring() method returned: nice knowing you! Original String: Good Morning! Welcome . Trimmed String:Good Morning! Welcome.
Finding whether string starts with or ends with a substring
string.startsWith() and string.endsWith() method
Example
public class StringBeginsWithEndsWith {
public static void main(String a[]){
String str1 ="Once upon a time";
if(str1.startsWith("On") == true){
System.out.println(str1 + " starts with On");
}
if(str1.endsWith("ime") == true){
System.out.println(str1 + " ends with ime");
}
}
}
Output
Once upon a time starts with On Once upon a time ends with ime
Replacing a substring with another substring in a String
Example
public class StringReplace {
public static void main(String a[]){
String str1="Where there is a will, there is a way";
System.out.println("Original String:");
System.out.println(str1);
String str2=str1.replace("is", "good");
System.out.println("String after using replace:");
System.out.println(str2);
}
}
Output
Original String: Where there is a will, there is a way String after using replace: Where there good a will, there good a way
Converting a String to Uppercase or Lowercase
Example
public class StringCaseConversion {
public static void main(String a[]){
String strNew="Great wall of China";
System.out.println("Original String: "+strNew);
String strLower= strNew.toLowerCase();
System.out.println("String in LowerCase: " + strLower);
String strUpper = strNew.toUpperCase();
System.out.println("String in UpperCase: " + strUpper);
}
}
Output
Original String: Great wall of China String in LowerCase: great wall of china String in UpperCase: GREAT WALL OF CHINA
Conversion between Primitive Data Type and String
Converting a Primitive Data Type into String and String to Primitive Data TypeExample
public class PrimitveDataToStringExample {
public static void main(String a[]){
byte b=12;
short s=24;
int i=64000;
long l=1289004200l;
float salary=60000.0f;
double amount=10456990.30;
char c='A';
boolean flag=true;
String sByte = String.valueOf(b);
String sShort = String.valueOf(s);
String sInt = String.valueOf(i);
String sLong = String.valueOf(l);
String sSalary = String.valueOf(salary);
String sAmount = String.valueOf(amount);
String sA = String.valueOf(c);
String sFlag = String.valueOf(flag);
byte byteFromString = Byte.parseByte(sByte);
short shortFromString = Short.parseShort(sShort);
int intFromString = Integer.parseInt(sInt);
long longFromString = Long.parseLong(sLong);
float floatFromString = Float.parseFloat(sSalary);
double doubleFromString = Double.parseDouble(sAmount);
char charFromString = sA.charAt(0);
boolean flagFromString = Boolean.parseBoolean(sFlag);
}
}
Java Objects vs primitive data types
Primitive data types occupy lesser memory and are efficient. Java Objects are created using the primitive data types and other Java objects as fields.