Posts

Showing posts with the label Java String Handling

How to check if an input character is a vowel

In this blog post, I will be demonstrating how you can check if an input character is a vowel. I will be using Enum for this. If you’d like to study enums in detail, you can refer to this blog post.   Consider the following code snippet: public enum Vowels {a,e,i,o,u;}public class CheckIfVowel {public static void main(String[] args) {System.out.println("Enter a character:");Scanner scanner = new Scanner(System.in);String input = scanner.nextLine();boolean found = false;for(Vowels vowel:Vowels.values()){if (vowel.name().equalsIgnoreCase(input)){found = true;break;}}if(!found) System.out.println("Input "+input +" is NOT a vowel");else System.out.println("Input "+input +" is a vowel");scanner.close();}} Code explanation First, the code declares an Enum called Vowels . It is assigned the vowels i.e. a,e,i,o,u .  We are using the CheckIfVowel class to check if the input character is a vowel. The input character is read using ...

How to reverse a sentence via Java

In this blog post, I will be demonstrating how you can reverse a sentence via Java. So if the input String is “Hello World”, the program will print “World Hello”.   Consider the following code snippet: package learnjava.strings;public class ReverseASentenceDemo {public static void main(String[] args) {String inputStr = "This is a test program";System.out.println("Input String is "+inputStr);String[] words = inputStr.split(" ");StringBuffer reversedString = new StringBuffer("");for(int i = words.length-1; i >= 0; i --){reversedString.append(words[i]);if(i != 0)reversedString.append(" ");}System.out.println("Reversed String is "+reversedString.toString());}}   In this code, the input String is first split using the String.split method. It is split based on spaces, so it returns an array of words. This array is then traversed in the reverse direction. Each word in the array is appended to a ne...

How to read a CSV file via Java

