JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

How To Split String In Java

April 7, 2014 by Krishna Srinivasan Leave a Comment

If you want to split the String value into the different parts based on the delimiter or regular expression, String class provides split() which does the job. It has two overloaded methods with the following syntax:

  1. split(String regex) – Splits this string around matches of the given regular expression.
  2. split(String regex, int limit) – Splits this string around matches of the given regular expression.

This example demonstrates with simple example to make the string splitting easier.

[code lang=”java”]
package javabeat.net.core;

import java.util.Arrays;

/**
* String Split Example
* @author Krishna
*
*/
public class StringSplitExample {
public static void main(String[] args) {
String str="This is test split string!!";

//Split the string with whitespace
String arr[] = str.split(" ");
System.out.println(Arrays.toString(arr));

//Split the string with whitespace and maximum two times
arr = str.split(" ",2);
System.out.println(Arrays.toString(arr));

//Split the string with regular expressions (only numbers)
str="This is7 testf5 split string99!!";
arr = str.split("[0-9]");
System.out.println(Arrays.toString(arr));

//Split the string with regular expressions (only alphabets)
str="345 789r 8778h 897h";
arr = str.split("[a-z]");
System.out.println(Arrays.toString(arr));

}
}
[/code]

Output…

[code]
[This, is, test, split, string!!]
[This, is test split string!!]
[This is, testf, split string, , !!]
[345 789, 8778, 897]
[/code]

Filed Under: Java Tagged With: Java String

Java String IndexOf Example

April 6, 2014 by Krishna Srinivasan Leave a Comment

Java String class consist of methods for finding the index of occurrence in the given string literals. If there is no occurrence of the given characters, then it will return the “-1”.  The following are the few methods which is very useful to find the string values.

  1. indexOf(char) – Returns the index of the character first occurrence in the given string. If it does not occur as a substring, -1 is returned
  2. lastIndexOf(char) – Returns the index of the character last occurrence in the given string. If it does not occur as a substring, -1 is returned
  3. lastIndexOf(string) – Returns the index within this string of the last occurrence of the specified substring. If it does not occur as a substring, -1 is returned
  4. lastIndexOf(string,fromIndex)  – Returns the index within this string of the last occurrence of the specified substring. If it does not occur as a substring, -1 is returned

Look at the below example for String indexOf() methods.

StringIndexExample.java

[code lang=”java”]
package javabeat.net.core;

/**
* String indexOf() Example
* @author krishna
*
*/
public class StringIndexExample {
public static void main(String args[]) {
String str = "Java Strings";

// indexOf(char)
System.out.println("indexOf(char) : " + str.indexOf(‘a’));

// indexOf(char) – non exist character
System.out.println("indexOf(char) – non exist character : "
+ str.indexOf(‘z’));

// lastIndexOf(char)
System.out.println("lastIndexOf(char) : " + str.lastIndexOf(‘a’));

// lastIndexOf(string)
System.out.println("lastIndexOf(string) : " + str.lastIndexOf("Str"));

// lastIndexOf(string,fromIndex)
System.out.println("lastIndexOf(string,fromIndex) : "
+ str.lastIndexOf("Str", 4));
}
}
[/code]

Output…

[code]
indexOf(char) : 1
indexOf(char) – non exist character : -1
lastIndexOf(char) : 3
lastIndexOf(string) : 5
lastIndexOf(string,fromIndex) : -1
[/code]

Filed Under: Java Tagged With: Java String

Java String Reverse using Recursion

April 6, 2014 by Krishna Srinivasan Leave a Comment

This example shows how to reverse a string using the recursion technique. There are several ways to reverse a string one I have explained using the StringBuffer.

Note: The best way is not to choose recursion technique for reversing the string. These concepts are usually used to teach students the recursion , not actual best practices in many cases while working on the real time applications. However, you could choose some other best approach for doing the reverse of string values.

Lets look at the example.

