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
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); } } }
2.2 How to get codepoints for a String?
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:
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?
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:
Digit ZERO is not considered in input name. So removing all Zero's
2.4 How to check the string is palindrome or not?
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"); } } }
2.5 How to check the String Palindrome recursively ?
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; }
2.6 How to count vowels and consonants for String ?
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:
Total count of vowels : 11 Total count of consonants : 20
2.7 How to compare different String objects with != operator ?
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.
2.8 How to find the first non repeated character from String ?
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)); }
2.9 How to convert String to Date in java 8?
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
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
2.11 How to check String contains only digits ?
public boolean checkStringOnlyDigitsIsDigit(String input) { IntStream intStream = input.chars(); boolean isMatched = intStream.anyMatch(ch -> Character.isDigit(ch)); return isMatched; }
2.12 How to reverse the words in String?
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; }
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.
No comments:
Post a Comment
Please do not add any spam links in the comments section.