In this blog post we look at the common Java code snippets that are useful during interview preperation.
1.#
public class Learn {
public static void main(String[] args) {
// adds ascii int of characters
System.out.println('a' + 'b');
}
}
Output
195
2.#
public class Learn {
public static void main(String[] args) {
// concats as string
System.out.println("hello" + 90 + 100);
}
}
Output
hello90100
3.#
public class Learn {
public static void main(String[] args) {
// adds the integer and then concats
System.out.println(90 + 100 + "hello");
}
}
Output
190hello
4.#
4.1 Reverse a string using charAt#
public class Learn {
public static void main(String[] args) {
String s = "abcdef";
String r = "";
for (int i = 0; i < s.length(); i++) {
// prepend each character
r = s.charAt(i) + r;
}
System.out.println(r);
}
}
Output
fedcba
4.2 Reverse a string using character array#
public class Learn {
public static void main(String[] args) {
String s = "abcdef";
// using toCharArray to copy elements to char array
char[] arr = s.toCharArray();
for (int i = arr.length - 1; i >= 0; i--)
System.out.print(arr[i]);
}
}
Output
fedcba
4.3 Reverse a string using Collections API#
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class Learn {
public static void main(String[] args) {
String s = "abcdef";
// copying elements to character array
char[] arr = s.toCharArray();
// creating new ArrayList
List<Character> l = new ArrayList<>();
// adding char elements to ArrayList
for (char c : arr)
l.add(c);
// Reversing the ArrayList
Collections.reverse(l);
// converting ArrayList to string
String res = l.stream().map(String::valueOf).collect(Collectors.joining());
System.out.println(res);
}
}
Output
fedcba
4.4 Reverse a string using Stack data type#
import java.util.Stack;
public class Learn {
public static void main(String[] args) {
String s = "abcdef";
// initializing a stack of type char
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
// pushing all the characters
stack.push(c);
}
String res = "";
while (!stack.isEmpty()) {
// popping all the chars and appending to temp
res += stack.pop();
}
System.out.println(res);
}
}
Output
fedcba
5.#
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Learn {
public static void main(String[] args) {
List<Employee> em = new ArrayList<>(Arrays.asList(new Employee("Raj", 30), new Employee("Anthony", 45),
new Employee("Zeba", 29), new Employee("Philip", 30), new Employee("Anish", 25)));
List<Employee> sorted = em.stream()
.sorted(Comparator.comparing(Employee::getName).thenComparing(Employee::getAge)).toList();
System.out.println(sorted);
}
}
class Employee {
private String name;
private int age;
public Employee() {
}
public Employee(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "(" + name + ", " + age + ")";
}
}
Output
[(Anish, 25), (Anthony, 45), (Philip, 30), (Raj, 30), (Zeba, 29)]
6.#
public class Learn {
public static void main(String[] args) {
String str1 = "Scaler";
String str2 = "Scaler";
String str3 = new String("Scaler");
// str1 and str2 refer to same literal in the string pool
System.out.println(str1 == str2);
// str1 and str3 have same content but refer to different literal in the heap memory
System.out.println(str1 == str3);
// checks if the content is same
System.out.println(str1.equals(str3));
}
}
Output
true
false
true
7.#
public class Learn {
public static void main(String[] args) {
Integer num1 = 100;
Integer num2 = 100;
Integer num3 = 500;
Integer num4 = 500;
if (num1 == num2) {
System.out.println("num1 == num2");
} else {
System.out.println("num1 != num2");
}
// Java specification states values between -127 and 127 are cached. Since 500
// is outside this range they refer to two different objects. Compare with
// intValue().
if (num3 == num4) {
System.out.println("num3 == num4");
} else {
System.out.println("num3 != num4");
}
}
}
Output
num1 == num2
num3 != num4
8.#
public class Learn {
public static void main(String[] args) {
try {
System.out.println("try block executed");
System.exit(0);
} catch (Exception exception) {
System.out.println("catch block executed");
} finally {
System.out.println("finally block executed");
}
}
}
Output
Try block executed
9.#
public class Learn {
public static void main(String[] args) {
Execute e = new Execute();
System.out.println(e.run());
}
}
class Execute {
String run() {
try {
System.out.println("in try");
return "data from try";
} catch (Exception exception) {
System.out.println("in catch");
return "data from catch";
} finally {
System.out.println("in finally");
return "data from finally";
}
}
}
Output
in try
in finally
data from finally
10.#
public class Learn {
public static void main(String[] args) {
PersonDto person = new PersonDto("Alice", 30);
System.out.println("Name: " + person.name());
System.out.println("Age: " + person.age());
System.out.println(person);
}
}
record PersonDto(String name, int age) {
}
Output
Name: Alice
Age: 30
PersonDto[name=Alice, age=30]
- Group Anagram
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Learn {
public static void main(String[] args) {
String[] one = new String[] { "eat", "tea", "tan", "ate", "nat", "bat" };
String[] two = new String[] { "act", "god", "cat", "dog", "tac" };
String[] three = new String[] { "listen", "silent", "enlist", "abc", "cab", "bac", "rat", "tar", "art" };
Learn l = new Learn();
l.findGroupAnagram(one);
l.findGroupAnagram(two);
l.findGroupAnagram(three);
}
public void findGroupAnagram(String[] arr) {
// this integer array keeps tract of string in a group
int[] arrbuff = new int[arr.length];
List<List<String>> result = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
// result from a group
List<String> subRes = new ArrayList<>();
// if a string is already part of a group
if (arrbuff[i] == 1) {
continue;
}
char[] prim = arr[i].toCharArray();
for (int j = 0; j < arr.length; j++) {
char[] sec = arr[j].toCharArray();
// if a string is already part of a group
if (arrbuff[j] == 1) {
continue;
}
Arrays.sort(prim);
Arrays.sort(sec);
// check if strings are anagram
if (Arrays.equals(prim, sec)) {
subRes.add(arr[j]);
// ensures that anagram string is alread check to skip loop
arrbuff[j] = 1;
}
}
result.add(subRes);
}
System.out.println(result);
}
}
Output
[[eat, tea, ate], [tan, nat], [bat]]
[[act, cat, tac], [god, dog]]
[[listen, silent, enlist], [abc, cab, bac], [rat, tar, art]]
12.#
Java find sum of integers in array
import java.util.Arrays;
import java.util.List;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
// using mapToInt
int res = list.stream().mapToInt(i -> i.intValue()).sum();
System.out.println(res);
}
}
Output
405
13.#
Java find sum of integers in array with reduce()
import java.util.Arrays;
import java.util.List;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
int res = list.parallelStream().reduce(0, (a, b) -> a + b);
System.out.println(res);
}
}
Output
405
14.#
Java find average of integers in array
import java.util.Arrays;
import java.util.List;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
double res = list.stream().mapToInt(a -> a).average().orElse(0);
System.out.println(res);
}
}
Output
33.75
15.#
Given a list of numbers, square them and filter the numbers which are greater 100 and then find the average of them.
import java.util.Arrays;
import java.util.List;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
double res = list.stream().map(e -> e * e).filter(e -> e > 100).mapToInt(e -> e).average().orElse(0);
System.out.println(res);
}
}
Output
14310.0
16.#
Given a list of numbers, return the even and odd numbers separately.
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
// the condition true (number is even) is mapped to true
Map<Boolean, List<Integer>> result = list.stream().collect(Collectors.partitioningBy(n -> n % 2 == 0));
// even numbers
System.out.println(result.get(true));
System.out.println(result.get(false));
}
}
Output
[8, 2, 36, 4, 78, 222, 24]
[1, 7, 9, 5, 9]
17.#
Given a list of numbers, find out all the numbers starting with 2.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
List<Integer> res = list.stream().map(e -> String.valueOf(e)).filter(e -> e.startsWith("2"))
.map(e -> Integer.valueOf(e)).collect(Collectors.toList());
System.out.println(res);
}
}
Output
[2, 222, 24]
18.#
Given a list of numbers, print the duplicate numbers.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
Set<Integer> res = list.stream().filter(e -> Collections.frequency(list, e) > 1).collect(Collectors.toSet());
System.out.println(res);
}
}
Output
[9]
19.#
Given a list of numbers, print the maximum and minimum values.
import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
IntSummaryStatistics stats = list.stream().mapToInt(e -> e).summaryStatistics();
System.out.println("max " + stats.getMax());
System.out.println("min " + stats.getMin());
}
}
Output
max 222
min 1
20.#
Given a list of numbers, sort them in ASC order and print.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
List<Integer> res = list.stream().sorted(Comparator.naturalOrder()).toList();
System.out.println(res);
}
}
Output
[1, 2, 4, 5, 7, 8, 9, 9, 24, 36, 78, 222]
21.#
Given a list of numbers, sort them in DESC order and print.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
List<Integer> res = list.stream().sorted(Comparator.reverseOrder()).toList();
System.out.println(res);
}
}
Output
[222, 78, 36, 24, 9, 9, 8, 7, 5, 4, 2, 1]
22.#
Given a list of numbers, return the first 5 elements and their sum.
import java.util.Arrays;
import java.util.List;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
int res = list.stream().limit(5).mapToInt(e -> e).sum();
System.out.println(res);
}
}
Output
30
23.#
Given a list of numbers, skip first 5 numbers and return the sum of remaining numbers.
import java.util.Arrays;
import java.util.List;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
int res = list.stream().skip(5).reduce(0, (subRes, e) -> subRes + e);
System.out.println(res);
}
}
Output
375
24.#
import java.util.Arrays;
import java.util.List;
public class Learn {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 7, 8, 9, 5, 2, 36, 4, 78, 222, 24, 9);
List<Integer> res = list.stream().map(e -> Math.powExact(e, 3)).toList();
System.out.println(res);
}
}
Output
[1, 343, 512, 729, 125, 8, 46656, 64, 474552, 10941048, 13824, 729]