StringReverseRecursion.java

[code lang=”java”]
package javabeat.net.core;

/**
* String reverse using recursion example
*
* @author krishna
*
*/
public class StringReverseRecursion {
public static void main(String args[]) {
String str = "Java 8 Released on March 18, 2014";
String reverse = recurive(str);
System.out.println(str + " : will be reversed to : "+ reverse);
}

/**
* Recursive call
* @param input
* @return
*/
static String recurive(String input) {
if (input.length() <= 1) {
return input;
}
return recurive(input.substring(1)) + input.charAt(0);
}
}
[/code]

Output…

[code]
Java 8 Released on March 18, 2014 : will be reversed to : 4102 ,81 hcraM no desaeleR 8 avaJ
[/code]

Filed Under: Java Tagged With: Java String

Java String Reverse using StringBuffer Example

April 6, 2014 by Krishna Srinivasan Leave a Comment

In this example we shall show you how to reverse the string object by using the Java StringBuffer class. StringBuffer class has a method reverse() which is convenient for reversing a given string value. As it is define in the specification:

Causes this character sequence to be replaced by the reverse of the sequence. If there are any surrogate pairs included in the sequence, these are treated as single characters for the reverse operation. Thus, the order of the high-low surrogates is never reversed. Let n be the character length of this character sequence (not the length in char values) just prior to execution of the reverse method. Then the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence.

StringBufferReverseExample.java

[code lang=”java”]
package javabeat.net.core;

/**
* StringBuffer reverse() method example
* @author krishna
*
*/
public class StringBufferReverseExample {
public static void main(String args[]){
StringBuffer buffer = new StringBuffer();
buffer.append("JavaBeat");
System.out.println("JavaBeat is reversed to :" + buffer.reverse());
}
}
[/code]

Output…

[code]
JavaBeat is reversed to :taeBavaJ
[/code]

Filed Under: Java Tagged With: Java String

Java String ReplaceAll Method Example

April 6, 2014 by Krishna Srinivasan Leave a Comment

In this example we shall explain the replaceAll() method in the String class. With the replaceAll() method we can replace the whole or part of the string or character sequences. String objects are immutable and cannot be changed the value. When ever you change the value, new string object is created. This method also creates the new object after replacing the values and return the new object. Lets look at the below example to understand this concept better. Some of the operations you can do using the replaceAll() method is:

  1. You can replace the single character
  2. You can replace the sequence of characters or a word
  3. You can replace using the regular expression

StringReplaceExample.java

[code lang=”java”]
package javabeat.net.core;

/**
* String replaceAll() method example
* @author krishna
*
*/
public class StringReplaceExample {
public static void main(String args[]){
String str = "String replaceAll() method example!!";
String strRegExTest = "Java 12 23 String 4 Replace Example";
String strObj = null;

// Replace all occurrences of "t" to "T"
strObj = str.replaceAll("t", "T");
System.out.println(strObj);

// Remove all occurrences of "!"
strObj = str.replaceAll("!", "");
System.out.println(strObj);

// Replace "example" to "Example"
strObj = str.replaceAll("example", "Example");
System.out.println(strObj);

// Remove all the numbers
strObj = strRegExTest.replaceAll("[0-9]+", "");
System.out.println(strObj);

// Replace all the words to "Word"
strObj = strRegExTest.replaceAll("[a-zA-Z]+", "Word");
System.out.println(strObj);

}
}
[/code]

Output…

[code]
STring replaceAll() meThod example!!
String replaceAll() method example
String replaceAll() method Example!!
Java String Replace Example
Word 12 23 Word 4 Word Word
[/code]

Filed Under: Java Tagged With: Java String

Java String Intern Method Example

April 6, 2014 by Krishna Srinivasan Leave a Comment

