Strings in Java: A string is one of the important concepts of Java programming language because its a commonly used java class library. In General, String is nothing but a sequence of characters, for example, “SoftwareTestingo,” “Testing.” But in Java, the string is an object which is created using the string class. The string objects are immutable; that means if they are created once, then they can’t be modified, and if you make any changes in the object, then that will create another new object. We can locate the string class inside the java.lang package.
What is the Strings in Java?
We Can create a string object in java two ways:
- By String literal
- By New Keyword
By String Literal
We can create a string by assigning a string literal to a String instance like below
String str1=”SoftwareTestingo”;
String str2=”SoftwareTestingo”;
If we created a string in this approach, then there is a problem. As we have already discussed that string is an object, and also we know that we are creating an object by using the new key work, but you can see the above statement we are not using any new keyword.
On Behalf of us, Java compiler does the same task and creates the string object and stores the literals, which is “SoftwareTestingo” and assigned to the string instances or objects. and also, the objects are stored inside the string constant pool.
String literal/constant pool: This is a special area of heap memory which is used for storing the String literal or string constants. So whenever you create a string object, then JVM first checks the string constant pool for the literal. If JVM found the literal in string constant pool, then, in that case, JVM is not going to create another object for the literal in the constant pool area. It only returns the already existed object reference to the new object.
If the object is not present in the constant pool, then only a new instance is going to created and placed on the pool area.
So in the below code :
String str1=”SoftwareTestingo”;
String str2=”SoftwareTestingo”;
In the above example, in the case of str1 JVM checks for “SoftwareTestingo” in string constant pool. The first time it will be not in the pool; hence, JVM created a new instance and placed it into the pool. In the case of str2, JVM will find the “SoftwareTestingo” in the pool. Hence no new instance will be created, and reference of the already existing instance will be returned.
By New Keyword
We can also create the string object by using the new keyword. But when you create a string object using the new keyword, then JVM creates a new object in the heap area without looking on the string constant pool.
If you create a string object like below:
String str1= new String (“SoftwareTestingo”);
String str2= new String (“SoftwareTestingo”);
Then, in this case, two different objects are created, but both the objects are the point to the same literal that is “SoftwareTestingo.”
Why are string objects immutable in java?
As we have discussed above string literal and string constant pool, we get to know that n number of the variable can refer to one object. So if you change the value by one reference variable, then it affects another reference variable because all share the same object value (in Our case “SoftwareTestingo”). That’s why in Java programming language Strings are immutable.
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"); } }
Read Also: Star Pyramid Patterns Program
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"); } }
Read Also: Star Pyramid Patterns Program
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)); } }
Execution: The output link
Check Also: Find out Factorial Number In Java
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); } } }
Execution: The Final Output Link
Check Also: Convert Binary Decimal Java Program
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")); } }
Check Also: Interview Related Java Programs
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); } }
Execution: The Final Output link
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"); } }
Check Also: Find Starting Character Of a String Using startsWith()
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"); } } }
Check Also: Reverse String From a Sentence Using Java
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); } }
Check Also: Swap Elements Without Third Variable
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]); } } }
Read Also: Find Pair Elements In an Array
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); } }
Check Also: Sort String By Using Sort() Method In Java
Output:
SoftwareTesting Blog String: Software StringBuilder: SoftwareTesting Blog StringBuffer: SoftwareTesting Blog
Leave a Reply