Java Flashcards
How do you reverse a String in Java? What can you check for using a reverse String?
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.
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 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.
Explain the difference between Java int and Java Integer, Float, and Double. Are they type safe against each other?
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 do you convert a String representation of a number to an int and to and Integer?
int i = Integer.parseInt(“123”)
Integer i = new Integer(“123”)
Floats work the same with Float(“123”)
How do you get and set values in a Java ArrayList?
Simply use array.get(index) to get a value at an index, and change a value at an index using array.set(index, newValue)
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?
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.
What function would you use to check if a character existed in a Java String? What returns if it does exist? Doesn’t exist?
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.
When comparing to Integers in Java, should you use .equals() or “==”?
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)
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?
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.
What function gets a substring of a String in java? What are the parameters, and why must you be careful when assigning them?
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.
Can you use a Java stream more than once? Why or why not?
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.
What does a Java stream’s .sorted() method return?
It returns a new stream that has sorted the Collections objects within it.
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?
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 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?
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.
What is an anonymous inner class in Java? How does it relate to lambda expressions?
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.