Java Flashcards

1
Q

How do you reverse a String in Java? What can you check for using a reverse String?

A

You can use the addition operator to add onto a Java String.

Make a new String that is initialized like String reverse = “”; Then write a for loop that starts at the original String’s last index, which is original.length() - 1. Inside the loop, reverse = reverse + original.charAt(i);

Key functions for Java Strings: length(), charAt(), + can add onto a String, toCharArray(), toUpperCase(), toLowerCase(), etc.

Can check if a String is a palindrome.

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

Does a Java while loop terminate when the condition is false or at the end of the loop when the condition is false?

How is a do-while loop different than a while loop?

A

A Java while loop does not terminate as soon as the condition is false. It will wait till it is both false and the end of the loop is reached.

A do-while loop is different because it executes the statement before checking if the condition is false. This way, even if the condition is always false, it will execute the statement once, whereas a while loop by itself would never execute the statement since the condition was never true.

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

Explain the difference between Java int and Java Integer, Float, and Double. Are they type safe against each other?

A

Java Integer, Float, and Double are wrapper classes. The wrapper class provides functions for data manipulation, like converting from string to int with parseInt, converting to binary, hex, or octal, and performing various operations like rotations. The primitive int type also can’t be used in a Collections object like List or ArrayList.

All of these wrapper classes and the primitive int class are type safe, so you can add them all together, for example, even though they are different types.

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

How do you convert a String representation of a number to an int and to and Integer?

A

int i = Integer.parseInt(“123”)

Integer i = new Integer(“123”)

Floats work the same with Float(“123”)

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

How do you get and set values in a Java ArrayList?

A

Simply use array.get(index) to get a value at an index, and change a value at an index using array.set(index, newValue)

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

What is the syntax to declare a Java HashMap with key type Character and value type Integer? How would you loop through it? Can primitives be used with HashMaps?

A

Map<Character, Integer> map = new HashMap<>();

for (Map.Entry<Character, Integer> entry : map.entrySet()) {
Character c = entry.getKey();
Integer i = entry.getValue();
}

Also:

map.forEach((k, v) -> System.out.println(“key: “ + k + “ value: “ + v));

map.keySet().forEach(k -> System.out.println(“key: “ + k);
map.values().forEach(v -> System.out.println(“value: “ + v);

Primitives like int and char cannot be used with a Java Map. Only the wrapper classes.

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

What function would you use to check if a character existed in a Java String? What returns if it does exist? Doesn’t exist?

A

String s = “string”
int index = s.indexOf(‘t’);

indexOf() function returns the index of a specified character. It will return the index if it exists and -1 if it does not exist. Cannot equal null.

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

When comparing to Integers in Java, should you use .equals() or “==”?

A

Use .equals() for Integers. For whatever reason, the “==” operator will still view them as unequal even if the int they are wrapping is the same. (May be false, but experienced this in one case)

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

What Java function rounds a number down regardless of where it lands in the decimal range? Round up? What data type does this function return? Can it be used with other data types? How?

A

From the java.lang.Math.*; library,
Math.floor() rounds any non-whole number down. Math.ceil() rounds up. This returns a Double data type. However, if you cast it to an int, you can get an int back.

This is useful for the min heap implementation. To get a parent node, Math.floor((currentIdx - 1) / 2); This is essential as the value divided by two on the second child will have decimal .5, which rounds up by default.

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

What function gets a substring of a String in java? What are the parameters, and why must you be careful when assigning them?

A

String str = “hello there”;
str.substring(startIndex, endIndex);

Be careful with endIndex. The startIndex is inclusive, so range 0 to 4 includes the ‘h’ in “hello”. However, the endIndex is exclusive, so setting the range from 0 to 4 will only yield “hell”. You must add 1 to the endIndex to get what you want.

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

Can you use a Java stream more than once? Why or why not?

A

No, you can only use a stream once. It is closed after an operation is performed on it to avoid having unused resources open or data leaks.

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

What does a Java stream’s .sorted() method return?

A

It returns a new stream that has sorted the Collections objects within it.

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

What is a better way to perform an operation on all objects in a Java List than looping through a for loop? How would you print those new values?

A

Use a Java stream. So for an array of numbers:

Stream<Integer> newNums = nums.stream().map(n -> n*2);</Integer>

This returns a new stream that contains all the numbers in the original array, but they’ve all been multiplied by 2.

To print the newNums stream:

newNums.forEach(n -> System.out.println(n));

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

How would you use Java streams to sort a list of Integers, extract the odd numbers, multiply them all by 4, and print them, all on a single line of code? What is this called?

A

nums.stream().sorted().filter(n -> n%2==1).map(n -> n*4).forEach(n -> System.out.println(n));

Creating a succession of streams like this is called the Builder pattern.

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

What is an anonymous inner class in Java? How does it relate to lambda expressions?

A

If you create an implementation of a Java interface without actually creating a class that implements the interface, you have created an anonymous inner class. You would do this when calling “new A()” on the interface and defining it in brackets immediately after. So, for example, overriding and implementing the predicate interface’s “test” method to return a predicate would be creating an anonymous inner class for predicate.

Predicate<Integer> pred = new Predicate() {

}</Integer>

Lambda functions allow us to specify that anonymous class without typing the whole thing out. (Note: this only works for functional interfaces — one abstract function — not normal interfaces — multiple abstract functions.)

n -> n==2

This is a lambda function that returns true if n equals 2 and false otherwise. A predicate would typically require us to make a Boolean function that returns true of false based on if/else statements, but lambda functions let us bypass that longer process.

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

How would you use the reduce method on a Java stream to return the sum of all the integers in an Integer List?

A

int result = nums.stream().reduce(0, (c,e) -> c+e);

The first value, 0, indicates where in the stream you want to begin. I’m this case it starts at index 0 at the beginning.

The second value is a lambda function that takes in two integers (c,e) and adds them together -> c+e. C is the starting value and e is the resulting value, so the first iteration, the first c value is the integer at index 0 and e is the Integer at index 1. Once they’re added together the original e value added to the original c value is the new c value used in the function on the second iteration. Once it’s gone through the whole stream of values, it returns the final e, which is the sum of all values in the original array.

17
Q

How do you run Java stream methods on multiple threads?

A

Instead of using .stream() on a Collections List, use .parallelStream(). This should be faster because it is run on multiple threads.

18
Q

What is the difference between a normal interface and a functional interface in Java? Is there an exception to the functional interface rule?

A

Normal interfaces have 2 or more abstract methods.

Functional interfaces have a single abstract method that can be implemented using a lambda expression instead of creating an anonymous inner class.

Most Java interfaces are functional interfaces.

The catch with the 1 method rule is that every class or interface in Java extends the Object interface. If you put any or all of the Object methods into the functional interface (String toString() for example), you will not get an error.

Note: you can use the annotation @FunctionalInterface above an interface to make sure it is a functional interface. Else, it will show an error.

19
Q

Can you create an interface object?

A

No, you cannot create an interface object. You can create a class that implements an interface and define the abstract methods of that interface. Then you can create an object of that class.