Arrays.asList()List.of() (Java 9+)Collections.addAll()Collections.singletonList()addAll() Method after Initializationput Method)remove Method)get Method)containsKey and containsValue)size Method)contains)clear Method)isEmpty Method)Here’s how you can perform these type conversions in Java:
To convert a char to an int, you can simply assign it or cast it to int. The ASCII (or Unicode) value of the character will be used as the integer value.
char ch = 'A';
int intValue = ch; // Implicit conversion
// or
int intValueExplicit = (int) ch; // Explicit casting
System.out.println(intValue); // Output: 65 (ASCII value of 'A')
To convert a float to an int, you need to use casting. This will truncate the decimal portion, so the result will be the integer part only.
float floatValue = 9.99f;
int intValue = (int) floatValue; // Explicit casting
System.out.println(intValue); // Output: 9
To convert an int to a char, you can cast it directly. The integer value will be interpreted as a Unicode (or ASCII) character.
int intValue = 65;
char ch = (char) intValue; // Explicit casting
System.out.println(ch); // Output: 'A' (character with ASCII value 65)
To convert an int to a float, you can assign it directly, as this is an implicit widening conversion.
int intValue = 10;
float floatValue = intValue; // Implicit conversion
System.out.println(floatValue); // Output: 10.0
Here’s how you can perform these conversions in Java:
float floatValue = 3.14f;
String floatToString = Float.toString(floatValue);
// or
String floatToString2 = String.valueOf(floatValue);
String str = "3.14";
float stringToFloat = Float.parseFloat(str);
int intValue = 42;
String intToString = Integer.toString(intValue);
// or
String intToString2 = String.valueOf(intValue);
String str = "42";
int stringToInt = Integer.parseInt(str);
To get a single character from a string, you can use charAt(index):
String str = "Hello";
char stringToChar = str.charAt(0); // gets the first character 'H'
char ch = 'H';
String charToString = Character.toString(ch);
// or
String charToString2 = String.valueOf(ch);
These methods will help you convert between these common types easily.
To convert a float to two decimal places in Java, you can use any of the following methods:
String.formatfloat number = 3.14159f;
String formatted = String.format("%.2f", number);
System.out.println(formatted); // Output: 3.14
System.out.printffloat number = 3.14159f;
System.out.printf("%.2f", number); // Output: 3.14
Math.roundYou can round the float to two decimal places by multiplying, rounding, and then dividing by 100:
float number = 3.14159f;
float rounded = Math.round(number * 100) / 100f;
System.out.println(rounded); // Output: 3.14
BigDecimal (Precise and Recommended for Calculations)BigDecimal is a good choice if you need exact rounding and precision.
float number = 3.14159f;
BigDecimal bd = new BigDecimal(Float.toString(number));
bd = bd.setScale(2, RoundingMode.HALF_UP);
System.out.println(bd); // Output: 3.14
float a = sc.nextFloat()*100;
int b = (int) a;
System.out.println(b/100.00);
Choose the method that best fits your needs. If you’re working with financial or high-precision data, BigDecimal is generally the best choice.
Here’s a comprehensive guide on initializing and using the String class in Java, along with an explanation of relevant methods such as insert, delete, get, search, iterate, size, contains, clear, isEmpty, and sort. I’ll cover each operation in detail and how it applies to strings in Java, totaling over 1000 words.
String Class in JavaIn Java, String is a built-in class that represents a sequence of characters. Strings are objects, not primitive types, and are immutable. Once created, the characters of a string cannot be changed. This immutability provides advantages, such as thread safety, but also requires extra care when performing operations that might alter the content of a String. For situations requiring modification, Java provides classes like StringBuilder and StringBuffer.
String str = "Hello, World!";.new Keyword: Alternatively, you can use the new keyword: String str = new String("Hello, World!");.String str = "";.String str = new String(charArray);.Since String objects are immutable, Java doesn’t provide a direct insert method for String. However, if you need to insert text at a specific index within a string, you can use StringBuilder, which allows modifications.
StringBuilder builder = new StringBuilder("Hello!");
builder.insert(5, ", World");
String result = builder.toString(); // Result: "Hello, World!"
Similarly, the String class lacks a delete method. But with StringBuilder, you can delete characters at specified indices.
StringBuilder builder = new StringBuilder("Hello, World!");
builder.delete(5, 7); // Deletes ", "
String result = builder.toString(); // Result: "HelloWorld!"
The String class has several methods to access characters:
charAt(int index): Returns the character at the specified index.substring(int beginIndex, int endIndex): Returns a part of the string as a new string, from beginIndex (inclusive) to endIndex (exclusive).Example:
String str = "Hello, World!";
char ch = str.charAt(1); // 'e'
String subStr = str.substring(0, 5); // "Hello"
There are several ways to search within a String:
indexOf(String str): Returns the index of the first occurrence of the specified substring. If not found, it returns -1.lastIndexOf(String str): Returns the index of the last occurrence of the specified substring.contains(CharSequence s): Returns true if the string contains the specified sequence of characters.String str = "Hello, World!";
int index = str.indexOf("World"); // 7
boolean containsWorld = str.contains("World"); // true
Iterating over a String is commonly done in two ways:
charAt: Access each character by its index.char array: Use toCharArray() to get a char array and iterate.String str = "Hello";
for (int i = 0; i < str.length(); i++) {
System.out.print(str.charAt(i) + " ");
}
// Or using toCharArray
for (char c : str.toCharArray()) {
System.out.print(c + " ");
}
The length() method in String returns the number of characters in the string. This is the equivalent of size in other collections.
String str = "Hello, World!";
int length = str.length(); // 13
The contains method checks if a String contains a specific sequence of characters.
String str = "Hello, World!";
boolean containsHello = str.contains("Hello"); // true
While String is immutable, you can “clear” it by reassigning an empty string to it.
String str = "Hello, World!";
str = ""; // Clear the content
In mutable contexts, you may choose StringBuilder for a clear-like operation by setting its length to 0.
StringBuilder builder = new StringBuilder("Hello, World!");
builder.setLength(0); // Clears the content
The isEmpty() method checks if a string is empty (i.e., has no characters, length() == 0).
String str = "";
boolean isEmpty = str.isEmpty(); // true
Sorting a string means rearranging its characters in a specific order, typically alphabetical. This is not a direct method on String but can be achieved by converting the string to a character array, sorting it, and creating a new string.
String str = "edcba";
char[] charArray = str.toCharArray();
Arrays.sort(charArray);
String sortedStr = new String(charArray); // "abcde"
equals(String str) and equalsIgnoreCase(String str): Check if two strings are equal or equal regardless of case.toUpperCase() and toLowerCase(): Convert all characters to uppercase or lowercase.trim(): Removes leading and trailing whitespace.replace(CharSequence target, CharSequence replacement): Replaces all occurrences of a substring.For mutable strings, Java provides StringBuilder and StringBuffer classes, with StringBuilder being faster but not thread-safe, while StringBuffer is thread-safe.
String comparison in Java can be done using equals for exact matches or compareTo for lexicographical order.
String a = "Apple";
String b = "Banana";
int result = a.compareTo(b); // Negative if a < b, zero if a == b, positive if a > b
The String class in Java is foundational, and understanding these methods is essential for efficient and effective text manipulation in Java applications. Since strings are immutable, modifying a String often requires reassignment, or you can use StringBuilder for cases where mutability is needed.
In Java, there are several ways to initialize an ArrayList. Each approach varies depending on the situation and requirements, offering flexibility in how elements are added to the list. Here’s a rundown of the most common methods to initialize an ArrayList.
This is the most straightforward way to initialize an empty ArrayList.
ArrayList<String> list = new ArrayList<>();
You can initialize an ArrayList with a specified initial capacity. This is helpful if you know the approximate number of elements the list will contain, as it reduces the need for resizing.
ArrayList<String> list = new ArrayList<>(10); // Initial capacity of 10
Arrays.asList()You can initialize an ArrayList with a predefined list of elements using Arrays.asList(). However, this will return a fixed-size list, so you can’t add or remove elements from it without creating a new list.
ArrayList<String> list = new ArrayList<>(Arrays.asList("Apple", "Banana", "Grapes"));
List.of() (Java 9+)Introduced in Java 9, List.of() allows you to create an immutable list with elements. You can then pass this immutable list to an ArrayList constructor to get a mutable list with predefined elements.
ArrayList<String> list = new ArrayList<>(List.of("Apple", "Banana", "Grapes"));
This approach uses an anonymous inner class to initialize the ArrayList. Although concise, it’s generally discouraged due to performance and memory overhead.
ArrayList<String> list = new ArrayList<String>() ;
You can use Java 8 Streams to initialize an ArrayList by collecting stream elements.
ArrayList<String> list = Stream.of("Apple", "Banana", "Grapes")
.collect(Collectors.toCollection(ArrayList::new));
Collections.addAll()Collections.addAll() is a convenient way to initialize an ArrayList with multiple elements.
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "Apple", "Banana", "Grapes");
If you already have another collection (like a Set or another List), you can initialize an ArrayList with its elements.
List<String> existingList = List.of("Apple", "Banana", "Grapes");
ArrayList<String> list = new ArrayList<>(existingList);
Collections.singletonList()Collections.singletonList() creates a one-element list, which can then be used to initialize an ArrayList. Note that Collections.singletonList() itself returns an immutable list, so it’s passed as an argument to create a mutable ArrayList.
ArrayList<String> list = new ArrayList<>(Collections.singletonList("Apple"));
addAll() Method after InitializationAnother way to populate an ArrayList after initialization is by using the addAll() method. This can be done either from another collection or directly using Arrays.asList().
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList("Apple", "Banana", "Grapes"));
An ArrayList in Java is a resizable array implementation in the java.util package, which offers a flexible, easy-to-use alternative to traditional arrays. It is part of Java’s List interface and provides several powerful methods to handle elements dynamically, making it a popular choice when the number of elements in a list changes frequently. Here’s a detailed look at how to use ArrayList with various methods and operations, such as insert, delete, get, search, iterate, size, contains, clear, isEmpty, and sort.
Inserting elements into an ArrayList is straightforward, thanks to methods like add():
add(E element): Adds the specified element to the end of the ArrayList.add(int index, E element): Inserts the specified element at the specified position.ArrayList<String> list = new ArrayList<>();
list.add("Apple"); // Adds "Apple" at the end
list.add("Banana"); // Adds "Banana" at the end
list.add(1, "Grapes"); // Inserts "Grapes" at index 1
System.out.println(list); // Output: [Apple, Grapes, Banana]
The add() method shifts elements to accommodate the new element at the specified index, if given.
Removing elements from an ArrayList can be done by index or by specifying the object.
remove(int index): Removes the element at the specified index.remove(Object obj): Removes the first occurrence of the specified element.ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Grapes");
list.remove(1); // Removes "Banana"
System.out.println(list); // Output: [Apple, Grapes]
list.remove("Apple"); // Removes "Apple" by element
System.out.println(list); // Output: [Grapes]
Using the remove(int index) shifts subsequent elements to the left, reducing the list’s size by one.
Retrieving elements at a specific index in ArrayList is handled by the get() method.
get(int index): Returns the element at the specified position.ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Grapes");
String fruit = list.get(1); // Retrieves "Banana"
System.out.println(fruit); // Output: Banana
Attempting to access an out-of-bounds index will throw an IndexOutOfBoundsException.
To search for elements in an ArrayList, you can use contains() or indexOf().
contains(Object obj): Checks if the list contains the specified element.indexOf(Object obj): Returns the index of the first occurrence of the specified element, or -1 if the element is not found.ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
boolean hasApple = list.contains("Apple"); // true
int index = list.indexOf("Banana"); // 1
System.out.println(hasApple); // Output: true
System.out.println(index); // Output: 1
Java provides multiple ways to iterate through an ArrayList.
for loop: Use a basic for loop with get(int index).for loop: Easier syntax, especially for collections.Iterator methods.ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Grapes");
// Using basic for loop
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
// Using enhanced for loop
for (String fruit : list) {
System.out.println(fruit);
}
// Using Iterator
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
The size() method returns the number of elements in an ArrayList.
size(): Returns the number of elements in the list.ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
System.out.println(list.size()); // Output: 2
The contains() method is used to check if an element exists in the list.
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
boolean exists = list.contains("Apple"); // true
System.out.println(exists); // Output: true
The clear() method removes all elements from the list, effectively making it empty.
clear(): Removes all elements from the list.ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.clear();
System.out.println(list.size()); // Output: 0
System.out.println(list); // Output: []
The isEmpty() method checks if the list contains any elements.
ArrayList<String> list = new ArrayList<>();
System.out.println(list.isEmpty()); // true
list.add("Apple");
System.out.println(list.isEmpty()); // false
Sorting in an ArrayList can be done using Collections.sort() for natural ordering or a custom Comparator.
ArrayList<String> list = new ArrayList<>();
list.add("Banana");
list.add("Apple");
list.add("Grapes");
Collections.sort(list);
System.out.println(list); // Output: [Apple, Banana, Grapes]
// Custom sorting
Collections.sort(list, Collections.reverseOrder());
System.out.println(list); // Output: [Grapes, Banana, Apple]
ArrayList maintains an array that grows dynamically, which incurs a slight overhead during resizing operations.ArrayList allows random access with constant time complexity O(1), it is efficient for accessing elements. However, inserting and deleting at arbitrary positions may take longer due to shifting.ArrayList can store null elements. Be cautious when handling lists with nulls, as this can lead to NullPointerException.The ArrayList class is a flexible and powerful data structure in Java, offering a variety of methods for efficient storage, retrieval, and manipulation of data.
The HashMap class in Java is one of the most commonly used data structures in the Java Collections Framework (JCF). It provides a way to store and retrieve key-value pairs and operates on the principle of hashing. With a HashMap, you can store data in key-value format, which enables fast access, insertion, and deletion based on unique keys. Let’s dive deep into each of the essential operations provided by the HashMap class, including its initialization, methods for data manipulation, retrieval, and common operations like checking its size or whether it is empty.
To create a HashMap, you use the constructor to instantiate a new object of this class. Java provides a few constructors that let you initialize a HashMap with default settings or with custom initial capacities and load factors. Here’s how you can initialize a HashMap:
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
// Basic initialization
HashMap<String, Integer> map = new HashMap<>();
// Initializing with specified initial capacity and load factor
HashMap<String, Integer> customMap = new HashMap<>(16, 0.75f);
}
}
The initial capacity specifies the number of buckets in the hash table, and the load factor is a measure of how full the HashMap can get before its capacity is automatically increased. The default load factor is 0.75, meaning that when the map reaches 75% of its capacity, it will resize.
put Method)The put method in HashMap allows you to add new key-value pairs or update the value of an existing key. Here’s how you use it:
map.put("Apple", 10);
map.put("Banana", 20);
map.put("Cherry", 30);
If the key already exists, put will update the key with the new value, and it will return the old value. If the key does not exist, it will add a new entry to the map.
remove Method)The remove method lets you delete key-value pairs based on the key. It returns the value associated with the key that was removed or null if the key does not exist.
// Removing an element by key
map.remove("Banana");
You can also specify both the key and the value in the remove method. This variation will only remove the key if the value matches the specified value.
map.remove("Cherry", 30);
get Method)The get method allows you to retrieve the value associated with a specific key. If the key is not present, get returns null.
int appleCount = map.get("Apple"); // returns 10
You can also use getOrDefault if you want to specify a default value that should be returned when the key is not present:
int mangoCount = map.getOrDefault("Mango", 0); // returns 0 if "Mango" is not found
containsKey and containsValue)The containsKey method checks if a specific key exists in the HashMap, while containsValue checks for the presence of a specific value.
boolean hasApple = map.containsKey("Apple"); // returns true
boolean hasFifty = map.containsValue(50); // returns false
There are multiple ways to iterate through a HashMap. Some of the common ways are:
forEach with Lambda Expressionsmap.forEach((key, value) -> System.out.println(key + " -> " + value));
entrySetfor (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
keySet and valuesTo iterate through only the keys:
for (String key : map.keySet()) {
System.out.println("Key: " + key);
}
To iterate through only the values:
for (Integer value : map.values()) {
System.out.println("Value: " + value);
}
size Method)The size method returns the number of key-value pairs in the HashMap.
int size = map.size(); // returns the size of the map
contains)HashMap does not directly have a contains method, but it provides containsKey and containsValue as mentioned above.
clear Method)The clear method removes all elements from the HashMap. After calling clear, the HashMap will be empty, with a size of 0.
map.clear(); // removes all entries
isEmpty Method)The isEmpty method checks if there are any entries in the HashMap. It returns true if the map is empty, and false otherwise.
boolean empty = map.isEmpty(); // returns true if map is empty
Since HashMap does not maintain order, you cannot directly sort it. If you want to sort by keys or values, you can use a TreeMap (for natural key order) or sort the entries using Java Streams. Here’s how to sort a HashMap by keys:
import java.util.Map;
import java.util.TreeMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("Banana", 20);
map.put("Apple", 10);
map.put("Cherry", 30);
Map<String, Integer> sortedMap = new TreeMap<>(map);
Or, to sort by values, you can use streams:
map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.forEach(entry -> System.out.println(entry.getKey() + " -> " + entry.getValue()));
Java’s HashMap uses separate chaining and tree-binning techniques to resolve collisions (when two keys hash to the same bucket). When the number of entries in a bucket exceeds a threshold, it is converted from a linked list to a balanced tree, which improves performance for large numbers of collisions.
A HashMap is fail-fast, which means that if you try to modify the map while iterating through it (e.g., by using put or remove), a ConcurrentModificationException is thrown. This happens because HashMap uses a modCount variable to keep track of structural changes, ensuring safe iteration.
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getKey().equals("Banana")) {
map.remove("Banana"); // Throws ConcurrentModificationException
}
}
To safely remove elements while iterating, use an Iterator:
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
if (entry.getKey().equals("Banana")) {
iterator.remove(); // Safe removal
}
}
The average time complexity of a HashMap is as follows:
put): (O(1)) on average, (O(n)) in the worst case (during resizing).get): (O(1)) on average.remove): (O(1)) on average.In practice, HashMap is highly efficient for most scenarios, but performance can degrade if there are too many hash collisions.
In summary, HashMap in Java is a highly versatile and efficient data structure that enables the storage and retrieval of key-value pairs with optimal performance. Through methods like put, get, remove, containsKey, and others, it provides flexible and powerful mechanisms to handle data in a way that supports fast access and modification. However, be mindful of its fail-fast behavior and the potential need to handle sorting and collisions effectively.