Java Tutorial Index

Java Tutorial Java Features C++ vs Java Java History Java Hello World Java Development Kit Java Runtime Environment Java Virtual Machine Difference between JDK, JRE, and JVM Memory Areas in Java Java Operators Java Keywords Primitive Data Types Variables

Java Loops

Java Do While Loop Java While Loop Java For Loop Java Enhanced For Loop

Java Programs

Java Basic Programs Factorial Program in Java Fibonacci Series Program in Java Prime Number Program in Java Palindrome Number Program in Java Armstrong Number Program in Java Anagram Program in Java Pattern Programs in Java Calculator Program in Java Leap Year Program in Java Addition Program in Java Number Pattern Programs in Java Star Pattern Programs in Java Package Program in Java Pyramid Program in Java Sorting Program in Java String Palindrome Program in Java Even Odd Program in Java For Loop Program in Java If Else Program in Java Switch Case Program in Java GCD Program in Java LCM Program in Java Hello Program in Java Matrix Program in Java Menu Driven Program in Java Series Program in Java Client Server Program in Java Swapping Program in Java Pig Latin Program in Java Tower of Hanoi Program in Java Recursion Program in Java Matrix Multiplication Program in Java Perfect Number Program in Java Classes and Objects in Java Example Programs String Programs in Java Array Programs in Java Constructor Program in Java Inheritance Program in Java Abstract class Program in Java Interface Program in Java Encapsulation Program in Java Polymorphism Program in Java Exception Handling Program in Java Multithreading Program in Java Thread Program in Java Collection Programs in Java ArrayList Program in Java Stack Program in Java Applet Program in Java Swing Program in Java JDBC Program in Java How to run Java program in command prompt How to run Java program in Eclipse Program to find and replace characters on string in java Program to find the duplicate characters in a string Program to check whether a given character is present in a string or not Java Program to Print Permutations of String Java program to find frequency of characters in a string Java Program to remove duplicate characters in a string

Java Sorting

Sorting Algorithms in Java Merge Sort in Java Quick Sort in Java Bubble Sort in Java Insertion Sort in Java Selection Sort in Java Heap Sort in Java Radix Sort in Java Topological Sort in Java Bucket Sort in Java Counting Sort in Java

Java OOPs Concepts

OOPs - Object Oriented Programming Objects and Classes in Java Methods in Java Java Naming Conventions Constructors in Java Java this keyword Java static keyword Inheritance in Java Aggregation in Java Java super keyword Constructor Chaining and Constructor Overloading Java Polymorphism Static and Dynamic Binding in Java Java Abstraction Abstract class in Java Interface in Java Difference between Abstract class and Interface Java final keyword Packages in Java Access Modifiers in Java Java Wrapper classes Java Numbers Java Characters Java Integer Java Boolean Java Arrays Java Command Line Arguments Java strictfp Keyword Java Math

Java Strings

Java Strings Java String Methods StringBuilder in Java StringBuffer in Java Java Regular Expressions StringBuffer vs StringBuilder String vs StringBuffer String vs StringBuilder String Manipulation in Java Java String Concatenation How to Reverse a String in Java String Array in Java How to Compare Two Strings in Java How to Concatenate Two Strings in Java Why String in Immutable in Java java.lang.NumberFormatException for Input String String Pool in Java Java Generate Random String How to take String Input in Java Java String Interview Questions

Java Exceptions

Exception Handling in Java Java try catch Java throw Java throws Difference between throw and throws Java finally Java Custom Exception Java Exception Propagation

Garbage Collection

Automatic Resource Management in Java Java Garbage Collection Java finalize() Java gc() Difference between final, finally and finalize

Multithreading

Multithreading in Java Process and Thread in Java Basic Terms in Multithreading Java Thread creation Thread Scheduler in Java Java Thread class DeadLock in Java

Java IO

Java IO Java Read File Java file Reader Java Buffer Reader Java file Writer Java BufferedWriter Java InputStreamReader Scanner in Java Java StringReader Java StringReader Class Java StringWriter Class Java PrintWriter Java File Java Read File Line By Line Java FileInputStream Java FileOutputStream Java Create File Java Delete File Java Open File Java Read File to String Java copy file Jar File in Java Java FileNotFoundException

Serialization

Java Serialization Java transient

Networking

Java Network Programming Java Socket Programming Java URL Java URLConnection HttpURLConnection in Java Java InetAddress Java DatagramSocket and Java DatagramPacket

AWT

Java AWT

Swing

Swing in Java

Java Collections

Collections in Java Java List Interface ArrayList in Java LinkedList in Java Vector in Java Stack in Java ArrayList vs LinkedList in Java ArrayList vs Vector in Java Java Set Interface HashSet in Java LinkedHashSet in Java TreeSet in Java Java Queue Interface PriorityQueue in Java Deque in Java ArrayDeque in Java Java Map Interface HashMap in Java LinkedHashMap in Java TreeMap in Java Dictionary in Java Hashtable in Java Properties in Java Collections class in Java Java Comparable Java Comparator Comparable vs Comparator in Java

Java Generics

Generics in Java

Java Annotations

Annotations in Java

Java JDBC

