Categories
java

StringBuilder in java with example

StringBuilder in java with example

In this tutorial we will learn StringBuilder in java with example.

StringBuilder in java is widely used to concat two strings 
It is non synchronized (Not thread safe)

Syntax

sb.append("")

Example

public class StringBuilderExample {

	public static void main(String[] args) {
		StringBuilder builder = new StringBuilder();
		// .append method used to concat string
		builder.append("This");
		builder.append(" is");
		builder.append(" an");
		builder.append(" example");

		// printing the string
		System.out.println(builder.toString());

	}
}

Output

This is an example
Reference

https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

https://beginnersbug.com/difference-between-stringbuffer-and-stringbuilder-in-java/

Categories
java

Split String in java using delimiter

Split String in java using delimiter

In this tutorial we will learn how to split a string in java using delimiter
we will use split method to split the string variable

Synatx

s.split(" "); // here delimiter is space
s.split("-"); // here - is space
s.split("_"); // here _ is space

Example using space

public class SplitStringExample {

	public static void main(String[] args) {
		String s = "this is an example";
		// In below line we used space as a delimiter
		String[] split = s.split(" ");
		// we will get the splited string as array
		// In below line we using for loop to print each array value
		for (int i = 0; i < split.length; i++) {
			System.out.println(split[i]);
		}
	}
}

Output

this
is
an
example

Example using –

public class SplitStringExample {

	public static void main(String[] args) {

		String s = "google-yahoo";
		// In below line we used space as a delimiter
		String[] split = s.split("-");
		// we will get the splited string as array
		//In below line we using for loop to print each array value
		for (int i = 0; i < split.length; i++) {
			System.out.println(split[i]);
		}

	}

}

Output

google
yahoo
Reference

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)