Monday 2 October 2017

String in Java

String: -
String is a class in java and defined in java.lang package. It’s not a primitive data type like int and long. String class represents character Strings. String is immutable and final in java. It is sequence of characters or character Arrays.  
String class implements Serializable, Comparable and CharSequence interfaces.

string implements serializable, comparable, charsequence

CharSequence Interface
The CharSequence interface is used to represent sequence of characters. It is implemented by String, StringBuffer and StringBuilder classes. It means, we can create string in java by using these 3 classes.

charsequence
The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new instance is created. For mutable string, you can use StringBuffer and StringBuilder classes.
How to create String Object?
There is two ways to create String Object:
1-    By String literal
2-    By new keyword
1-   String literal:-
Java String literal is created by using double quotes.
Ex.: String str=”hello”;
Every time you create a String literal, the JVM checks the String constant pool first. If the String already exists in the pool, a reference to the pooled String instance is returned. If String doesn't exist in the pool, a new String instance is created and placed in the pool.
Ex.:
String s1=”hai”;
String s2=”hai”;// will not create new instance
2: By new keyword
String s=new String("hai");//creates two objects and one reference variable 
In this case, jvm will create a new String Object  by new keyword  in heap area and another String object is created in String constant pool if it(String literal (“hai”)) is not there already and if it is already there then its pooled reference. And one reference; s is created it refers to the object heap(non pool);
JVM store String Object in heap if it is created via new keyword but if you want to store it into String constant pool then you need to call intern() method  to store String object into String constant pool or it return the reference if there is already a String with equal value present in the pool.

Write a method to check if input String is Palindrome?

A String is Palindrome if it’s same after reversed. Ex: kak
String class doesn’t provide any method to reverse the String but StringBuffer and StringBuilder both have reverse method.

private static boolean isPalindrome(String s) {
        if (s == null)
            return false;
        StringBuilder sBuild = new StringBuilder(s);
        sBuild.reverse();
        return sBuild.toString().equals(s);
    }
We can check to String is palindrome are not without any predefined methods..
Like.
private static boolean isPalindromeString(String s) {
        if (s == null)
            return false;
        int length = s.length();
        //System.out.println(length / 2);
        for (int i = 0; i < length / 2; i++) {
 
            if (s.charAt(i)!= s.charAt(length - i - 1))
                return false;
        }
        return true;
    }
  
We can get reverse String as …

String input = "HelloBossItIs";

        // getBytes() method to convert string
        // into bytes[].
        byte [] strAsByteArray = input.getBytes();

        byte [] result =
                   new byte [strAsByteArray.length];

        // Store result in reverse order into the
        // result byte[]
        for (int i = 0; i<strAsByteArray.length; i++)
            result[i] =
             strAsByteArray[strAsByteArray.length-i-1];
        System.out.println(new String(result));


We can do it via StringBuilder also..reverse Order
String input = "HelloBossItIs";

        StringBuilder input1 = new StringBuilder();

        // append a string into StringBuilder input1
        input1.append(input);

        // reverse StringBuilder input1
        input1 = input1.reverse();

        // print reversed String
        for (int i=0; i<input1.length(); i++)
            System.out.print(input1.charAt(i));

Converting String into Character Array..in reverse order

String input = "HelloBossItIs";

        // convert String to character array
        // by using toCharArray
        char[] ch = input.toCharArray();

        for (int i = ch.length-1; i>=0; i--)
            System.out.print(ch[i]);
Convert the input string into character array by using the toCharArray():

String input = "HelloBosItIs";
        char[] temparray = input.toCharArray();
        int left, right=0;
        right = temparray.length-1;

        for (left=0; left < right ; left++ ,right--)
        {
            // Swap values of left and right
            char temp = temparray[left];
            temparray[left] = temparray[right];
            temparray[right]=temp;
        }

        for (char c : temparray)
            System.out.print(c);
        System.out.println();
Reverse String via Collections:-
String input = "HelloBossItIs";
        char[] ch = input.toCharArray();
        List<Character> list = new ArrayList<>();

        for (char c: ch)
            list.add(c);

        Collections.reverse(list);
        ListIterator li =list.listIterator();
        while (li.hasNext())
            System.out.print(li.next());
    }


