Java Cheat Sheet and Common Int. Questions Flashcards
- Cover all of Java basic syntax and concepts - Cover common Java int. questions
What are all of the ways to compare a String in Java?
There are many ways to compare two Strings in Java:
Using == operator Using equals() method Using compareTo() method [Comparable interface compares values and returns an int, these int values may be less than, equal, or greater than 0] Using compareToIgnoreCase() method Using compare() method
Note: String is immutable in java. When two or more objects are created without new keyword, then both objects reference the same value. Double equals operator actually compares objects references, so should only be used for reference checking.
Thus, it’s highly preferable to use equals() or compareTo() when you want to check for value only for strings.
What is Reflection in Java? What are the most common Reflection methods?
Reflection
How do you convert an int[] or char[] to a String in Java?
How do you convert a String of numbers to int?
What about to an Integer?
What about Integer or int converted to a String?
//Primitive Array of int or char to a String: int[] arr = new int[] {2,3,4,5}; String s = Arrays.toString(arr);
//String of numbers to int: String nums = "12345"; int i = Integer.parseInt(nums);
//String of numbers to Integer Integer j = Integer.valueOf(nums);
//Integer and int converted to a string int k = 234; Integer r = 567; String s = String.valueOf(k); String s2 = String.valueOf(r);
How do you create a List in Java WITHOUT using add to manually add in each value?
//Option 1: List words = Arrays.asList("pen", "custom", "orphanage", "forest", "bubble", "butterfly");
//Option 2: List ints = new ArrayList(List.of(1,2,3));
Use Java streams to convert an ArrayList of Integer to a primitive int[], and then from primitive int[] to ArrayList
What about String? ArrayList of String to String[] and String[] to ArrayList of String? Without stream and with streams.
//Use stream to convert int[] to AL:
int[] ints = new int[] {1,2,3,4,5};
ArrayList ints_al = Arrays.stream(ints)
.boxed()
.collect(Collectors.toCollection(ArrayList::new));
//Convert from ArrayList to int[] ArrayList al3 = new ArrayList(List.of(1,2,3)); int[] converted = al3.stream().mapToInt(v -> v).toArray();
//Convert ArrayList to String[]: no stream ArrayList names = new ArrayList(List.of("Someone","You","Know")); String[] prim_names = names.toArray(new String[names.size()]);
//Convert ArrayList to String[] using streams: String[] prim_names2 = names.stream().toArray(String[]::new); Arrays.stream(prim_names2).forEach(s2 -> System.out.print(s2 + " "));
//Convert String[] to ArrayList using stream: String[] oldarr = new String[] {"Who","is","this"}; ArrayList newarr = Arrays.stream(oldarr).collect(Collectors.toCollection(ArrayList::new));
Convert an ArrayList of Integer to int[] using streams.
Bonus: How do you print a primitive array using streams?
//Use stream to convert ArrayList to int[] ArrayList al2 = new ArrayList(); al2.add(6); al2.add(7); al2.add(8); int[] prim_al2 = al2.stream().mapToInt(v -> v).toArray();
//Print primitive array using streams: Arrays.stream(prim_al2).forEach(i -> System.out.print(i + " "));
//Print array without using stream: System.out.println(Arrays.toString(prim_al2));
How do you print an int[] using forEach?
How do you print an ArrayList using forEach?
int[] numbs = new int[] {1,2,3,4,5};
Arrays.stream(numbs).forEach(i -> System.out.print(i + “ “));
ArrayList al3 = new ArrayList(List.of(5,4,3,2,1)); al3.forEach(j -> System.out.print(j))
Highest value from HashMap using streams?
Bonus: What about using a loop?
Answer
Highest key from a HashMap using streams?
Bonus: What about using a loop?
Answer
Key based on the highest value in a HashMap using streams
Bonus: Do it using a loop.
Answer
What are the three major ways to loop over an array in Java?
Bonus: What about an ArrayList ?
int[] nums = new int[10];
//Way #1: while loop int i = 0; while(i < nums.length) { nums[i] = i; i++; }
//#2 for loop: for(int j = 0; j < nums.length; j++) { nums[j] = j; }
//Way #3: stream with forEach Arrays.stream(arr).forEach(x -> ...);
//Bonus: For an ArrayList, regular for loop using .size() as the limit, enhanced.for loop, or stream.
Palindrome
Answer
FizzBuzz
Answer
Reverse a linked list
Answer
How do you print the Java version and specification version to the console?
System.out.println(“Your Java version: “);
System.out.println(System.getProperty(“java.version”));
System.out.println(System.getProperty(“java.specification.version”));
How do you take input from the console in Java?
Scanner my_scan = new Scanner(System.in); String my_str = my_scan.nextLine();
What is the easiest way to reverse a String in Java?
String input = “something”;
String input = "Geeks for Geeks"; StringBuilder sb = new StringBuilder(); sb.append(input); sb.reverse(); String reversed = sb.toString(); System.out.println(reversed);
Convert a String to a StringBuilder and then to an int and an Integer:
//Convert String to StringBuilder to Integer String numbers ="123"; StringBuilder sb = new StringBuilder(numbers); int x = Integer.parseInt(sb.toString()); Integer y = Integer.valueOf(sb.toString()); System.out.println(x + '\n'); System.out.println(y + '\n');
How do you convert a String to a float in java?
Now, how do you round the float to 2 places?
What happens if the round does not need to be past two decimal places? How do you force the resultant String to have two decimal points? (Ie.4.99 -> 5.00)
import java.math.BigDecimal;
//Convert String to float: String N = "7132.1358"; float pf = Float.parseFloat(N); Float f = Float.valueOf(N);
//Round a float to certain decimal place: BigDecimal bd = new BigDecimal(N); bd = bd.setScale(2, BigDecimal.ROUND_HALF_EVEN); System.out.println(bd.floatValue());
//When round goes to .0 and does not need a second place, the above will not work once converted to a String. This code converts the BigDecimal to a String and then adds another 0:
String bds = bd.toString(); if(bds.substring(bds.length()-2,bds.length()).equals(".0")) { bds.concat("0"); }
How do you print a float to the console in Java?
Now, what about printing it to 2 decimal places?
(Hint: Actually a tricky question!)
float val = 5.12345f;
System.out.printf(Float.toString(val) + “\n”);
System.out.printf(“%.2f”, val);
//Trick: Use Float.toString() is good practice when you don’t want any rounding.
Name the most common methods of StringBuilder / StringBuffer class.
Why do we use StringBuilder?
Which one is synchronized?
Bonus: How do you create a String from a char[] and a char[] from a String ?
StringBuilder append(X x) //VERY COMMON char charAt(int index) IntStream chars() StringBuilder delete(int start, int end) //COMMON int indexOf() //VERY COMMON int lastIndexOf() StringBuilder replace(int start, int end, String str) StringBuilder reverse() String substring() String toString() //VERY COMMON Int length() //VERY COMMON
StringBuilder and StringBuffer are important because they are needed in Java since Strings are immutable. They provide a way to have a directly mutable character sequence.
StringBuffer is synchronized while StringBuilder is not synchronized. This results in a small performance hit for using StringBuffer but it should get used in multithreaded code.
//Bonus: String convertme = "convertme"; char[] converted = convertme.toCharArray(); String convertedback = Arrays.toString(converted);
Convert an ArrayList of Integer to a primitive int[] using Java streams.
Convert an ArrayList of Strings to String[] with and without streams.
//Use stream to convert an ArrayList of Integers to int[] ArrayList al2 = new ArrayList(); al2.add(6); al2.add(7); al2.add(8); int[] prim_al2 = al2.stream().mapToInt(v -> v).toArray();
//SAY OUT LOUD TWICE: “To covert an ArrayList of Integer to a primitive array with streams, use mapToInt then toArray.”
//Convert ArrayList of String to String[]: no stream ArrayList names = new ArrayList(List.of("Someone","You","Know")); String[] prim_names = names.toArray(new String[names.size()]);
//Convert ArrayList of String to String[] using streams: String[] prim_names2 = names.stream().toArray(String[]::new);
Show some of the most common Arrays utility methods in Java.
//Arrays utility methods given a PRIMITIVE array:
Arrays.sort(arr, Comparator);
Arrays.equals(arr1,arr2);
newarr = Arrays.copyOf(oldarr,oldarr.length);
Arrays.fill(arr,val,start,end);
String s = Arrays.toString(arr);
newarr = Arrays.copyOfRange(oldarr,from,to);
ArrayList x = Arrays.asList(arr);
Name the most common ArrayList utility methods in Java.
Answer
Invert a Binary Tree: Based on TreeNode root
public TreeNode invertTree(TreeNode root) { if(root==null){ return root; } invertTree(root.left); invertTree(root.right); TreeNode t = root.left; root.left = root.right; root.right = t; return root; }
Formula to find all prime numbers M <= N:
Recommendation: Make an isPrime method to handle the inner loop.
class Dcoder { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int M = Integer.parseInt(sc.next()); int N = Integer.parseInt(sc.next()); while(M <= N) { if(isPrime(M)) { System.out.println(M); } M++; } } static boolean isPrime(int M) { if(M ==0 || M == 1) { return false; } int k = 2; while(k < M) { if(M%k == 0) { return false; } k++; } return true; } }
What is the easiest way to reverse a primitive array in Java?
What about ArrayList?
//Reverse a primitive array Collections.reverse(Arrays.asList(myArray)); // Note this will return a List so needs to be converted back to primitive array.
//Reverse an ArrayList or List Collections.reverse(myArray);
How do you sort an array in reverse?
What about sorting in reverse while using streams?
Answer
What is a functional interface?
Name the most common functional interfaces in Java.
Anser
Remove Duplicates in 4 Different Ways in Java:
Hint: Set, Stream, For loop + HashMap, in-place algorithm
Answer
Explain what a Set is and give some code examples for the most common methods in a Set.
“The set interface is present in the java.util package and extends the Collection interface. It is used when you want an unordered collection where there are no duplicates.”
//Set most common: add, remove, removeAll, retainAll, size, toArray, equals, contains, iterator
Set s = new HashSet(); s.add("Geeks"); s.add("Geeks"); s.add("Example"); s.add("Example"); Set a = new HashSet(); a.addAll(Arrays.asList( new Integer[] { 1, 3, 2, 4, 8, 9, 0 })); Iterator i = s.iterator(); while (i.hasNext()) System.out.println(i.next());
How do you Reverse an array in Java? What about an ArrayList?
//Reversal of order in Java:
Collections.reverse(listOfProducts);
Collections.reverse(Arrays.asList(arr));
How do you Reverse an array in Java? What about an ArrayList?
Collections.reverse(listOfProducts);
Collections.reverse(Arrays.asList(arr));
//NOTE: Does not SORT the array, just reverses order
How do you SORT an array in reverse order?
BONUS: Sort it in reverse order using Java 8+ streams:
Arrays.sort(arr_integer, Collections.reverseOrder());
//using streams:
list = list.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
Explain the most common methods and classes under the Tree interface in Java.
Answer
Explain inner classes with code examples in Java.
HINT: There are 3 types
Answer
Explain Java Optionals and give some code examples.
Answer
Explain the Stack interface in Java and give some code examples of its most common methods.
Answer
Explain LinkedList in Java and give some code examples.
Answer
Explain the Map Interface in Java and give some code examples of its most common methods.
Answer
Explain how to measure performance in Java while showing a code example of it.
Answer
Primitive data types in Java: there are 8
byte short int long float double boolean char
What are the most common Collections interfaces in Java?
What are the most common Collections classes in java?
Map, List, Set, Queue
ArrayList, HashSet, HashMap, TreeSet, LinkedList, PriorityQueue
How do you iterate through a HashMap in Java?
BONUS: What about in reverse order (assuming it’s ordered)?
Iterate thru HashMap in Java
How do you print a double with precision amount?
print a double
How do you convert an int, double, or float to a String in Java?
BONUS: What about converting a string to an int, double, or float?
s
How do you convert a String into an Integer? What about primitive int?
How do you convert these back into String?
package Stuff;
public class Playground { public static void main(String[] args) { //Converting String to int and Integer String xyz = "123"; Integer xyz_Integer = Integer.valueOf(xyz); int xyz_int = Integer.parseInt(xyz); System.out.println("int is = " + String.valueOf(xyz_int)); System.out.println("Integer is equal to = " + xyz_Integer.toString()); } }
How do you find the number of bits in an integer in Java?
BONUS: How do you convert an integer to it’s binary String equivalent?
import java.lang.Integer; public class BitCounting { public static int countBits(int n){ return Integer.bitCount(n); } }
//BONUS: int a = 10; System.out.println(Integer.toBinaryString(a));