3:50 pm - Thursday February 19, 0720

Strings in java with Example Program

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

Strings

  •  The Java platform provides the  strings class to create and manipulate strings.
  • Strings are a sequence of characters. In the Java programming language, strings are objects.
  • The String class is immutable, so that once it is created a String object cannot be changed.

Creating Strings

  • Direct way to create a string is to write:

String greeting = “Hello world!”;

“Hello world!” is a string.

  • As with any other object, you can create String objects by using the new keyword and a constructor.
System.out.println(helloString);
char[] helloArray = {
'h', 'e', 'l', 'l', 'o', '.'
};
String helloString = new String(helloArray);

Java String Methods

The following program explains the usage of the some of the basic String methods like ;

1. compareTo(String anotherString)
Compares two strings lexicographically.

2. charAt(int index)
Returns the character at the specified index.

3. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.

4. length()
Returns the length of this string.

5. equals(Object anObject)
Compares this string to the specified object.

6. equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.

7. toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.

7. toLowerCase()
Converts all of the characters in this String to upper case using the rules of the default locale.

9. concat(String str)
Concatenates the specified string to the end of this string.

10. indexOf(int ch)

Returns the index within this string of the first occurrence of the specified character.

11. indexOf(int ch, int fromIndex)

Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

12. indexOf(String str)

Returns the index within this string of the first occurrence of the specified substring.

13. indexOf(String str, int fromIndex)

Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

14. lastIndexOf(int ch)

Returns the index within this string of the last occurrence of the specified character.

15. lastIndexOf(int ch, int fromIndex)

Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

16. lastIndexOf(String str)

Returns the index within this string of the rightmost occurrence of the specified substring.

17. lastIndexOf(String str, int fromIndex)

Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

18. substring(int beginIndex)

Returns a new string that is a substring of this string.

19. substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string.

20. replace(char oldChar, char newChar)

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

21. trim()

Returns a copy of the string, with leading and trailing whitespace omitted.

22. toString()


String Length

You can use with strings is the length() method, which returns the number of characters contained in the string object.

int length()

Returns the length of this String.

String message=”Welcome”;

Message.length();//(returns 7)

Concatenating Strings

The String class includes a method for concatenating two strings:

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in:

"My name is ".concat("Rumplestiltskin");

Strings are more commonly concatenated with the + operator, as in

"Hello," + " world" + "!"

which results in

"Hello, world!"

The + operator is widely used in print statements. For example:

String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");

which prints

Dot saw I was Tod

Such a concatenation can be a mixture of any objects.

Creating Format Strings

use of the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement.

For example, instead of

System.out.printf("The value of the float " +"variable is %f, while " +"the value of the " +"integer variable is %d, " +"and the string is %s",  floatVar, intVar, stringVar);

you can write

String fs;
fs = String.format("The value of the float " + "variable is %f, while " +"the value of the " +"integer variable is %d, " + " and the string is %s",floatVar, intVar, stringVar);
System.out.println(fs);

Converting Between Numbers and Strings

The Number subclasses that wrap primitive numeric types ( Byte, Integer, Double, Float, Long, and Short) each provide a class method named valueOf that converts a string to an object of that type.

public class ValueOfDemo {
public static void main(String[] args) {

// this program requires two
// arguments on the command line
if (args.length == 2) {
// convert strings to numbers
float a = (Float.valueOf(args[0])).floatValue();
float b = (Float.valueOf(args[1])).floatValue();

// do some arithmetic
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " +(a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " +(a / b));
System.out.println("a % b = " +(a % b));
} else {
System.out.println("This program " +"requires two command-line arguments.");
}
}
}

Note:

A primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we could use:

float a = Float.parseFloat(args[0]);
float b = Float.parseFloat(args[1]);

Converting Numbers to Strings

Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:

int i;
// Concatenate "i" with an empty string;
// conversion is handled for you.
String s1 = "" + i;

Each of the Number subclasses includes a class method, toString(), that will convert its primitive type to a string. For example:

int i;
double d;
String s3 = Integer.toString(i);
String s4 = Double.toString(d);

Manipulating Characters in a String

Getting Characters and Substrings by Index

You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1. For example, the following code gets the character at index 9 in a string:

String anotherPalindrome =

“Niagara. O roar again!”;

char aChar = anotherPalindrome.charAt(9);

Indices begin at 0, so the character at index 9 is ‘O’, as illustrated in the following figure:

The StringBuilder Class

StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations.

public class StringBufferDemo {                   
public static void main(String[] args) {
		// Examples of Creation of Strings
		StringBuffer strBuf1 = new StringBuffer("Bob");
		StringBuffer strBuf2 = new StringBuffer(100); // With capacity 100
		StringBuffer strBuf3 = new StringBuffer(); // Default Capacity 16
		System.out.println("strBuf1 : " + strBuf1);
		System.out.println("strBuf2 capacity : " + strBuf2.capacity());
		System.out.println("strBuf3 capacity : " + strBuf3.capacity());
	}
}

StringBuffer Methods

The following program explains the usage of the some of the basic StringBuffer methods like ;

1. capacity()
Returns the current capacity of the String buffer.

2. length()
Returns the length (character count) of this string buffer.

3. charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.

4. setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch

5. toString()
Converts to a string representing the data in this string buffer

6. insert(int offset, char c)
Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded ‘insert’ methods which can be used based on the application need.

7. delete(int start, int end)
Removes the characters in a substring of this StringBuffer

8. replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with characters in the specified String.

9. reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.

10. append(String str)
Appends the string to this string buffer.
Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used based on the application need.

11. setLength(int newLength)
Sets the length of this String buffer.

java String compare to determine Equality

java string compare can be done in many ways as shown below. Depending on the type of java string compare you need, each of them is used.

*== Operator
*equals method
*compareTo method

Comparing using the == Operator

The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the ‘==’ operator does not compare the content of the text present in the String objects.

Example:

public class StringComparision2 {

	public static void main(String[] args) {
		String name1 = "Bob";
		String name2 = new String("Bob1");
		String name3 = "Bob";
		// 1st case
		if (name1.equals(name2)) {
			System.out.println("The strings are equal.");
		} else {
			System.out.println("The strings are unequal.");
		}
		// 2nd case
		if (name1.equals(name3)) {
			System.out.println("The strings are equal.");
		} else {
			System.out.println("The strings are unequal.");
		}
	}
}
Filed in: Z-A All Java Codes

No comments yet.

Leave a Reply