Java JDBC Tutorial JDBC Architecture Types of JDBC Drivers JDBC vs ODBC Java Database Connectivity with MySQL Java Database Connectivity with Oracle Statements in java Prepared statement in Java Resultset in java Java ResultSetMetaData DatabaseMetaData in Java Callable Statement in Java Transaction Management in Java Design of JDBC

Java Differences

Java vs DotNET Java vs JavaScript Python vs Java Kotlin vs Java Java vs C++ C# vs Java Java float vs double Java vs Scala Java vs Go Java vs Golang Java Extends vs Implements Java vs Node.js Static vs Non-static in Java C vs Java int vs Integer in Java Java protected vs private Java vs Dot Net Stack vs Heap in Java Java Array vs ArrayList Java SE vs EE Class vs Object in Java Java vs Bedrock Difference between = = and equals ( ) in java Difference between C, C++, java HashMap Vs HashTable Checked vs Unchecked Exceptions in Java Difference between print() and println() in Java Differences between Lock and Monitor in Java Concurrency Differences between Set and List in Java How to calculate time difference in Java Char and String differences in Java Difference between String, StringBuffer and StringBuilder in java Difference between String and Char Array in Java Differences between Byte Code and Machine Code Difference between String Tokenizer and split Method in Java Difference between JIT and JVM in Java Difference Between Data Hiding and Abstraction in Java Difference between String Tokenizer and Split Method in Java Difference Between BufferedReader and FileReader Difference Between Thread.start() and Thread.run()

How to

How to convert String to String array in Java How to find length of integer in Java How to get Day Name from Date in Java How to open the Java control panel How to resolve Illegal state exceptions in Java How to reverse a linked list in java How to encrypt password in Java How to calculate time complexity of any program in Java How to check version of java in Linux How to enable java in chrome How to run Java program How to set path in Java How to check the Java version in cmd How to install Java in Windows 10 How to run Java program in cmd How to add double quotes in a string in Java How to convert list to String in Java How to call a method in Java How to Set Environment Variables for Java How to sort an array in Java How to Create Immutable Classes in Java How to iterate HashMap in Java How to write Java program How to create an array in Java How to create a package in Java How to generate random numbers in Java How to input String in Java How to Create Singleton Class in Java How to create thread in Java How to find length of String in Java How to sort a string in Java How to use scanner in Java How to achieve multiple inheritance in Java How to find the length of an Array in Java How to Read Java JSON file How to run Java program in Eclipse How to call a function in Java How to create array of objects in Java How to create custom exception in Java How to import packages in Java How to run applet Program in Java How to take Array Input in Java How to achieve abstraction in Java How to call static method in Java How to compare characters in Java How to compare dates in Java How to create a linked list in Java How to download Eclipse for Java How to get ASCII value of char in Java How to get the current date and time in Java How to handle NullPointerException in Java How to initialize string array in Java How to Install Java on MAC How to run java program in ubuntu How to find characters with the maximum number of times in a string java How to Set Java_home in Linux How to Split the String in Java with Delimiter How to take Multiple String Input in Java using Scanner class How to uninstall the Java in Ubuntu How to Update Java How to add Elements in Array in Java How to avoid deadlock in java How to Split String by Comma in Java How to remove special characters from String in Java How to remove last character from String in Java How to Read XML Files in Java How to download and install Eclipse in Windows How to Create an API in Java How to Round Double Float up to Two Decimal Places in Java How to create a mirror image of a 2D array in Java How to set timer in Java

Java 8 Features

Java 8 Features Lambda Expressions in Java Functional Interface in Java Streams in Java Java Base64 Encoding and Decoding Type Annotations in Java Java Stringjoiner Class Parallel Arrays Sort in Java Bifunction in java 8 Java 8 filters list Java 8 Consumer Interface in Java

Java 9 Features

Java 9 Tutorial Java 9 Try With Resources Java 9 Interface Private Method

Java 12

What’s new in Java 12

Java 13

Java 13 New Features

Java 14

New Features of Java 14

Java 15

What’s New in Java 15

Java 16

Java 16

Java 17

What is new in Java 17

Java Servlet Tutorial

Java Servlets Tutorial

Java JSP Tutorial

Java JSP Tutorial

Hiberate Tutorial

Hibernate Tutorial

Spring Tutorial

Spring Tutorial

Spring MVC Tutorial

Spring MVC Tutorial

Jenkins Tutorial

Jenkins Tutorial Jenkins java net socket connection time out

Java Math Methods

Math.abs() Math.acos() Math.addExact() Math.asin() Math.atan () Math.atan2() Math.cbrt() Math.ceil() Math.copysign() Math.cos() Math.cosh() Math.decrementExact() Math.exp() Math.expm1() Math.floor() Math.floorDiv() Math.floorMod() Math.fma() Math.getExponent() Math.hypot() Math.IEEEremainder() Math.incrementExact() Math.log() Math.log10() Math.log1p() Math.max() Math.min() Math.multiplyExact() Math.multiplyFull() Math.negateExact() Math.nextAfter() Math.nextDown() Math.nextUp() Math.pow() Math.random() Math.rint() Math.round() Math.scalb() Math.signum() Math.sin() Math.sinh() Math.sqrt() Math.subtractExact() Math.tan() Math.tanh() Math.toDegrees() Math.toIntExact() Math.toRadians() Math.ulp()

