String Programs in Java For Interview: If you’re looking to score a job that involves Java, it’s important to brush up on your string knowledge. In this article, we’ll go over some of the most commonly asked Java string interview questions so you can hit the ground running in your next interview.
If you’re looking to land a Java programming job, it’s important that you have a strong understanding of the String class. Nearly every Java application makes use of strings in some way, so demonstrating your knowledge of this fundamental class is essential for impressing potential employers.
String Programs in Java
In this article, you will find a list of Java String Programs Interview Questions that focus on topics like thread-safety, immutability, string methods in Java, StringBuilder and StringBuffer, memory consumption, comparing String instances in Java, using String as the key in HashMap, equals() vs == check for Strings.
You can find a list of Java String solved programs with solutions and detailed explanations below. All examples are compiled and tested on a Windows system.
How to Reverse Each Word In a String Using Charat() in Java With Example?
package com.java.Softwaretestingblog; public class ReverseEachWord { static void reverseEachWordOfString(String inputString) { String[] words = inputString.split(" "); String reverseString = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; String reverseWord = ""; for (int j = word.length()-1; j >= 0; j--) { reverseWord = reverseWord + word.charAt(j); } reverseString = reverseString + reverseWord + " "; } System.out.println("Entered String :- "+inputString); System.out.println("After Reverse Each Word :- "+reverseString); } public static void main(String[] args) { // TODO Auto-generated method stub reverseEachWordOfString("SoftwareTestingBlog is a Testing Blog"); } }
Output:
Entered String :- SoftwareTestingBlog is a Testing Blog After Reverse Each Word :- golBgnitseTerawtfoS si a gnitseT golB
How to Reverse String In Java With Out Using Collection Example?
package com.java.Softwaretestingblog; public class ReverseAString { public static void main(String[] args) { // TODO Auto-generated method stub String str = "SoftwareTestingBlog"; char[] strArray = str.toCharArray(); for (int i = strArray.length - 1; i >= 0; i--) { System.out.print(strArray[i]); //Output : golBgnitseTerawtfoS } } }
Output:
golBgnitseTerawtfoS
How to Reverse Each Word In a String Using Charat() in Java With Example?
package com.java.Softwaretestingblog; public class ReverseEachWord { static void reverseEachWordOfString(String inputString) { String[] words = inputString.split(" "); String reverseString = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; String reverseWord = ""; for (int j = word.length()-1; j >= 0; j--) { reverseWord = reverseWord + word.charAt(j); } reverseString = reverseString + reverseWord + " "; } System.out.println("Entered String :- "+inputString); System.out.println("After Reverse Each Word :- "+reverseString); } public static void main(String[] args) { // TODO Auto-generated method stub reverseEachWordOfString("SoftwareTestingBlog is a Testing Blog"); } }
Output:
Entered String :- SoftwareTestingBlog is a Testing Blog After Reverse Each Word :- golBgnitseTerawtfoS si a gnitseT golB
How to Remove Duplicate HashSet With Java Collection?
package com.java.Softwaretestingblog; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class RemoveDuplicateWithCollection { public static void main(String[] args) { // TODO Auto-generated method stub List<String> arraylist = new ArrayList<String>(); arraylist.add("www.SoftwareTestingblog.in"); arraylist.add("Interview Questions"); arraylist.add("SoftwareTestingBlog"); arraylist.add("java"); arraylist.add("Collections Interview Questions"); arraylist.add("www.SoftwareTestingblog.in"); arraylist.add("Java Experience Interview Questions"); System.out.println("Before Removing duplicate elements:"+arraylist); HashSet<String> hashset = new HashSet<String>(); /* Adding ArrayList elements to the HashSet * in order to remove the duplicate elements and * to preserve the insertion order. */ hashset.addAll(arraylist); // Removing ArrayList elements arraylist.clear(); // Adding LinkedHashSet elements to the ArrayList arraylist.addAll(hashset ); System.out.println("After Removing duplicate elements:"+arraylist); } }
Output:
Before Removing duplicate elements:[www.SoftwareTestingblog.in, Interview Questions, SoftwareTestingBlog, java, Collections Interview Questions, www.SoftwareTestingblog.in, Java Experience Interview Questions] After Removing duplicate elements:[www.SoftwareTestingblog.in, java, Collections Interview Questions, Java Experience Interview Questions, Interview Questions, SoftwareTestingBlog]
How to Find the Last Character Index from String Using lastIndexOf()?
package com.java.Softwaretestingblog; public class StringLastIndex { public static void main(String[] args) { // TODO Auto-generated method stub String str = "Use this string for testing this"; System.out.println("Basic lastIndexOf() example"); System.out.println("Char 's' at last occurance: "+str.lastIndexOf('s')); System.out.println("String \"this\" at last occurance: "+str.lastIndexOf("this")); /** * Returns the last occurance from specified start index, * searching backward starting at the specified index. */ System.out.println("first occurance of char 's' from 24th index backwards: " +str.lastIndexOf('s',24)); System.out.println("First occurance of String \"this\" from 26th index backwards: " +str.lastIndexOf("this",26)); } }
Output:
Basic lastIndexOf() example Char 's' at last occurance: 31 String "this" at last occurance: 28 first occurance of char 's' from 24th index backwards: 22 First occurance of String "this" from 26th index backwards: 4
How to Split String Message Into Tokens In Java With Example?
package com.java.Softwaretestingblog; import java.util.StringTokenizer; public class StringTokens { public static void main(String[] args) { // TODO Auto-generated method stub String msg = "http://10.123.43.67:80/"; StringTokenizer st = new StringTokenizer(msg,"://."); while(st.hasMoreTokens()) { System.out.println(st.nextToken()); } } }
Output:
http 10 123 43 67 80
How to Split String Message By Using Space Tokenizer In Java?
package com.java.Softwaretestingblog; import java.util.StringTokenizer; public class StringSplitToken { public static void main(String[] args) { // TODO Auto-generated method stub String msg = "Software Testing Blog"; StringTokenizer st = new StringTokenizer(msg," "); System.out.println("Count: "+st.countTokens()); } }
Output:
Count: 3
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
How to Initialize String Variable In Java With Example?
package com.java.Softwaretestingblog; public class Initialize_String_Variable { public static void main(String[] args) { // TODO Auto-generated method stub String abc = "This is a string object"; String bcd = new String("this is also string object"); char[] c = {'a','b','c','d'}; String cdf = new String(c); String junk = abc+" This is another String object"; System.out.println("======================="); System.out.println(abc); System.out.println(bcd); System.out.println(cdf); System.out.println(junk); } }
Output:
This is a string object this is also string object abcd This is a string object This is another String object
How to Find Character Index From a String Using indexOf()?
package com.java.Softwaretestingblog; public class CharacterIndex { public static void main(String[] args) { // TODO Auto-generated method stub String str = "Use this string for testing this"; System.out.println("Basic indexOf() example"); System.out.println("Char 's' at first occurance: "+str.indexOf('s')); System.out.println("String \"this\" at first occurance: "+str.indexOf("this")); /** * Returns the first occurance from specified start index */ System.out.println("First occurance of char 's' from 4th index onwards : " +str.indexOf('s',4)); System.out.println("First occurance of String \"this\" from 6th index onwards: " +str.indexOf("this",6)); } }
Output:
Basic indexOf() example Char 's' at first occurance: 1 String "this" at first occurance: 4 First occurance of char 's' from 4th index onwards : 7 First occurance of String "this" from 6th index onwards: 28
How to Compare String Values using Equals() & equalsIgnoreCase()?
package com.java.Softwaretestingblog; public class CompareString { public static void main(String[] args) { // TODO Auto-generated method stub String x = "SOFTWARETESTINGBLOG"; String y = "softwaretestingblog"; /** * We cannot use '==' operator to compare two strings. * We have to use equals() method. */ if(x.equals(y)) { System.out.println(x+" And " + y + " Both strings are equal."); } else { System.out.println(x+" And " + y + " Both strings are not equal."); } /** * We can ignore case with equalsIgnoreCase() method */ if(x.equalsIgnoreCase(y)) { System.out.println(x+" And " + y + " Both strings are equal."); } else { System.out.println(x+" And " + y + " Both strings are not equal."); } } }
How to Concat two String In Java With Example Updated?
package com.java.Softwaretestingblog; public class Concat2String { public static void main(String[] args) { // TODO Auto-generated method stub String b = "jump "; String c = "No jump"; /** * We can do string concatenation by two ways. * One is by using '+' operator, shown below. */ String d = b+c; System.out.println("By Using + Operator :- "+d); /** * Another way is by using concat() method, * which appends the specified string at the end. */ d = b.concat(c); System.out.println("Using Concat() method :- "+d); } }
Output:
By Using + Operator :- jump No jump Using Concat() method :- jump No jump
How to Compare two String Values Using contentEquals() In Java?
package com.java.Softwaretestingblog; public class Compare2String { public static void main(String[] args) { // TODO Auto-generated method stub String c = "We are comparing the content with a StringBuffer content"; StringBuffer sb =new StringBuffer("We are comparing the content with a StringBuffer content"); /** * We can use contentEquals() method to compare content with a StringBuffer. * It returns boolean value. */ if(c.contentEquals(sb)) { System.out.println("The content is equal"); } else { System.out.println("The content is not equal"); } } }
Output:
The content is equal
How to Remove Unnecessary Spaces Using Trim() In Java Example?
package com.java.Softwaretestingblog; public class RemoveSpaces { public static void main(String[] args) { // TODO Auto-generated method stub String str = " SoftwareTestingBlog "; System.out.println("After Remove The Unnecessary Spaces From String:- "+str.trim()); } }
Output:
After Remove The Unnecessary Spaces From String:- SoftwareTestingBlog
How to Compare two String Using matches In Java With Example?
package com.java.Softwaretestingblog; public class StringMatches { public static void main(String[] args) { // TODO Auto-generated method stub String[] str = {"www.softwaretestingblog.com", "http://softwaretestingblog.com"}; for(int i=0;i < str.length;i++){ if(str[i].matches("^www\\.(.+)")) { System.out.println(str[i]+" Starts with 'www'"); } else { System.out.println(str[i]+" is not starts with 'www'"); } } } }
Output:
www.softwaretestingblog.com Starts with 'www' http://softwaretestingblog.com is not starts with 'www'
How to Replace Character In A String Using replace() In Java?
package com.java.Softwaretestingblog; public class ReplaceCharacter { public static void main(String[] args) { // TODO Auto-generated method stub String str = "This is an example string"; System.out.println("Replace char 's' with 'o':"+str.replace('s', 'o')); System.out.println("Replace first occurance of string\"is\" with \"ui\":" +str.replaceFirst("is", "ui")); System.out.println("Replacing \"is\" every where with \"no\":" +str.replaceAll("is", "no")); } }
Output:
Replace char 's' with 'o':Thio io an example otring Replace first occurance of string"is" with "ui":Thui is an example string Replacing "is" every where with "no":Thno no an example string
How to Count Number Of Lines In A String In Java?
package com.java.Softwaretestingblog; public class CountLineInString { public static void main(String[] args) { // TODO Auto-generated method stub String str = "line1\nline2\nline3\rline4"; System.out.println(str); int count = getLineCount(str); System.out.println("line count: "+count); } private static int getLineCount(String str) { return str.split("[\n|\r]").length; } }
Output:
line1 line2 line3 line4 line count: 4
Find Word Count In a String Using Java With Example?
package com.java.Softwaretestingblog; public class NoOfWordsString { public static void main(String[] args) { // TODO Auto-generated method stub int word=1, i; String str="count number of words and sapces"; /*String [] str1=str.split(" "); int count=str1.length; System.out.println(count);*/ for( i=0;i<str.length();i++) { if(str.charAt(i)==' ') word++; } //System.out.println(i); System.out.println("Number of words="+word); System.out.println("Number of spaces="+(word-1)); } }
Output:
Number of words=6 Number of spaces=5
Write a Program to Reverse String In Java Program Example?
package com.java.Softwaretestingblog; import java.util.Scanner; public class ReverseString { public static void main(String[] args) { // TODO Auto-generated method stub String orginal,reverse=""; Scanner in=new Scanner(System.in); System.out.println("Enter a string:-"); orginal=in.nextLine(); int l=orginal.length(); //System.out.println(l); for(int i=l-1;i>=0;i--) { reverse=reverse+orginal.charAt(i); } //System.out.println("Reverse of entered string is: "+reverse); /*StringBuffer s=new StringBuffer("SoftwareTestingBlog"); System.out.println(s.reverse()); */ if(orginal.equals(reverse)) { System.out.println("Given string palindrome:-"+reverse); } else { System.out.println("Given string not a palindrome:-"+reverse); } } }
Output:
Enter a string:- SoftwareTestingBlog Given string not a palindrome:-golBgnitseTerawtfoS
Write a Program to Reverse Vowels Of a String?
package com.softwaretestingblog.InterviewPgms; public class ReverseStringVowelsOnly { public static String reverseVowels(String string) { String vowelsStr = "aeiouAEIOU"; int lo = 0; int hi = string.length() - 1; char[] ch = string.toCharArray(); while (lo < hi) { if (!vowelsStr.contains(String.valueOf(string.charAt(lo)))) { lo++; continue; } if (!vowelsStr.contains(String.valueOf(string.charAt(hi)))) { hi--; continue; } // swaping variables swap(ch, lo, hi); lo++; hi--; } return String.valueOf(ch); } private static void swap(char[] ch, int lo, int hi) { char temparray = ch[lo]; ch[lo] = ch[hi]; ch[hi] = temparray; } public static void main(String[] args) { System.out.println("Input String:- SoftwareTestingBlog"); System.out.println("After reversing vowels in a string = "+reverseVowels("SoftwareTestingBlog")); } }
Output:
Input String:- SoftwareTestingo After reversing vowels in a string = SoftwireTestango
Write a Program To Find The Numbers In a String and Sum Of The Numbers?
package com.java.Softwaretestingblog; public class DigitInString { public static void main(String[] args) { // TODO Auto-generated method stub String a = "m22n3j5"; int sum = 0; for(int i = 0; i < a.length(); i++) { if(Character.isDigit(a.charAt(i))) { sum = sum + Integer.parseInt(a.charAt(i)+""); } } System.out.println("Sum Of Numbers In The String :- "+sum); } }
Final Output:
Sum Of Numbers In The String :- 12
In This Post, we are trying to share the Java Programs Examples with Output, which is related to Java Interview Questions for experienced and few more Java Programs to Practise. Also, we try to share the Java Programs PDF and Java Interview Questions PDF versions tool
Write a Program To Find out Integer String Java Program?
package com.java.basics; public class IntegerToString { public static void main(String[] args) { int a = 1234; int b = -1234; String str1 = Integer.toString(a); String str2 = Integer.toString(b); System.out.println("String str1 = " + str1); System.out.println("String str2 = " + str2); System.out.println("---------------------------"); int c = 1234; String str3 = String.valueOf(c); System.out.println("String str3 = " + str3); System.out.println("---------------------------"); int d = 1234; Integer obj = new Integer(d); String str4 = obj.toString(); System.out.println("String str4 = " + str4); System.out.println("---------------------------"); } }
How to Reverse Words Of A String without Out Using Any Methods?
package com.softwaretestingblog.programs; public class ReverseWordOfString { static void reverseEachWordOfString(String inputString) { String[] words = inputString.split(" "); String reverseString = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; String reverseWord = ""; for (int j = word.length()-1; j >= 0; j--) { reverseWord = reverseWord + word.charAt(j); } reverseString = reverseString + reverseWord + " "; } System.out.println("Original String: - "+inputString); System.out.println("After Reverse Each Word In The String : - "+reverseString); System.out.println("-------------------------"); } public static void main(String[] args) { reverseEachWordOfString("Software Testing Blog"); reverseEachWordOfString("Manual Selenium Automation Testing"); reverseEachWordOfString("I am string not reversed"); reverseEachWordOfString("Reverse Me"); } }
Output:
Original String: - Software Testing Blog After Reverse Each Word In The String : - erawtfoS gnitseT golB ------------------------- Original String: - Manual Selenium Automation Testing After Reverse Each Word In The String : - launaM muineleS noitamotuA gnitseT ------------------------- Original String: - I am string not reversed After Reverse Each Word In The String : - I ma gnirts ton desrever ------------------------- Original String: - Reverse Me After Reverse Each Word In The String : - esreveR eM -------------------------
How to Sort String By Using Sort() Method In Java With Example?
package com.softwaretestingblog.programs; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class SortString { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader s=new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter a String"); str=s.readLine(); char [] charArry=str.toCharArray(); Arrays.sort(charArry); String nstr=new String(charArry); System.out.println("The sorted String is:-" +nstr); } }
Output:
Enter a String: Software Testing Blog The sorted String is:- BSTaeefggilnoorsttw
How to Compare two String Using equals() In Java With Example?
package com.softwaretestingblog.programs; public class StringCompareEqual { public static void main(String[] args) { // TODO Auto-generated method stub String s="SoftwareTestingBlog"; String obj=new String("SoftwareTestingBlog"); boolean result=s.equals(obj); if(result) { System.out.println("Values Matched"); System.out.println(s.hashCode()); System.out.println(obj.hashCode()); } else { System.out.println("Values Not Matched"); } } }
Output:
Values Matched 964009355 964009355
How to Swap Two String With Out Using Any Method In Java?
package com.softwaretestingblog.programs; import java.util.Scanner; public class SwapTwoString { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); System.out.println("Enter First String :"); String s1 = sc.next(); System.out.println("Enter Second String :"); String s2 = sc.next(); System.out.println("Before Swapping :"); System.out.println("s1 : "+s1); System.out.println("s2 : "+s2); //Swapping starts s1 = s1 + s2; s2 = s1.substring(0, s1.length()-s2.length()); s1 = s1.substring(s2.length()); //Swapping ends System.out.println("After Swapping :"); System.out.println("s1 : "+s1); System.out.println("s2 : "+s2); } }
Output:
Enter First String : Software Enter Second String : Testing Before Swapping : First String : Software Second String : Testing After Swapping : First String : Testing Second String : Software
How to Divide a String Using a split() Method In Java?
package com.softwaretestingblog.programs; public class StrSplit { public static void main(String[] args) { // TODO Auto-generated method stub String str = "This program splits a string based on space"; String[] tokens = str.split(" "); /*for(String s:tokens) { System.out.println(s); }*/ for(int i=0;i<tokens.length;i++) { System.out.println(tokens[i]); } } }
Output:
This program splits a string based on space
StringBuffer Works In Detail: How String vs StringBuilder vs StringBuffer Works In A Java Program?
package com.softwaretestingblog.programs; public class StringvsStringBuildervsStringBuffer { // Concatenates to String public static void concat1(String s1) { s1 = s1 + "Testing Blog"; System.out.println(s1); } // Concatenates to StringBuilder public static void concat2(StringBuilder s2) { s2.append("Testing Blog"); } // Concatenates to StringBuffer public static void concat3(StringBuffer s3) { s3.append("Testing Blog"); } public static void main(String[] args) { String s1 = "Software"; concat1(s1); // s1 is not changed System.out.println("String: " + s1); StringBuilder s2 = new StringBuilder("Software"); concat2(s2); // s2 is changed System.out.println("StringBuilder: " + s2); StringBuffer s3 = new StringBuffer("Software"); concat3(s3); // s3 is changed System.out.println("StringBuffer: " + s3); } }
Output:
SoftwareTesting Blog String: Software StringBuilder: SoftwareTesting Blog StringBuffer: SoftwareTesting Blog
Write a Program To Find Specific Character Index In Java With Example?
package com.java.Softwaretestingblog; public class FIndIndex { public static void main(String[] args) { // TODO Auto-generated method stub String s = "Learn Share Learn"; int output = s.indexOf('S') ; // returns 6 System.out.println("The Index Of Character s Is : "+output); } }
Output:
The Index Of Character S Is : 6
How to Find the Starting Character Of a String Using startsWith() In Java?
package com.softwaretestingblog.programs; public class StringStarts_with { public static void main(String[] args) { // TODO Auto-generated method stub String str = "This is an example string."; System.out.println("Is this string starts with \"This\"? "+str.startsWith("This")); } }
Output:
Is this string starts with "This"? true Is this string starts with "is"? false Is this string starts with "is" after index 5? true
How to Find The Sum Of Numeric Value in a String In Java?
package com.java.Softwaretestingblog; import java.util.Scanner; public class SumNumericValueInString { public static void main(String[] args) { // TODO Auto-generated method stub @SuppressWarnings("resource") Scanner sc=new Scanner(System.in); System.out.println("Enter a String"); String c=sc.next(); String digits = ""; int sum=0; for(int i=0;i<c.length();i++) { char ch = c.charAt(i); if (Character.isDigit(ch)) { digits = digits+ch; System.out.print(ch+"+"); } } System.out.println(); int no1=Integer.parseInt(digits),rem=0; while(no1>0) { rem=no1%10; sum=sum+rem; no1=no1/10; } System.out.println("Sum Of Digits :- "+sum); } }
Output:
Enter a Alphanumeric String Software123Testing456Blog 1+2+3+4+5+6+ Sum Of Digits :- 21
How to Extract Number From A String In Java With Example?
package com.softwaretestingblog.programs; import java.util.Scanner; public class ExtractNumberFromString { public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.println("Enter a String"); String c=sc.next(); String digits = ""; int no=34; int sum=0; for(int i=0;i<c.length();i++) { char ch = c.charAt(i); if (Character.isDigit(ch)) { digits = digits+ch; sum=no+Integer.parseInt(digits); } } System.out.println(sum); //System.out.println(digits); } }
Conclusion:
To help you prepare for your next Java interview, here is everything you need to know about Java String Programs. These questions will not only help you better understand Strings in Java, but could also open the door to learning more about them.
If you familiarize yourself with these common String Programs in Java interview questions, you will increase your chances of getting hired.
If you have any questions or would like to report an error, please contact us through our contact page or leave a comment below. We will do our best to respond as quickly as possible.
Leave a Reply