Write a method that will remove given character from the String?

private static String removeChar(String str, char c) {
        if (str == null)
            return null;
        return str.replaceAll(Character.toString(c), "");
    }

public static String removeCharInString (String string, char charToBeRemoved) {
        if (string == null)
             return "";
             StringBuilder strBuild = new StringBuilder ();
        for (int i = 0; i < string.length (); i++) {
            char chr = string.charAt (i);
            if (chr == charToBeRemoved)
                continue;
            strBuild.append (chr);       }
        return strBuild.toString ();
    }


Convert string into lower case without using any predefined method
1:-
public static void toLowerCase(String a){
 
for (int i = 0; i< a.length(); i++){
 
    char aChar = a.charAt(i);
    if (65 <= aChar && aChar<=90){
    aChar = (char)( (aChar + 32) ); 
    }
 
    System.out.print(a);
 }
2:-
public static void printLowerCase(String a){
    for(char ch: a.toCharArray()) {
       if(ch >= 'A' && ch <= 'Z')
          ch += 'a' - 'A';
       System.out.print(ch);
    }
}
3:-
public static String toLowerCase(String input){
            if(input == null){
                return input;
            }
            StringBuilder builder = new StringBuilder();
            for(int i=0;i<input.length();i++){
                char stringChar = input.charAt(i);
 
                if(65 <= stringChar && stringChar <=90){
                    stringChar = (char)( (stringChar + 32) ); 
                    builder.append(stringChar);
                }
                else if (97 <= stringChar && stringChar<=122)
                {
                    builder.append(stringChar);
                }
            }
            if(builder.length() ==0){
                builder.append(input);
            }
            return builder.toString();
        }
 
4:-
private String txt;
    private char lower;
 
public void print()
    {
        for(int i=0;i<txt.length();i++)
        {
            if('A' <= txt.charAt(i) && txt.charAt(i) <= 'Z')
            {
                lower = (char)(txt.charAt(i) + 32);
                System.out.print(lower);
            }
            else
            {
                lower = txt.charAt(i);
                System.out.print(lower);
            }
        }
    }
5:-
char ch;
            int temp;
            Scanner scan = new Scanner(System.in);
 
            System.out.print("Enter a Character in Lowercase : ");
            ch = scan.next().charAt(0);
 
            temp = (int) ch;
            temp = temp - 32;
            ch = (char) temp;
 
            System.out.print("Equivalent Character in Uppercase = " +ch);
Convert string into uppercase
1:-
public static void toUpperCase(String a){
 
for (int i = 0; i< a.length(); i++){
 
    char aChar = a.charAt(i);
    if (97< aChar && aChar<=122){
    aChar = (char)( (aChar -32) ); 
    }
 
    System.out.print(a);
 }
2:-
private String txt;
    private char upper;
 
public void print()
    {
        for(int i=0;i<txt.length();i++)
        {
            if('a' <= txt.charAt(i) && txt.charAt(i) <= 'z')
            {
                lower = (char)(txt.charAt(i) - 32);
                System.out.print(lower);
            }
            else
            {
                lower = txt.charAt(i);
                System.out.print(upper);
            }
        }
    }
3:-

public static void printUpperCase(String a){
    for(char ch: a.toCharArray()) {
       if(ch >= 'a' && ch <= 'z')
          ch += 'A' - 'a';
       System.out.print(ch);
    }
}

4:-

public static String toUpperCase(String input){
            if(input == null){
                return input;
            }
            StringBuilder builder = new StringBuilder();
            for(int i=0;i<input.length();i++){
                char stringChar = input.charAt(i);
 
                if(92 <= stringChar && stringChar <=122){
                    stringChar = (char)( (stringChar - 32) ); 
                    builder.append(stringChar);
                }
                else if (65 <= stringChar && stringChar<=90)
                {
                    builder.append(stringChar);
                }
            }
            if(builder.length() ==0){
                builder.append(input);
            }
            return builder.toString();
        }
 


What is String subSequence method?


Java 1.4 introduced CharSequence interface and String implements this interface.
CharSequence invokes substring method internally.

public CharSequence subSequence(int beginIndex, int endIndex) {
    return this.substring(beginIndex, endIndex);
}


String str = "hellobossit.i.am";
            System.out.println("Last 3 char String: " +
 str.subSequence(str.length() - 3, str.length()));
            System.out.println("First 5 char String: " +
 str.subSequence(0, 5));
            System.out.println("website name: " +
 str.subSequence(5, 12));
            // substring vs subSequence
            System.out.println("substring == subSequence ? " + 
(str.substring(5, 12) == str.subSequence(5, 12)));
            System.out.println("substring equals subSequence ? " +
 (str.substring(5, 12).equals(str.subSequence(5, 12))));

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of char values.
No.
Method
Description
1
returns char value for the particular index
2
returns string length
3
returns formatted string
4
returns formatted string with given locale
5
returns substring for given begin index
6
returns substring for given begin index and
 end index
7
returns true or false after matching the 
sequence of

char value
8
returns a joined string
9
returns a joined string
10
checks the equality of string with object
11
checks if string is empty
12
concatinates specified string
13
replaces all occurrences of specified char value
14
replaces all occurrences of specified CharSequence
15
compares another string. It doesn't check case.
16
returns splitted string matching regex
17
returns splitted string matching regex and limit
18
returns interned string
19
returns specified char value index
20
returns specified char value index starting
with given index
21
returns specified substring index
22
returns specified substring index starting
with given index
23
returns string in lowercase.
24
returns string in lowercase using
specified locale.
25
returns string in uppercase.
26
returns string in uppercase using
specified locale.
27
removes beginning and ending
spaces of this string.
28
converts given type into string. It
is overloaded.


How to compare two Strings in java program?


String class  implements Comparable interface and having two methods
1-campareTo()
2-compareTo(String anotherString)
These methods are used to compare two String Objects.
If this method return zero then in this case equals(String str) return true
compareToIgnoreCase(String str), it use String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison, if value return zero then equalsIgnoreCase(String str) will also return true.


We can compare string in java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.
There are three ways to compare string in java:
  1. By equals() method
  2. By = = operator
  3. By compareTo() method

1) String compare by equals() method

The String equals() method compares the original content of the string. It compares values of string for equality. String class provides two methods:
  • public boolean equals(Object another) compares this string to the specified object.
  • public boolean equalsIgnoreCase(String another) compares this String to another string, ignoring case.
1.    class Teststringcomparison1{  
2.     public static void main(String args[]){  
3.       String s1="Sager";  
4.       String s2="Sager";  
5.       String s3=new String("Sager");  
6.       String s4="Sachin";  
7.       System.out.println(s1.equals(s2));//true  
8.       System.out.println(s1.equals(s3));//true  
9.       System.out.println(s1.equals(s4));//false  
10.  }  
11. }  
Output:true
       true
       false
1.    class Teststringcomparison2{  
2.     public static void main(String args[]){  
3.       String s1="sager";  
4.       String s2="SAGER";  
5.       System.out.println(s1.equals(s2));//false  
6.       System.out.println(s1.equalsIgnoreCase(s2));//true  
7.     }  
8.   
Output:
false
true

2) String compare by == operator

The = = operator compares references not values.
1.    class Teststringcomparison3{  
2.     public static void main(String args[]){  
3.       String s1="sager";  
4.       String s2="sager";  
5.       String s3=new String("sager");  
6.       System.out.println(s1==s2);//true (because both refer to same instance)  
7.       System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)  
8.     }  
9.    }  