Java String Methods

toCharArray() copyValueOf() endsWith() equals() equalsIgnoreCase() format() getBytes() getChars() hashCode() indexOf() intern() isEmpty() join() lastIndexOf() length() replace() replaceAll() replaceFirst() split() startsWith() subSequence() substring() toLowerCase() toUpperCase() trim() valueOf()

Java Conversion

Java Convert String to int Java Convert int to String Java Convert String to long Java Convert long to String Java Convert String to float Java Convert float to String Java Convert String to double Java Convert double to String Java Convert String to Date Java Convert Date to String Java Convert String to Object Java Convert Object to String Java Convert String to char Java Convert char to String Java Convert int to long Java Convert long to int

Misc

List all files in a Directory in Java Nonagonal number in Java Null Pointer Exception in Java Package naming convention in Java Packages Program in java Pangram Program in Java PriorityBlockingQueue Class in Java Race Condition in Java Repdigit Numbers in Java Reserved Keywords in Java Rotate matrix by 90 degrees in Java Segment Tree in Java Sierpinski Number in Java Sort Dates in Java Thread Safety and How to Achieve it in Java Normal and Trace of a Matrix in Java Transient variable in Java Tribonacci series in Java Web Crawler in Java Zigzag Traversal of Binary Tree in Java Java Full Stack Java IO filenotfoundexception Java Output Formatting Java Plot Java Pop Java program to print matrix in Z form Java Set to List Java Switch string Java Thread Lifecycle: States and Stages Java Viva Questions and Answers Lazy Propagation in Segment Tree in Java Level order Traversal of a Binary Tree in Java Method chaining in Java Narcissistic Number in Java Java Case Keyword Java Try-Catch Block Java Class KeywordJava concurrency interview questions Java Continue Keyword Java CountDownLatch Java Default Keyword Java Double Keyword Java Editors Java Else Keyword Java Enum Keyword Java Extends keywordJava Finally Keyword Java Font Example of Static import in Java How Many Ways to Create Objects in Java Implementing Queue Using Array in Java Instanceof operator in Java Interchange Diagonal elements in Java Java Arrays Fill Java Char Keyword Convert list to array Java Convert milliseconds to date in Java Copy data/content from one file to another in java CRC Program in Java Creating a Jar file in Java Crown Pattern in Java Difference Between Access Specifiers and Modifiers in Java Difference Between Java and PHP Difference Between replace() and replaceall() in Java Duodecimal in Java Finding middle node of a linked list in Java Group by in Java 8 Hollow Diamond Pattern in Java How annotations work in Java Java Boyer Moore Catalan number in Java Cosmic Superclass in Java Difference between this and super in Java Fall through in Java Figurate Number in Java Java Anon Proxy Java RMI Lazy loading in Java Magnanimous Number in java Shallow copy in Java String to JSON in Java Tetranacci Number in Java Vigesimal in Java Why main method is static in Java Add Time in Java Bellman Ford Algorithm in Java Best Java Libraries Blockchain in Java Blocking Queue in Java Example Bully Algorithm code in Java Contextual keywords in Java Convert JSON File to String in Java Determine the Upper Bound of a Two-Dimensional Array in Java Java.net.ConnectionException Java.net.SocketException Web Service Response Time Calculation in Java Functional Interfaces in Java Singleton class in Java Awesome explanation of Strings in Java Object class in Java Static class in Java All the important string methods in Java String Handling Method in Java What are Array strings in Java Advantages and Disadvantages of Strings in Java Big Decimal class in Java Class definition in Java Replace character in string Java String Coding Interview Questions in Java What is String in Java? String isnullorempty in Java String Matches in Java Trim Method in String Java Bean class in Java Libraries in Java Arithmetic Operations on String in Java Convert Char array to string in java Check whether Java is installed or not How to stop execution after a certain time in Java Jagged Array in Java Java ArraylistRemove() Time Complexity Java Swing Time Picker Zigzag Array in Java Array and String based questions in Java Array and String with Examples in Java Best Practices to use String Class in Java What is string in Java why it's immutable Java String Java String Inbuilt functions Java String Matches vs Contains Sum of digits in string in java Check the presence of Substring in a String in java Java import packages Interfaces and Classes in Strings in Java Maximum length of string in java Hidden classes in Java Class memory in Java public static void main string args meaning in java Reverse a String in Java String Concatenation in Java Buffer reader to read string in Java Split String into String Array in Java Reverse a String using Collections in Java Upcasting and Downcasting in Java String Declaration in Java Method Overloading In Java Java Solid Principles Java Architecture Binary Search Java Star Program in Java Java Type Casting Java Pass-by-Reference Java Framework List Java Destructors Java Control Statements Java Byte Code Java Beans Java Identifiers Character Array in Java Java Applications Java Substring Java Session Non-primitive data types in Java Matrix Multiplication in Java JIT in Java Java Tokens Java Externalization Default Virtual Behaviour in C++ vs Java Why we use static in Java Session Tracking in Java Knapsack problem in Java Java Logo Java exception list Java Iterator Java instance variable Frugal number in Java Fork Join in Java Date time API in java Compile time vs Runtime in java Compare time in java AES 256 Encryption in Java Advanced Java skills What is advance Java? User Defined Exception in Java Upcasting in Java Tree Implementation in Java Special Operators in Java Reentrant Lock in Java Perfect Number in Java Java logger Java LinkedList vs ArrayList File Operation in Java Constructor Overloading in Java Conditional operator in Java Concurrent Linked Deque in Java with Examples Command Class in Java Java Break Keyword Best Java IDE Association in Java Access specifiers in Java AbstractSet Class in Java Adapter class in Java Composition in Java Mutable and Immutable in Java Static() Function in Java Traverse through HashMap in Java Vectors in Java Creation of Multi Thread in java Java Enumeration Compile-time Error in Java Java Get Time in UTC Java.sql.Time Format Structure of Java Program Thread Concept in Java Creation of Multi-Thread in Java Enterprise Java Beans POJO in Java Volatile keyword in Java Java Constant Collection Interfaces in Java with Examples Deadlock Prevention and avoidance in Java Java Boolean Keyword Java Byte Keyword Java List Implementations Java Xml Parser Method Overriding in Java RMI program in Java Virtual Function in Java What is interpreter in Java? Advanced Java Viva Questions Application of Array in Java Economical number in Java Iterate JSON array in Java Java callable example Java Command not found Java Date add Days Java File Extension Java Location Java Trim User Defined Custom Exceptions in Java Java array list remove time complexity Java.lang.Exception.NoRunnableMethods Java Map Example Java Obfuscator Java Pi Java Queue Java time local date Java Xmx Uses of Java Applet Life Cycle in Java Best Java Security Framework BigDecimal toString() in Java Jdoodle Java Literals in Java MVC in Java Powerful Number in Java Read the XLSX file in Java Relatively Prime in Java Root exception in java What is anagram in Java? Accessors and Mutator in Java Bottom view of a binary tree in Java Convert List to String in Java Equidigital in Java How to check data type in Java IdentityHashMap in Java Java Clone Array Java LDAP Authentication Java List Node Java Password Generator Magic Square in Java Pancake Sorting in Java Practical Number in Java Sublime Number in Java Sudoku in Java Compare Two Times in Java Diffie Hellman Algorithm in Java How to Reduce Time Complexity in Java Java calculate age Map of Map in Java Minimum XOR value pair in Java Palindrome Partitioning problem in Java Pernicious Number in Java Prime Points in Java Rectangular Numbers in Java Sleep Time in Java The final Keyword in Java Types of Statements in Java Unicode System in Java Zig Zag star and Number Pattern in Java Balanced Prime Number in Java ConcurrentSkipListSet in Java Construct the Largest Number from the Given Array in Java CopyOnWriteArrayList in Java Cyclic Barrier in Java Dangling Else problem in Java Display Unique Rows in a Binary Matrix in Java Empty Statement in Java Factorial of a Large Number in Java Facts about null in Java Rehashing in Java Singleton Design Pattern in Java Zebra Puzzle Problem in Java XOR of Array Elements Except Itself in Java Types of Sockets in Java Thread Synchronization in Java Set Up the Environment in Java Method and Block Synchronization in Java Fibodiv Number in Java House Numbers in Java GCD of Different SubSequences in Java Hogben Numbers in Java Decagonal Numbers in Java Converting Roman to Integer Numerals in java Check if the given array is mirror inverse in Java Caesar Cipher Program in Java Block Swap Algorithm for array rotation in Java Java Binary Tree Binary Strings Without Consecutive Ones in Java Beautiful Array in Java Balanced Parentheses in Java Arithmetic exception in Java Add numbers represented by Linked Lists in Java Two Decimal Places Java Intersection Point of two linked list in Java Find next greater number with same set of digits in Java Getter and Setter Method in Java Example Java Binary to Hexadecimal Java Calculate Average of List Iccanobif Numbers in Java Java delete directory Java For Keyword Java Float Keyword Java Instanceof Keyword Java If Keyword Java Int Keyword Java Import Keyword Java Package Keyword Java Static Keyword Java Public Keyword Java Implements Keyword Java Private keyword Java Protected Keyword Java Short Keyword Java Long Keyword Java Interface Keyword Java Try Keyword Java New Keyword Java Return Keyword Tug of War in Java Types of Events in Java

