| Lang Package - String
|
|
Home | Lang Basics |
String | StringBuffer |
Thread |
Wrapper Class | String Tokenizer
|
|
String:
We can't modify the character
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings.
Because String objects are immutable they can be shared. For example:
String str = "abc"; -> Default Method
String str = new String("abc");
|
Example:
import java.lang.*;
class MakeString
{
public static void main(String args[])
{
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
Output:
Java
Java
|
String Length:
public int length()
Returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string.
|
Example:
import java.lang.*;
class StringLength
{
public static void main(String args[])
{
char chars[] = {'a', 'b', 'c'};
String s = new String(chars);
System.out.println(s.length());
}
}
Output:
3
|
String Concatenation:
public String concat(String str)
Concatenates the specified string to the end of this string.
If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created,
representing a character sequence that is the concatenation of the character sequence represented by this String object and the
character sequence represented by the argument string.
|
Example:
import java.lang.*;
class ConCat
{
public static void main(String args[])
{
String s = "four: " + 2 + 2;
System.out.println(s);
}
}
Output:
four : 22
|
String charAt():
public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence
is at index 0, the next at index 1, and so on, as for array indexing.
|
Example:
import java.lang.*;
public class Program
{
public static void main(String[] args)
{
String str = "Hello, World!";
// Get the character at positions 0 and 12.
int index1 = str.charAt(0);
int index2 = str.charAt(12);
// Print out the results.
System.out.println("The character at position 0 is " +
(char)index1);
System.out.println("The character at position 12 is " +
(char)index2);
}
}
Output:
The character at position 0 is H
The character at position 12 is !
|
String getChars():
public void getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
Copies characters from this string into the destination character array.
The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1
(thus the total number of characters to be copied is srcEnd-srcBegin). The characters are copied into the subarray
of dst starting at index dstBegin and ending at index:
dstbegin + (srcEnd-srcBegin) - 1
|
Example:
import java.lang.*;
public class getChars
{
public static void main(String[] args)
{
String str = "This is a String.";
// Copy the contents of the String to a byte array.
// Only copy characters 5 through 10 from str.
// Fill the source array starting at position 3.
char[] arr = new char[] { ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ' };
str.getChars(5, 10, arr, 3);
// Display the contents of the byte array.
System.out.println("The char array equals \"" +
arr + "\"");
}
}
Output:
The char array equals " is a "
|
String getBytes():
public void getChars(int srcBegin,
int srcEnd,
char[] dst,
int dstBegin)
Copies characters from this string into the destination byte array. Each byte receives the 8 low-order bits of the corresponding
character. The eight high-order bits of each character are not copied and do not participate in the transfer in any way.
|
Example:
import java.lang.*;
public class getBytes
{
public static void main(String[] args)
{
String str = "This is a String.";
// Copy the contents of the String to a byte array.
byte[] arr = str.getBytes();
// Create a new String using the contents of the byte array.
String newStr = new String(arr);
// Display the contents of the byte array.
System.out.println("The new String equals \"" +
newStr + "\"");
}
}
Output:
The new String equals "This is a String."
|
String toCharArray():
public char[] toCharArray()
Converts this string to a new character array.
|
Example:
import java.lang.*;
public class tocharArray
{
public static void main(String[] args)
{
String str = "This is a String.";
// Convert the above string to a char array.
char[] arr = str.toCharArray();
// Display the contents of the char array.
System.out.println(arr);
}
}
Output:
This is a String.
|
String equals():
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that
represents the same sequence of characters as this object.
|
Example:
import java.lang.*;
public class Equals
{
public static void main(String[] args)
{
String p1 = "chennaisunday";
String p2 = "dorabujji";
String p3 = "chennaisunday";
// Are any of the above Strings equal to one another?
boolean equals1 = p1.equals(p2);
boolean equals2 = p1.equals(p3);
// Display the results of the equality checks.
System.out.println("\"" + p1 + "\" equals \"" +
p2 + "\"? " + equals1);
System.out.println("\"" + p1 + "\" equals \"" +
p3 + "\"? " + equals2);
}
}
Output:
"chennaisunday" equals "dorabujji"? false
"chennaisunday" equals "chennaisunday"? true
|
String equalsIgnoreCase():
public boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case.
Two characters c1 and c2 are considered the same, ignoring case if at least one of the following is true:
The two characters are the same (as compared by the == operator).
Applying the method Character.toUpperCase(char) to each character produces the same result.
Applying the method Character.toLowerCase(char) to each character produces the same result.
|
Example:
import java.lang.*;
public class MainClass {
public static void main(String args[]) {
String s1 = "Hello";
String s4 = "HELLO";
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}
Output:
Hello equalsIgnoreCase HELLO -> true
|
String startsWith():
public boolean startsWith(String prefix,
int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
|
Example:
import java.lang.*;
public class StrStartWith{
public static void main(String[] args) {
System.out.println("String start with example!");
String str = "Welcome to chennaisunday";
String start = "Wel";
System.out.println("Given String : " + str);
System.out.println("Start with : " + start);
if (str.startsWith(start)){
System.out.println("The given string is start with Wel");
}
else{
System.out.println("The given string is not start with Wel");
}
}
}
Output:
String starts with example!
Given String : Welcome to chennaisunday
Start with: Wel
The given string is start with Wel
|
String endsWith():
public boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
|
Example:
import java.lang.*;
public class StringendsWith
{
public static void main(String[] args)
{
String str1 = "My name is deepu";
String str2 = "My name is bajju";
// The String to check the above two Strings to see
// if they end with this value (ju).
String endStr = "ju";
// Do either of the first two Strings end with endStr?
boolean ends1 = str1.endsWith(endStr);
boolean ends2 = str2.endsWith(endStr);
// Display the results of the endsWith calls.
System.out.println("\"" + str1 + "\" ends with " +
"\"" + endStr + "\"? " + ends1);
System.out.println("\"" + str2 + "\" ends with " +
"\"" + endStr + "\"? " + ends2);
}
}
Output:
"My name is deepu" ends with "ju"? false
"My name is bajju" ends with "ju"? true
|
String compareTo():
public int compareTo(Object o)
Compares this String to another Object. If the Object is a String, this function behaves like compareTo(String).
Otherwise, it throws a ClassCastException (as Strings are comparable only to other Strings).
|
Example:
public class CompareToLong {
public static void main(String args[]) {
// two long objects initialized
Long x = new Long(12);
Long y = new Long(21);
// method checks the numerical values of two objects
if (x.compareTo(y) == 0) {
System.out.println("both long objects are equal");
}
else if (x.compareTo(y) != 0) {
System.out.println("long objects are not equal");
}
// here method checks just the value hold by the String objects not how
// the the values are assigned
String m = "this is my" + " first page";
String n = "this is my first page";
if (m.compareTo(n) == 0) {
System.out.println("both Strings are equal");
} else if (m.compareTo(n) != 0) {
System.out.println("Strings are not equal");
}
}
}
Output:
long objects are not equal
both Strings are equal
|
String substring():
public String substring(int beginIndex)
Returns a new string that is a substring of this string. The substring begins with the character at the specified index
and extends to the end of this string.
Examples:
"unhappy".substring(2) returns "happy"
"emptiness".substring(9) returns "" (an empty string)
|
Example:
public class subString
{
public static void main(String[] args)
{
String str = "Navy blue is my favorite color.";
// Get a substring of the above string starting from
// index 5 and ending at index 24.
String newStr = str.substring(5, 24);
// Display the two strings for comparison.
System.out.println("old = " + str);
System.out.println("new = " + newStr);
}
}
Output:
old = Navy blue is my favorite color.
new = blue is my favorite
|
String replace():
public String replace(char oldChar,
char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
If the character oldChar does not occur in the character sequence represented by this String object, then a reference to this String object is returned. Otherwise, a new String object is created that represents a character sequence identical to the character sequence represented by this String object, except that every occurrence of oldChar is replaced by an occurrence of newChar.
|
Example:
import java.lang.*;
public class JavaStringReplaceExample{
public static void main(String args[]){
String str="Replace Region";
System.out.println( str.replace( 'R','A' ) );
System.out.println( str.replaceFirst("Re", "Ra") );
System.out.println( str.replaceAll("Re", "Ra") );
}
}
Output:
Aeplace Aegion
Raplace Region
Raplace Ragion
|
String trim():
public String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
If this String object represents an empty character sequence, or the first and last characters of character sequence represented
by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.v
Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty
string is created and returned.
Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index
of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring
of this string that begins with the character at index k and ends with the character at index m-that is, the result
of this.substring(k, m+1).
This method may be used to trim whitespace from the beginning and end of a string; in fact, it trims all ASCII control characters as well.
|
Example:
import java.lang.*;
public class StringTrim{
public static void main(String[] args) {
System.out.println("String trim example!");
String str = " chennaisunday";
System.out.println("Given String :" + str);
System.out.println("After trim :" +str.trim());
}
}
Output:
String trim example!
Given String : chennaisunday
After trim:chennaisunday
|
| Back to top |