Output:true
       false

3) String compare by compareTo() method

The String compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
  • s1 == s2 :0
  • s1 > s2   :positive value
  • s1 < s2   :negative value
1.    class Teststringcomparison4{  
2.     public static void main(String args[]){  
3.       String s1="sager";  
4.       String s2="sager";  
5.       String s3="raju";  
6.       System.out.println(s1.compareTo(s2));//0  
7.       System.out.println(s1.compareTo(s3));//1(because s1>s3)  
8.       System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )  
9.     }  
1. }  
Output:0
       1
       -1




Immutable String in Java

In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
Let's try to understand the immutability concept by the example given below:
1.    class Testimmutablestring{  
2.     public static void main(String args[]){  
3.       String string1="abcd";  
4.       string1.concat(" def");//concat() method appends the string at the end  
5.       System.out.println(string1);//will print abcd because strings are immutable objects  
6.     }  
7.    }  

Output:abcd
 
 
 
 
If we create two String literal Object having same value, then only first time String literal object being created only if it is not there in String Constant Pool, and then string2 two pointing that previously created String literal object in String Constant Pool
 
String string1=”abcd”;
String string2=”abcd”;
Then in both are pointing same String Object;


1.    class Testimmutablestring1{  
2.     public static void main(String args[]){  
3.       String s="abcd";  
4.       s=s.concat(" ef");  
5.       System.out.println(s);  
6.     }  
7.    }  