Java String Interview Questions

Java String Interview Questions

String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept.  So, we should not ignore this section as it is important. In this section, we are going to enlist some important asked in Java String interview questions.

1) What are the differences between C, C++ strings and Java strings?

In C or C++, strings are not treated as objects. The C or C++ strings are terminated with the null character. However, Java strings are never terminated with the null character. Strings in Java are also treated as objects.

2) How are the strings stored in the memory?

The strings are stored in heap memory. The exact region where the strings are stored depends on their creation. If the strings are created using the new keyword, the strings are stored outside the string pool. If the strings are created using the string literals, the strings are stored inside the string pool.

3) Which one should be preferred, == operator or the equals() method to make a comparison between two string objects?

The equals() method should be preferred over the == operator, as the == operator only compares the references of the string objects, whereas the equals() method compares the content of the string objects.

4) What is the need for StringBuffer and StringBuilder classes when we have already got the String class?

In Java, the String class is always immutable. Therefore, any kind of modification in the objects of the String class leads to the creation of new objects, which lead to performance issue, as the creation of new objects consumes memory as well as time. To avoid the performance issue, the StringBuffer and StringBuilder classes were introduced in Java. Note that StringBuffer and StringBuilder classes create mutable objects.

5) Where the String pool is located in the memory?

The String pool is a portion of memory that is located inside the heap memory. It is used to store string literals.

