Categories
Interview java String

count number of words in string using java

In this post, we will learn about count number of words in string using java

In below example we using split method to count number of words in a sentence.

If String have more than one space consecutively, then we need to replace with one string using below code

sentence.replaceAll("\\s+", " ").trim();
Syntax
properString.split(" ");
Example using split
public class CountWords {

	public static void main(String[] args) {

		try {
			String sentence = "    The pen    is mightier than the sword . ";
			String properString = sentence.replaceAll("\\s+", " ").trim();
			String[] split = properString.split(" ");
			System.out.println("The sentence have " + split.length + " words");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
The sentence have 8 words
Example using StringTokenizer
import java.util.StringTokenizer;

public class CountWords {

	public static void main(String[] args) {
		try {
			String sentence = "    The pen    is mightier than the sword . ";
			StringTokenizer tokens = new StringTokenizer(sentence);
			System.out.println("The sentence have " + tokens.countTokens() + " words");

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
The sentence have 8 words
Github

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

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

Related Articles

find the first occurrence of a character in string using java

Categories
java String

find the first occurrence of a character in string using java

In this post, we will learn to find the first occurrence of a character in string using java

As like in above image we are going to take String “BeginnersBug” for our example.

This array starts from 0 index to 11.

In this example, we are going to find the first occurrence of character ‘e’. which is 1

Note: that indexOf is case sensitive. It will return -1 if the character is not found

Syntax
	int indexOf = s.indexOf('e');
Example
public class FirstOccurance {

	public static void main(String[] args) {
		try {
			String s = "BeginnersBug";
			int indexOf = s.indexOf('e');
			System.out.println("The first occurance of e is " + indexOf);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
Example
The first occurance of e is 1
Github

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

Related Articles

find the last index of a character in string using java

Categories
java String

find the last index of a character in string using java

In this post, we will learn to find the last index of a character in string using java

As like in above image we are going to take String “BeginnersBug” for our example.

This array starts from 0 index to 11.

In this example, we are going to find the last occurrence of character ‘B’. which is 9

Note: that lastIndexOf is case sensitive. It will return -1 if the character is not found

Syntax
s.lastIndexOf('B');
Example
public class LastIndex {

	public static void main(String[] args) {
		try {
			String s = "BeginnersBug";
			int indexOf = s.lastIndexOf('B');
			System.out.println("The last index of B is " + indexOf);

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

	}
}
Output
The last index of B is 9
Github

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

Related Articles

find the first occurrence of a character in string using java

Convert String to lowercase using java

Categories
java String

How to compare two strings in java

In this post, We will learn How to compare two strings in java

It might sounds easy. But we need to take care of few things while comparing two Strings

Avoid ==

If you are newbie to java, This might surprise you

while you use == to compare string it will not check the value of two strings

Instead of that it will check the reference of two Strings

"BeginnersBug" == new String("BeginnersBug") 
// Above check will return false 

In the above snippet even though both the String are equal it will return false because both are not same object

.equals() method

.equlas method will compare two strings with the value irrespective of its object

Even though if it is two different object it will compare the value of two string

"BeginnersBug".equals(new String("BeginnersBug")) 
// Above check will return true

In the above code snippet it will compare two string value and it will return true for the condition

. equalsIgnoreCase() method

equalsIgnoreCase() method will ignore the case while checking the value of two Strings

If you want to check two Strings irrespective of case sensitive you can use this method

"beginnersbug".equalsIgnoreCase(new String("BeginnersBug")) 
// Above method will return true

In the above code snippet equalsIgnoreCase method will ignore the case sensitive. So it is returning true for the statement

Example

public class CompareStringExample {
	public static void main(String[] args) {
		try {
			// Example 1 == Below check will failS
			if ("BeginnersBug" == new String("BeginnersBug")) {
				System.out.println("Example 1 : Both the strings are equal");
			} else {
				System.out.println("Example 1 : Both the strings are not equal");
			}

			// Example 2 .equals()
			if ("BeginnersBug".equals(new String("BeginnersBug"))) {
				System.out.println("Example 2 : Both the strings are equal");
			} else {
				System.out.println("Example 2 : Both the strings are not equal");
			}

			// Example 3 .equalsIgnoreCase()
			if ("beginnersbug".equalsIgnoreCase(new String("BeginnersBug"))) {
				System.out.println("Example 3 : Both the strings are equal");
			} else {
				System.out.println("Example 3 : Both the strings are not equal");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
Example 1 : Both the strings are not equal
Example 2 : Both the strings are equal
Example 3 : Both the strings are equal
Reference

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

Related Articles

Convert String to lowercase using java

Print a String in java with example

Categories
java

convert int to String in java with example

In this post, we will learn to convert int to String in java with example

Even this is a simple post, But it is difficult to remember all syntax. We can easily convert int to String using valueOf() method

Syntax
String.valueOf(i);
Example
public class ConvertInttoString {

	public static void main(String[] args) {

		int i = 99;
		String stringValue = String.valueOf(i);
		System.out.println("Converted String " + stringValue);
	}

}
Output
Converted String 99
Related Articles

Convert String to lowercase using java

convert String to date in java with example

Github

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

Categories
java

Print a String in java with example

Print a String in java

In this tutorial, we will learn to print a String in java with example


Syntax

System.out.println("");

Example

public class PrintExample {

  public static void main(String[] args) {
    String printingText = "Hello World";
    // Below line will print above string variable
    System.out.println(printingText);
  }
}

Output

Hello World

Reference

https://docs.oracle.com/javase/tutorial/getStarted/application/index.html

Download

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

Categories
java String

Convert String to lowercase using java

Convert String to lowercase using java

In this example we will learn to convert a String to lowercase using java

Syntax

<span class="token function">toLowerCase</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

Example

public class StringLowerCase {

  public static void main(String[] args) {
    String s="A guy from New WORLD ";
    // Below line will convert your string to lower case
    String lowerCase=s.toLowerCase();
    System.out.println(lowerCase);
  }
}

Output

a guy from new world

Reference

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

Categories
Interview java

Print non repeated characters in java

Print non repeated characters in java

In this example we will print non repeated characters from a string using java 
This is mostly asked in the java programming interview 

Example

import java.util.ArrayList;

public class NonRepeatedCharcters {

  public static void main(String[] args) {
    String s = "BeginnersBug";
    String nonRepeatedChars = "";
    ArrayList arrayList = new ArrayList();
    char[] charArray = s.toCharArray();

    for (int i = 0; i < charArray.length; i++) {
      // Checking that character already exists on array list
      boolean contains = arrayList.contains(charArray[i]);
      if (!contains) {        
        arrayList.add(charArray[i]);
        nonRepeatedChars += charArray[i];
      }
    }
    System.out.println(nonRepeatedChars);
  }
}

Output

Beginrsu

Array List Reference

 https://beginnersbug.com/arraylist-in-java/

Download Source Code

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

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/