Output:- abcdef

Why string objects are immutable in java?

1.       String pool is possible only because String is immutable in java, this way Java Runtime saves a lot of java heap space because different String variables can refer to same String variable in the pool. If String would not have been immutable, then String interning would not have been possible because if any variable would have changed the value, it would have been reflected to other variables also.
String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
The following code will create only one string object in the heap.
String string1 = "abcd";
String string2 = "abcd";
Here is how it looks:
If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
2.       If String is not immutable then it would cause severe security threat to the application. For example, database username, password are passed as String to get database connection and in socket programming host and port details passed as String. Since String is immutable it’s value can’t be changed otherwise any hacker could change the referenced value to cause security issues in the application.
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.
Here is a code example:
boolean connect(string s){
   if (!isSecure(s)) { 
throw new SecurityException(); 
}              
    //here will cause problem, if s is changed before this by using other references.    
    causeProblem(s);
}
 
3.       Since String is immutable, it is safe for multithreading and a single String instance can be shared across different threads. This avoid the usage of synchronization for thread safety, Strings are implicitly thread safe.
4.       Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader. For example, think of an instance where you are trying to load java.sql.Connection class but the referenced value is changed to myhacked.Connection class that can do unwanted things to your database.
5.       Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.
6.    Because immutable objects can not be changed, they can be shared among multiple threads freely. This eliminates the requirements of doing synchronization.

Can we use String in switch case?

Java switch case is a neat way to code for conditional flow, just like if-else conditions. Before Java 7, the only means to achieve string based conditional flow was using if-else conditions. But Java 7 has improved the switch case to support String also.

 

Java switch case String Example

Here I am providing a java program that shows the use of String in java switch case statements. For comparison, I am also providing another method which does the same conditional flow using if-else conditions.
SwitchStringExample.java
public class SwitchStringExample {
      public static void main(String[] args) {
             printColorUsingSwitch("red");
             printColorUsingIf("red");
             // switch case string is case sensitive
             printColorUsingSwitch("RED");
            printColorUsingSwitch(null);
      }
      private static void printColorUsingIf(String color) {
             if (color.equals("blue")) {
                    System.out.println("BLUE");
             } else if (color.equals("red")) {
                    System.out.println("RED");
             } else {
                    System.out.println("INVALID COLOR CODE");
             }
      }
private static void printColorUsingSwitch(String color) {
             switch (color) {
             case "blue":
                    System.out.println("BLUE");
                    break;
             case "red":
                    System.out.println("RED");
                    break;
             default:
                    System.out.println("INVALID COLOR CODE");
             }
      }
}
RED
RED
INVALID COLOR CODE
Exception in thread "main"
java.lang.NullPointerException at com.journaldev.util.SwitchStringExample.printColorUsingSwitch(SwitchStringExample.java:24)
      at com.journaldev.util.SwitchStringExample.main(SwitchStringExample.java:10)
Keys points to know for java switch case String are:
1.    Java switch case String make code more readable by removing the multiple if-else-if chained conditions.
2.    Java switch case String is case sensitive, the output of example confirms it.
3.    Java Switch case uses String.equals() method to compare the passed value with case values, so make sure to add a NULL check to avoid NullPointerException.
4.    According to Java 7 documentation for Strings in Switch, java compiler generates more efficient byte code for String in Switch statement than chained if-else-if statements.
5.    Make sure to use java switch case String only when you know that it will be used with Java 7 else it will throw Exception.

