Wednesday, February 3, 2016

Why String is immutable in Java?

Why String is immutable in Java?

String is immutable for several reasons, here is a summary:

·         Security: Parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
·         String pool : If String weren’t immutable , then we never had String pool great feature in String class. Let say  :
String a=“Paras”;
String b=“Paras”
We all know that a and b points to same Object in heap, if a changed to ”Chawla”, b will still point to “Paras” which is not possible if String weren’t immutable.

String a="Paras";
String b=a;
System.out.println(a==b);
a="Chawla";
System.out.println(a +b);

Output:
true
ChawlaParas

·         Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues. Since String is immutable it can safely share between many threads which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally.
·         Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object). String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocations.
·         Class loadingString is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state). Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"

If I have class with all static members is it immutable?

If your class has only static members, then objects of this class are immutable, because you cannot change the state of that object ( you probably cannot create it either :) )



Tuesday, February 2, 2016

Convert HashMap to Array List

 Conver HashMap into Array List

package com.tutorials.maptolist;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

public class HashMapToList {

     public static void main(String[] args) {

          // Conversion Of HashMap Keys Into ArrayList
          // public abstract Set<K> keySet();

          HashMap<String, String> map = new HashMap<String, String>();
          map.put("Paras", "Chawla");
          map.put("Nonu", "Gupta");
          Set<String> set = map.keySet();
          List<String> keyList = new ArrayList<String>(set);
          System.out.println(keyList);

          // Conversion Of HashMap values Into ArrayList
          // public abstract Collection<V> values();
          Collection<String> values = map.values();
          List<String> valueList = new ArrayList<String>(values);
          System.out.println(valueList);

          // Conversion Of HashMap’s Key-Value Pairs Into ArrayList.Creating an ArrayList Of Entry objects
          // entrySet : Returns a Set view of the mappings contained in this map.
          // public abstract Set<Entry<K, V>> entrySet();

          Set<Entry<String, String>> entrySet = map.entrySet();
          ArrayList<Entry<String, String>> listOfEntry = new ArrayList<Entry<String, String>>(
                   entrySet);
          for (Entry<String, String> entry : listOfEntry)
              System.out.println(entry.getKey() + " : " + entry.getValue());

          System.out.println(listOfEntry);
     }
}
Output :
[Nonu, Paras]
[Gupta, Chawla]
Nonu : Gupta
Paras : Chawla


[Nonu=Gupta, Paras=Chawla]

Monday, February 1, 2016

First Repeated , Non-Repeated Character in a String

First Repeated , Non-Repeated Character in a String

public class FirstRepeatedNonRepeatedChar {

            public static void main(String[] args) {
                        System.out.println("Enter String");
                        Scanner scan = new Scanner(System.in);
                        String inputString = scan.next();
                        firstRepeatedNonRepeatedChar(inputString);
                        scan.close();
            }

            public static void firstRepeatedNonRepeatedChar(String inputString) {
                        // Creating a HashMap containing char as a key and occurrences as a
                        // value
                        HashMap<Character, Integer> map = new HashMap<>();
                        // Converting String to Array
                        char[] charArray = inputString.toCharArray();
                        // Checking each char of strArray... for new characters, always enter
                        // in else part
                        for (char c : charArray) {
                                    if (map.containsKey(c))
                                                map.put(c, map.get(c) + 1);
                                    else
                                                map.put(c, 1);
                        }
                        System.out.println("Map is "+map);
                        for (char c : charArray) {
                                    if (map.get(c) > 1) {
                                                System.out.println("First Repeated Character in" + inputString
                                                                        + "is " + c);
                                                break;
                                    }
                        }
                        for (char c : charArray) {
                                    if (map.get(c) == 1) {
                                                System.out.println("First Non-Repeated Character in"
                                                                        + inputString + "is " + c);
                                                break;
                                    }
                        }
            }
}


Output :

Enter String
Paras
Map is {s=1, r=1, P=1, a=2}
First Repeated Character in Paras is a

First Non-Repeated Character in Paras is P

Find the longest palindrome in a String

Find the longest palindrome in a String

public class LongestPalindrome {
            static int maxPalinLength;
            static String longestPal=null;
            public static void main(String[] args) {
                        System.out.println("Enter String");
                        Scanner scan = new Scanner(System.in);
                        String str = scan.next();
                        int length = str.length();
                        // Finding all combinations of String
                        for (int j = 0; j < length - 1; j++) {
                                    for (int i = j; i < length - 1; i++) {
                                                longestPalindrome(str.substring(j, i + 2));
                                    }
                        }
                        System.out.println("Longest Palindrome is "+ longestPal);
                        scan.close();
            }

            public static void longestPalindrome(String str) {
                        int length = str.length();
                        String reverse = "";
                        for (int i = length - 1; i >= 0; i--) {
                                    reverse = reverse + str.charAt(i);
                        }
                        // Checking if Strings are equal...
                        if (str.equals(reverse)) {
                                    // Finding the longest Palindrome
                                    if(length>maxPalinLength){
                                                longestPal=str;
                                                maxPalinLength=length;
                                    }
                        }
            }
}


Output:

Enter String
abfgerccdedccfgfer


Longest Palindrome is ccdedcc