Java String Examples

The String class implements immutable character strings, which are read-only once the string object has been created and initialized. All string literals in Java programs, are implemented as instances of String class.

The easiest way to create a Java String object is using a string literal:

String str1 = "I can't be changed once created!";

A Java string literal is a reference to a String object. Since a String literal is a reference, it can be manipulated like any other String reference. i.e. it can be used to invoke methods of String class.

For example,

int myLenght = "Hello world".length();

The Java language provides special support for the string concatenation operator (+), which has been overloaded for Java Strings objects. String concatenation is implemented through the StringBuffer class and its append method.

For example,

String finalString = "Hello" + "World";

Would be executed as

String finalString = new StringBuffer().append("Hello").append("World").toString();

The Java compiler optimizes handling of string literals. Only one String object is shared by all strings having same character sequence. Such strings are said to be interned, meaning that they share a unique String object. The Java String class maintains a private pool where such strings are interned.

For example,

String str1="Hello";
String str2="Hello";
If(str1 == str2)
System.out.println("Equal");

Would print Equal when executed.

Since the Java String objects are immutable, any operation performed on one String reference will never have any effect on other references denoting the same object.

String Constructors

String class provides various types of constructors to create String objects. Some of them are,

String()
Creates a new String object whose content is empty i.e. "".

String(String s)
Creates a new String object whose content is same as the String object passed as an argument.

Note: Invoking String constructor creates a new string object, means it does not intern the String. Interned String object reference can be obtained by using intern() method of the String class.

String also provides constructors that take byte and char array as an argument and returns String object.

String equality - Compare Java String

String class overrides the equals() method of the Object class. It compares the content of the two string object and returns the boolean value accordingly.

For example,

String str1="Hello";
String str2="Hello";
String str3=new String("Hello") //Using constructor.

If(str1 == str2)
System.out.println("Equal 1");
Else
System.out.println("Not Equal 1");

If(str1 == str3)
System.out.println("Equal 2");
Else
System.out.println("I am constructed using constructor, hence not interned");

If( str1.equals(str3) )
System.out.println("Equal 3");
Else
System.out.println("Not Equal 3");

The output would be,
Equal 1
Not Equal 2
Equal 3

Note that == compares the references not the actual contents of the String object; Where as equals method compares actual contents of two String objects.

String class also provides another method equalsIgnoreCase() which ignores the case of contents while comparing.

Apart from these methods String class also provides compareTo methods.

int compareTo(String str2)
This method compares two Strings and returns an int value. It returns
- value 0, if this string is equal to the string argument
- a value less than 0, if this string is less than the string argument
- a value greater than 0, if this string is greater than the string argument

int compareTo(Object object)
This method behaves exactly like the first method if the argument object is actually a String object; otherwise, it throws a ClassCastException.

Java String Examples

17 Comments

  • Hi can anyone help me in a string prog i.e
    if i enter a string 123 then the output should be displayed as the entered string is Numeric.
    and if i enter the string 123abc the output should be displayed as entered string is Alphanumeric.

    please help me out regarding this i am a beginner so its little confusing !!

    • import java.util.Arrays;

      public class String4 {

      public static void main(String[] args) {

      java.util.Scanner scn=new java.util.Scanner(System.in);

      System.out.println(“enter a String:”);

      String s1=scn.nextLine();

      for(int i=0;i<=s1.length()-1;i++)

      {

      char c=s1.charAt(i);

      if((c>=65&&c<=90)||(c>=97&&c<=122))

      {

      System.out.println(“string is alpha numeric”);

      break;

      }

      else

      {

      System.out.println(“string only numeric”);

      break;

      }

      }

      }

      }

  • “i want to make approx words from given letters “
    <input>[a,b,n,m,k]
    <output>[abnmk,bnmka,nmbak……..]
    plz any one can make this coding in core java……plz post….or mail me”manna.ramkrishna@yahoo.com”

  • The actual output would be like this :

    Equal 1

    I am constructed using constructor, hence not interned

    Equal 3

    NOTE: Not Equal 2 // is wrong

    thank you

  • Hi everyone! Can you please help me with this problem?

    Negotiating a consumer loan is not always straightforward. One form of loan is the discount installment loan, which works as follows. Suppose a loan has a face value of 1000 pesos, the interest rate is 15 percent, and the duration is 18 months. The interest is computed by multiplying the face value of 1000 pesos by 0.15 to yield 150 pesos. The figure is then multiplied by the loan period for 1.5 years to yield 225 pesos as the total interest owed. The amount is immediately deducted from the face value, leaving the consumer with only 775 pesos. Repayment is made in equal monthly installments based on the face value. Thus, the monthly loan payment will be 1000 pesos divided by 18, of 55.56 pesos. This method of calculation may not be too bad of the consumer needs 775 pesos, but the calculation is a bit more complicated if the consumer needs 1000 pesos. Write a program that will take three inputs: the amount the consumer needs to receive, the interest rate, and the duration of the loan in months. The program should then calculate the face value required in order for the consumer to receive the amount needed and should also calculate the monthly payment.

  • Hello plz help me in a string prog i.e

    if i enter a string “JAVA”, it should print “KBWB” i.e. next character of each input string

  • Just curious why you are incorrectly using uppercase in your code, Though I am very impressed with the lesson here with the constructor .. thank you for that good bit of information!

  • Hi can anyone help
    String price=”$200″;
    String quantity=”5″;
    int actualresult=1000;
    int expectedresult

    Not able to find any matching example
    tried every string function

Sponsors

Facebook Fans