Following programs are for performing the strings basic operations in java like string concatenation, string compare. To perform the string concatenation, string compare in java uses the inbuilt methods in java.

String Length:

Program: Find the length of string

Here we first create the string named str and use the length() method to get the size of the String.

class StringExample
{
  public static void main(String[] args) 
 {
    String str = "Hello World";
    System.out.println("The string is: " + str);
    System.out.println("The length of the string: " + str.length());
  }
}

Output:

The string is: Hello World
The length of the string: 11

String Length

String Concatenation:

Program: Join the Two strings using concat()

In this program we use the concat() function for concatenation of two strings. Here we concate or join the two strings str1 and str2 using concat() method and produce the joinedString as a single string.

class StringExample
 {
  public static void main(String[] args)
 {
    String str1 = "Hello! ";
    System.out.println("First String: " + str1);

    String str2 = "World";
    System.out.println("Second String: " + str2);

    String joinedString = str1.concat(str2);
    System.out.println("Joined String: " + joinedString);
  }
}

Output:

First String: Hello!
Second String: World
Joined String: Hello! World

String Concatenation

We can also use + operator for concatenation of strings in the below program we use this + operator and join the string.

Program: Join the two strings using + operator

class StringExample
{
  public static void main(String[] args)
 {

    String str1 = "Hello! ";
    System.out.println("First String: " + str1);

    String str2 = "World";
    System.out.println("Second String: " + str2);

    String joinedString = str1 + str2;
    System.out.println("Joined String: " + joinedString);
  }
}

Output:

First String: Hello!
Second String: World
Joined String: Hello! World

String concatenation in java

String Compare

class StringCompare
{
  public static void main(String[] args) 
{
    String str1 = "Java Programming";
    String str2 = "Java Programming";
    String str3 = "Python Programming";

    boolean rst1 = str1.equals(str2);
    System.out.println("Strings str1 and srt2 are equal: " + rst1);

    boolean rst2 = str1.equals(str3);
    System.out.println("Strings str1 and str3 are equal: " + rst2);
  }
}

Output:

Strings str1 and srt2 are equal: true
Strings str1 and str3 are equal: false

String Compare

In the above example it returns the true if both strings are equals otherwise it returns false. We can also use compareTo() method or == operator for string comparison.

If you want to learn more string methods in java then please see this article Java String Methods with Examples.

Leave a Reply

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

Back to Top