IQ-String



  • What is String in Java?

            String is a Class, not a keyword in java and defined in java.lang package.
String in immutable and final in Java and JVM uses String Pool to store all the String objects.
We can instantiate a String object using double quotes and overloading of "+" operator for concatenation.
---------------------------------


  • What are different ways to create String Object?

                      String str = "abc";
                      String str = new String("abc");
---------------------------------


  • How to compare two Strings in java?

                You can not use "==" operator to compare two strings.
                String provides equals() method to compare two string objects.
                Also you can ignore case during string compare by calling equalsIgnoreCase() method
               '==' operator compares the object reference but not the string value.
---------------------------------


  • How to convert String to char ?

               This is a tricky because String is a sequence of characters,
       so we can't convert it to a single character.
               We can use use charAt method to get the character at given index or we can use toCharArray() method to convert String to character array.
---------------------------------


  • How to convert String to byte array and vice versa?

                 We can use String getBytes() method to convert String to byte array
                        and
                 we can use String constructor new String(byte[] arr) to convert byte array to String.
---------------------------------


  • Is String a primitive type or derived type?

                       String is a derived type.
---------------------------------


  • How string objects is spacial as compared to objects of other derived types?

                One special thing about string objects is that we can create string objects without using new operator i.e by using string literals.
                This is not possible with other derived types (except wrapper classes).
               One more special thing about strings is that you can concatenate two string objects using ‘+’. This is the relaxation java gives to string objects as they will be used most of the time while coding. And also java provides string constant pool to store the string objects.
---------------------------------


  • Why String is immutable or final in Java?

                 There are several benefits of String because it's immutable and final.

                 There are various reasons to make String immutable.

                 String pool
                 Thread Safe
                 Security
                 Class Loading
                 Cache hash value

              - String Pool is possible because String is immutable in java.
              - Since String is immutable, it's safe to use in multi-threading and we don't need any synchronization.
              - Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader.
              - It increases security because any hacker can't change its value and it's used for storing sensitive information such as database username, password etc.
---------------------------------


  • 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.
---------------------------------


  • Can we use String in switch case?

                 Java 7 extended the capability of switch case to use Strings also, earlier java versions doesn't support this.
---------------------------------


  • Where exactly string constant pool is located in the memory?

                  Inside the heap memory. JVM reserves some part of the heap memory to store string objects created using string literals.
---------------------------------


  • What is String Pool?

              String Pool is a pool of Strings stored in Java heap memory.
              We know that String is special class in java and we can create String object using new operator as well as providing values in double quotes.
---------------------------------


  • What is string constant pool?

               String objects are most used data objects in Java. Hence, java has a special arrangement to store the string objects.
               String Constant Pool is one such arrangement. String Constant Pool is the memory space in heap memory specially allocated to store the string objects created using string literals. In String Constant Pool, there will be no two string objects having the same content.

               Whenever you create a string object using string literal, JVM first checks the content of the object to be created.
               If there exist an object in the string constant pool with the same content, then it returns the reference of that object.
              It doesn’t create a new object. If the content is different from the existing objects then only it creates new object.
---------------------------------


  • Does String is thread-safe in Java?

                Strings are immutable, so we can't change it's value in program. Hence it's thread-safe and can be safely used in multi-threaded environment.
---------------------------------


  • What is string intern?

               String object in the string constant pool is called as String Intern.
               You can create an exact copy of heap memory string object in string constant pool.
               This process of creating an exact copy of heap memory string object in the string constant pool is called interning. intern() method is used for interning.
---------------------------------


  • 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.
---------------------------------


  • Which class will you recommend among String, StringBuffer and StringBuilder classes if I want mutable and thread safe objects?

                  StringBuffer (it is thread safe & mutable)
                         because
                  String - immutable
                  String builder - mutable but not thread safe
---------------------------------


  • What do you mean by mutable and immutable objects?

               Immutable objects are like constants. You can’t modify them once they are created. They are final in nature.

               Where as mutable objects are concerned, you can perform modifications to them.
---------------------------------


  • How StringBuffer And StringBuilder Differ From String Class?

                String objects created using java.lang.String class are immutable. Once they are created, they can not be modified.
                If you try to modify them, a new string object will be created with modified content. This property of String class may cause some memory issues for applications which need frequent modification of string objects.
                To overcome this behavior of String class, two more classes are introduced in Java to represent the strings. They are StringBuffer and StringBuilder. Both these classes are also members of  java.lang package same as String class.
---------------------------------


  • How do you create mutable string objects?

                By using StringBuffer and StringBuilder classes. These classes provide mutable string objects.
---------------------------------


  • How to check if two Strings are anagram in java?

               Anagrams means if two String have same characters but in different order. For example: Angel and Angel are anagrams
              There are many ways to check if Strings are anagrams. Some of them are:

               Using String methods
               Using array.sort
---------------------------------


  • How to calculate String memory usage

                For reasons we'll explore below, the minimum memory usage of a Java String (in the Hotspot Java 6 VM) is generally as follows:

                Minimum String memory usage (bytes) = 8 * (int) ((((no chars) * 2) + 45) / 8)
                          Or, another way:

               multiply the number of characters of the String by two;
               add 38;
               if the result is not a multiple of 8, round up to the next multiple of 8;
               the result is generally the minimum number of bytes taken up on the heap by the String.
---------------------------------


  • What is the purpose of toString() method in java ?

               The toString() method returns the string representation of any object.
               If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc.
depends on your implementation.
---------------------------------


  • How to split a string with white space characters?

                We can simple do split using regular expression. "\s" stands for white space characters such as " ", "\t", "\r", "\n".

                 String[] strArray = aString.split("\\s+");
---------------------------------


  • How to check if String has all unique characters in java?

                There are multiple ways to find if String has all unique characters or not.

                          Using HashSet
                          Using indexOf and lastIndexOf methods of String
                          By Using ascii value of characters.
---------------------------------


  • What substring() method does?

                In JDK 6, the substring() method gives a window to an array of chars which represents the existing String, but do not create a new one. To create a new array to back string, you can do add an empty string like the following:

                str.substring(m, n) + ""
               This will create a new char array that represents the new string. The above approach sometimes can make your code faster, because Garbage Collector can collect the unused large string and keep only the sub string.

               In JDK 7, substring() creates a new char array, not uses the existing one.


No comments:

Post a Comment

Home

Mastering Java Interview Questions: Your Comprehensive Guide         If you're preparing for a Java interview or just lookin...