String in Java Example

Posted on

String is a combination of character combined together. Java implement string as an object which make handling of string convenient. Java provides various methods, which makes handling of String as object easy, we’ll see them all going futher.

A String created is immutable, which is no hurdle in performing operation provided by Java on it. Every time an operation is performed on string object, a new string object is created with modifications and assigned to it.

This can be overcome by use of mutable string type StringBuilder or StringBuffer.

String Constructor:

String str= new String();

This is used to create an empty instance of string.

String str= new String(char charsval[]);

This used to create an string with string characters defined in charsval. The resultant output will be concatenated characters. Let’s see an example

Output:

This will initialize str with string “abc”.

String str= String(char chars[ ], int startIndex, int numChars):

This will initialize string object str with characters defined in chars with starting and number of characters followed by it.

Example:

Output:

This will initialize the string object str with “cde”.

String str=new String(Sting StrObj);

This will initialize the str with string object stored in StrObj.

String length:

This will return the number of characters in string object on which the function has been called.

str.length will return 5.

String literals:

String literals are a way by which string object can be initialized.

String methods can also be called directly on string literals as: “abc”.length(), this will return to be 3, which exactly the same as in case of string object.

String Concatenation:

Java doesn’t allow any operator to be applied on String object. However it has exception for ‘+’ operator which is used for concatenation of two string.

Above example demonstrate the concatenation of string literals; this method can also be applied on concatenation of other data types with string.

Output:

You’ve scored 90 out of 100

Here in this internal mechanism convert the data type of number to string while concatenation with string literals.

String Conversion and toString( )

We saw in above example, a data of type int is converted to String type when concatenating with data of type string. This is done by overloaded method defined by String.valueof(). For simple data type, this method converts them to type String and returns human readable string. But for type object, it calls toString method.

Every class implements toString methods and it can be overridden to provide our own implementation.

Signature of toString method:

String toString()

Let’s see an example to demonstrate how this can achieved.

Main Class file: ToStringExample.java

Class file: toStringDetails.java

OutPut:

Welcome to Code2Succeed.com

String returned from toString method is Welcome to Code2Succeed.com

 

We kicked off understanding of string that it is easy to handle string as object as it provides various methods which makes it easy to handle. Below are the listed methods which can be used on String-

  • charAt( )

    This can be used to extract a single character from given string at specified index location.

    Its signature is defined as-

    char charAt(int where);

    Example-

    Output:

    Character at index location 1 is: b

  • getChars( )

    This is used to extract more than one character at a time. It signature is defined as-

    void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

    Explanation:

    sourceStart, sourceEnd- This used to specify the start and end index from where characters are required to be extracted. The characters are extracted from sourceStart and sourceEnd-1 index location.

    target[]: This is the array defined in which characters will be stored. One must ensure that it’s size matches the length of characters.

    targetStart: This specifies the index location in target array, starting where the characters will be copied.

    Example:

    Output:
    code2succeed.com

  • toCharArray( )

    This method is used to convert all characters in a string object to character array. It always return an array of character for the string on which this method has been called.

    Signature-

    char[ ] toCharArray( )

    Example:

    This will convert the str of type string into character array.

  • equals( )

    This will compare two given string return true or false depending upon if content is same or not. This method also considers letter case i.e. will return false if two string only differentiate capital case or letter case.

    Signature-

    boolean equals(Object str)

    Output:
    false
    false
    true

  • equalsIgnoreCase( )

    This is same perform same as equals() method except for letter case differentiation. This will ignore the difference of small or capital case.

    Signature-

    boolean equalsIgnoreCase(String str)

    Example:

    Output:
    true

  • regionMatches( )

    This method is used to compare specific region inside the given string with specified start index and number of characters to be compared.

    Signature:

    boolean regionMatches(int startIndex, String str2,int str2StartIndex, int numChars)

    boolean regionMatches(boolean ignoreCase,int startIndex, String str2,int str2StartIndex, int numChars)

  • startsWith( ) and endsWith( )

    This method returns true if the string on which this function has been called starts or ends with specified string.

    Example-


    This will return true, if given string starts with Welcome and if not then return false. Similar is the case with endWith().

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.