Java Program to find all Permutations of a String

Permutation of String in Java Algorithm

To get all the permutations, we will first take out the first char from String and permute the remaining chars.
If String = “ABC”
First char = A and remaining chars permutations are BC and CB.
Now we can insert first char in the available positions in the permutations.
BC -> ABC, BAC, BCA
CB -> ACB, CAB, CBA
So we can write a recursive function call to return the permutations and then another function call to insert the first characters to get the complete list of permutations.
public class StringHelper {
    public static Set<String> permutationFinder(String str) {
        Set<String> perm = new HashSet<String>();
        //Handling error scenarios
        if (str == null) {
            return null;
        } else if (str.length() == 0) {
            perm.add("");
            return perm;
        }
        char initial = str.charAt(0); // first character
        String rem = str.substring(1); // Full string without first character
        Set<String> words = permutationFinder(rem);
        for (String strNew : words) {
            for (int i = 0;i<=strNew.length();i++){
                perm.add(charInsert(strNew, initial, i));
            }
        }
        return perm;
    }
public static String charInsert(String str, char c, int j) {
        String begin = str.substring(0, j);
        String end = str.substring(j);
        return begin + c + end;
    }
 
    public static void main(String[] args) {
        String s = "AAC";
        String s1 = "ABC";
        String s2 = "ABCD";
        System.out.println("\nPermutations for " + s + " are: \n" + permutationFinder(s));
        System.out.println("\nPermutations for " + s1 + " are: \n" + permutationFinder(s1));
        System.out.println("\nPermutations for " + s2 + " are: \n" + permutationFinder(s2));
    }
}
Note that I have used SET to remove duplicates, so that it works for those strings also having same chars.
Here is the output of the above program:
Permutations for AAC are: 
[AAC, ACA, CAA]
 
Permutations for ABC are: 
[ACB, ABC, BCA, CBA, CAB, BAC]
 
Permutations for ABCD are: 
[DABC, CADB, BCAD, DBAC, BACD, ABCD, ABDC, DCBA, ADBC, ADCB, CBDA, CBAD, DACB, ACBD, CDBA, CDAB, DCAB, ACDB, DBCA, BDAC, CABD, BADC, BCDA, BDCA]
That's all for finding all permutations of a String in java.

 

Difference between String, StringBuffer and StringBuilder?


String is immutable and final in java, so whenever we do String manipulation, it creates a new String. String manipulations are resource consuming, so java provides two utility classes for String manipulations - StringBuffer and StringBuilder.
StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So when multiple threads are working on same String, we should use StringBuffer but in single threaded environment we should use StringBuilder.
StringBuilder performance is fast than StringBuffer because of no overhead of synchronization.
String is one of the most widely used class in java programming and one of the most important topic in core java interview. If you are writing a program which prints something on console, we use String.
This tutorial is aimed to focus on major features of String class and then we will compare String vs StringBuffer vs StringBuilder.

String in Java

1.       String class represents character strings, we can instantiate String by two ways.
String str = "abc"; or String str = new String ("abc");
2.       String is immutable in java, so its easy to share it across different threads or functions.
3.       When we create a String using double quotes, it first looks for the String with same value in the JVM string pool, if found it returns the reference else it creates the String object and then place it in the String pool. This way JVM saves a lot of space by using same String in different threads. But if new operator is used, it explicitly creates a new String in the heap memory.
4.       + operator is overloaded for String and used to concatenate two Strings. Although internally it uses StringBuffer to perform this action.
5.       String overrides equals() and hashCode() methods, two Strings are equal only if they have same characters in same order. Note that equals() method is case sensitive, so if you are not looking for case sensitive checks, you should use equalsIgnoreCase() method.
6.       A String represents a string in the UTF-16 format
7.    String is a final class with all the fields as final except “private int hash”. This field contains the hashCode() function value and created only when hashCode() method is called and then cached in this field. Furthermore, hash is generated using final fields of String class with some calculations, so every time hashCode() method is called, it will result in same output. For caller, its like calculations are happening every time but internally it’s cached in hash field.

