Core Java

Java String Programs – Programming Examples for Interviews (2021)

A quick guide to java string based interview programming questions and examples.

1. Overview

In this article, We will see what are the String programs frequently asked in the java interviews.

All may be asked in the face to face or telephonic technical rounds. Every java programmer must know all of these questions.

Some of these will be tricky but easy if you understand clearly.

2. Java String Programs

Next, Look at the java string based programs with example codes.

2.1 How to split the string with a delimiter

01
02
03
04
05
06
07
08
09
10
11
12
public class StringSplitExample1 {
 
    public static void main(String[] args) {
        String str = "java@program@to.com";
 
        String[] splitArray = str.split("@");
 
        for(String value : splitArray){
            System.out.println(value);
        }
    }
}

Full Article on String Splitting

2.2 How to get codepoints for a String?

1
2
3
4
5
6
7
String str = "Code Points as Stream";
System.out.println("Input string value : "+str);
 
IntStream intStream = str.codePoints();
System.out.println("Printing each char from string as ASCII value");
 
intStream.forEach(value -> System.out.print(value+" "));

Output:

1
2
3
Input string value : Code Points as Stream
Printing each char from string as ASCII value
67 111 100 101 32 80 111 105 110 116 115 32 97 115 32 83 116 114 101 97 109

2.3 How to remove the Zero’s from String?

1
2
3
4
5
6
String str = "Digit ZERO 0 is not considered in input name. So removing all Zero's 00000000";
IntStream intStream = str.codePoints();
 
String zeroRemovedString = intStream.filter(ch -> ch != 48)
         .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
         .toString();

Output:

1
Digit ZERO  is not considered in input name. So removing all Zero's

Full Article on String codepoints()

2.4 How to check the string is palindrome or not?

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
public class StringPalindromeAppend {
 
    public static void main(String[] args) {
         
        String input1 = "civic";
         
        StringBuffer buffer = new StringBuffer();
 
        for (int i = input1.length() - 1; i >= 0; i--) {
            buffer.append(input.charAt(i));
        }
         
        String reversedString1 = buffer.toString();
 
        if (input1.equals(reversedString1)) {
            System.out.println(input1 + " is a palindrome");
        } else {
            System.out.println(input1 + " is not a palindrome");
        }
 
    }
}

Full article on String Palindrome checking in different ways

2.5 How to check the String Palindrome recursively ?

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
public static boolean isPalindrome(String s) {
 
    // if the string has one or zero characters then recursive call is stopped.
    if (s.length() == 0 || s.length() == 1)
        return true;
 
    // checking the first and last character of the string. if equals then call the
    // same function with substring from index 1 to length -1. Because substring
    // excludes the endIndex.
    // if these two values are not same then string is not Palindrome so this
    // returns false.
    if (s.charAt(0) == s.charAt(s.length() - 1))
        return isPalindrome(s.substring(1, s.length() - 1));
 
    // this statment is executed if and if only first and last character of string
    // at any time is not equal.
    return false;
}

Full explanation on String Palindrome Using recursion

2.6 How to count vowels and consonants for String ?

01
02
03
04
05
06
07
08
09
10
11
12
String input = "This is using Collectors api methods !!!!";
 
List<Character> vowels = new ArrayList<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
input = input.toLowerCase();
 
IntStream stream = input.chars();
 
Map<Boolean, Long> finalResultMap = stream.mapToObj(ch -> (char) ch).filter(ch -> (ch >= 'a' && ch <= 'z'))
        .collect(Collectors.partitioningBy(ch -> vowels.contains(ch), Collectors.counting()));
 
System.out.println("Total count of vowels : " + finalResultMap.get(new Boolean(true)));
System.out.println("Total count of consonants : " + finalResultMap.get(new Boolean(false)));

Output:

1
2
Total count of vowels : 11
Total count of consonants : 20

Java 8 Examples to get the count and consonants from String with explanation

2.7 How to compare different String objects with != operator ?

1
2
3
4
5
6
7
String status = new String("Failure");
 
if (status.intern() != "Failure") {
    System.out.println("Valid age");
} else {
    System.out.println("Invalid age");
}

Use intern() method to get the original string from String constant pool for string contents comparision with != operator.

Understand != operator with Strings

2.8 How to find the first non repeated character from String ?

01
02
03
04
05
06
07
08
09
10
public static String firstNonRepeatedCharacterJava8(String input) {
 
  Map chars = input.codePoints().mapToObj(cp -> cp)
    .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
 
  int pos = chars.entrySet().stream().filter(e -> e.getValue() == 1L).findFirst().map(Map.Entry::getKey)
    .orElse(Integer.valueOf(Character.MIN_VALUE));
 
  return String.valueOf(Character.toChars(pos));
 }

Full Article in different ways (Java 8)

2.9 How to convert String to Date in java 8?

1
2
3
4
5
6
7
String isoDateInString = "May 30, 2020";
 
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern("MMM d, yyyy");
 
LocalDate date = LocalDate.parse(isoDateInString, customFormatter);
 
System.out.println("Locale Date : "+date); // 2020-05-30

Examples on String to Date in different ways

2.10 How to convert String to Int ?

Conversion from String to integer can be done using following techniques.

  • Integer.parseInt()
  • Integer.valueOf()
  • Integer Constructor
  • DecimalFormat

Read full article on String to int

2.11 How to check String contains only digits ?

1
2
3
4
5
6
7
8
public boolean checkStringOnlyDigitsIsDigit(String input) {
 
 IntStream intStream = input.chars();
 boolean isMatched = intStream.anyMatch(ch -> Character.isDigit(ch));
 
 return isMatched;
 
}

Full article

2.12 How to reverse the words in String?

01
02
03
04
05
06
07
08
09
10
11
12
13
public String reverseWordsWithStringBuilder(String input) {
 
  // step 1: converting input string into stream.
  Stream-<String-> stream = pattern.splitAsStream(input);
 
  // step 2: reversing each word.
  Stream->StringBuilder-> intermeidateOutput = stream.map(word -> new StringBuilder(word).reverse());
 
  // step 3: merging all reversed words with empty space " "
  String reversedInput = intermeidateOutput.collect(Collectors.joining(" "));
 
  return reversedInput;
 }

Full article

3. Conclusion

In this article, we have seen the most used java string programs with examples. All questions are already explained in different ways in the previous article.

Published on Java Code Geeks with permission by Venkatesh Nukala, partner at our JCG program. See the original article here: Java String Programs – Programming Examples for Interviews (2021)

Opinions expressed by Java Code Geeks contributors are their own.

Venkatesh Nukala

Venkatesh Nukala is a Software Engineer working for Online Payments Industry Leading company. In my free time, I would love to spend time with family and write articles on technical blogs. More on JavaProgramTo.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button