String Operations in Java - PRsBlog
Home >> Java >> String Operations in Java
Strings In Java

String Operations in Java

Class String provide no of methods to perform string operations in java. We already discussed about ways of creating Strings. In java whenever compiler get a string literal it treats it as an string objects. String literals are any thing enclosed in double quotes. In java string operations are one of the most used thing. Lets discuss some of very frequent and important string operations f java.

1. Finding length of string:

Class String provided a method called length() to find the number of characters of the string.


public int length();


One thing we should notice is that we can call method length by direct with string literal. This shows that string literals are objects in java.

2. Concatenation

  •    We can concatenate strings by using concatenate (+) operator. A new string is formed after inserting second string following first string. We can directly print the string or assign it to another reference.                      Example String Operations  1:
    Generally + operator helps to manage long strings. + operator is most frequently used inside print statement. We can concatenate the different data types with strings. As we concatenated integer with string. Here whenever compiler encounter string as operand of + operator it automatically convert another operand into equivalent string and perform concatenation. Compiler uses toString() method to convert any other datatype into string. Last two statements in the example shows that arithmetic operations are better to enclosed in parenthesis to avoid the undesired output.
  • We also can concatenate the string using concat() method of class String.                                                     Signature:                              public String concat(String);                                                                                     Example String Operations 2:
    The concat() method adds argument string after calling string and return as new string. We can pass an string reference or string literal in this method.

3. String Comparison

Strings can be compared by following methods.

  • equals() method: this method take a string as argument and compare the order and values of characters inside the string. It returns boolean value if number and order of character is same, otherwise false.
  • equals to (==)operator: This method compares address rather than values. If two string  references are pointing to the same string object it will return true, otherwise false.
  • compareTo() method : This method compares string in lexicographical way and return an integer representing difference between strings.

Example of String Operations 2:


String Operations

please Leave comments in case of confusion….

About Log Raj Bhatt

Leave a Reply

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