Easy Tutorial
For Competitive Exams

Java Programming String

What is String?

String is nothing but a sequence of characters. For e.g. “Hello” is a string of 5 characters.

In java, string is an immutable object .

What is an Immutable object?

An object whose state cannot be changed after it is created is known as an Immutable object.

String, Integer, Byte, Short, Float, Double and all other wrapper class's objects are immutable.

How to create a String in java?

There are two ways to create a String in Java

  • String literal
  • Using new keyword

Using a String literal:

String literal is a simple string enclosed in double quotes " ". A string literal is treated as a String object.

Example

String str1 = "Hello";

Using new Keyword

Example

String str3 = new String("Java");

How to initialize String in java?

We can create and initialize string object by calling its constructor, and pass the value of the string.

we can pass character array to the string constructor.

We can also directly assign string value to the string reference, which is equals to creating string object by calling constructor.

The empty string constructor will create string object with empty value.

Example

public class Initialization {
    public static void main(String a[]){
        String abc = "This is java";
        System.out.println(abc);
        String bcd = new String("this is also java");
        System.out.println(bcd);
        char[] c = {'a','b','c','d'};
        System.out.println(c);
        String cdf = new String(c);
        System.out.println(cdf);
        String junk = abc+" This is welcome message";
        System.out.println(junk);
    }
}
Try it Yourself

String Methods:

How to convert Character array to String object?

By using String.copyValueOf() method you can convert char array to string object.

Also you can copy range of character array to string.

Example

public class ArrayCopy {
    public static void main(String a[]){
        char ch[] = {'M','y',' ','J','a','v','a',' ','e','x','a','m','p','l','e'};
        String chStr = String.copyValueOf(ch);
        System.out.println(chStr);
        String subStr = String.copyValueOf(ch,3,4);
        System.out.println(subStr);
    }
}
Try it Yourself

How to append or concat two Strings in java?

You can append two strings by just using "+" sign.

Also you can concatinate two string objects by calling concat() method.

Example

public class StringConcat {
    public static void main(String a[]){
        String b = "jump ";
        String c = "No jump";
        String d = b+c;
        System.out.println(d);
        d = b.concat(c);
        System.out.println(d);
    }
}
Try it Yourself

How to compare two strings using compareTo() method?

The method compareTo() is used for comparing two strings lexicographically.

Each character of both the strings is converted into a Unicode value for comparison.

If both the strings are equal then this method returns 0 else it returns positive or negative value.

Example

public class Demo{
    public static void main(String args[]){
       String str1="fruits";
       String str2="fruits are good";
       int result=str1.compareTo(str2);
       System.out.println(result);
}
}
Try it Yourself

How to get substring from the string using substring(int beginIndex)?

It returns the substring starting from the specified index(beginIndex) till the end of the string.

Example

public class Demo{
     public static void main(String args[]){
         String str=new String("welcome to java");
         System.out.println("value returned:");
         System.out.println(str.subString(10));
     }
}
Try it Yourself

How to get substring from the string using substring(int beginIndex,int endIndex)?

It returns substring starts with character at beginIndex and ends with the character at endIndex.

Example

public class Demo{
     public static void main(String args[]){
          String str=new String("welcome to java");
          System.out.println("value returned:");
          System.out.println(str.substring(10,13));
    }
}
Try it Yourself

How to compare two String objects in java?

You can not use "==" operator to compare two strings.

String provides equals() method to compare two string objects.

'==' operator compares the object reference but not the string value.

Example

public class MyStringEquals {
    public static void main(String a[]){
          String str1=new String("fruits");
          String str2=new String("FRUITS");
          System.out.println("return:"+str1.equals(str2));
}
}
Try it Yourself

We can ignore case during string compare by calling equalsIgnoreCase() method.

Example

public class MyStringEquals {
    public static void main(String a[]){
        String str1=new String("fruits");
        String str2=new String("FRUITS");
        System.out.println("return:"+str1.equalsIgnoreCase(str2));
   }
}
Try it Yourself

How to find length of the String in java?

We can use lenght() to find length of the string.

Example

public class MyStringLength {
   public static void main(String a[]){
        String str = "This is Java";
        System.out.println("String length: "+str.length());
       
    }
}
Try it Yourself

How to get byte array from a string object in java?

You can use getBytes() methode to convert string object to byte array.

Example

public class MyStringBytes {
   public static void main(String a[]){
        String str = "core java api";
        byte[] b = str.getBytes();
        System.out.println("String length: "+str.length());
        System.out.println("Byte array length: "+b.length);
    }
}
Try it Yourself

How to get index of a character or string from another String in java?

By using indexOf() method we get the position of the sepcified string or char from the given string.

We can also get the index starting from a specified position of the string.

