ZOFTINO.COM android and web dev tutorials

Java Strings

In Java, primitive data type char stores one character. To store text which contains more than one character, Java provides String class. Sequence of characters is stored in a string object and methods provided by string can be used to perform various operations on strings.

Table of Contents

String Object

String object can be created many ways. You can simply assign text to a string variable and complier will create string object.

String offer = "Flat 50% off";

String object can be created using new operator passing either char array or text in double quote.

		char[] nameChar = {'j','a','v','a'};
		String name = new String (nameChar);
		
		String offer = new String ("Flat 50% off");

Immutable

String is an immutable class, once string object is created, it can’t be modified. For example, you have a String variable with leading and trailing spaces and you want to remove those space characters, you can do so by calling trim() method on the string object, but it will create new string object and you need to assign it to a String variable in order to use the trimmed version of the string.

		String dev = " development ";
		String devNoSpace = dev.trim();

Concatenating Strings

You can add two string objects to create a new string object using + operator or concat() method.

		String store = "amazon";
		String offer = "fashion 20% off";
		
		String storeOffer = store+" "+offer;
		System.out.println(storeOffer);
		
		storeOffer = store.concat(" - ").concat(offer);
		System.out.println(storeOffer);

Output :

amazon fashion 20% off
amazon - fashion 20% off

Obtain Character from String at a Specific Position

To get a character at a specific position in the text, you can use charAt() method on the String object. For example, to find out whether input ssn string is in format or not , charAt() method can be used.

	public static boolean isSSNFormat(String ssn) {
		if(ssn.charAt(3) == '-' && ssn.charAt(7) == '-' ) {
			return true;
		}
		return false;
	}
		boolean isSSN = isSSNFormat("123-456-7890");
		System.out.println("is ssn in format : "+isSSN);

String to Char Array

You can convert string to char array using toCharArray() method. For example, to find out whether an offer is a flat discount or percentage of price, first char array is obtained using toCharArray() method and each character is examined to see if there is a digit followed by percentage symbol.

	public static boolean isFlatDiscount(String offer) {
		char prevChar = ' ';
		for(char a : offer.toCharArray()) {
			if(a == '%' && Character.isDigit(prevChar)) {
				return false;
			}
			prevChar = a;
		}
		return true;
	}
		boolean disc = isFlatDiscount("Fashion upto 20% off");
		System.out.println("discount type : "+disc);	

String Contains Text

To find out if a string contains another string, we can use contains() method. For example, to check if cashback keyword is there in a offer text, method contains() is used.

		String deal = "upto 20% cashback";
		if(deal.contains("cashback")) {
			System.out.println("It is a cashback offer");
		}

Strings Comparison

Two strings can be compared lexicographically using compareTo() and compareToIgnoreCase() methods.

		String offerOne = "fashion 20% off";
		String offerTwo = "fashion 40% off";
		
		int compStatus = offerOne.compareTo(offerTwo);
		
		if(compStatus == 0) {
			System.out.println("same text");
		}else if(compStatus > 0) {
			System.out.println("offer one is greater than offer two");
		}else {
			System.out.println("offer one is less than offer two");
		}

Output:

offer one is less than offer two

To check if two string objects are equal, you can use equal() and equalIgnoreCase() methods.

		String storeName = "amazon";
		String inputStore = "ebay";
		if(storeName.equals(inputStore)) {
			System.out.println("same store");
		}else {
			System.out.println("two different stores");
		}

String Starts and Ends with Text

To find out if a string starts with or ends with the given text, methods startWith() and endsWith() can be used.

		String offerOne = "flat 20% off on mobiles";
		if(offerOne.startsWith("flat")) {
			System.out.println("same discount on all items in the category");
		}
		String offerTwo = "upto 20% off on electronics, $200 max";
		if(offerTwo.endsWith("max")) {
			System.out.println("discount with upper limit");
		}

Formatting Strings

You can use format() of String class to format string. The method takes format string and arguments to the format as input.

		String offerFormat = "upto %d%s off on %s at %s";
		String offer = String.format(offerFormat, 35,"%", "fashion", "amazon");
		System.out.println(offer);

Output:

upto 35% off on fashion at amazon

Finding Char Position in String

To find position of a char or string in a string, you can use indexOf() method and its variants.

		String offerOne = "flat 20% off on mobiles";
		int index  = offerOne.indexOf('%');
		System.out.println("% index "+index);
		
		index  = offerOne.indexOf("off");
		System.out.println("off index "+index);

Output:

% index 7
off index 9

To find out index of a char or string after a specific position, you can use indexOf() method as shown below.

		String phoneNum = "01-123-456-7890";
		int idx = phoneNum.indexOf('-', 4);
		System.out.println("% index "+idx);

Output:

% index 6