Image
In this blog post, I will be covering how you can read a CSV file via Java. What is a CSV file? CSV stands for Comma Separated Values.  The fields in a CSV file are separated by commas.  So for example, a CSV file will be seen in Notepad as follows:   However, if you open the same CSV file in Excel and will be seen as follows:   A CSV file is used to store tabular data. You can open a CSV file in Microsoft Excel. Code to read CSV file Consider the following code sample: package learnjava.io;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class ReadCSVDemo {public static void main(String[] args) {String fileName="F:/Test.csv";try {BufferedReader br = new BufferedReader(new FileReader(fileName));String str = br.readLine();while(str != null){String[] contents = str.split(",");for(String cell:contents){System.out.print(cell);}str = br.readLine();System.out.println...

How to check if a String is a substring of another String

In this blog post, I will be explaining how you can check if a String is a substring of another String. Consider the following code snippet: package learnjava.strings;public class CheckSubstringDemo {public static void main(String[] args) {String strToCheck = "Hello World";String valueToCheck = "Hello";//Method 1 - Use Containsif(strToCheck.contains(valueToCheck))System.out.println(valueToCheck+" is present in "+strToCheck);elseSystem.out.println(valueToCheck+" is NOT present in "+strToCheck);//Method 2 - Use startsWith and indexOfif(strToCheck.startsWith(valueToCheck) || strToCheck.indexOf(valueToCheck) > 0)System.out.println(valueToCheck+" is present in "+strToCheck);elseSystem.out.println(valueToCheck+" is NOT present in "+strToCheck);}}   This code snippet demonstrates two ways to check if a String is a substring of another String. Method 1: This method uses the String.contains method. This returns true if the ...

How to check if a String has digits in Java

In this blog post, I will be explaining how you can check if a String has digits. There are several ways to do this. Consider the following code snippet:   package learnjava.strings;import java.util.regex.Pattern;public class CheckIfStringHasDigits {public static void main(String[] args) {String str = "Hello123";String regex = ".*[0-9].*";//Method 1 - Using String.matchesboolean matches = str.matches( regex );System.out.println("Using String.matches="+matches);//Method 2 - Using pattern.matchesmatches = Pattern.matches( regex , str);System.out.println("Using pattern.matches="+matches);//Method 3 - using pattern.compilematches = Pattern.compile( regex).matcher( str ).find();System.out.println("Using Pattern.compile="+matches);//Method 4 - Checking each characterboolean digitFound = false;char[] characters = str.toCharArray();for(char c:characters){if(Character.isDigit(c)){digitFound = true;break;}}System.out.println("Using manua...

How to split a String via Java

In this blog post, I will be explaining how you can split a String via Java. Consider the following code snippet: package learnjava.strings;public class SplitStringDemo {public static void main(String[] args) {String str = "This is a test String";String[] words = str.split(" ");System.out.println("There are "+words.length+" words");for(String word:words){System.out.println(word);}}} There is a method called String.split . It accepts any regular expression. It splits the String around matches of the specified regular expression. Here, I am simply using a space. This will split the input sentence into words. So if you run the above code, you will get the following output: There are 5 wordsThisisatestString  

How to find the count of each character in a String in Java

In this blog post, I will be demonstrating how you can determine the number of occurrences of each character in a String. Consider the following code snippet: package learnjava.strings;import java.util.HashMap;import java.util.Map;public class CountCharactersDemo {public static void main(String[] args) {String str = "Hello World";Map<Character,Integer> characterCountMap = new HashMap<Character,Integer>(); //map stores each character and its countchar[] charsInStr = str.toCharArray();for(char c:charsInStr){if(characterCountMap.containsKey(c)){ //if the character is already in the map, just increment its countint count = characterCountMap.get(c);count++;characterCountMap.put(c, count);}else{ //if the character is not in the map, add it to the mapcharacterCountMap.put(c, 1);}}for(Character c:characterCountMap.keySet()){System.out.println("Character "+c+" occurs "+characterCountMap.get(c));}}}   The  characterCountMap defines a...

How to convert a String to lowercase in Java

In this blog post, I will be explaining how you can convert a String to lowercase in Java. Consider the following code snippet:   </pre>package learnjava.strings;public class StringLowerCaseDemo {public static void main(String[] args) {String str = "Hello World";str = str.toLowerCase();System.out.println(str);}}<pre>   There is a String.toLowerCase method. This converts the String object on which it is invoked to lowercase and returns the converted String. So when you run the above code, you will get the following output: hello world

How to remove a character from a String via Java

In this blog post, I will be explaining how you can remove a character from a String via Java. Consider the following code snippet: package learnjava.strings;public class RemoveCharacterDemo {public static void main(String[] args) {String str = "Hello World";String modifiedStr = str.replace("l", "");System.out.println(modifiedStr);}}   There is a method String.replace . This replaces the specified character with another character. Here, we are replacing the character ‘l’ with an empty character. So effectively, it is like removing the character “l”. When you run this code, you will get the following output: Heo Word  

How to convert a String to uppercase

In this blog post, I will be explaining how you can convert a String to uppercase. Consider the following code snippet:   package learnjava.strings;public class StringUpperCaseDemo {public static void main(String[] args) {String str = "Hello World";str = str.toUpperCase();System.out.println(str);}}   There is a String.toUpperCase method. This converts the String object on which it is invoked to uppercase and returns the converted String. So when you run the above code, you will get the following output: HELLO WORLD

String vs StringBuffer vs StringBuilder

A very common interview question is to ask the difference between String, StringBuffer and StringBuilder . So in this blog post, I am going to explain how they are different.   What is a String? A String is a Java class. It is designed to hold a set of characters like alphabets, numbers, special characters, etc. String objects are constants, their values cannot be changed after they are created. So, String objects are also called immutable objects. For example, consider the following code snippet: String str = "abc"; //line 1str = str+"xyz"; //line 2 When the line 2 is executed, The object “ abc ” remains as it is and a new object is created  with the value “abc” appended with “xyz”.  The object reference “ str ” no longer points to the memory address of “ abc “, but it points to the address of “abc xyz “. And what about “ abc “? It continues to exist as it is until it is ...

How are Java Strings immutable

Image
You might have heard a lot about Java Strings being immutable . You might have also faced interview questions where you are asked to explain this. In this blog post, I will be shedding some light on this with examples.   So yes, Java Strings are indeed immutable . So what does immutable mean? It means that String objects are constants, their values cannot be changed after they are created. Now consider the following code: String str= "abc";str= "xyz";   Is the above code valid?  Yes, the above lines are perfectly valid. Now this might appear confusing to a new programmer because we are changing the value of “ str”  from “ abc ” to “ xyz “.  But that is not so. The object “ abc ” remains as it is and a new object “ xyz ” is created.  The object reference “ str ” no longer points to the memory address of “ abc “, but it points to the address of “ xyz “. And what ...

How to convert a String to a Date

In this blog post, I will be demonstrating how you can convert a String to a Date object. Consider the following code snippet: public class StringToDate {public static void main(String[] args) {System.out.println("Enter a date:");Scanner scanner = new Scanner(System.in);String dateStr = scanner.nextLine();System.out.println("Input date is "+dateStr);SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");try {Date date = simpleDateFormat.parse(dateStr);System.out.println("Date in date format is "+date);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}scanner.close();}} The input Date in String format is read using the  Scanner  class. The code uses the  SimpleDateFormat class. This is a class that provides date formatting functions. In the constructor, you need to specify the format in which the input date is specified as a String. So in this case, I have specified “ dd-MM-yyyy ” which ...

How to reverse a String in Java

In this post, I will demonstrate how to reverse a String in Java. You can do this in the most obvious way i.e. iterating through the String in the reverse order and creating a new String. The following code snippet demonstrates this:   private static String reverse(String str){String reversedString = &quot;&quot;;for(int i = str.length()-1;i &gt;=0 ; i--){reversedString = reversedString + str.charAt(i);}return reversedString;}   A better way is to use Java’s StringBuilder class that has an in-built reverse method. The following code snippet demonstrates this:   StringBuilder strBuilder = new StringBuilder(str);String reversedString = strBuilder.reverse().toString();  

How to find the number of words in a Sentence

In order to find the number of words in a sentence, you can use the String.split method. The following code demonstrates this:   package demo;public class StringDemo {public static void main(String[] args) {String str = "My first Java program";String[] words = str.split(" ");System.out.println("There are "+words.length+" words");}} So the split method splits the given String on the basis of the space character. It returns a String array with all the words in the input String. You can use any other character to split the String as well. When you run this code, it will print the following on the console: There are 4 words  

How to check if a String has only alphabets

You can use Java regular expressions to check if a String has only alphabets as follows: package demo;public class StringDemo {public static void main(String[] args) {String str = "HelloWorld";String regex = "^[a-zA-Z]+$";boolean matches = str.matches(regex);System.out.println(matches);}}   The above code will print true when you run it. If you change the String str to have any other characters like numbers or special characters, it will print false.

How to replace a character in a String with another character

There is a replace method provided by the String class that can be used to replace a character in a String with another character. The following code snippet demonstrates this:   package demo;public class StringDemo {public static void main(String[] args) {String str = "Hello World";String modifiedStr = str.replace('o', 'i');System.out.println("Modified String is "+modifiedStr);}}     So the above code will replace all occurrences of the letter ‘o’ in the String “Hello World”  an ‘i’ and will print the following: Helli Wirld