6) How the substring() method works internally in Java?

The working of the substring() method varies if one moves from the JDK – 6 to JDK – 7. There was a major issue with the substring() method of the JDK – 6 version. It was found that there was a memory leak issue with the substring() method when dealt with the strings of the larger size. As Java strings are an array of characters, the substring() method for JDK – 6, shared the same characters of that string upon which the method is invoked. Consider the following code snippet.

 String str = “Hello India”;
 // no new string object created
 String subStr = str.substring(0, 4); // Hell 

Here, for the variable subStr, no new string is created, and the characters ‘H’, ‘e’, ‘l’, ‘l’ are shared between str and subStr. Thus, one can say both subStr and Str are holding the reference of the string “Hello India”. Now consider the following scenario.

 String str = “Hello India”;
 String subStr = str.substring(0, 4); // Hell
 str = null; // object for Hello India is collected by garbage collector 

After doing str = null, the string object for “Hello India” is not eligible for the garbage collection as subStr is also holding the reference. This leads to a memory leak if the string is of a larger size. For example, if a string is comprising of thousand characters and the substring is sharing only three characters, then the string object of the thousand characters cannot be deleted, as its three characters are shared. Thus, only for 3 characters, it is not correct to hold the memory of 1000 – 3 = 997 characters.

To resolve this issue, the working of the substring() method was modified in the JDK – 7.  In JDK – 7, the substring() method does not share the characters. Instead of sharing the characters, a new string is created.

7) Predict the output of the following program with the explanation.

 public class ABC
 {
 // main method
 public static void main(String argvs[])
 {
     int j = 7;
     // \u000d j = 9;
     System.out.println("The value is : " + j);
 }
 } 

Output:

The value is : 9

Explanation: At first glance, it seems that the value of j should be 7. However, the value is 9. The reason for the value 9 is the Java compiler. The compiler first parses the Unicode present in the code. Therefore, before any lexical translation \u000d is evaluated. The Unicode moves the following code in the next line. Thus, // \u000d j = 9; gets converted into the following.

 //
 j = 9; 

Now, when the lexical translation happens, the value of j gets updated to 9.          

8) How many ways are there to create String objects?

There are three ways to create String objects.

1) By using a string literal.

String str = “Hello World”;

2) By passing string in the constructor of the String class.

String str = new String(“Hello Constructor”);

3)  Using character array

 Character arr[] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’};
 String str = new String(arr); // Hello World string is generated 

9) Is it valid to use string literals in the Switch case?

It depends on the JDK version. From JDK 7, it is valid to use string literals in the Switch case. Before JDK 7, it was not possible to use a string literal in the Switch case.

10) Name the character encoding used in Java 9.

In Java 9, the UTF-8 character encoding is used by default. When JVM starts, System.getProperty(“file.encoding”, “UTF - 8”); gets called. UTF-8 is used as default when the file.encoding attribute is absent. However, this encoding can be changed by the programmer.

11) Why a Java programmer gives priority to the char[] instead of a string while storing a password?

The password of any user is a piece of very sensitive information. Therefore, security is the main concern while storing the password. As String is immutable in Java, therefore when string is used for storing the password, the password remains in the String pool for a long time for serving the purpose of reusability. Thus, there are high chances that it will remain in the memory for a longer period of time, which may lead to a security threat. Also, one cannot change the content of string as it will lead to the creation of a new string.

Using the char[] array, one can explicitly wipe the password content after the validation is complete. In other words, one can manipulate the char[] array data, but not the data present in a string, as strings are immutable in Java.

12) What is StringJoiner in Java?

The java.util package provides the StringJoiner class that is used to generate a sequence of characters or strings. The generated strings are separated by a delimiter. The StringJoiner class also provides the facility to add prefix and suffix to the string. Whatever we can achieve using the StringJoiner class can be achieved using the StringBuilder class using the append() method. However, the StringJoiner class makes the code less verbose. The StringJoiner class is introduced in Java 8 and is a final class.

13) Explain the concept of String intern.

The intern() method ensures that only one copy of a string value is present in the string pool. Therefore, the intern() method puts the string in the string pool. By default, the string literals are created in the string pool as they use the intern() method implicitly. However, to put strings created using the new keyword in the string pool, we have to use the intern() method explicitly.

 String st1 = new String("Tutorial & Example");  // outside the string pool
 String st2 = new String("Tutorial & Example").intern(); // in the string pool
 String st3 = "Tutorial & Example"; // always in string pool 

