Users Online
· Members Online: 0
· Total Members: 188
· Newest Member: meenachowdary055
Forum Threads
Latest Articles
Articles Hierarchy
Java String Tutorial
Java String Tutorial
Tutorial | Java Strings - Stuff You Must Know! |
Tutorial | String Length() Method |
Tutorial | String indexOf() Method |
Tutorial | String charAt() Method |
Tutorial | String compareTo() Method in Java |
Tutorial | String contains() Method |
Tutorial | String endsWith() Method |
Tutorial | Java String replace(), replaceFirst() and replaceAll() Method |
Tutorial | Java String toLowercase() and toUpperCase() Methods |
Tutorial | How to convert a Java String to Integer ? |
Tutorial | Working with HashMaps in Java |
Java String Manipulation: Functions and Methods with EXAMPLE
What are Strings?
A string in literal terms is a series of characters. Hey, did you say characters, isn’t it a primitive data type in Java. Yes, so in technical terms, the basic Java String is basically an array of characters.
So my above string of “ROSE” can be represented as the following –
In this tutorial, you will learn-
- What are Strings?
- Why use Strings?
- String Syntax Examples
- String Concatenation
- Important Java string methods
Why use Strings?
One of the primary functions of modern computer science, is processing human language.
Similarly to how numbers are important to math, language symbols are important to meaning and decision making. Although it may not be visible to computer users, computers process language in the background as precisely and accurately as a calculator. Help dialogs provide instructions. Menus provide choices. And data displays show statuses, errors, and real-time changes to the language.
As a Java programmer, one of your main tools for storing and processing language is going to be the String class.
String Syntax Examples
Now, let’s get to some syntax,after all, we need to write this in Java code isn’t it.
String is an array of characters, represented as:
//String is an array of characters char[] arrSample = {'R', 'O', 'S', 'E'}; String strSample_1 = new String (arrSample);
In technical terms, the String is defined as follows in the above example-
= new (argument);
Now we always cannot write our strings as arrays; hence we can define the String in Java as follows:
//Representation of String String strSample_2 = "ROSE";
In technical terms, the above is represented as:
= ;
The String Class Java extends the Object class.
String Concatenation:
Concatenation is joining of two or more strings.
Have a look at the below picture-
We have two strings str1 = “Rock” and str2 = “Star”
If we add up these two strings, we should have a result as str3= “RockStar”.
Check the below code snippet,and it explains the two methods to perform string concatenation.
First is using “concat” method of String class and second is using arithmetic “+” operator. Both results in the same output
public class Sample_String{ public static void main(String[] args){ //String Concatenation String str1 = "Rock"; String str2 = "Star"; //Method 1 : Using concat String str3 = str1.concat(str2); System.out.println(str3); //Method 2 : Using "+" operator String str4 = str1 + str2; System.out.println(str4); } }
Important Java string methods :
Let’s ask the Java String class a few questions and see if it can answer them ;)
String "Length" Method
How will you determine the length of given String? I have provided a method called as “length”. Use it against the String you need to find the length.
public class Sample_String{ public static void main(String[] args){ //Our sample string for this tutorial String str_Sample = "RockStar"; //Length of a String System.out.println("Length of String: " + str_Sample.length());}}
output:
Length of String: 8
String "indexOf" Method
If I know the length, how would I find which character is in which position? In short, how will I find the index of a character?
You answered yourself, buddy, there is an “indexOf” method that will help you determine the location of a specific character that you specify.
public class Sample_String{ public static void main(String[] args){//Character at position String str_Sample = "RockStar"; System.out.println("Character at position 5: " + str_Sample.charAt(5)); //Index of a given character System.out.println("Index of character 'S': " + str_Sample.indexOf('S'));}}
Output:
Character at position 5: t Index of character 'S': 4
String "charAt" Method
Similar to the above question, given the index, how do I know the character at that location?
Simple one again!! Use the “charAt” method and provide the index whose character you need to find.
public class Sample_String{ public static void main(String[] args){//Character at position String str_Sample = "RockStar"; System.out.println("Character at position 5: " + str_Sample.charAt(5));}}
Output:
Character at position 5: t
String "CompareTo" Method
Do I want to check if the String that was generated by some method is equal to something that I want to verify with? How do I compare two Strings?
Use the method “compareTo” and specify the String that you would like to compare.
Use “compareToIgnoreCase” in case you don’t want the result to be case sensitive.
The result will have the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.
public class Sample_String{ public static void main(String[] args){//Compare to a String String str_Sample = "RockStar"; System.out.println("Compare To 'ROCKSTAR': " + str_Sample.compareTo("rockstar")); //Compare to - Ignore case System.out.println("Compare To 'ROCKSTAR' - Case Ignored: " + str_Sample.compareToIgnoreCase("ROCKSTAR"));}}
Output:
Compare To 'ROCKSTAR': -32 Compare To 'ROCKSTAR' - Case Ignored: 0
String "Contain" Method
I partially know what the string should have contained, how do I confirm if the String contains a sequence of characters I specify?
Use the method “contains” and specify the characters you need to check.
Returns true if and only if this string contains the specified sequence of char values.
public class Sample_String{ public static void main(String[] args){ //Check if String contains a sequence String str_Sample = "RockStar"; System.out.println("Contains sequence 'tar': " + str_Sample.contains("tar"));}}
Output:
Contains sequence 'tar': true
String "endsWith" Method
How do I confirm if a String ends with a particular suffix? Again you answered it. Use the “endsWith” method and specify the suffix in the arguments.
Returns true if the character sequence represented by the argument is a suffix of the character sequence represented by this object.
public class Sample_String{ public static void main(String[] args){ //Check if ends with a particular sequence String str_Sample = "RockStar"; System.out.println("EndsWith character 'r': " + str_Sample.endsWith("r"));}}
Output:
EndsWith character 'r': true
String "replaceAll" & "replaceFirst" Method
I want to modify my String at several places and replace several parts of the String?
Java String Replace, replaceAll and replaceFirst methods. You can specify the part of the String you want to replace and the replacement String in the arguments.
public class Sample_String{ public static void main(String[] args){//Replace Rock with the word Duke String str_Sample = "RockStar"; System.out.println("Replace 'Rock' with 'Duke': " + str_Sample.replace("Rock", "Duke"));}}
Output:
Replace 'Rock' with 'Duke': DukeStar
String Java "tolowercase" & Java "touppercase" Method
I want my entire String to be shown in lower case or Uppercase?
Just use the “toLowercase()” or “ToUpperCase()” methods against the Strings that need to be converted.
public class Sample_String{ public static void main(String[] args){//Convert to LowerCase String str_Sample = "RockStar"; System.out.println("Convert to LowerCase: " + str_Sample.toLowerCase()); //Convert to UpperCase System.out.println("Convert to UpperCase: " + str_Sample.toUpperCase());}}
Output:
Convert to LowerCase: rockstar Convert to UpperCase: ROCKSTAR
Important Points to Note:
- String is a Final class; i.e once created the value cannot be altered. Thus String objects are called immutable.
- The Java Virtual Machine(JVM) creates a memory location especially for Strings called String Constant Pool. That’s why String can be initialized without ‘new’ keyword.
- String class falls under java.lang.String hierarchy. But there is no need to import this class. Java platform provides them automatically.
- String reference can be overridden but that does not delete the content; i.e., if
String h1 = "hello";
h1 = "hello"+"world";
then "hello" String does not get deleted. It just loses its handle.
- Multiple references can be used for same String but it will occur in the same place; i.e., if
String h1 = "hello";
String h2 = "hello";
String h3 = "hello";
then only one pool for String “hello” is created in the memory with 3 references-h1,h2,h3
- If a number is quoted in “ ” then it becomes a string, not a number anymore. That means if
String S1 ="The number is: "+ "123"+"456";
System.out.println(S1);
then it will print: The number is: 123456
If the initialization is like this:
String S1 = "The number is: "+(123+456);
System.out.println(S1);
then it will print: The number is:579 That's all to Strings!
String Length() Method in Java with Example
What is String "Length" Method in Java?
This function is used to get the length of a Java String. The string length method returns the number of characters written in the String. This method returns the length of any string which is equal to the number of 16-bit Unicode characters in the string.
String "Length" Method Syntax:
public int length()
Parameters:
NA
Return Value:
This method returns the length of the string.
Java string Length Method Examples:
In this program, we have two Strings and we find out the length of them using length() method.
public class Sample_String { public static void main(String[] args) { //declare the String as an object S1 S2 String S1 = "Hello Java String Method"; String S2 = "RockStar"; //length() method of String returns the length of a String S1. int length = S1.length(); System.out.println("Length of a String is: " + length); //8 Length of a String RockStar System.out.println("Length of a String is: " + S2.length()); } }
Output:
Length of a String is: 24
Length of a String is: 8
String indexOf() Method in Java with EXAMPLE
What is Java String IndexOf Method?
The indexOf method is used to get the integer value of a particular index of String type object, based on criteria specified in the parameters of the IndexOf method.
A common scenario can be when a system admin wants to find the index of the '@' character of the email Id of a client and then wants to get the remaining substring. In that situation, IndexOf method can be used.
Syntax
The syntax of this Java method is:
public int indexOf(int cha)
Parameters
cha − a character.
Return Value
This Java method returns the index within this string of the first occurrence of the specified character. It returns -1 if the character does not occur.
The Java String IndexOf method has four overloads. All the overloads return an integer type value, representing the returned index. These overloads differ in the type and number of parameters they accept.
IndexOf(char b)
This method returns the index of the character 'b' passed as parameter. If that character is not available in the string, the returned index would be -1.
IndexOf(char c, int startindex)
The given method would return the index of the first occurrence of character 'c' after the integer index passed as second parameter "startindex." All the occurrences of character 'c' before the "startindex" integer index would be ignored.
IndexOf(String substring)
The above method returns the index of the first character of the substring passed as a parameter to it. If that substring is not available in the string, the returned index would be -1.
IndexOf(String substring, int startindex)
This Java method returns the index of the first character in the substring passed as the first parameter, after the "startindex" index value. If substring starts from the passed integer value of "startindex", that substring would be ignored.
Example
public class Sample_String { public static void main(String args[]) { String str_Sample = "This is Index of Example"; //Character at position System.out.println("Index of character 'x': " + str_Sample.indexOf('x')); //Character at position after given index value System.out.println("Index of character 's' after 3 index: " + str_Sample.indexOf('s', 3)); //Give index position for the given substring System.out.println("Index of substring 'is': " + str_Sample.indexOf("is")); //Give index position for the given substring and start index System.out.println("Index of substring 'is' form index:" + str_Sample.indexOf("is", 5)); } }
Output:
Index of character 'x': 12
Index of character 's' after 3 index: 3
Index of substring 'is': 2
Index of substring 'is' form index:5
String charAt() Method in Java with Example
Why use string "charAt" Method?
The charat method returns the character at the definite index. In this method index value should be between 0 and string length minus 1
Method Syntax:
public char charAt(int index)
Parameter input:
index – This Java method accepts only single input which is an int data type.
Method Returns:
This method returns a character type data based on the index input
Exception:
Throws java.lang.StringIndexOutOfBoundsException if index value is not between 0 and String length minus one
Example 1:
public class CharAtGuru99 { public static void main(String args[]) { String s1 = "This is String CharAt Method"; //returns the char value at the 0 index System.out.println("Character at 0 position is: " + s1.charAt(0)); //returns the char value at the 5th index System.out.println("Character at 5th position is: " + s1.charAt(5)); //returns the char value at the 22nd index System.out.println("Character at 22nd position is: " + s1.charAt(22)); //returns the char value at the 23th index char result = s1.charAt(-1); System.out.println("Character at 23th position is: " + result); } }
Output:
Character at 0 position is: T
Character at 5th position is: i
Character at 22nd position is: M
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
Some important things about this Java charAt method:
- This Java method takes an argument which is always int type.
- This method returns the character as char for the given int argument. The int value specifies the index that starts at 0.
- If the index value is higher than string length or a negative, then IndexOutOfBounds Exception error occurs.
- The index range must be between 0 to string_length-1.
String compareTo() Method in Java with Example
What is compareTo() method in Java?
compareTo() method is used to perform natural sorting on string. Natural sorting means the sort order which applies on the object, e.g., lexical order for String, numeric order for Sorting integers, etc.
Lexical order is nothing but alphabetically order. compareTo methods does a sequential comparison of letters in the string that have the same position.
compareTo is defined in interface java.lang.Comparable
Syntax :
public int compareTo(String str)
Parameter input :
str – This method only accepts only one input String data type.
Method Returns:
This Java method returns an int datatype which is based on the lexicographical comparison between two strings.
- returns < 0 then the String calling the method is lexicographically first
- returns == 0 then the two strings are lexicographically equivalent
- returns > 0 then the parameter passed to the compareTo method is lexicographically first.
Let's understand with an example:
Example 1:
public class Sample_String { public static void main(String[] args) { String str_Sample = "a"; System.out.println("Compare To 'a' b is : " + str_Sample.compareTo("b")); str_Sample = "b"; System.out.println("Compare To 'b' a is : " + str_Sample.compareTo("a")); str_Sample = "b"; System.out.println("Compare To 'b' b is : " + str_Sample.compareTo("b")); } }
Output
Compare To 'a' b is : -1
Compare To 'b' a is : 1
Compare To 'b' b is : 0
Here,
- Character a comes before b alphabetically. Hence output is -1
- Character b comes after a alphabetically. Hence output is 1
- Character b are equivalent, hence output is 0.
You can use method Use "compareToIgnoreCase" in case you don't want the result to be case sensitive.
Example 2:
public class Sample_String { public static void main(String[] args) { //Compare to a String String str_Sample = "RockStar"; System.out.println("Compare To 'ROCKSTAR': " + str_Sample.compareTo("rockstar")); //Compare to - Ignore case System.out.println("Compare To 'ROCKSTAR' - Case Ignored: " + str_Sample.compareToIgnoreCase("ROCKSTAR")); } }
Output
Compare To 'ROCKSTAR': -32
Compare To 'ROCKSTAR' - Case Ignored: 0
When to use CompareTo() method?
CompareTo() is used for comparing two strings lexicographically. Each character of both strings are converted into a Unicode value. However, if both the strings are equal, then this method returns 0 else it only result either negative or positive value.
In this method, if the first string is always lexicographically higher than second string, it returns a positive number.
if a1 > a2, it returns negative number
if a1 < a2, it returns positive number
if a1 == a2, it returns 0
Example 3:
public class Compare { public static void main(String[] args) { String s1 = "Guru1"; String s2 = "Guru2"; System.out.println("String 1: " + s1); System.out.println("String 2: " + s2); // Compare the two strings. int S = s1.compareTo(s2); // Show the results of the comparison. if (S < 0) { System.out.println("\"" + s1 + "\"" + " is lexicographically higher than " + "\"" + s2 + "\""); } else if (S == 0) { System.out.println("\"" + s1 + "\"" + " is lexicographically equal to " + "\"" + s2 + "\""); } else if (S > 0) { System.out.println("\"" + s1 + "\"" + " is lexicographically less than " + "\"" + s2 + "\""); } } }
Output:
String 1: Guru1
String 2: Guru2
"Guru1" is lexicographically higher than "Guru2"
String contains() Method in Java with Example
What is contains()method in Java?
The contains() method is Java method to check if String contains another substring or not. It returns boolean value so it can use directly inside if statements.
Syntax of String "Contain" method
public boolean String.contains(CharSequence s)
Parameters
S − This is the sequence to search
Return Value
This method returns true only if this string contains "s" else false.
Exception
NullPointerException − if the value of s is null.
Example 1:
public class Sample_String { public static void main(String[] args) { String str_Sample = "This is a String contains Example"; //Check if String contains a sequence System.out.println("Contains sequence 'ing': " + str_Sample.contains("ing")); System.out.println("Contains sequence 'Example': " + str_Sample.contains("Example")); //String contains method is case sensitive System.out.println("Contains sequence 'example': " + str_Sample.contains("example")); System.out.println("Contains sequence 'is String': " + str_Sample.contains("is String")); } }
Output:
Contains sequence 'ing': true
Contains sequence 'Example': true
Contains sequence 'example': false
Contains sequence 'is String': false
When to use Contains() method?
It is a common case in programming when you want to check if specific String contains a particular substring. For example, If you want to test if the String "The big red fox" contains the substring "red." This method is useful in such situation.
Example 2: Java String contains() method in the if else Loop
public class IfExample { public static void main(String args[]) { String str1 = "Java string contains If else Example"; // In If-else statements you can use the contains() method if (str1.contains("example")) { System.out.println("The Keyword :example: is found in given string"); } else { System.out.println("The Keyword :example: is not found in the string"); } } }
Output:
The Keyword :example: is not found in the string
String endsWith() Method in Java with Example
What is String "endsWith" Method?
The Java endsWith method is used to check whether the string is ending with user-specified substring or not. Based on this comparison it will return boolean True or False.
Syntax
Public endsWith(suffix)
Parameters
suffix – This is a suffix.
Return Value
- False: Character sequence supplied in "suffix" DOES NOT matches the end sequence of the calling string
- True: Character sequence supplied in "suffix" matches the end sequence of the calling string
Exception
None
Example:
public class StringEx1 { public static void main(String[] args) { String str_Sample = "Java String endsWith example"; //Check if ends with a particular sequence System.out.println("EndsWith character 'e': " + str_Sample.endsWith("e")); System.out.println("EndsWith character 'ple': " + str_Sample.endsWith("ple")); System.out.println("EndsWith character 'Java': " + str_Sample.endsWith("Java")); } }
Output:
EndsWith character 'e': true
EndsWith character 'ple': true
EndsWith character 'Java': false
The java.lang.String.endsWith() returns true if this string ends with the specified suffix.
Java String replace(), replaceFirst() & replaceAll() Method EXAMPLE
Java String has three types of Replace method
- replace
- replaceAll
- replaceFirst.
With the help of these you can replace characters in your string. Lets study each in details:
1. Java String replace() Method
Description:
This Java method returns a new string resulting from replacing every occurrence of characters with a new characters
Syntax:
public Str replace(char oldC, char newC)
Parameters:
oldCh − old character.
newCh − new character.
Return Value
This fucntion returns a string by replacing oldCh with newCh.
Example 1
public class Guru99Ex1 { public static void main(String args[]) { String S1 = new String("the quick fox jumped"); System.out.println("Original String is ': " + S1); System.out.println("String after replacing 'fox' with 'dog': " + S1.replace("fox", "dog")); System.out.println("String after replacing all 't' with 'a': " + S1.replace('t', 'a')); } }
Output:
Original String is ': the quick fox jumped
String after replacing 'fox' with 'dog': the quick dog jumped
String after replacing all 't' with 'a': ahe quick fox jumped
2.Java String Replaceall()
Description
The java string replaceAll() method returns a string replacing all the sequence of characters matching regular expression and replacement string.
Signature:
public Str replaceAll(String regex, String replacement)
Parameters:
regx: regular expression
replacement: replacement sequence of characters
Example 2
public class Guru99Ex2 { public static void main(String args[]) { String str = "Guru99 is a site providing free tutorials"; //remove white spaces String str2 = str.replaceAll("\\s", ""); System.out.println(str2); } }
Output:
Guru99isasiteprovidingfreetutorials
3. Java - String replaceFirst() Method
Description
The method replaces the first substring of the given string which matches that regular expression.
Syntax
public Str replaceFirst(String rgex, String replacement)
Parameters
rgex − the regular expression to which given string need to matched.
replacement − the string that replaces regular expression.
Return Value
This method returns resulting String as an output.
Example 3:
public class Guru99Ex2 { public static void main(String args[]) { String str = "This website providing free tutorials"; //Only Replace first 's' with '9' String str1 = str.replaceFirst("s", "9"); System.out.println(str1); } }
Output:
Thi9 website providing free tutorials
Java String toLowercase() and toUpperCase() Methods
1. tolowercase() method
This Java string method converts every character of the particular string into the lower case by using the rules of the default locale.
Note: This method is locale sensitive. Therefore it can show unexpected results if used for strings which are intended to be interpreted separately.
Syntax
public String toLowerCase()
Parameters
NA
Return Value
It returns the String, which is converted to lowercase.
Example 1:
public class Guru99 { public static void main(String args[]) { String S1 = new String("UPPERCASE CONVERTED TO LOWERCASE"); //Convert to LowerCase System.out.println(S1.toLowerCase()); } }
Output:
uppercase converted to lowercase
2. toUppercase () method
The toUppercase() method is used to convert all the characters in a given string to upper case.
Syntax:
toUpperCase()
Parameters:
NA
Returns value:
String in an uppercase letter.
Example 2:
public class Guru99 { public static void main(String args[]) { String S1 = new String("lowercase converted to uppercase"); //Convert to UpperCase System.out.println(S1.toUpperCase()); } }
Output:
LOWERCASE CONVERTED TO UPPERCASE
How to easily Convert String to Integer in JAVA
There are two ways to convert String to Integer in Java,
- String to Integer using Integer.parseInt()
- String to Integer using Integer.valueOf()
Let’s say you have a string – strTest - that contains a numeric value.
String strTest = “100”;Try to perform some arithmetic operation like divide by 4 – This immediately shows you a compilation error.
class StrConvert{ public static void main(String []args){ String strTest = "100"; System.out.println("Using String:" + (strTest/4)); } }
Output:
/StrConvert.java:4: error: bad operand types for binary operator '/' System.out.println("Using String:" + (strTest/4));
Hence, you need to convert a String to int before you peform numeric operations on it
Example 1: Convert String to Integer using Integer.parseInt()
Syntax of parseInt method as follows:
int <IntVariableName> = Integer.parseInt(<StringVariableName>);
Pass the string variable as the argument.
This will convert the Java String to java Integer and store it into the specified integer variable.
Check the below code snippet-
class StrConvert{ public static void main(String []args){ String strTest = "100"; int iTest = Integer.parseInt(strTest); System.out.println("Actual String:"+ strTest); System.out.println("Converted to Int:" + iTest); //This will now show some arithmetic operation System.out.println("Arithmetic Operation on Int: " + (iTest/4)); } }
Output:
Actual String:100 Converted to Int:100 Arithmetic Operation on Int: 25
Example 2: Convert String to Integer using Integer.valueOf()
Integer.valueOf() Method is also used to convert String to Integer in Java.
Following is the code example shows the process of using Integer.valueOf() method:
public class StrConvert{ public static void main(String []args){ String strTest = "100"; //Convert the String to Integer using Integer.valueOf int iTest = Integer.valueOf(strTest); System.out.println("Actual String:"+ strTest); System.out.println("Converted to Int:" + iTest); //This will now show some arithmetic operation System.out.println("Arithmetic Operation on Int:" + (iTest/4)); } }
Output:
Actual String:100 Converted to Int:100 Arithmetic Operation on Int:25
NumberFormatException
NumberFormatException is thrown If you try to parse an invalid number string. For example, String ‘Guru99’ cannot be converted into Integer.
Example:
public class StrConvert{ public static void main(String []args){ String strTest = "Guru99"; int iTest = Integer.valueOf(strTest); System.out.println("Actual String:"+ strTest); System.out.println("Converted to Int:" + iTest); } }
Above example gives following exception in output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Guru99"
HashMap in Java Learn with Example
What is Hashmap in Java?
A HashMap basically designates unique keys to corresponding values that can be retrieved at any given point.Features of Java Hashmap
a) The values can be stored in a map by forming a key-value pair. The value can be retrieved using the key by passing it to the correct method.b) If no element exists in the Map, it will throw a ‘NoSuchElementException’.
c) HashMap stores only object references. That is why, it is impossible to use primitive data types like double or int. Use wrapper class (like Integer or Double) instead.
Using HashMaps in Java Programs:
Following are the two ways to declare a Hash Map:HashMap<String, Object> map = new HashMap<String, Object>(); HashMap x = new HashMap();
- get(Object KEY) – This will return the value associated with a specified key in this Java hashmap.
- put(Object KEY, String VALUE) – This method stores the specified value and associates it with the specified key in this map.
Java Hashmap Example
Following is a sample implementation of java Hash Map:import java.util.HashMap; import java.util.Map; public class Sample_TestMaps{ public static void main(String[] args){ Map<String, String> objMap = new HashMap<String, String>(); objMap.put("Name", "Suzuki"); objMap.put("Power", "220"); objMap.put("Type", "2-wheeler"); objMap.put("Price", "85000"); System.out.println("Elements of the Map:"); System.out.println(objMap); } }
Output:
Elements of the Map: {Type=2-wheeler, Price=85000, Power=220, Name=Suzuki}
Example 2: Remove a value from HashMap based on key
import java.util.*; public class HashMapExample { public static void main(String args[]) { // create and populate hash map HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put(1,"Java"); map.put(2, "Python"); map.put(3, "PHP"); map.put(4, "SQL"); map.put(5, "C++"); System.out.println("Tutorial in Guru99: "+ map); // Remove value of key 5 map.remove(5); System.out.println("Tutorial in Guru99 After Remove: "+ map); } }
Output:
Tutorial in Guru99: {1=Java, 2=Python, 3=PHP, 4=SQL, 5=C++} Tutorial in Guru99 After Remove: {1=Java, 2=Python, 3=PHP, 4=SQL}
Lets us ask a few queries to the Hash Map itself to know it better
Q: So Mr.Hash Map, how can I find if a particular key has been assigned to you?
A: Cool, you can use the containsKey(Object KEY) method with me, it will return a Boolean value if I have a value for the given key.
Q: How do I find all the available keys that are present on the Map?
A: I have a method called as keyset() that will return all the keys on the map. In the above example, if you write a line as – System.out.println(objMap.keySet());
It will return an output as-
[Name, Type, Power, Price]
Similarly, if you need all the values only, I have a method of values().
System.out.println(objMap.values());
It will return an output as-
[Suzuki, 2-wheeler, 220, 85000]
Q: Suppose, I need to remove only a particular key from the Map, do I need to delete the entire Map?
A: No buddy!! I have a method of remove(Object KEY) that will remove only that particular key-value pair.
Q: How can we check if you actually contain some key-value pairs?
A: Just check if I am empty or not!! In short, use isEmpty() method against me ;)