Saturday, August 4, 2012

Java String tutorial

A string is an ordered sequence of symbols. Sting class is included in java.lang package. So each class in Java, can use String class without importing any package. The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

Java String Class/Java String API

Java String class or Java String API is under package java.lang. String class provides various methods to play with strings for example: length(), charAt(int index), substring(int begin, int end), StringTokenizer (it’s a class), toUpperCase(), equals()…. and some others.

Java String Array

We may also declare arrays of type string. String Array can store strings in it.

Example:


Java Code:
1
2
3
4
5
6
String[] str_array = new String[2];
str_array[0] = "Java String";
str_array[1] = "Java String Array";
     
System.out.println("Index 0: " + str_array[0]);
System.out.println("Index 1: " + str_array[1]);
Output:

Index 0: Java String
Index 1: Java String Array

Arrays in Java start from index 0. In the above example, first we declared an array named str_array of size 2. It means it will have index 0 and 1. We added some text in arrays index 0 and 1 and then displayed on the console.

Java String – Concatenation

Java Strings can be concatenated using operator ‘+’.

Example:

Java Code:
1
2
3
4
String a = "Java String1";
String b = "Java String2";
         
System.out.println("Concatenating strings: " + a + b);
Output:

Concatenating strings: Java String1Java String2

In the above example, we concatenated 3 strings and printed on the console.

Java: Convert String to int

In Java programming, converting String to integer is easy. Though programmer who had worked in C++, might think converting String to Integer will be tricky, but its not the case. Java has wrapper classes for this purpose. We will use Integer wrapper class to convert String to int.

Example:

Java Code:
1
2
3
4
String str_int = "10";
int a = Integer.parseInt(str_int);
// printing a which is integer
System.out.println("Java String to int: " + a);
Output:

Java String to int: 10

Java Split String:

Java String class has many functions that can be used to split string according to requirements.

Example:

Java Code:
1
2
3
4
5
6
7
String str_a = "Java String";
// Java String Length
int len = str_a.length();
System.out.println("Length of string is: " + len);
// start index is 0
System.out.println("Character at 5: " + str_a.charAt(5));
System.out.println("Characters form 5 till end: " + str_a.substring(5, len));
Output:

Length of string is: 11
Character at 5: S
Characters form 5 till end: String

In the given example, first we used length() function to get the length of the string. We stored the length into a variable for later use. Then we used chatAt() function to simply print the character at 5th position of the string. Point to note is that indexes also start here with zero as in arrays. At the end we used function substring() to extract a string from str_a. substring() function takes two input parameters. First one is the start index and second one is the ending index. This function will extract string between the given indexes (inclusive).

Java String Comparison

Java String compare is very commonly used by Java programmers but it’s a bit tricky. Some of us might make mistake while doing it and get wrong
results. Normally we use == (double equal) for comparison. This should not be used for reference datatypes. String is a reference data type so one should avoid using == for String comparison. If we use == for comparison, it wont be a syntax error. It will actually compare references of two strings.

Example:

Java Code:
1
2
3
4
5
6
7
8
9
10
11
12
String a  = new String("Java String1");
String b = new String("Java String1");
         
if(a == b)
        System.out.println("Both Java Strings are equal.");
else
    System.out.println("Java Strings are not equal.");
         
if(a.equals(b))
    System.out.println("Both Java Strings are equal.");
else
    System.out.println("Java Strings are not equal.");
Output:

Java Strings are not equal.
Both Java Strings are equal.

In the given example, first we compared the references of the two strings. If condition failed as both have different references. Then we compared the contents of the strings using eduals() method and got the desired output.

In Java, string can lexicographically be compared using compareTo() and compareToIgnoreCase() functions. These functions return value 0 if the argument is a string lexicographically equal to the string with which it is called; a value less than 0 if the argument is a string lexicographically greater than string with which it is called; and a value greater than 0 if the argument is a string lexicographically less than string with which it is called.

Java String Replace:

You are not supposed to make your own methods for replacing characters in a String. Java String class provides methods for replacing characters in Strings. There are many situations. Lets start with a simple one. Lets say we want to replace all occurrences of a given character in a String.

Example:

Java Code:
1
2
3
4
String str_original = "A Java String";
String str_replaced = str_original.replace( 'a', 'b' );
System.out.println( "Original String = " + str_original );
System.out.println( "Replaced String = " + str_replaced );
Output:

Original String = A Java String
Replaced String = A Jbvb String
Java is case sensitive so character ‘a’ is replaced by character ‘b’ and character ‘A’ has remained unchanged.

Now lets assume we want to replace a character in a String at a specified position. We can use the following function for this purpose:

Java Code:
1
2
3
public static String replaceCharAt(String s, int pos, char c) {
   return s.substring(0,pos) + c + s.substring(pos+1);
}
Example:

Java Code:
1
System.out.println( "Replacing char at given position: " + replaceCharAt("Java String",1,'J') );
Output:

Replacing char at given position: JJva String

Java: String to Char Array:

Sometimes, programmers need to convert a String to character array. Java String API provides a method called toCharArray() that simple convert the String passed as argument to a character array.

Example:

Java Code:
1
2
3
4
5
6
7
8
String str_a = "Java String";
char[] char_array = new char[str_a.length()];
         
char_array = str_a.toCharArray();      
     
for (int i = 0; i < str_a.length(); i++){
    System.out.print (char_array[i]);
}
Output:

Java String

The above example is obvious but it contains some important programming tips. As we know that array cannot be of open size and we have to mention the size of array while declaring it. Now we could have declared a character array of large size to cope with the problem in hand. But better way is to declare the array to exactly the size we need. Since we want to store characters of String str_a in our array, so we used length() function to get the size of string and then we declared the character array of that size.

