5 Strings — Java Programming
5.1. Introduction
Strings play an important role in Java programming. Let us explore various classes and functions related to Strings.
5.2 Strings
A string is an array of characters. We can define string as below:
char chars[] = {'a','b','c'};
A string has a fixed number of characters. In Java, a string is an object of the class, which belongs to java.lang package. The string class is available to all classes by default. String objects are immutable- that is once the object is created, the contents cannot be changed. A variable declared as a String reference can be changed to point at some other String object at any time.
For example:
String str=”this is an example”; System.out.println(str);
Constructor is used as in the statement String s=new String();
String belong to the package java.lang.String
5.2.1 Different ways of calling the String constructor
|
String Constructor |
Description |
|
public String(); |
Instantiating a String object. |
|
public String(char value[]); |
Give a character array. |
|
public String(char value[], int offset, int count); |
Get the substring starting from offset count number of chars. |
|
public String(String value); |
Directly give the string constant as the parameter. |
5.2.2 Methods of String class
|
Method |
Description |
|
public int length(); |
Returns the length of the String. |
|
public char charAt(int index) |
Return the character at the specified index |
|
public int indexOf(int ch) public int indexOf(int ch, int fromindex) public indexOf(String s) public indexOf(string s, int f) |
Returns the index of the first occurrence of the character, ch. If unsuccessful returns -1 Returns the first occurrence of the character, ch, that is greater than or equal to from index, if not successful return -1. Returns index of the first of the first occurrence of the specified string Returns index of the first occurrence of the specified string. |
|
public int lastIndexOf(int ch) public int lastIndexOf(int c, int f) public int lastIndexOf(String s) public int lastIndexOf(String s,int f) |
Returns the index of the last occurrence of the specified character, ch. If Unsuccessful -1 is returned Return the last occurrence from the specified index, if unsuccessful returns -1. Returns the index of the last occurrence of the specified string. Returns the index of last occurrence of the specified string. |
|
public string substring(int beginIndex, int endIndex) |
Create and returns a new string that is a sub string from the specified beginIndex to the specified endindex. |
|
public boolean equals(object obj) |
The result is true if the argument is not null and is string object that represents the same sequence of characters as this object obj. |
|
public String replace(char oldch, char newch) |
Returns a new string resulting from replacing all occurrences of oldch in this string with newch. |
|
public Boolean startsWith(String prefix) |
Return true if the character sequence represented by the argument is a prefix of the character sequence |
|
public Boolean startsWith(string prefix, int offset) |
Return true if the character sequence represented by the argument is a prefix of the substring of this object starting at index offset, returns false otherwise. |
|
public String toLowerCase() |
Converts a string to lowercase. |
|
public String toString() |
This object that is already a string is returned. |
|
public String t8oUppercase() |
Converts a string to uppercase. |
|
public String trim() |
Removes white spaces from both ends of a string. |
|
public static String valueof(Boolean b) |
Creates the string representation of the Boolean argument. |
|
public static String valueOf(char c) |
Creates the string representation of the char argument. |
5.3 String buffers
The String class provides many capabilities for manipulating strings.
Unlike String objects, stringBuffer objects are modifiable.
For example
StringBuffer st; st=new StringBuffer(10);
Also there is flexibility, if the number of characters is more than specified, then automatically the string buffer expands to accommodate those extra characters.
5.3.1 The methods of string buffer
|
public StringBuffer append(char c) |
Appends the string representation of the char argument to this StringBuffer object |
|
public int capacity() |
Returns the current capacity of this StringBuffer object |
|
public char charAt(int index) |
Determines the character at a specific index in this StringBuffer object |
|
public void getChar(int srcbegin, int srcend, char dest[], int destBegin) |
Characters are copied from this StringBuffer object into the destination character array dest. |
|
public StringBuffer insert(int offset, char c) |
Inserts the string representation of the char argument into the StringBuffer object |
|
public StringBuffer insert(int offset, char str[]) |
Inserts the string representation of the char array argument into this StringBuffer object |
|
public int length() |
Returns the number of characters in the StringBuffer object |
|
public StringBuffer reverse() |
The reverse of the sequence replaces the character sequence contained in this StringBuffer. |
|
public void setcharAt(int index, char ch) |
The character at the specified index of this string buffer is set to ch. |
|
public string toString() |
A new string object is allocated and initialized to contain the character sequence currently represented by the StringBuffer object. |
Program 5.1. To find the length of a given string using a custom defined function
//strlen.java //click here for code import java.lang.*; class len{ public static int findlen(String s){ int i,length; length=s.length(); return length; } } class strlen{ public static void main(String args[]){ StringBuffer s =new StringBuffer("finding my length?"); System.out.println(len.findlen(s.toString())); } } // Output: 18
Program 5.2 Program to reverse a string using custom define function
//reversing.java //click here for code import java.lang.*; class rev{ public static String reverse(String s){ int i,length; length=s.length(); StringBuffer revst = new StringBuffer(length); for(i=length-1;i>=0;i--) { revst.append(s.charAt(i)); } return revst.toString(); } } class reversing{ public static void main(String args[]) { StringBuffer s = new StringBuffer("I am getting reversed"); System.out.println(rev.reverse(s.toString())); } } /*Output: desrever gnitteg ma I */
Program 5.3 Program to sort a set of strings
//sortStrings.java //Click here for code import java.io.*; public class sortStrings{ public static void main(String args[]) { int n=0; String ns; String name[]; name=new String[20]; try{ DataInputStream in; in=new DataInputStream(System.in); System.out.println("enter value for n"); System.out.flush(); ns=in.readLine(); n=Integer.parseInt(ns); System.out.println("enter the names"); System.out.flush(); for(int i=0;i<n;i++) { System.out.flush(); name[i]=in.readLine(); } for(int i=0;i<n-1;i++) for(int j=i+1;j<n;j++) { String t; if(name[i].compareTo(name[j])<0) { t=name[i]; name[i]=name[j]; name[j]=t; } } } catch(Exception e) { System.out.println("IO error"); System.exit(1); } System.out.println("sorted names"); for(int i=0;i<n;i++) { System.out.println(name[i]); } } } /* Output: enter value for n 2 enter the names program java sorted names program java */
5.4 Summary
In this chapter you have been introduced with strings and string buffers.