×

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

Scanner in Java

Static way of Programming: When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a...

4 minutes read.

Java 16

Java 16 is the most recent short-term incremental release, based on Java 15, and it was released on March 16, 2021. Records and sealed classes are just two of the...

11 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Java Trim

Leading and leaving spaces are removed by the built-in Java String trim() method. Space seems to have the Unicode element of "x0040." Java trim() function looks for all of these...

3 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface). Because it compares the instance with type, the...

3 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

Java Continue Keyword

The java keyword ‘continues’ has also been called as java continue statement.The main concepts of the java continue statement or keyword is used in the controlling of the loop structure.Java...

3 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Deadlock Prevention and avoidance in Java

This tutorial will discuss deadlock prevention and Avoidance in Java programming language. Introduction Multithreading in Java includes deadlock. We can multitask by running several threads concurrently in the multithreading environment. Deadlock occurs...

4 minutes read.

Java Math addExact() Method

The addExact() method of Math class returns the sum of the two arguments, throwing an exception if the result overflows a long or an int. Syntax public static int addExact (int x,...

1 minute read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.