Java String Cheat Sheet

Last updated on May 22,2019 4.3K Views
A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop. A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop.

Are you a Java programmer looking for a quick guide on Java Concepts? If yes, then you must take Strings into your consideration. This Java String cheat sheet is designed for the Java aspirants who have already embarked on their journey to learn Java. So, let’s quickly get started with this Java String Cheat Sheet.

Java String Cheat Sheet

String is a sequence of characters. But in Java, a string is an object that represents a sequence of characters. The java.lang.String class is used to create string object.

Java - Kotlin vs Java - Edureka

Creating a String

String in Java is an object that represents a sequence of char values. A String can be created in two ways:

  1. Using a literal
  2. Using ‘new’ keyword
String str1 = “Welcome”; // Using literal

String str2 = new String(”Edureka”); // Using new keyword

String Pool

Java String pool refers to a collection of Strings which are stored in heap memory. In this, whenever a new object is created, String pool first checks whether the object is already present in the pool or not.

     String str1 = "abc";
     String str2 = "abc";
    
   System.out.println(str1 == str2);
   System.out.println(str1 == "abc");

String Conversions

String to Int Conversion

	String str="123";
	int inum1 = 100; 
	int inum2 = Integer.parseInt(str);// Converting a string to int

String to Double conversion

	String str = "100.222";
	double dnum = Double.parseDouble(str); //displaying the value of variable dnum

Int to String Conversion

      int var = 111;
      String str = String.valueOf(var);     
      System.out.println(555+str); // Conversion of Int to String

Double to String Conversion

double dnum = 88.9999;  //double value
String str = String.valueOf(dnum);  //conversion using valueOf() method

Important Programs

Finding duplicate characters in a String

This program helps you to find out the duplicate characters in a String.

Removing Trailing Spaces of a String

This program tells you how to trim trailing spaces from the string but not leading spaces.

public void countDupChars(String str)
{
//Create a HashMap 
    Map<Character, Integer> map = new HashMap<Character, Integer>(); 
     //Convert the String to char array
    char[] chars = str.toCharArray();
for(Character ch:chars){
      if(map.containsKey(ch)){
         map.put(ch, map.get(ch)+1);
      } else {
         map.put(ch, 1);
        }
   }
Set<Character> keys = map.keySet(); //Obtaining set of keys  
public static void main(String a[]){
Details obj = new Details();
System.out.println("String: Edureka"); 
obj.countDupChars("Edureka"); 
System.out.println("
String: StringCheatSheet"); 
obj.countDupChars("StringCheatSheet"); 
 }
} 
int len = str.length();
    for( ; len > 0; len--)
    {
      if( ! Character.isWhitespace( str.charAt( len - 1)))
         break;
    }
    return str.substring( 0, len);

StringJoiner Class

StringJoiner mystring = new StringJoiner("-"); 
// Passing Hyphen(-) as delimiter   
mystring.add("edureka");   
// Joining multiple strings by using add() method 
mystring.add("YouTube");   

String reverse using Recursion

class StringReverse 
{ 
 /* Function to print reverse of the passed string */
    void reverse(String str) 
    { 
        if ((str==null)||(str.length() <= 1)) 
           System.out.println(str); 
        else
        { 
            System.out.print(str.charAt(str.length()-1)); 
            reverse(str.substring(0,str.length()-1)); 
        } 
    } 
    /* Driver program to test above function */
    public static void main(String[] args){ 
        String str = "Edureka for Java"; 
        StringReverse obj = new StringReverse(); 
        obj.reverse(str); 
    }     
}

Reversing a String entered by user

String str = "Welcome To Edureka";
String[] strArray = str.split(" ");

for (String temp: strArray)
{
System.out.println(temp);
  for(int i=0; i<3; i++)
  {
char[] s1 = strArray[i].toCharArray();
for (int j = s1.length-1; j>=0; j--) 
{
System.out.print(s1[j]);
}

String Classes & Interfaces

String vs String Buffer

StringStringBuffer
It is immutable.It is mutable.
String is slow and consumes more memory when you concat too many strings. StringBuffer is fast and consumes less memory when you concat strings.
String class overrides the equals() method of Object class. StringBuffer class doesn’t override the equals() method of Object class.

String Buffer vs String Builder

StringBufferStringBuilder
StringBuffer is synchronized i.e. thread safe.StringBuilder is non-synchronized i.e. not thread safe.
StringBuffer is less efficient than StringBuilder as it is synchronized.StringBuilder is more efficient than StringBuffer because it is not synchronized.

Now, interfaces that are implemented by String, StringBuffer and StringBuilder are shown in the below code.

//String implements all the 3 interfaces
public final class String extends Object
implements Serializable, Comparable<String>, CharSequence

//StringBuffer implements Serializable & CharSequence interfaces
public final class StringBuffer extends Object
implements Serializable, CharSequence

//StringBuilder implements Serializable & CharSequence interfaces
public final class StringBuilder extends Object
implements Serializable, CharSequence

String vs StringBuffer vs StringBuilder

In the below code, we will perform concatenation operation with 3 different classes. But, concatenation will happen only with String Buffer and Builder.

class Edureka{ 
    // Concatenates to String 
    public static void concat1(String s1) 
    { 
        s1 = s1 + "edurekablog"; 
    } 
    // Concatenates to StringBuilder 
    public static void concat2(StringBuilder s2) 
    { 
        s2.append("edurekablog"); 
    } 
    // Concatenates to StringBuffer 
    public static void concat3(StringBuffer s3) 
    { 
        s3.append("edurekablog"); 
    } 
   public static void main(String[] args) 
    { 
        String s1 = "Andvideos"; 
        concat1(s1);  // s1 is not changed 
        System.out.println("String: " + s1); 
        StringBuilder s2 = new StringBuilder("Andvideos"); 
        concat2(s2); // s2 is changed 
        System.out.println("StringBuilder: " + s2); 
        StringBuffer s3 = new StringBuffer("Andvideos"); 
        concat3(s3); // s3 is changed 
        System.out.println("StringBuffer: " + s3); 
    } 
}

Hence, in the output, s1 will remain unchanged and s2 and s3 will change and concatenation occurs.

String Methods

Few of the most important and frequently used String methods are listed below:

str1==str2 //compares address;
String newStr = str1.equals(str2); //compares the values
String newStr = str1.equalsIgnoreCase() //compares the values ignoring the case
newStr = str1.length() //calculates length
newStr = str1.charAt(i) //extract i'th character
newStr = str1.toUpperCase() //returns string in ALL CAPS
newStr = str1.toLowerCase() //returns string in ALL LOWERCASE
newStr = str1.replace(oldVal, newVal) //search and replace
newStr = str1.trim() //trims surrounding whitespace
newStr = str1.contains("value"); //check for the values
newStr = str1.toCharArray(); // convert String to character type array
newStr = str1.IsEmpty(); //Check for empty String
newStr = str1.endsWith(); //Checks if string ends with the given suffix

Immutable Strings

In Java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.

class Stringimmutable{  

 public static void main(String args[]){  

   String s="JavaStrings";  
   s.concat(" CheatSheet");
  System.out.println(s); 

}
}

Output will be JavaStrings  because strings are immutable and the value will not be changed.

With this, we come to an end of Java String Cheat Sheet. Check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java, J2EE & SOA Certification Training is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming that includes Interfaces, Exception Handling and JDBC Projects.

Comments
0 Comments

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.