Java Tricks
Java Tricks
Java Tricks
toLowerCase();
2. While creating function always create outside the main function by using public static return
type function name
3. To get the ith index of string use str.chatAt(i)
4. To get the length of string use str.length() and for array use arr.length
5. To convert a char to int use : int p = Integer.parseInt(String.valueOf(s.charAt(i)));
6. Array declaration
int n=s.length();
int [][]t=new int[n][n];
to get the max and min use Math.max(a,b);
7. String str = "chandrabhushan"; // Convert string to a character array char[] charArray =
str.toCharArray(); // Sort the character array Arrays.sort(charArray);
8. To check weather a charestor is int or not use Charecter.isDigit(ch);
9. Arrays.toString() is a static method in the java.util.Arrays class that provides a simple way to print
an array in a human-readable format. Instead of printing the memory reference of the array, it
converts the elements of the array into a string representation.
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(numbers)); // op: [1, 2, 3, 4, 5]
10. To sort the array using opposite way we can use:
Coparator.reverseOrder();
i.e : Collections.sort(list,Comparator.reverseOrder());
double d = 123.4567;
System.out.format("%.3f\n", d);
d = Double.parseDouble(formatted);
System.out.println(d);
BigInteger b,a;
b = BigInteger.valueOf(4);
a = BigInteger.valueOf(6);
System.out.println(b);
BigInteger c = b.add(a);
BigInteger d = a.multiply(b);
System.out.println(d);
System.out.println(c);
Arrays Class
Commonly Used Methods in the Arrays Class
Sorting Arrays:
Arrays.sort(array, fromIndex, toIndex): Sorts the specified range of the array into ascending
order.
Searching Arrays:
Arrays.binarySearch(array, key): Searches the specified array for the specified value using the
binary search algorithm. The array must be sorted.
Filling Arrays:
Arrays.fill(array, value): Assigns the specified value to each element of the specified array.
Arrays.fill(array, fromIndex, toIndex, value): Assigns the specified value to each element of the
specified range of the array.
Copying Arrays:
Arrays.copyOf(original, newLength): Copies the specified array, truncating or padding with zeros
(if necessary) so the copy has the specified length.
Arrays.copyOfRange(original, from, to): Copies the specified range of the specified array into a
new array.
Comparing Arrays:
Arrays.equals(array1, array2): Returns true if the two specified arrays are equal to one another.
Arrays.deepEquals(array1, array2): Returns true if the two specified arrays are deeply equal to
one another (used for nested arrays).
Collections.shuffle(list);
Collections.reverse(list);
Collections.fill(list, "Date");
2. Stack
push(element): Adds an element to the top of the stack.
pop(): Removes and returns the top element of the stack. Throws an EmptyStackException if the stack
is empty.
peek(): Returns the top element without removing it. Also throws an EmptyStackException if empty.
isEmpty(): Checks if the stack is empty, returning true if so, and false otherwise.
search(object): Searches for an element and returns its 1-based position from the top. Returns -1 if the
element isn’t found.
3. Queue
Queue<Integer> queue = new LinkedList<>();
add(element): Inserts an element at the end of the queue. Throws an exception if the queue
is full.
offer(element): Similar to add, but returns false if the queue is full rather than throwing an
exception.
remove(): Removes and returns the front element. Throws a NoSuchElementException if the
queue is empty.
poll(): Removes and returns the front element, or returns null if the queue is empty.
peek(): Retrieves, but does not remove, the front element. Returns null if the queue is empty.
element(): Similar to peek(), but throws a NoSuchElementException if the queue is empty.
4. PriorityQueue
Min-heap: PriorityQueue<Integer> pq = new PriorityQueue<>();
Max-heap: PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
add(element) / offer(element): Inserts an element into the queue in the correct order.
peek(): Retrieves, but does not remove, the head of the queue (smallest or highest-priority element).
poll(): Retrieves and removes the head of the queue. Returns null if the queue is empty.
5. ArrayDeque
1. Adding Elements
addFirst(E e): Adds the specified element at the front of the deque.
addLast(E e): Adds the specified element at the end of the deque.
offerFirst(E e): Inserts the element at the front; returns true if successful, false if not.
offerLast(E e): Inserts the element at the end; returns true if successful, false if not.
push(E e): Adds the element at the front of the deque (for stack functionality).
offer(E e): Adds the element to the end (same as offerLast).
2. Removing Elements
removeFirst(): Removes and returns the first element. Throws an exception if the deque is
empty.
removeLast(): Removes and returns the last element. Throws an exception if the deque is empty.
pollFirst(): Removes and returns the first element, or returns null if the deque is empty.
pollLast(): Removes and returns the last element, or returns null if the deque is empty.
pop(): Removes and returns the first element (for stack functionality). Throws an exception if the
deque is empty.
poll(): Removes and returns the first element (same as pollFirst).
3. Accessing Elements
getFirst(): Retrieves, but does not remove, the first element. Throws an exception if the deque is
empty.
getLast(): Retrieves, but does not remove, the last element. Throws an exception if the deque is
empty.
peekFirst(): Retrieves, but does not remove, the first element, or returns null if the deque is
empty.
peekLast(): Retrieves, but does not remove, the last element, or returns null if the deque is
empty.
peek(): Retrieves, but does not remove, the first element (same as peekFirst).
4. Checking Elements
contains(Object o): Checks if the deque contains the specified element, returning true if it does,
false otherwise.
isEmpty(): Checks if the deque is empty, returning true if it has no elements, false otherwise.
6. Set
Set<String> hashSet = new HashSet<>();
Set<String> treeSet = new TreeSet<>();
Set<String> linkedHashSet = new LinkedHashSet<>();
Types of Sets in Java
1. HashSet:
o Does not maintain any order of elements.
o Allows null elements.
o Fastest for basic operations (add, remove, contains).
o Backed by a hash table, so the order is unpredictable.
2. LinkedHashSet:
o Maintains insertion order.
o Allows null elements.
o Slightly slower than HashSet due to the ordering overhead.
o Useful when you need a set that keeps elements in the order they were added.
3. TreeSet:
o Maintains elements in sorted (ascending) order.
o Does not allow null elements.
o Implements NavigableSet and is backed by a Red-Black tree.
o Useful when you need elements to be sorted automatically
Traversing hashSet
or
while (iterator.hasNext()) {
System.out.println(fruit);
7. Map
Map<String, Integer> map = new HashMap<>();
// Adding key-value pairs to the HashMap map.put("Apple", 10);
// Accessing values based on keys System.out.println("Value for key 'Apple': " +
map.get("Apple"));
// Checking if a key exists if (map.containsKey("Banana")) { System.out.println("The
map contains key 'Banana'."); }
// Iterating over the map for (Map.Entry<String, Integer> entry : map.entrySet())
{ System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); }
// Removing a key-value pair map.remove("Orange");
// Size of the map System.out.println("Size of the map: " + map.size());
map.put("Banana", 20);
Set<String> keys = map.keySet();
System.out.println("Keys: " + keys); // Output: Keys: [Apple, Banana]
map.replace("Apple", 15);
System.out.println(map.get("Apple")); // Output: 15
map.getOrDefault is a method in Java’s Map interface that allows you to retrieve the
value associated with a specific key, or return a default value if the key doesn’t exist in
the map. This can be useful to avoid NullPointerException or needing to check for the
key’s existence before accessing it.
Map<String, Integer> map = new HashMap<>(); map.put("apple", 3);
map.put("banana", 2); // Existing key int appleCount = map.getOrDefault("apple",
0); // Returns 3 System.out.println("Apple count: " + appleCount); // Non-existing key
int orangeCount = map.getOrDefault("orange", 0);