String vs StringBuffer

Since String is immutable in java, whenever we do String manipulation like concat, substring etc, it generates a new String and discard the older String for garbage collection.
These are heavy operations and generate a lot of garbage in heap. So Java has provided StringBuffer and StringBuilder class that should be used for String manipulation.
StringBuffer and StringBuilder are mutable objects in java and provide append(), insert(), delete() and substring() methods for String manipulation.

StringBuffer vs StringBuilder

StringBuffer was the only choice for String manipulation till Java 1.4 but it has one disadvantage that all of its public methods are synchronized. StringBuffer provides Thread safety but on a performance cost.
In most of the scenarios, we don’t use String in multithreaded environment, so Java 1.5 introduced a new class StringBuilder that is similar with StringBuffer except thread safety and synchronization.
So if you are in a single threaded environment or don’t care about thread safety, you should use StringBuilder else use StringBuffer. See this post for performance benchmarking between StringBuffer and StringBuilder.

String vs StringBuffer vs StringBuilder

1.    String is immutable whereas StringBuffer and StringBuider are mutable classes.
2.    StringBuffer is thread safe and synchronized whereas StringBuilder is not, thats why StringBuilder is more faster than StringBuffer.
3.    String concat + operator internally uses StringBuffer or StringBuilder class.
4.    For String manipulations in non-multi threaded environment, we should use StringBuilder else use StringBuffer class.
That’s all for a quick roundup of difference between String vs StringBuffer vs StringBuilder. In most of the scenarios for string manipulation, StringBuilder is better suited than StringBuffer.
StringBuffer vs StringBuilder is a popular interview question in core java interview. Let’s look into some important points when comparing StringBuilder vs StringBuffer.

StringBuffer vs StringBuilder

1.    StringBuffer is the thread safe utility class to perform several operations on Strings. It contains append() and insert() methods that are widely used to perform operation on Strings in a multi-thread environment. If you will check the source code, most of its functions are synchronized for thread safety.
Since most of the String operations, for example concatenation happens in a single thread environment, Java 1.5 introduced another utility class StringBuilder to perform similar operations but doesn’t provide thread safety. If you will look into its source code, all the methods are unsynchronized. This is the most important point for StringBuffer vs StringBuilder.
2.    StringBuffer has some extra methods such as substringlengthcapacitytrimToSize etc. However these are not required since you have all these present in String too. That’s why these methods were never implemented in StringBuilder class.
3.    StringBuffer was introduced in Java 1.0 whereas StringBuilder class was introduced in Java 1.5 after looking at shortcomings of StringBuffer
4.    StringBuilder is faster than StringBuffer because of no synchronization.
When I started learning java, the one thing I stick to my heart is to avoid synchronization as far as possible as it adds an extra overhead to the system and slows down the processing.

 

StringBuilder vs StringBuffer Performance

Here, I am trying to check the effect on performance because of synchronization with a sample program that performs append() and insert() on StringBuffer and StringBuilder object for multiple times.
public class TestString {
 
      public static void main(String[] args) {
            System.gc();
            long start=new GregorianCalendar().getTimeInMillis();
            long startMemory=Runtime.getRuntime().freeMemory();
            StringBuffer sb = new StringBuffer();
            //StringBuilder sb = new StringBuilder();
            for(int i = 0; i<100000; i++){
                  sb.append(":"+i);
                  sb.insert(i, "Hi");
            }
            long end=new GregorianCalendar().getTimeInMillis();
            long endMemory=Runtime.getRuntime().freeMemory();
            System.out.println("Time Taken:"+(end-start));
            System.out.println("Memory used:"+(startMemory-endMemory));
      }
}
I changed the value of i in the above code from 1,000 to 1,00,000 and logged the time taken and memory used. I ran the same code for StringBuffer object also to check the time and memory values. I have executed the code 5 times for each case and then calculated the average values.

What does String intern() method do?

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
This method always return a String that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

Why String is popular HashMap key in Java?

Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

String Concatenation in Java