The intern() method returns the canonical representation of the string. When the intern() method is executed, a check is performed whether the string object is already present in the string pool or not. If it is present, its reference is returned; otherwise, a new string object is generated in the string pool.

14) Why key in a Java HashMap is usually a string?

String is usually used as a key in a Java HashMap because strings are immutable in Java. Thus, when the key of a Java HashMap is hashed, its value never changes in the case of a string, as the manipulation of string leads to the generation of a new string. Therefore, the hashed value can be cached to make the performance of the program better.

15) Explain the string subSequence() method.

The CharSequence interface declares the subSequence() method. As the String class implements the CharSequence interface, it has to define the subSequence() method. The subSequence() method internally calls the subString() method and returns a CharSequence.

16) Why is String final or immutable in Java?

Following are some of the reasons for the String to be final or immutable in Java:

  • String literals are always stored in the String pool. Therefore, the String class has to be immutable. Without immutability, the String pool cannot exist.
  • The Java classloader uses strings to load classes. The immutability of the strings ensures that the correct class is loaded.
  • String immutability provides safety when it is used in the multithreading environment. We do not need to worry about synchronization because of the immutability.

17) Is autoboxing or unboxing possible in Java strings? Why?

No, autoboxing or unboxing is not possible in strings. Autoboxing and unboxing are the features of the wrapper classes. Java recognizes Boolean, Byte, Character, Float, Integer, Long, Short, and Double classes as the wrapper class. Therefore, neither autoboxing nor unboxing is possible in Java strings.

18) String objects are unique from the other objects of the derived types in Java. Why?

The creation of objects in the other derived classes is only possible using the new keyword (barring the wrapper classes). However, the String objects can be created without using the new keyword. One more unique feature about the String objects is that one can concatenate two String objects using the + operator. Such relaxation is not provided to the other derived class.

19) Explain the format() method of the Java String class. How is it different from the printf() method?

The format() method of the Java String class is used to format the string. The printf() method also formats the string. The main difference between the printf() method and the format() method is that the printf() method prints the formatted string, and the format() method returns the formatted string.

20) Observe the following statements and decide which one is better.

 // statement - 1
 st1.equals("Tutorial & Example");  // where st1 is a string type variable
 // statement - 2
 "Tutorial & Example".equals(st1); // where st1 is a string type variable 

In the above two statements, the second statement should be preferred over the first statement. We know that Strings are considered as objects in Java. Therefore, if the st1 is not initialized with any value, then the st1 contains the null value. Thus, the st1.equals(“Tutorial & Example”); gets translated to null.equals(“Tutorial & Example”); which results in the generation of NullPointerException.

The second statement does not face any issue. In case st1 becomes null, “Tutorial & Example”.equals(st1); gets converted into “Tutorial & Example”.equals(null); which does not give an exception and results in the false value. Thus, unlike the first statement, the second statement is not prone to any error or exception.

21) Consider a scenario in which we want to perform multiple string concatenation and modification. In such a case, which class should we use that improves the performance of the code and the code must be thread-safe?

We have three prominent classes in the field of strings. The String class, StringBuilder class, and the StringBuffer class.

The String class cannot be used as it is immutable. Thus, string concatenation or modification leads to the generation of new strings, which hampers the performance of the program. Hence, the String class cannot be used.

The StringBuffer class is mutable. Hence, one can perform the string concatenation of modification easily, without the creation of any new objects. Thus, the performance is improved. However, the StringBuffer class does not facilitate thread safety. Hence, the StringBuffer class also cannot be used in the given scenario.

The StringBuilder class is mutable. Hence, any manipulation operation does not generate a new object. Thus, this class also improves performance. The StringBuilder class provides the thread-safe facility. Therefore, the StringBuilder class is the most appropriate class that should be used in this scenario.

22) Explain how many objects are created when the below-mentioned two statements are executed simultaneously?

 String st1  = new String("Tutorial & Example"); // statement - 1
 String st2 = "Tutorial & example"; // statement - 2 

It seems that only two objects are created: one for first statement, and another for second statement. However, the total number of objects created is three: two for first statement, and one for second statement. First, the object for the string literal "Tutorial & Example" is created in the string pool, then another object is created outside the string pool in the heap memory, as we have used a new keyword.

For the second statement, a string literal is used. Therefore, JVM (Java Virtual Machine) checks whether the literal is present in the string pool or not. It is found that the string literal is not present in the pool. It is because Java is a case-sensitive language, and example and Example words are treated differently. Hence, an object is created for the second statement also.

23) What is the fastest way to copy a String array?

The arraycopy( ) method can be used to copy quickly an array of any type from one place to another. It is much faster than the equivalent loop written out longhand in Java. Here is an example of two arrays being copied by the arraycopy( ) method. First, a is copied to b. Next, all of a’s elements are shifted down by one. Then, b is shifted up by one.

static byte a[] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };

static byte b[] = { 77, 77, 77, 77, 77, 77, 77, 77, 77, 77 };

24) Is there any difference between == operator and equals() method?

The == operator checks for equality of reference variables and returns true if both point to the same object in memory.

The equals() method is a method that compares two Strings based on their content and returns true if they're equal.

