Archive for Java

Java Strings

Sunday, May 15th, 2011

Java Strings

By: Pankaj Yadav

It represents a sequence of characters. In java, Strings are class object and implements using the three classes as following

*.String

*.StringBuffer

*.StringBuilder

String: It is an object of the String class. It can be created as follows:

Syntax:

String  StringName;
String name = new String("string");

Example:

  String name;

  name = new String("Panakj");
  //And it can be same done as follows:

  String name= new String ("Pankaj");

String Array

String array can be created as follows:

String  nameArray[]= new String[3];

Java String Methods

String class has a number of methods that allows us to accomplish a variety of string manipulations. And the methods of java string class as follows:

toLowerCase() Convert the whole string to lower case

toUpperCase() Convert the string to upper case

replace(”x”,”y”) replaces the x with y

trim() removes the white spaces from beginning and end of string

equals() True if the first string is equal to the other string

equalsIgnoreCase() Ignore String letters A=a are equals and Returns if firststr=secondstr

length() gives length of the string

charAt(n) returns the nth character of the string

compareTo() Returns negative if s1s2, and zero on s1=s2

concat() Concatenates string first with second

substring(n) it returns the part of string between from nth place

substring(n,m) returns string between n and m characters

Java String Examples:


class StringJavaExample
{
	static String name[]={"Pankaj","Amit","Jon","Marry","Vinita"};

	public static void main(String args[])
	{
		int size=name.length;
		String temp=null;
		for(int i=0;i<size;i++)
		{
			for(int j=i+1;j<size;j++)
			{
				if (name[j].compareTo(name[i])<0)
				{
					//swaping string
					temp=name[i];
					name[i]=name[j];
					name[j]=temp;
				}
			}
		}
		for (int i=0;i<size;i++)
		{
			System.out.println(name[i]);
		}
	}
}

Output

Amit

Jon

Marry

Pankaj

Vinita

Java StringBuffer Class:

String creates a fixed length. Where StringBuffer creates strings of flexible length and can be modified.

The methods of the StringBuffer class as follows:

setChartAt(n,’x’) Modifies nth character to x

append() it appends stri1 to str2

insert(n,str2) inserts str2 at nth positon str1

setLength(n) Set the length of the string to n.