String Class Simplified in Java

1
88
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

 

String Class Simplified in Java
String Class Simplified in Java

String Class Simplified in Java:

Java string represents character String.All string literals (example -“Java”) is an instance of this class.Strings are constant,their values can not be changed after they are created.This is why String is a immutable class.In other way every String class is final and it can not be subclassed. Java String is a very important class to carry out day to day coding.

String Creation techniques

Create String from Array of Characters

java String is an array of characters.But showing String as an array of characters is very troublesome and tedious to code.String falls under java.lang.String class hierarchy.The import is automatic hence we do not need to import it manually. A String is an Object.The object contains data(a sequence of characters)

Example is given below:


char[] myString={'I','N','D','I','A'};
String myFinalString=new String(myString);
 

Java has come up with an important class called String to omit this issue.

Direct String creation


String myFinalString="INDIA";
 

To create a String assign a double quoted constant to a String variable. Java automatically converts the string literals into a String object.

The String class actually uses a java character array.It is private to String class,so we can not get the characters and change them.

Arrays in Java are real objects that knows its own length,so String objects do not need a special terminator.

Create String using Array and encoding scheme

byte[] data={65,66,67};
String myString=new String(data,"8859_5");
The arguments are:
byte array
encoding scheme 

If we do not wish to provide a encoding scheme,we can pass only the byte array.Default encoding scheme will be used in that case.

Create Strings from other data types

There are several datatypes that can be converted to String. There are various overloaded versions of String.valueOf() methods available.

Example:

String myString=String.valueOf(1);//int to String
String myString=String.valueOf(2.0f);//float to String
String myString=String.valueOf(false);//boolean to String

Converting Objects to String:

toString() is a method to convert objects into String.If the object is null,the equivalent string output will be null.

Concatenation:

Java String supports the concatenation for two different strings. This operation is done with “+” operator. This + is an overloaded operator and signifies to concatenate in the context of String.


public class StringTest{
public static void main(String[] args)
{
String first="Hello";
String second="World";
String finalString=first+second;
System.out.println(finalString);
}
}

Output of the code is :
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
HelloWorld

Literal Strings can not span across lines in java.But we can concatenate lines to produce the same result.

String myString="Hello".concat(" java");

Few important methods to remember about String Class:

No Method Name Method Description Return Comment
1 int length() Returns the length of the String Object int
2 int indexOf(‘character’) Returns the index of the given character int index If the character is inside the String it will return the first occurance, if the character is not inside of the given string, it will return -1
3 char chatAt(index) Returns the character present at the given index char if the index is inside the bound, it will return the character but if the index is outside of the Bound, it will throw an StringIndexOutOfBoundsException
4 boolean contains(“Char sequence”) Returns true if the character or character sequence or String is present inside the given string , else it will return false boolean true or false in case we test if the String contains null, it will return null pointer Exception
5 boolean endsWith(‘Character’) Returns true if the given string ends with the specified character else return false boolean true or false
6 String replaceAll(“search String”,”replace String”) Returns the changed String if a valid replacement found else returns the original string String The changed output does not gets assigned to the variable automatically, we need to assign them
7 String replaceFirst(“search String”,”replace String”) Returns the changed String if a valid replacement found for the first occurance else returns the original string String The changed output does not gets assigned to the variable automatically, we need to assign them
8 String toLowerCase(“String whose case needs to be changed”) Returns the lowercase representation of the String specified String The changed output does not gets assigned to the variable automatically, we need to assign them
9 String toUpperCase(“String whose case needs to be changed”) Returns the uppercase represenatation of the string specified String The changed output does not gets assigned to the variable automatically, we need to assign them
10 int indexOf(Char c,int StartIndex) Returns the index of the character specified after the index specified instead of searching from begining if no match found it will retun -1 int Overloaded version of indexOf() method
11 int indexOf(String subString) Returns the index of the subString specified from begining if no match found it will retun -1 int Overloaded version of indexOf() method
12 int indexOf(String subString,int startIndex) Returns the index of the subString specified after the index specified instead of searching from begining if no match found it will retun -1 int Overloaded version of indexOf() method
13 int compareTo(String string1,String string2) lexicographically compares two strings and based on the comparison,it may return 0, negative value or a positive value int 0 means it is a exact match,positive means the first string is lexicographically ahead of the second string and a negative means first string is lexicographically behind.
14 String concate(String string1) it will concatenate teh given string with another string String

Example of each function is given below:


public class StringTest{
public static void main(String[] args)    
{
//Declare and define a String    
String first="INDIA";
String second="INDIAINDIA";
String third="abc";
//get the lenth of the String
System.out.println("The size is"+first.length());
//get the index of the given valid character
System.out.println("The index of D is "+first.indexOf('D'));
//get the index of the given invalid character
System.out.println("The index of E is "+first.indexOf('E'));
//get the character at a given index-index starts at 0
System.out.println("The Character at 2 is "+first.charAt(2));
//check contain() method for "IA"
boolean flag1=first.contains("IA");
System.out.println("The Character sequence IA is present in the string "+flag1);
//check contain() method for "DA" i.e invalid character sequence
boolean flag2=first.contains("DA");
System.out.println("The Character sequence DA is present in the string "+flag2);
//Check the end with function with valid character
boolean flag3=first.endsWith("A");
System.out.println("The string does ends with A "+flag3);
//Check the end with function with invalid character
boolean flag4=first.endsWith("I");
System.out.println("The string does ends with I "+flag4);
//replceAll() valid test
System.out.println("Testing replace All with IN with in "+second+" becomes "+second.replaceAll("IN","in"));
//replceAll() invalid test
System.out.println("Testing replace All with IN with in "+second+" becomes "+second.replaceAll("TA","in"));
//replceFirst() valid test
System.out.println("Testing replace First with IN with in "+second+" becomes "+second.replaceFirst("IN","in"));
//replceAll() invalid test
System.out.println("Testing replace All with IN with in "+second+" becomes "+second.replaceFirst("TA","in"));
//test tolowercase
System.out.println("Testing toLowercase method "+second+" becomes "+second.toLowerCase());
//test toUpperCase
System.out.println("Testing toUpperCase method "+third+" becomes "+third.toUpperCase());

}
}

The output of the code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
The size is5
The index of D is 2
The index of E is -1
The Character at 2 is D
The Character sequence IA is present in the string true
The Character sequence DA is present in the string false
The string does ends with A true
The string does ends with I false
Testing replace All with IN with in INDIAINDIA becomes inDIAinDIA
Testing replace All with IN with in INDIAINDIA becomes INDIAINDIA
Testing replace First with IN with in INDIAINDIA becomes inDIAINDIA
Testing replace All with IN with in INDIAINDIA becomes INDIAINDIA
Testing toLowercase method INDIAINDIA becomes indiaindia
Testing toUpperCase method abc becomes ABC

Overloaded functions of indexOf() methods:


public class StringTest{
public static void main(String[] args)    
{
String a="10abd10ab";
//test of indexOf(char,startindex) for a valid test
System.out.println("The index of second a character "+a.indexOf('a',3));
//test of indexOf(char,startindex) for a invalid test
System.out.println("The index of second e character "+a.indexOf('e',3));
//test of indexOf(subString) for a valid test
System.out.println("The index of subString "+a.indexOf("ab"));
//test of indexOf(subString) for a valid intest
System.out.println("The index of subString "+a.indexOf("abc"));
//test of indexOf(subString,startIndex) for a valid test
System.out.println("The index of subString "+a.indexOf("ab",3));
//test of indexOf(subString,startIndex) for a valid intest
System.out.println("The index of subString "+a.indexOf("abc",3));
}
}

output of the code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
The index of second a character 7
The index of second e character -1
The index of subString 2
The index of subString -1
The index of subString 7
The index of subString -1

String is a final class i.e once created they can not be altered or deleted.There handle gets changed. So while overriding a String. An new String object gets created,the pointer or handles the new object.This is why String is called immutable class. JVM creates memory in the String Constant pool.This is also the reason why String can be initiated without a new operator.

public class StringTest{
public static void main(String[] args)    
{
String a="India";
a="India"+"n";
System.out.println(a);
}
}

output of the program:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
Indian

In this case a becomes “Indian”,but the String “India” still remains in the String pool,(does not get deleted). It just looses the handle.
Similarly for multiple occurrences of the same String will not create multiple Strings in the pool. It is just one String gets created and the variables hold the reference of that String.


String a="India";
String b="India";
String c="India";

Here a,b,c three variable points to the same String in the pool.

If a number is quoted with double quote, it becomes a string not a number anymore.

public class StringTest{
public static void main(String[] args)    
{
String a="10";
System.out.println("value of a"+a);
System.out.println("Trying to add 2 with a"+a+2);
}
}

output of the code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
value of a10
Trying to add 2 with a102
In this case a represents 10 as string when it gets 2 that is of numeric, the auto boxing features gets activated then converted to an Object type as new Integer(2). Second, the + operator is an overloaded operator that represents concatenation. The Object , new Integer(2) gets converted to String using toString() method. Last- the compiler concatenate two strings. Hence we get 102 as output.

The next question is how to get is as numberic?

Well for that we have String parsing methods:


public class StringTest{
public static void main(String[] args)    
{
String a="10";
int b=Integer.parseInt(a);
System.out.println("Numberic value of a "+a);
System.out.println("add 2 with b gives "+(b+2));
}
}

output of this code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
Numberic value of a 10
add 2 with b gives 12

If the String represents combination of String and number or two primitive values. The parsing will not happen.Instead JVM will throw an exception called java.lang.NumberFormatException

public class StringTest{
public static void main(String[] args)    
{
String a="10abd";
int b=Integer.parseInt(a);
System.out.println("Numberic value of a "+a);
System.out.println("add 2 with b gives "+(b+2));
}
}

The output of the code:
$javac StringTest.java
$java -Xmx128M -Xms16M StringTest
Exception in thread “main” java.lang.NumberFormatException: For input string: “10abd”
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at StringTest.main(StringTest.java:5)

 

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here