Java Cheat Sheet and Common Int. Questions Flashcards

- Cover all of Java basic syntax and concepts - Cover common Java int. questions

1
Q

What are all of the ways to compare a String in Java?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is Reflection in Java? What are the most common Reflection methods?

A

Reflection

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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?

A
//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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you create a List in Java WITHOUT using add to manually add in each value?

A
//Option 1:
List words = Arrays.asList("pen", "custom", "orphanage", "forest", "bubble", "butterfly");
//Option 2:
List ints = new ArrayList(List.of(1,2,3));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

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.

A

//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));
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Convert an ArrayList of Integer to int[] using streams.

Bonus: How do you print a primitive array using streams?

A
//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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you print an int[] using forEach?

How do you print an ArrayList using forEach?

A

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))
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Highest value from HashMap using streams?

Bonus: What about using a loop?

A

Answer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Highest key from a HashMap using streams?

Bonus: What about using a loop?

A

Answer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Key based on the highest value in a HashMap using streams

Bonus: Do it using a loop.

A

Answer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the three major ways to loop over an array in Java?

Bonus: What about an ArrayList ?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Palindrome

A

Answer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

FizzBuzz

A

Answer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Reverse a linked list

A

Answer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you print the Java version and specification version to the console?

A

System.out.println(“Your Java version: “);
System.out.println(System.getProperty(“java.version”));
System.out.println(System.getProperty(“java.specification.version”));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you take input from the console in Java?

A
Scanner my_scan = new Scanner(System.in);
String my_str = my_scan.nextLine();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the easiest way to reverse a String in Java?

String input = “something”;

A
String input = "Geeks for Geeks"; 
StringBuilder sb = new StringBuilder(); 
sb.append(input); 
sb.reverse();
String reversed = sb.toString();
System.out.println(reversed);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Convert a String to a StringBuilder and then to an int and an Integer:

A
//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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

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)

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

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!)

A

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.

21
Q

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 ?

A
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);
22
Q

Convert an ArrayList of Integer to a primitive int[] using Java streams.

Convert an ArrayList of Strings to String[] with and without streams.

A
//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);
23
Q

Show some of the most common Arrays utility methods in Java.

A

//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);

24
Q

Name the most common ArrayList utility methods in Java.

A

Answer

25
Q

Invert a Binary Tree: Based on TreeNode root

A
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;
}
26
Q

Formula to find all prime numbers M <= N:

Recommendation: Make an isPrime method to handle the inner loop.

A
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;
   }
 }
27
Q

What is the easiest way to reverse a primitive array in Java?

What about ArrayList?

A
//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);
28
Q

How do you sort an array in reverse?

What about sorting in reverse while using streams?

A

Answer

29
Q

What is a functional interface?

Name the most common functional interfaces in Java.

A

Anser

30
Q

Remove Duplicates in 4 Different Ways in Java:

Hint: Set, Stream, For loop + HashMap, in-place algorithm

A

Answer

31
Q

Explain what a Set is and give some code examples for the most common methods in a Set.

A

“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());
32
Q

How do you Reverse an array in Java? What about an ArrayList?

A

//Reversal of order in Java:
Collections.reverse(listOfProducts);
Collections.reverse(Arrays.asList(arr));

33
Q

How do you Reverse an array in Java? What about an ArrayList?

A

Collections.reverse(listOfProducts);
Collections.reverse(Arrays.asList(arr));

//NOTE: Does not SORT the array, just reverses order

34
Q

How do you SORT an array in reverse order?

BONUS: Sort it in reverse order using Java 8+ streams:

A

Arrays.sort(arr_integer, Collections.reverseOrder());

//using streams:
list = list.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());

35
Q

Explain the most common methods and classes under the Tree interface in Java.

A

Answer

36
Q

Explain inner classes with code examples in Java.

HINT: There are 3 types

A

Answer

37
Q

Explain Java Optionals and give some code examples.

A

Answer

38
Q

Explain the Stack interface in Java and give some code examples of its most common methods.

A

Answer

39
Q

Explain LinkedList in Java and give some code examples.

A

Answer

40
Q

Explain the Map Interface in Java and give some code examples of its most common methods.

A

Answer

41
Q

Explain how to measure performance in Java while showing a code example of it.

A

Answer

42
Q

Primitive data types in Java: there are 8

A
byte	
short	
int
long	
float	
double	
boolean
char
43
Q

What are the most common Collections interfaces in Java?

What are the most common Collections classes in java?

A

Map, List, Set, Queue

ArrayList, HashSet, HashMap, TreeSet, LinkedList, PriorityQueue

44
Q

How do you iterate through a HashMap in Java?

BONUS: What about in reverse order (assuming it’s ordered)?

A

Iterate thru HashMap in Java

45
Q

How do you print a double with precision amount?

A

print a double

46
Q

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?

A

s

47
Q

How do you convert a String into an Integer? What about primitive int?

How do you convert these back into String?

A

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());
  }
 }
48
Q

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?

A
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));