25) Are Strings thread-safe?

In Java, every immutable object is thread-safe. Hence, String is also thread-safe. Java provides the StringBuffer class that is thread-safe while the StringBuilder class is not thread-safe because it is mutable and does not use the synchronized keyword.

26) How to count the number of vowels present in a string using recursion?

FileName: StringVowels.java

 public class StringVowels
 {
 // Method to check for the vowels
 Boolean isVowel(char c)
 {
 // for small letters
 if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
 {
     return true;
 }
 // for capital letters
 if(c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U')
 {
     return true;
 }
 return false;
 }
 public int countVowels(String s1, int i, int size)
 {
 // handling base case
 if(i >= size)
 {
     return 0;
 }
 // getting character from the string
 char ch = s1.charAt(i);
 if(isVowel(ch))
 {
 // vowel found!
 // increment the count by 1 and recursively
 // check for the rest of the string
 return 1 + countVowels(s1, i + 1, size);
 }
 // vowel not found!
 // do not increment the count by 1 and recursively
 // check for the rest of the string
 return countVowels(s1, i + 1, size);
 } 
 // main method
 public static void main(String argvs[])
 {
     // instantiating the class StringVowels
     StringVowels svObj = new StringVowels();
     // input string
     String s1 = "Keep";
     // calculating the size of the input string
     int size = s1.length();
     // invoking the method countVowels()
     // storing the result
     int cntVowel = svObj.countVowels(s1, 0, size);
     // displaying the result
     System.out.println("String " + s1 + " has " + cntVowel + " vowels.");
     // another input string
     s1 = "Apple";
     size = s1.length();
     cntVowel = svObj.countVowels(s1, 0, size);
     System.out.println("String " + s1 + " has " + cntVowel + " vowels.");
 }
 } 

Output:

 String Keep has 2 vowels.
 String Apple has 2 vowels. 

27) How to count the number of words present in a string?

FileName: StringWords.java

 public class StringWords
 {
 // Method to count words of the string str
 public int countWords(String str)
 {
 // to store total
 // count of words
 int count = 0;
 // size of the string str
 int size = str.length();
 for(int i = 0; i < size; i++)
 {
     // current character
     char ch = str.charAt(i);
     if(i > 0)
     {
         // previous character
         char prv = str.charAt(i - 1);
         // if the previous character
         // is a blank space and the current 
         // character is not blank, a beginning of
         // new word is started.
         if(prv == ' ' && ch != ' ')
         {
             count = count + 1;
         }
     }
     if(i == 0)
     {
         // handling the scenario when there is no space on the 
         // left side of the first word of the string
         if(ch != ' ')
         {
             count = count + 1;
         }
     }
 }
 return count;
 }
 // main method
 public static void main(String argvs[])
 {
     // instantiating the class StringWords
     StringWords swObj = new StringWords();
     // input string
     String s1 = "New Delhi the captial city of the country India.";
     // invoking the method countWords()
     // storing the result
     int cntWords = swObj.countWords(s1);
     char ch = '"';
     // displaying the result
     System.out.println("The string " + ch + s1 + ch + " has " + cntWords + " words.");
     // another input string
     s1 = "   Hello   To Every One . ";
     cntWords = swObj.countWords(s1);
     System.out.println("The string " + ch + s1 + ch + " has " + cntWords + " words.");
 }
 } 

Output:

 The string "New Delhi the captial city of the country India." has 9 words.
 The string "   Hello   To Every One. " has 5 words. 

28) Write a program in Java to find the percentage of lowercase, uppercase, digits, and other characters from the given string.

FileName:  StringCharPercentage.java

 public class StringCharPercentage
 {
 // A method to find the percentage of uppercase letters
 public int upperCaseCount(String str)
 {
 // calculating size of the string
 int size = str.length();
 int count = 0;
 for(int i = 0; i < size; i++)
 {
     char c = str.charAt(i);
     if(Character.isUpperCase(c))
     {
         count = count + 1;
     }
 }
 return count;
 }
 // A method to find the percentage of lowercase letters
 public int lowerCaseCount(String str)
 {
 // calculating size of the string
 int size = str.length();
 int count = 0;
 for(int i = 0; i < size; i++)
 {
     char c = str.charAt(i);
     if(Character.isLowerCase(c))
     {
         count = count + 1;
     }
 }
 return count;
 }
 // A method to find the percentage of digits letters
 public int digitCount(String str)
 {
 // calculating size of the string
 int size = str.length();
 int count = 0;
 for(int i = 0; i < size; i++)
 {
     char c = str.charAt(i);
     if(Character.isDigit(c))
     {
         count = count + 1;
     }
 }
 return count;
 }
 // A method to find the percentage of digits letters
 public void findPercentage(String str)
 {
 // length of the string is the
 // total number of characters present
 // in the string
 int totalChars = str.length();
 // invoking upperCaseCount() method
 int countUpperCase = upperCaseCount(str);
 // invoking lowerCaseCount() method
 int countLowerCase = lowerCaseCount(str);
 // invoking digitCount() method
 int countDigit = digitCount(str);
 // other characters are all the characters that
 // are not uppercase or lowercase or digits
 int otherChars = totalChars -
                    (countUpperCase + countLowerCase + countDigit);
 // calculating percentanges for each type of letters
 double percentUpperCase = (countUpperCase * 100) / totalChars;
 double percentLowerCase = (countLowerCase * 100) / totalChars;
 double percentDigit = (countDigit * 100) / totalChars;
 double percentOtherChars = (otherChars * 100) / totalChars;
 char ch = '"';
 // displaying the results
 System.out.println("In the string " + ch + str + ch);
 System.out.println("Percentage of uppercase letters are: " + percentUpperCase);
 System.out.println("Percentage of lowercase letters are: " + percentLowerCase);
 System.out.println("Percentage of digits are: " + percentDigit);
 System.out.println("Percentage of other characters are: " + percentOtherChars);
 }
 // main method
 public static void main(String argvs[])
 {
 // input string  
 String s = "New Delhi is the capital city of the country India.";
 // creating an object of the class StringCharPercentage
 StringCharPercentage scObj = new StringCharPercentage();
 // invoking the method findPercentage()
 scObj.findPercentage(s);
 System.out.println(); // new line
 s = "My $$ Passion 00 is %^ to play Cricket.";
 scObj.findPercentage(s);
 }
 } 

