×

String Coding Interview Questions in Java

  • What is String in Java?
    In Java, a String is a Class that is defined in the java.lang package. It isn't a basic data type like int or long. Character Strings are represented by the String class. A string is utilized in practically all Java programs, and there are a few fascinating facts about it that we should be aware of. In Java, String is immutable and final, and the JVM stores all String objects in a String Pool.
    Other interesting features of String include the ability to create a String object with double quotes and the overloading of the "+" operator for concatenation.
  • Define different ways to create String, with Syntax?

    The normal way to create a string in Java is to simply write:-

             String s = “Hello World”;

The compiler constructs a String object with the value "Hello world!" whenever it detects a string phrase in your code.

String objects cannot be made by using the new keyword and a function Object, just like any other object. The String class provides 11 constructors that allow you to set the string's initial value from a variety of sources, including an array of characters.

Another way to create a string is :-

String s = new String (“Hello World”);

String Buffer:-

StringBuffer is a String companion class that provides a lot of the same functionality as strings. StringBuffer shows growable and writable character sequences, whereas string shows fastened-length, unchangeable character sequences.

Syntax:

StringBuffer s = new StringBuffer("Hello World");

String Tokenizer:-

The StringTokenizer class in Java is used to tokenize a string.

String Joiner:-

String Joiner is a java.util package class that is used to build a sequence of characters divided by a delimiter and optionally starting with a transferred prefix and finishing with a transferred suffix.

Syntax:

public StringJoiner(CharSequence delimiter);

As we study in the above part, we have sufficient knowledge about replacing a character in string

So, there are three ways to replace character in a string:

 String Builder:

In contrast to the String Class, the StringBuilder class includes a built-in function for this — setCharAt (). By calling this function and giving the character and the index as parameters, you can replace the character at a given index.

Syntax:

StringBuilder str = new StringBuilder();

str.append("GFG");
  • Write a method to extract a specific character from a particular String?
    The replaceAll method can be used to replace all instances of a String with another String. The crucial thing to remember is that it takes a String as an argument, therefore we'll build a String with the Character class and use it to replace all of the characters with an empty String.

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


  • Write a specific method to determine if an input String is a Palindrome?
    When the value of a String is the same when it is reversed, it is said to be Palindrome. "aba" is an example of a Palindrome String.
    The String class does not have a reverse method, but the StringBuffer and StringBuilder classes have. We can utilize the reverse method to see if the String is a palindrome or not.
private static boolean isPalindrome(String str) {
        if (str == null)
            return false;
        StringBuilder strBuilder = new StringBuilder(str);
        strBuilder.reverse();
        return strBuilder.toString().equals(str);
    }
  • Define the String subsequence method?
    The only justification for the implementation of the subSequence function in the String class is that Java 1.4 introduced the CharSequence interface, which String implements. It uses the String substring function internally.
  • Define a way to convert a String to a byte array and vice versa?
    To convert a String to a byte array, we use the String getBytes() method, and to convert a byte array to a String, we use the String function Object() new String(byte[] arr).
  • How can we split String in java?
    Split(String regex) can be used to split a String into a String array based on a regular expression.
  • What do you mean by String Pool?
    String Pool is a Java stack memory pool of Strings, as the name implies. We know that String is a specific Java class and that we can use the new operator to construct String objects as well as provide data in double-quotes.
  • Program to find length of String?
public class EqualsSample{ 
         public static void main(String args[]){ 
 
                 String s1="helloworld "; 
                 String s2="hello";  
 
                 System.out.println(s1.length()); 
                 // 10 is the length of helloworld string
 
                 System.out.println(s2.length()); 
                 //5 is the length of hello string
          }
          }

Output:

10
5
  • Program to replace characters of String?
public class EqualsSample{ 
          public static void main(String args[]){ 
 
                   String s1="swap";
                   String s2 = replace(“w”,”n”); 
 
                   System.out.println(s2);
          }
}

Output:

Snap
  • Program to change string in Lowercase?
public class ToLowerCaseSample{ 
            public static void main(String args[]){ 
 
                  String s1="HELLO WORLD"; 
                  String s2 = s1.toLowerCase(s1);
 
                  System.out.println(s2);
            }
}

Output:

hello world
  • Program to change string in uppercase?
public class ToUpperCaseSample{ 
           public static void main(String args[]){ 
 
                  String s1="helloworld "; 
String s2 = s1.toUpperCase(s1);
 
                  System.out.println(s2);
           }
 }

Output:

HELLOWORLD
  • Program to trim the String?
public class TrimSample{ 
            public static void main(String args[]){ 
 
                  String s1="      My name is          ";  
 
                  System.out.println(s1 +”:Thomson”);
                  System.out.println(s1.trim() +”:Thomson”);
             }
}

Output:

      My name is          :Thomson
My name is Thomson
  • Program to split the String?
public class SplitSample{ 
             public static void main(String args[]){ 
 
                String s1="Hey I Am John"; 
                String [] s2 = s1.split(“\\s”); 
                //splits based on whitespace
 
                 for(String word: s2){
                          System.out.println(s2);
                 }
          }
}

Output:

Hey
I
Am
John
  • Program to compare two Strings?
public class CompareToSample{ 
           public static void main(String args[]){ 
           String s1="string "; 
           String s2="string"; 
           String s3="ring"; 
           String s4="swing"; 
 
           System.out.println(s1.compareTo(s2));
           //0 because both are equal 
 
           System.out.println(s1.compareTo(s3));
           //1 because "s" is 1 time greater than "r"
 
           System.out.println(s1.compareTo(s4)); 
           // -3 because "t" is 3 times lower than "w"
           }
 }

Output:

0
1
-3
  • Program to return the character value at a particular index?
public class CharAtSample{
           public static void main(String args[]){
                       String sample = “Hello World”;
                       char ch1 = sample.charAt(1);
                       System.out.println(ch1);
           }
}

Output:

E

Related Topics

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Difference between Constructor and Method in Java

What is Constructor? In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to...

13 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

How to download and install Eclipse in Windows?

Download and Install Eclipse on Windows Eclipse is an open source IDE (Integrated Development Environment) which is used to help the programmers to provide a platform to write and run the...

1 minute read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.