String manipulation is one of the most read and confused subject for the Java programmers. String literals are stored in the string pool where identical objects are pointing to the same reference. If you look at the below example, we have created the “JavaBeat” string using the literals and “new” operator. When we create the string literals, identical literals are pointing to the same location, it will never create the new object in the memory. When we use the “new” operator, it creates the new object in the memory. But, if you are using the intern() method on string objects, it will return the object from the string pool instead of creating a new object. If you look at the below example, you could easily understand it better.

  • What is difference between equals() and == ?
  • HashCode and equals methods

[code lang=”java”]
package javabeat.net.core;

/**
* String intern() example
* @author krishna
*
*/
public class StringInternExample {
public static void main(String args[]){
String str1 = "JavaBeat";
String str2 = "JavaBeat";
String str3 = new String("JavaBeat");
String str4 = new String("JavaBeat").intern();
System.out.println(str1==str2);
System.out.println(str1==str3);
System.out.println(str1==str4);
}
}
[/code]

Output…

[code]
true
false
true
[/code]

Filed Under: Java Tagged With: Java String

Java – String matches() Method Example

March 20, 2014 by Krishna Srinivasan Leave a Comment

This example shows how to use the String.matches() method for testing the regular expressions against any other strings. Using the regular expressions are very efficient to save lot of code for the validations. For example, you can use the pre-defined regular expression to validate the email address without extra code.

[code lang=”java”]
package javabeat.net.util;
/**
* String.matches() example
* @author krishna
*
*/
public class StringMatchExample {
public static void main(String[] args) {
String str = "Java String Examples";
String email = "abc@site.com";
// Checks if string has only letters a-z, A-Z
System.out.println(str.matches("[a-zA-Z *]+$"));

// Checks if string has preceding and trailing word "String"
System.out.println(str.matches("(.*)String(.*)"));

// Checks if the exact word is Java
System.out.println(str.matches("Java"));

// Checks if the string starts with letters "Java"
System.out.println(str.matches("Java(.*)"));

// Checks if string is valid email address
System.out.println(email
.matches("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*"
+ "(\\.[A-Za-z]{2,})$"));
}
}

[/code]

Output

[code]
true
true
false
true
true
[/code]

Filed Under: Java Tagged With: Java String

How To Convert String To Byte In Java?

January 23, 2014 by Krishna Srinivasan Leave a Comment

This tutorial highlights the simple example to demonstrates how to convert a string object to the byte stream. We can simply use the getBytes() method in the string object to convert the string to bytes array. Lets look at the example program.

[code lang=”java”]
package javabeat.net.core;

public class StringToByteExample {
public static void main(String[] argv) {

String str = "JavaBeat Website";
byte[] bytes = str.getBytes();

System.out.println("String Value : " + str);
System.out.println("String [Byte Format] : " + bytes);
System.out.println("—–Printing Bytes Array——-");
for (int i=0;i<bytes.length;i++){
System.out.println(bytes[i]);
}

}
}
[/code]

Output

[code]
String Value : JavaBeat Website
String [Byte Format] : [B@15f5897
—–Printing Bytes Array——-
74
97
118
97
66
101
97
116
32
87
101
98
115
105
116
101
[/code]

Filed Under: Java Tagged With: Java Basics, Java String

How To Convert Char To String In Java?

January 23, 2014 by Krishna Srinivasan Leave a Comment

This post highlights a simple example to demonstrates how to convert a char datatype to a string object. Lets look at the example program.

[code lang=”java”]
package javabeat.net.core;

public class CharToStringExample {
public static void main(String args[]) {
String str = "javabeat";

// convert a String object to char
char charVal = str.charAt(3);
System.out.println(charVal);

// convert char back to String object
String convertStr = Character.toString(charVal);

//Check if it matches with the char
if ("a".equals(convertStr)) {
System.out.println("Value Matching");
}
}
}
[/code]

Output

[code]
a
Value Matching
[/code]

Filed Under: Java Tagged With: Java Basics, Java String

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved