Strings in Java


There are Three Types of Strings
1. String
2. String Buffer
3. String Builder

Creating String Objects


While executing Java code the values assigned to the variables will be stored in memory called heap memory.
1. When we use literals to create variables it will be stored in a string constant pool inside the heap memory.

  • in this case, when we give same value to 2 different variables, the 2 variables will be mapped to the same value as shown in the above fig. i.e., the second variable acts as a reference to the first one.

2. When we use a new keyword it will be directly stored in the heap memory.

  • in this case, even if we give same value to two different variables, the two variables will Store the same data 2 times, one for each as shown in the above fig.

String Methods


This is how we can print two strings


Comparing String Objects


To compare string objects we use ==
To compare string objects values we use .equals(#)

While comparing string objects values to ignore case we use .equalsIgnoreCase(#)

Printing the String in Lowercase

To get the output of String to Lowercase we use .toLowerCase()


Printing the String in Uppercase

To get the output of String to Uppercase we use .toUpperCase()


Printing specific character

To get the output of specific character of String we use .charAt(#)


Printing " in java

To print " or ' as a string we need to use \ before the " or '


Printing a null string

If The string value is Null and if we directly printed it we will get an error.
To avoid printing null string values we can use the above code.
If the string value is blank we can print the string value without an error.

String Buffer and String Builder



  • .append("#") //it will add after the string.
  • .insert( #,"#") // it will insert in the given position.
  • .replace(#,#,"#") // it will replace the string between the start and end values we given.
  • .delete(#,#) // it will delete the string between the start and end values we given.
  • .reverse() //  it will reverse the entire string.

These are some of the main string buffer and StringBuilder methods.

Post a Comment

0 Comments