HTML Java

Java String Methods


Java String methods

  • split(): Its use to split the string using given regex expression 2 types of split() method.

    split(String regexExpression): This method Splits the String with the given Expression and return the array of string.

  • split(String regexExpression, int limit): This method Splits the String with the given Expression and return the array of string with the given limit.

Example

package com.string;

public class StringSplit {

  public static void main(String[] args) {
   String[] stringArr1;
   String[] stringArr2;
   String s = "coders-arts-sof-stack";
   stringArr1 = s.split("-");
   System.out.println("String splited by given Expression");
   for(String strings : stringArr1) {
     System.out.println(strings);
   }
   stringArr2 = s.split("-",3);
   System.out.println("String splited by given Expression and limit");
   for(String strings : stringArr2) {
     System.out.println(strings);
   }
 }
}
Try it »


  • contains(): Check if strings contains specified sequence of character or not if contains then retrun true else return false.

Example

package com.string;

public class StringContains {

  public static void main(String[] args) {
   String s = "hello codersarts";
   System.out.println(s.contains("ell"));
   System.out.println(s.contains("help"));
 }
}
Try it »


  • length(): Its use to find the length of the string

Example

package com.string;

public class StringLength {

  public static void main(String[] args) {
   String s1 = "coders";
   String s2 = "arts";
   System.out.println(s1.length());
   System.out.println(s2.length());
 }
}
Try it »


  • replace(): It is used to replace a specific part of string with other string. There are four alternatives of replace() method.
    • replace(char oldCharSeq, char newCharSeq) : This method replace all the occurence of oldCharSeq with newCharSeq.
    • replace(CharSequence target, CharSequence replacement) : This method replace all the occurence of target with replacement.
    • replaceAll()(String regexExp, String replaceExp) : This method replace all the occurence of substring matches with the given regexExp;
    • replaceFirst()(String regexExp, String replaceExp) : This method replace all the occurence of substring matches with the given regexExp;

Example

package com.string;

public class StrinReplace {

  public static void main(String[] args) {
   String str = "Hello Codersarts";
   str =str.replace('e','o');
   System.out.println("After replacing e with o :");
   System.out.println(str);

   String str1 = "Hello Codersarts , Hello Ankit";
   str1 =str1.replace("Hello","Hi");
   System.out.println("After replacing Hello with Hi :");
   System.out.println(str1);

   String str2 = "Hi Codersarts , Hi Ankit";
   str2 =str2.replace("Hi","Hello");
   System.out.println("After replacing Hi with Hello :");
   System.out.println(str2);

 }
}
Try it »


  • substring(): This method is use to get a part of the String.

Example

package com.string;

public class SubString {

  public static void main(String[] args) {
   String str = "Hello Codersarts";
   str = str.substring(2,8);
   System.out.println(str);
 }
}
Try it »


  • toString(): If you want to print object then compiler invokes toString method of Object class. And we can also overide this method and print the object values according to the program like this:

Example

package com.string;

class Employee{
 int emp_Id;
 String emp_Name;

 public Employee (int id, String name) {
  emp_Id = id;
  emp_Name = name;
 }

 @Override
 public String toString() {
  return "Employee [emp_Id=" + emp_Id + ", emp_Name=" + emp_Name + "]";
 }
}

public class ToString {

 public static void main(String args[]) {
  Employee e = new Employee(1,"Ankit");
  System.out.println(e);

 }
}
Try it »


  • String Concatenation : It is use to combine 2 string by using “+” into single string.

Example

package com.string;

public class StringConcat {

 public static void main(String[] args) {
  String s1 = "Coders";
  String s2 = "arts";
  String s3 = s1+s2;
  System.out.println("Strings before Concatenation");
  System.out.println(s1);
  System.out.println(s2);
  System.out.println("Strings after Concatenation");
  System.out.println(s3);
 }
}
Try it »


  • trim(): This method is use to remove the spaces from the begining and ending in the String Unicode value for Space : '\u0020' and return string after removing spaces.

    Note: But it doesn’t remove middle spaces.

Example

package com.string;

public class StringTrim {

 public static void main(String args[]) {
  String str1 = " Hello Codersarts ";
  String str2 = " Hi Codersarts";
  String str3 = "Bye Codersarts ";
  System.out.println(str1.trim());
  System.out.println(str2.trim());
  System.out.println(str3.trim());

 }
}
Try it »


  • charAt(): This method is use to get the character ftom the String in the given index.

    Note: If index is not Found then It will shows StringIndexOutOfBoundsException index starts from 0 to n-1;

Example

package com.string;

public class StringCharAt {

 public static void main(String[] args) {
  String str = "coders arts";
  System.out.println(str.charAt(8));
 }
}
Try it »


  • endsWith(): This method is use to check the given string ends with the given character of sequence of not if it does then it return true or else return false.

Example

package com.string;

public class StringEndsWith {

 public static void main(String[] args) {
  String str = "!Hello Codersarts @";
  System.out.println(str.endsWith("s @"));
  System.out.println(str.endsWith("s !"));
 }
}
Try it »


  • intern(): Its a native method when this method is called on String object. If the String pool already has a String with the same value then it return that refernce to that object if its not in the pool then its added to the pool and return the reference of that object.

Example

package com.string;

public class StringIntern {

public static void main(String[] args) {

// S1 refers to Object in the Heap Area
String str1 = new String("coders"); // Line-1

// S3 refers to Object in the SCP Area
String str3 = "coders"; // Line-3

// S2 refers to Object in SCP Area
String str2 = str1.intern(); // Line-2

// Comparing memory locations
// s1 is in Heap
// s2 is in SCP
System.out.println(str1 == str2);

// Comparing only values
System.out.println(str1.equals(str2));

// comparing memory locations in SCP
//str2 now is having location of str1 from StringPoolConstant because when str2 = str1.intern()
// it will return the string copy from the pool
System.out.println(str2 == str3);

str4= str3.intern();
System.out.println(str4 == str3);

}

}
Try it »


  • split() with multiple Delimeter: This method is use to split the string with the given delimeters.

Example

package com.string;

public class StringMultipleDelimeter {

public static void main(String[] args) {
String url = "https:secure//www.google.com/coders-arts";
String [] tokens = url.split(":|//|/|-");
for(String s : tokens) {
System.out.println(s);
}
}

}
Try it »


  • toLowerCase(): This method is use to convert the string into lower case like if string is “Ram” then it will convert into “ram”.

Example

package com.string;

public class StringUpperCase {

public static void main(String[] args) {

String str = "Hello CodersArts";
System.out.println(str.toUpperCase());
}

}
Try it »


  • toUpperCase(): This method is use to convert the string into upper case like if string is “ram” then it will convert into “RAM”.

Example

package com.string;

public class StringUpperCase {

public static void main(String[] args) {

String str = "Hello CodersArts";
System.out.println(str.toUpperCase());

}

}
Try it »


  • isEmpty(): This method is use to check whether string is empty or not if it is empty then return true or else false.

Example

package com.string;

public class StringEmpty {

public static void main(String[] args) {
String s1 = "coders";
String s2 = "";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}

}
Try it »


  • join() : This method is used to concatenate the each element with the given delimeter and return the String.

Example

package com.string;

public class StringJoin {

public static void main(String args[]) {

String str = String.join(">","apple","boy","cat");
System.out.println(str);
}

}
Try it »


  • lastIndex(): This method is use to get the last index of any given character in the given string.

Example

package com.string;

public class StringLastIndex {

public static void main(String[] args) {
String str = "coders arts";
System.out.println(str.lastIndexOf('s'));
}

}
Try it »


  • startsWith(): This method is use to check the whether the given string starts with the given strings or not.
      It has two types:
    • boolean startsWith(String s): If it starts from the given string then it returns true or else false.
    • boolean startsWith( String s,int fromIndex): if it starts from the given index which is given to check the string then returns true or else false.

Example

package com.string;

public class StringStartsWith {

public static void main(String[] args) {

String str = "Hello Codersarts";
System.out.println(str.startsWith("H"));
System.out.println(str.startsWith("e"));
System.out.println(str.startsWith("H",0));
System.out.println(str.startsWith("e",0));
}

}
Try it »


  • toCharArray(): This method is use to convert the string into Array of Character.

Example

package com.string;

public class StringToCharArray {

public static void main(String[] args) {

System.out.println("String is :" +str);
String str = "Hello Codersarts";
System.out.println("String Converted into char Array:");
char [] ch = str.toCharArray();
for(int i=0;i < ch.length;i++) {
System.out.println(ch[i]);
}
}

}
Try it »