Example

public class MyStringIndexOf {
   public static void main(String[] a){
       String str=new String("welcome to java");
       System.out.println("index found at:");
       System.out.println(str.indexOf('o'));
         
    }
}
Try it Yourself

How to get Lastindex of a character or string from another String in java?

By using lastIndexOf() method you can get last occurence of the the reference string or character.

Also lastIndexOf() method gives last occurence based on a specific position.

Example

public class MyStrLastIndexOf {
     public static void main(String a[]){
           String str=new String("welcome to java");
           System.out.println("Last index found at:");
           System.out.println(str.lastIndexOf('o'));
    }
}
Try it Yourself

How to find a string start with another string value in java?

By using startsWith() method, you can get whether the string starts with the given string or not.

Also this method tells that the string occurence at a specific position.

Example

public class MyStrStartsWith {
     public static void main(String a[]){
         String str=new String("welcome to java");
         System.out.println("value returned:");
         System.out.println(str.startsWith("welcome"));
    }
}
Try it Yourself

How to find a string ends with another string value in java?

By using endsWith() method, you can get whether the string ends with the given string or not.

Also this method tells that the string occurence at a specific position.

Example

public class MyStringEnd {
     public static void main(String a[]){
            String str=new String("welcome to java");
            System.out.println("value returned:");
            System.out.println(str.endsWith("java"));
    }
}
Try it Yourself

How to extract Char Array From String in java?

By using getChars() method, you can copy range of characters from the given string.

Example

public class MyCharArrayCopy {
     public static void main(String a[]){
           String str = "Copy chars from this string";
           char[] ch = new char[5];
           str.getChars(5, 10, ch, 0);
           System.out.println(ch);
    }
}
Try it Yourself

How to replace string characters in java?

String provides replace() method to replace a specific character or a string which occures first.

replaceAll() method replaces a specific character or a string at each occurence.

Example

public class MyStringReplace {
    public static void main(String a[]){
         String str = "This is an example string";
         System.out.println("Replace char 's' with 'o':"+str.replace('s', 'o'));
         System.out.println("Replace first occurance of string 'is' with 'ui':"+str.replaceFirst("is", "ui"));
         System.out.println("Replacing 'is' every where with 'no':"+str.replaceAll("is", "no"));
    }
}
Try it Yourself

How to change case of a string characters in Java?

toUpperCase() method converts all string characters to upper case.

toLowerCase() method converts all string characters to lower case.

Example

public class MyStringCase {
    public static void main(String a[]){
        String str = "Change My Case";
        System.out.println("Upper Case: "+str.toUpperCase());
        System.out.println("Lower Case: "+str.toLowerCase());
    }
}
Try it Yourself

How to trim spaces in the given string in java?

The trim() function removes all kind of space characters at both ends, means removes starting and trailing spaces.

These space characters includes normal space, enter, new line, tab, etc.

Example

public class MyStringTrim {
    public static void main(String a[]){
        String str = "  Junk   ";
        System.out.println(str.trim());
    }
}
Try it Yourself

How to match a format in string using regular expression?

String.matches() method helps to match the string with a regex.

Below example checkes weather given string starts with "www" or not.

Example

public class MyStrMatches {
    public static void main(String a[]){
           String[] str = {"www.easytutorial.in", "easytutorial.in"};
            for(int i=0;i < str.length;i++){
            if(str[i].matches("^www\\.(.+)")){
                System.out.println(str[i]+" Starts with 'www'");
            } else {
                System.out.println(str[i]+" is not starts with 'www'");
            }
        }
    }
}
Try it Yourself

How to print string representation of object in Java?

toString() method returns the string representation of the object in java.

Example

public class Car {
     public String toString(){
  return "This is my car object";
 }
 public static void main(String args[]){
  Car c=new Car();  
  System.out.println(c);
 }
}
Try it Yourself

How to remove html tags from a string?

Example

public class MyHtmlTagRemover {
        public static void main(String a[]){
        String text = "I don't want this to be bold<\\B>";
        System.out.println(text);
        text = text.replaceAll("\\<.*?\\>", "");
        System.out.println(text);
    }
}
Try it Yourself

How to split a string?

We are using String.split() method with the use of regular expression [\n|\r]. It will split the string based on the new line char and carriage return char. After the split, we will get string array, and returning length of the array.

Example

public class MyStringLineCounter {
     public static int getLineCount(String text){
            return text.split("[\n|\r]").length;
    }
      public static void main(String a[]){
         String str = "line1\nline2\nline3\rline4";
         System.out.println(str);
         int count = getLineCount(str);
        System.out.println("line count: "+count);
    }
}
Try it Yourself

Solve this!!

#21114,21115,21116,21117
Share with Friends