Output:

 In the string "New Delhi is the capital city of the country India."
 Percentage of uppercase letters are: 5.0
 Percentage of lowercase letters are: 74.0
 Percentage of digits are: 0.0
 Percentage of other characters are: 19.0
 In the string "My $$ Passion 00 is %^ to play Cricket."
 Percentage of uppercase letters are: 7.0
 Percentage of lowercase letters are: 53.0
 Percentage of digits are: 5.0
 Percentage of other characters are: 33.0 

29) Write a program in Java to find the permutation of the given string.

Permutation of the string can be achieved by the technique of backtracking. The following program shows the same.

FileName: StringPermute.java

 public class StringPermute
 {
 // method for generate perumuatation of string str
 public void permute(char charArr[], int i, int size)
 {
 // handling base case
 if(i >= size)
 {
 // converting char array to str
 String str = String.valueOf(charArr);
 // printing the string
 System.out.println(str);
 return;
 }
 for(int j = i; j < size; j++)
 {
 // swap the characters
 char ch1 = charArr[i];
 charArr[i] = charArr[j];
 charArr[j] = ch1;
 // recursively find the permutation
 permute(charArr, i + 1, size);
 // swapping again to maintain the
 // previous order, which is called backtracking
 ch1 = charArr[i];
 charArr[i] = charArr[j];
 charArr[j] = ch1;
 }
 }
 // main method
 public static void main(String argvs[])
 {
 // input string
 String str = "abc";
 // calculating size of the input string
 int size = str.length();
 // converting the string into char array
 char chrArr[] = str.toCharArray();
 char ch = '"';
 System.out.println("Permutations of the string " + ch + str + ch + " are: \n ");
 // creating an object of the StringPermute class
 StringPermute spObj = new StringPermute();
 // invoking the method permute()
 spObj.permute(chrArr, 0, size);
 }
 } 

Output:

 Permutations of the string "abc" are:
 abc
 acb
 bac
 bca
 cba
 cab 

30) Write a program in Java to find the minimum number of characters that must be added at the beginning of the given string to make it a palindrome.

It is one of the tricky questions that is frequently asked in interviews. The approach is to find the largest palindromic substring by removing the characters, one by one, from the end. The number of characters deleted is our answer. Let’s observe the following program for a better understanding.

FileName: StringPalindrome.java

 public class StringPalindrome
 {
 // A method to check whether the string is a
 // palindrome or not
 public boolean isLargestPalindrome(String str)
 {
     int size = str.length();
     for (int j = 0, i = size - 1; j <= i; j++, i--)
     {
         if (str.charAt(j) != str.charAt(i))
         {
             return false;
         }
     }
     return true;
 }
 // main method
 public static void main(String[] args)
 {
     // input string
     String str = "BBBABABAA";
     // for storing the number
     // of characters that has been deleted
     int count = 0;
     // to indicate when the largest palindrome is found
     boolean flag = false;
     // calculating the size of the input string
     int size = str.length();
     // creating an object of the StringPalindrome class
     StringPalindrome spObj = new StringPalindrome();
     while (size > 0)
     {
         // invoking the method isLargestPalindrome()
         // and storing the result
         boolean isPalin = spObj.isLargestPalindrome(str);
         if (isPalin)
         {
             // largest palindrome string found!
             // no need to proceed further
             flag = true;
             break;
         }
         else
         {
             // control reaching here means
             // one more character has to be deleted
             // hence, count needs to be incremented by 1
             count = count + 1;
             // eliminate the last character of the string
             str = str.substring(0, size - 1);
             // updating the size
             size = str.length();
         }
     }
     // displaying the number of
     // characters to be inserted at
     // the front end
     if (flag)
     {
         System.out.print("The number of characters to be inserted"
                           + " to make the string palindrome are: " + count);
     }
 }
 } 

Output:

The number of characters to be inserted to make the string palindrome are: 6



ADVERTISEMENT
ADVERTISEMENT