char[] char_array = new char[str_a.length()];

Later we printed each character of the character array.

Java: Convert String to Date

Sometimes you face situation, where the date is in some String variable and you need to store it in Date object for calculations. Java provides support for this as well.

Example:

Java Code:
1
2
3
String strTmp = "05/17/07";
Date dtTmp = new SimpleDateFormat("MM/dd/yy").parse(strTmp);
System.out.println("Date is : " + dtTmp);
Output:

Date is : Thu May 17 00:00:00 CEST 2007

Please note, you have to import following packages before using the above code.

Java Code:
1
2
import java.util.Date;
import java.text.SimpleDateFormat;
dtTmp is of type Date and it contains date and can be used in further calculations.

Java: Convert Number to String

Many times while coding, situation will arise when you have to convert an integer into String. String API provides a was for that too. We have to use Wrapper class for this.

Example:

Java Code:
1
2
3
int int_num = 10;
String str_num = Integer.toString(int_num);
System.out.println("Integer converted to String: " + str_num);
Output:

Integer converted to String: 10

Java: String to Long

Converting value stored in String variable to Long is also very simple. Just use Wrapper class Long and method parseLong() and you will get Long value. Store it in Long variable or just simply use it in your calculations.

Example:

Java Code:
1
2
3
String str_num = "1001";
long long_num = Long.parseLong(str_num);
System.out.println("String converted to Long: " + long_num);
Output:

String converted to Long: 1001

Java. String to Double:

Converting value stored in String variable to Double is also very simple. Just use Wrapper class Double and method parseDouble() and you will get Double value. Store it in Double variable or just simply use it in your calculations.

Example:

Java Code:
1
2
3
String str_num = "1001.66";
double double_num = Double.parseDouble(str_num);
System.out.println("String converted to double: " + double_num);
Output:

String converted to double: 1001.66

Java: char to String:

Sometimes, it happens that you are required to convert value stored in a character to String. Again Wrapper classes provides the solution. Character wrapper class can be used to achieve the results.

Example:

Java Code:
1
2
3
char a= 'a';
String myString = Character.toString(a);
System.out.println("Character converted to String: " + myString);
Output:

Character converted to String: a

Java: Byte Array to String:

Converting ByteArray to String is simple in Java. You just have to use constructor of String class.

Example:

Java Code:
1
2
3
byte[] byteArray = null;
//someInputStream.read(byteArray);
String str = new String(byteArray);
In the above example, we assume that byte array will be filled by inputstream. InputStream might be reading from some socket connection.

Java String Manipulation:

String manipulation in Java is very easy as java.lang.String API (commonly known as string API) provides a lot of useful function to make the life of developer easier. Let consider the following example:

Example:

Java Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
int int_a = 25;
String str_a = "I have ";
String str_b = " dollars.";
String str_c = str_a + int_a + str_b;
System.out.println(str_c);
  
// now we want to add int_b value
int int_b = 30;
 
int int_c = int_a + int_b;
         
str_c = str_c.replace(Integer.toString(int_a),Integer.toString(int_c));
System.out.println(str_c);
Output:

I have 25 dollars.
I have 55 dollars

This example will clear your concepts about Java String manipulation. We have an integer value in int_a that has to be placed between two Strings. It is simply done by:

Java Code:
1
String str_c = str_a + int_a + str_b;
Java 5 compilier implicitly converted int_a to String. Now we want to add int_b into int_a. This is simple and easily done:
int int_c = int_a + int_b;

Now we have to replace int_a with int_c in String str_c. We will use replace() function of Java String API but problem is, replace() function expects two String arguments and we have int arguments. So we have to convert both int to String. This can be done using Wrapper classes. So replace statement will look like:

Java Code:
1
str_c = str_c.replace(Integer.toString(int_a),Integer.toString(int_c));
Now str_c has the updated text.

Java String Upper/Lower cases:

Java String API provides methods to change the case of the String. Methods like toUpperCase(), toLowerCase are very useful for programmers. If these were not provided, consider the coding you have to do to change each character one by one in loops.

Example:

Java Code:
1
2
3
4
5
6
String str_orig = "Java String";
System.out.println("Original String: " + str_orig);
String str_low = str_orig.toLowerCase();
System.out.println("Lower case String: " + str_low);
String str_upper = str_low.toUpperCase();
System.out.println("Upper case String. " + str_upper);
Output:

Original String: Java String
Lower case String: java string
Upper case String. JAVA STRING

Java String Trim:

Java String API includes a function called trim() that is used to return a copy of the string, with leading and trailing whitespace omitted. It does not remove spaces inbetween strings.

Example:

Java Code:
1
2
3
String str_a = "  Java  String  ";
System.out.println("String is: " + str_a + " of length: " + str_a.length()  );
System.out.println("Trimmed String is: " + str_a.trim() + " of length: " + str_a.trim().length());
Output:

String is: Java String of length: 16
Trimed String is: Java String of length: 12

Java StringTokenizer Class:

Sometimes it's necessary to break a large string into smaller components. These small components are called tokens. Java’s utility package has a class called StringTokenizer (java.util.Stringtokenizer) that can be used to get tokens from a large String.

Example:

Java Code:
1
2
3
4
5
6
String str_a = "Java String API Conversions";
         
StringTokenizer st = new StringTokenizer(str_a);
while (st.hasMoreTokens()) {
   System.out.println(st.nextToken());
}
Output:

Java
String
API
Conversions

The aim of this Java String tutorial was to give you basic understanding of Java String API and also to introduce you with some useful String functions. I hope this helps.

No comments:

Post a Comment

Udah di baca kan.... kritik dan sarannya saya persilahkan ^_^..jangan lupa isi Buku tamunya juga ya...