Categories
java

Difference between StringBuffer and StringBuilder in java

Difference between StringBuffer and StringBuilder in java

In this tutorial, we will learn the difference between StringBuffer and StringBuilder in java

StringBuffer and StringBuilder are mostly used for string operations in java. but it  has some difference in nature, let’s see the difference below.

StringBuilder StringBuffer
It is not thread safe,which means It is not synchronizedIt is thread safe, which means it is synchronized
It is faster than StringBufferIt is slower than StringBuilder

StringBuffer Syntax

StringBuffer buffer = new StringBuffer();
//.append is the keyword to concat the strings
buffer.append("");

StringBuilder Syntax

StringBuilder builder = new StringBuilder();
// .append method used to concat string
builder.append("");

Examples

StringBufferhttps://beginnersbug.com/stringbuffer-example-in-java/
StringBuilderhttps://beginnersbug.com/stringbuilder-java/
Reference

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

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

Categories
java

StringBuffer example in java

StringBuffer example in java

In Below example we will learn how to use StringBuffer example in java

StringBuffer is a thread safe, which means only one thread can at once
So It will be slow compared to StringBuilder.

Example

public class StringBufferExample {

	public static void main(String[] args) {
		
		//In below line we are defining the string buffer
		StringBuffer buffer = new StringBuffer();
		//.append is the keyword to concat the strings
		buffer.append("This");
		buffer.append(" is a ");
		buffer.append("String Buffer ");
		buffer.append("Example");
		
		System.out.println(buffer.toString());

	}

}

Output

This is a String Buffer Example

Reference

https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html

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

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)

Categories
java

String to int in java

String to int in java

Converting string to int in java is frequently used by java developers,
In this example we will learn how to convert from string to int using java

Syntax

Integer.parseInt("100");
Integer.valueOf("1000");

Example using parseInt method

public class StringToIntExample {
	public static void main(String[] args) {
		try {
			String s = "100";
			// Below line will convert string to int using parseInt
			int numberValue = Integer.parseInt(s);
			System.out.println("Printing integer value " + numberValue);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

Printing integer value 100

Example using valueOf method

public class StringToIntExample {
	public static void main(String[] args) {
		try {
			String s = "222";
			// Below line will convert string to int using valueOf
			int numberValue = Integer.valueOf(s);
			System.out.println("Printing integer value " + numberValue);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

Printing integer value 222

Exception

java.lang.NumberFormatException: For input string:
we have a possible to get above exception when a string have alphabets in it

Example for Exception

public class StringToIntExample {
	public static void main(String[] args) {
		try {
			// In below string we have alphabets so we cannot convert it to int
			String s = "222A";
			// Below line will convert string to int using valueOf
			int numberValue = Integer.valueOf(s);
			System.out.println("Printing integer value " + numberValue);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

java.lang.NumberFormatException: For input string: "222A"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at com.geeks.overloading.StringToIntExample.main(StringToIntExample.java:9)
Reference

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

Categories
collections java

Sort an Arraylist in java with example

In this tutorial, we will learn how to Sort an Arraylist in java with example by ascending order using collections class

If you are new to array list refer below link to understand array list
https://beginnersbug.com/arraylist-in-java/

Features

  • Sort the specified list into ascending order,
  • This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
  • The specified list must be modifiable, but need not be resizable.

Syntax

Collections.sort(list);

Example

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortArrayListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList();
        list.add("Car");
        list.add("Zebra");
        list.add("Apple");
        list.add("Ball");
        System.out.println("Array list values before sorting \n");
        for (String string : list) {
            System.out.println("Value is " + string);
        }
        // Below sort method will sort your list
        Collections.sort(list);
        System.out.println("\nArray list values after sorting \n");
        for (String string : list) {
            System.out.println("Value is " + string);
        }
    }
}

Output

Array list values before sorting 

Value is Car
Value is Zebra
Value is Apple
Value is Ball

Array list values after sorting 

Value is Apple
Value is Ball
Value is Car
Value is Zebra

Reference

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html

Related Articles

iterate stream with index in Java8

foreach in java8 using streams

Categories
collections java

HashMap in java with example

HashMap in java with example

In this tutorial we will learn about HashMap in java with example

Hashmap is used store key and value pair in java which implemented map interface internally

Features

  • It will not allow duplicate keys
  • We can store null value as a key
  • It is not thread safe

Example


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashmapExample {
	public static void main(String[] args) {
		try {
			Map<String, String> hashMap = new HashMap();
			hashMap.put("1", "Car");
			hashMap.put("2", "Bus");
			hashMap.put("3", "Train");

			for (Map.Entry<String, String> entry : hashMap.entrySet()) {
				System.out.println(entry.getKey() + " Value is " + entry.getValue());
			}
			System.out.println("---------------");
			// Below code only work above java 8
			hashMap.forEach((key, value) -> {
				System.out.println("Value of " + key + " is " + value);
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

1 Value is Car
2 Value is Bus
3 Value is Train
---------------
Value of 1 is Car
Value of 2 is Bus
Value of 3 is Train

Reference

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
https://beginnersbug.com/check-key-exists-in-hashmap-java/

Download

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/HashmapExample.java

Categories
collections java

ArrayList in java with example

 

In this tutorial we will learn ArrayList in java with example 

In Java we can achieve the dynamic array using arraylist.
ArrayList class available on util package, so we don’t need to import any extra packages, In below example 

  • created new arraylist
  • added value to arraylist
  • printing the array list value by using for loop 

Example

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {
	  public static void main(String[] args) {
      List arrayList = new ArrayList();
      arrayList.add("Java");
      arrayList.add("Java 8");
      arrayList.add("Java 11");
      for (int i = 0; i < arrayList.size(); i++) {
    System.out.println("Value at the index of " + i + " "+arrayList.get(i));
     }
   }
}

Output

Value at the index of 0 Java
Value at the index of 1 Java 8
Value at the index of 2 Java 11
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/ArrayListExample.java

Related Articles

Sort an Arraylist in java with example

iterate stream with index in Java8

 

Categories
date java

print current date in java with example

print current date in java with example

In this post we will learn to print current date in java with examples
Here we used Date.java from java.util package
In this example the time zone will be your default system time zone

Example

import java.util.Date;

public class DateExample {
	   
	public static void main(String[] args) {
          Date date = new Date();
          System.out.println("Current Date : " + date);
     }
}

Output

Current Date : Mon Dec 23 21:35:59 IST 2019
Reference

https://beginnersbug.com/add-3-days-to-the-current-date-in-java/

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/DateExample.java

Categories
java

do while in java with example

do while in java with example

In this tutorial, we will learn do while in java with example

do while is little bit different from other looping statements, because other looping statements while execute only when condition satisfy

But do while will execute without condition once, after that it will check condition to execute next statement

Syntax

do{  
//code
}while(condition);  

Example

public class DoWhileExample {
	  
	public static void main(String[] args) {
       int i = 1;
       do {
          System.out.println("Loop Count " + i);
          i++;
      } while (i <= 5);
   }
}

Output

Loop Count 1
Loop Count 2
Loop Count 3
Loop Count 4
Loop Count 5
Download

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/DoWhileExample.java

Related Articles

https://beginnersbug.com/while-loop-using-boolean-datatype-in-java/