In java, string concatenation forms a new string that is the combination of multiple strings. There are two ways to concat string in java:
  1. By + (string concatenation) operator
  2. By concat() method

1) String Concatenation by + (string concatenation) operator

Java string concatenation operator (+) is used to add strings. For Example:
1.   class TestStringConcatenation1{  
2.    public static void main(String args[]){  
3.      String s="Sager"+" Pillu";  
4.      System.out.println(s);//Sager Pillu  
5.    }  
6.   }  
Output:
Sager Pillu
 
The Java compiler transforms above code to this:
1.   String s=(new StringBuilder()).append("Sager").append(" Pillu).toString();  

In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its append method. String concatenation operator produces a new string by appending the second operand onto the end of the first operand. The string concatenation operator can concat not only string but primitive values also. For Example:
1.   class TestStringConcatenation2{  
2.    public static void main(String args[]){  
3.      String s=50+30+"Sager"+40+40;  
4.      System.out.println(s);//80Sager4040  
5.    }  
6.   }  

80Sager4040

 

2) String Concatenation by concat() method

The String concat() method concatenates the specified string to the end of current string. Syntax:
public String concat(String another)  
//Let's see the example of String concat() method.
1.   class TestStringConcatenation3{  
2.    public static void main(String args[]){  
3.      String s1="Sager ";  
4.      String s2="Pillu";  
5.      String s3=s1.concat(s2);  
6.      System.out.println(s3);//Sager Pillu  
7.     }  
8.   }  
Outpout:
Sager Pillu

                                                         

Substring in Java

A part of string is called substring. In other words, substring is a subset of another string. In case of substring startIndex is inclusive and endIndex is exclusive.
You can get substring from the given string object by one of the two methods:
  1. public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
  2. public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
In case of string:
  • startIndex: inclusive
  • endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
1.    String s="hello";  
2.    System.out.println(s.substring(0,2));//he  
In the above substring, 0 points to h but 2 points to e (because end index is exclusive).

Example of java substring

1.    public class TestSubstring{  
2.     public static void main(String args[]){  
3.       String s="SagerPillu";  
4.       System.out.println(s.substring(5));//Pillu 
5.       System.out.println(s.substring(0,5));//Sager  
6.     }  
7.    }  

Pillu
Sager


Java String class methods

The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based or mobile application.
Let's see the important methods of String class.

Java String toUpperCase() and toLowerCase() method

The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter.
1.    String s="Sager";  
2.    System.out.println(s.toUpperCase());//SAGER  
3.    System.out.println(s.toLowerCase());//sager  
4.    System.out.println(s);//Sager(no change in original)  


Java String trim() method

The string trim() method eliminates white spaces before and after string.
1.    String s="  Sager  ";  
2.    System.out.println(s);//  Sager    
3.    System.out.println(s.trim());//Sager  

Java String startsWith() and endsWith() method

1.    String s="Sager";  
2.     System.out.println(s.startsWith("Sa"));//true  
3.     System.out.println(s.endsWith("r"));//true  
4.     

Java String charAt() method

The string charAt() method returns a character at specified index.
1.    String s="Sager";  
2.    System.out.println(s.charAt(0));//S  
3.    System.out.println(s.charAt(3));//e  
 

Java String length() method

The string length() method returns length of the string.
1.    String s="Sager";  
2.    System.out.println(s.length());//5  


Java String intern() method


A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
1.    String s=new String("Sager");  
2.    String s2=s.intern();  
3.    System.out.println(s2);//Sager  

Java String valueOf() method

The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string.
1.    int a=10;  
2.    String s=String.valueOf(a);  
3.    System.out.println(s+10);  


Java String replace() method


The string replace() method replaces all occurrence of first sequence of character with second sequence of character.
1.    String s1="Java is a programming language. Java is a platform. Java is an Island.";    
2.    String replaceString=s1.replace("Java","Mava");//replaces all occurrences of "Java" to "Kava"    
3.    System.out.println(replaceString);    
Output:
Mava is a programming language. Mava is a platform. Mava is an Island.






String in Java

String: - String is a class in java and defined in java.lang package. It’s not a primitive data type like int and long. String class rep...