To find out index of last occurrence of a char or string, you can use lastIndexOf() method.

String phoneNum = "01-123-456-7890";
int lastIndex = phoneNum.lastIndexOf("-");
System.out.println("last index "+lastIndex);

Output:

last index 10

String Length

To find out the length of a string, you can use length() method.

		String coupon = "Upto 10% off";
		if(coupon.length() > 12) {
			System.out.println("category specific offer");
		}else {
			System.out.println("simple offer");
		}

Output:

simple offer

String Matching Using Regular Expressions

You can use matches() method to find out whether a string object matches to the given regular expressions. For example, to check if a string contains only digits and hyphen, pass the regular expression [0-9,-]* to matches method.

		String phoneNum = "01-123-456-7890";
		boolean foundMatch = phoneNum.matches("[0-9,-]*");
		System.out.println("string matches to regx "+foundMatch);
		String storeNme = "nordstorm";
		if(storeNme.matches("[a-zA-Z]*")){
			System.out.println("valid store name");
		}

For more information about how to construct regular expressions, see regular expressions.

String Region Match

To find out if a region in a string matches to a region in another string, regionMatches() method can be used. It takes off set index, second string, off set index in second string and string length to be matched.

The example below checks if the region of 3 chars in dealOne after index 9 matches to the region of 3 characters in dealTwo after index 8.

		String dealOne= "upto 45% off on fashion";
		String dealTwo= "flat 5% off on fashion";
		
		if(dealOne.regionMatches(9, dealTwo, 8, 3)) {
			System.out.println("region match found");
		}

Replacing String

To replace part of a string with another string, you can use replace() method.

		String coupon = "flat $200 off on purchase of clothing";
		coupon = coupon.replace("clothing", "fashion items");
		System.out.println(coupon);

Output:

flat $200 off on purchase of fashion items

You can use replaceAll() method to replace all occurrences of a string in a string with another string. To replace only first occurrence of a string in a string with another string, you can use replaceFirst() method.

Splitting String

You can split a string at the occurrence of the specified string and create array of strings using split() method of string object. The split() method takes matching string as regular expression.

		String phoneNum = "01-123-456-7890";
		String[] phoneNums = phoneNum.split("-");
		for(String phoneN : phoneNums) {
			System.out.println("split phone num "+phoneN);
		}

Output:

split phone num 01
split phone num 123
split phone num 456
split phone num 7890

Sub String

You can get part of a string as string object using substring() method, it takes substring’s beginning and ending indices as arguments.

		String phoneNum = "01-123-456-7890";
		String subStr = phoneNum.substring(3, 6);
		System.out.println(subStr);

Output:

123

Trim

To trim leading and trailing space characters, you can use trim() method.

		String storeNme = " nordstorm ";
		System.out.println(storeNme.trim());

Output:

nordstorm

StringBuilder

StringBuilder is similar to String class except that StringBuilder object can be modified, meaning it is mutable. If you need to modify string object many times, using StringBuilder improves the performance. Otherwise use String object. In addition to length which tells the number of characters a StringBuilder object contains, StringBuilder allocates space for additional characters, the extra space is called capacity which can be obtained using capacity() method. Capacity is automatically increased as necessary to accommodate additional characters.

StringBuilder methods are not thread safe and they run fast.

		StringBuilder sb = new StringBuilder("amazon : ");
		sb.append("flat 30% off on appliance ");
		sb.append(200);
		sb.append(" max");
		
		System.out.println(sb.toString());

StringBuilder has methods to append various types of data and it provides methods to insert, replace and delete characters.

		StringBuilder sb = new StringBuilder("amazon : ");
		sb.append("flat 30% off on appliance ");
		System.out.println(sb.toString());
		sb.delete(9, 13);
		sb.insert(9, "upto");		
		System.out.println(sb.toString());

Output:

amazon : flat 30% off on appliance 
amazon : upto 30% off on appliance

StringBuffer

StringBuffer is similar to StringBuilder except that all the methods of StringBuffer are thread-safe. This should be used if multiple threads access variables, otherwise StringBuilder is efficient one.

CharSequence

CharSequence is an interface implemented by CharBuffer, Segment, String, StringBuffer, StringBuilder classes. Like any other interface, any objects which implements CharSequence can be passed as argument to methods which accept CharSequence as parameter.

	public static void printString(CharSequence str) {
		System.out.println(str);
	}

Example method printString() can be passed any object which implements CharSequence such as string, string builder and string buffer.

		String couponLatest = "everything on sale";
		StringBuilder cashback = new StringBuilder("3% cashback on laptops");
		StringBuffer sale = new StringBuffer("extra 5% off on all items");
		
		printString(couponLatest);
		printString(cashback);
		printString(sale);

Output:

everything on sale
3% cashback on laptops
extra 5% off on all items