fruit.substring(2, 5)
return?Reasoning: The substring method is accepting two arguments.
boolean b1 = true, b2 = false; int i1 = 1, i2 = 2;
(i1 | i2) == 3
i2 && b1
b1 || !b2
(i1 ^ i2) < 4
Reasoning: i2 && b1 is not allowed between int and boolean.
1: class Main {
2: public static void main (String[] args) {
3: int array[] = {1, 2, 3, 4};
4: for (int i = 0; i < array.size(); i++) {
5: System.out.print(array[i]);
6: }
7: }
8: }
Reasoning: array.size() is invalid, to get size or length of array array.length can be used.
interface Interface1 {
static void print() {
System.out.print("Hello");
}
}
interface Interface2 {
static void print() {
System.out.print("World!");
}
}
super1.print(); super2.print();
this.print();
super.print();
Interface1.print(); Interface2.print();
String str = "abcde";
str.trim();
str.toUpperCase();
str.substring(3, 4);
System.out.println(str);
Reasoning: You should assign the result of trim back to the String variable. Otherwise, it is not going to work, because strings in Java are immutable.
class Main {
public static void main (String[] args){
System.out.println(print(1));
}
static Exception print(int i){
if (i>0) {
return new Exception();
} else {
throw new RuntimeException();
}
}
}
interface One {
default void method() {
System.out.println("One");
}
}
interface Two {
default void method () {
System.out.println("One");
}
}
class Three implements One, Two {
public void method() {
super.One.method();
}
}
class Three implements One, Two {
public void method() {
One.method();
}
}
class Three implements One, Two {
}
class Three implements One, Two {
public void method() {
One.super.method();
}
}
class Main {
public static void main (String[] args) {
List list = new ArrayList();
list.add("hello");
list.add(2);
System.out.print(list.get(0) instanceof Object);
System.out.print(list.get(1) instanceof Integer);
}
}
package mypackage;
public class Math {
public static int abs(int num){
return num < 0 ? -num : num;
}
}
package mypackage.elementary;
public class Math {
public static int abs (int num) {
return -num;
}
}
import mypackage.Math;
import mypackage.elementary.*;
class Main {
public static void main (String args[]){
System.out.println(Math.abs(123));
}
}
Explanation: The answer is "123". The abs()
method evaluates to the one
inside mypackage.Math class, because the import statements of the form:
import packageName.subPackage.*
is Type-Import-on-Demand Declarations, which never causes any other declaration to be shadowed.
1: class MainClass {
2: final String message() {
3: return "Hello!";
4: }
5: }
6: class Main extends MainClass {
7: public static void main(String[] args) {
8: System.out.println(message());
9: }
10: String message() {
11: return "World!";
12: }
13: }
Explanation: Compilation error at line 10 because of final methods cannot be overridden, and here message() is a final method, and also note that Non-static method message() cannot be referenced from a static context.
class Main {
public static void main(String[] args) {
System.out.println(args[2]);
}
}
java Main 1 2 "3 4" 5
java Main 1 "2" "2" 5
java Main.class 1 "2" 2 5
java Main 1 "2" "3 4" 5
class Main {
public static void main(String[] args){
int a = 123451234512345;
System.out.println(a);
}
}
Reasoning: The int type in Java can be used to represent any whole number from -2147483648 to 2147483647. Therefore, this code will not compile as the number assigned to 'a' is larger than the int type can hold.
class Main {
public static void main (String[] args) {
String message = "Hello world!";
String newMessage = message.substring(6, 12)
+ message.substring(12, 6);
System.out.println(newMessage);
}
}
for (Pencil pencil : pencilCase) {}
for (pencilCase.next()) {}
for (Pencil pencil : pencilCase.iterator()) {}
for (pencil in pencilCase) {}
System.out.print("apple".compareTo("banana"));
0
names.sort(Comparator.comparing(String::toString))
Collections.sort(names)
names.sort(List.DESCENDING)
names.stream().sorted((s1, s2) -> s1.compareTo(s2)).collect(Collectors.toList())
new SimpleDateFormat("yyyy-MM-dd").format(new Date())
new Date(System.currentTimeMillis())
LocalDate.now()
Calendar.getInstance().getTime()
Explanation: LocalDate is the newest class added in java 8
int0
is divisible by 5
:boolean isDivisibleBy5 = _____
int0 / 5 ? true: false
int0 % 5 == 0
int0 % 5 != 5
Math.isDivisible(int0, 5)
class Main {
public static void main(String[] args){
for (int i=0; i<10; i=i++){
i+=1;
System.out.println("Hello World!");
}
}
}
Explanation: Observe the loop increment. It's not an increment, it's an assignment(post).
public class Jedi {
/* Constructor A */
Jedi(String name, String species){}
/* Constructor B */
Jedi(String name, String species, boolean followsTheDarkSide){}
}
Note: This code won't compile, possibly broken code sample.
import java.util.LinkedList;
public class Main {
public static void main(String[] args){
LinkedList<Integer> list = new LinkedList<>();
list.add(5);
list.add(1);
list.add(10);
System.out.println(list);
}
}
class Main {
public static void main(String[] args){
String message = "Hello";
for (int i = 0; i<message.length(); i++){
System.out.print(message.charAt(i+1));
}
}
}
"nifty".getType().equals("String")
"nifty".getType() == String
"nifty".getClass().getSimpleName() == "String"
"nifty" instanceof String
import java.util.*;
class Main {
public static void main(String[] args) {
List<Boolean> list = new ArrayList<>();
list.add(true);
list.add(Boolean.parseBoolean("FalSe"));
list.add(Boolean.TRUE);
System.out.print(list.size());
System.out.print(list.get(1) instanceof Boolean);
}
}
1: class Main {
2: Object message() {
3: return "Hello!";
4: }
5: public static void main(String[] args) {
6: System.out.print(new Main().message());
7: System.out.print(new Main2().message());
8: }
9: }
10: class Main2 extends Main {
11: String message() {
12: return "World!";
13: }
14: }
public static void main(String[] args) {
try {
System.out.println("A");
badMethod();
System.out.println("B");
} catch (Exception ex) {
System.out.println("C");
} finally {
System.out.println("D");
}
}
public static void badMethod() {
throw new Error();
}
Explanation: Error
is not inherited from Exception
.
class Main {
static int count = 0;
public static void main(String[] args) {
if (count < 3) {
count++;
main(null);
} else {
return;
}
System.out.println("Hello World!");
}
}
import java.util.*;
class Main {
public static void main(String[] args) {
String[] array = {"abc", "2", "10", "0"};
List<String> list = Arrays.asList(array);
Collections.sort(list);
System.out.println(Arrays.toString(array));
}
}
[abc, 0, 2, 10]
[abc, 2, 10, 0]
[0, 10, 2, abc]
Explanation: The java.util.Arrays.asList(T... a)
returns a fixed-size list backed
by
the specified array. (Changes to the returned list "write through" to the array.)
class Main {
public static void main(String[] args) {
String message = "Hello";
print(message);
message += "World!";
print(message);
}
static void print(String message) {
System.out.print(message);
message += " ";
}
}
public class Main {
public static void main(String[] args) {
int x = 5;
x = 10;
System.out.println(x);
}
}
for (int i = 0; i < theList.size(); i++) {
System.out.println(theList.get(i));
}
for (Object object : theList) {
System.out.println(object);
}
Iterator it = theList.iterator();
for (it.hasNext()) {
System.out.println(it.next());
}
theList.forEach(System.out::println);
Explanation: for (it.hasNext())
should be while (it.hasNext())
.
boolean healthyOrNot = isHealthy("avocado");
volatile
affect how a variable is handled?
char smooch = 'x';
System.out.println((int) smooch);
public class Nosey {
int age;
public static void main(String[] args) {
System.out.println("Your age is: " + age);
}
}
public class Duck {
private String name;
Duck(String name) {}
}
Duck waddles = new Duck();
ducks.add(waddles);
Duck duck = new Duck("Waddles");
ducks.add(waddles);
ducks.add(new Duck("Waddles"));
ducks.add(new Waddles());
UnsupportedClassVersionError
it means the code was ___
on a
newer
version of Java than the JRE ___
it.public class TheClass {
private final int x;
}
public TheClass() {
x += 77;
}
public TheClass() {
x = null;
}
public TheClass() {
x = 77;
}
private void setX(int x) {
this.x = x;
}
public TheClass() {
setX(77);
}
Explanation: final
class members are allowed to be assigned only in three places:
declaration, constructor or an instance-initializer block.
public class Solution {
public static void main(String[] args) {
for (int i = 44; i > 40; i--) {
System.out.println("f");
}
}
}
abstract
classes
are true?1. They can be instantiated.
2. They allow member variables and methods to be inherited by subclasses.
3. They can contain constructors.
1: int a = 1;
2: int b = 0;
3: int c = a/b;
4: System.out.println(c);
Reasoning:
public class TestReal {
public static void main (String[] argv)
{
double pi = 3.14159265; //accuracy up to 15 digits
float pi2 = 3.141F; //accuracy up to 6-7 digits
System.out.println ("Pi=" + pi);
System.out.println ("Pi2=" + pi2);
}
}
The default Java type which Java will be using for a float variable will be double.
So, even if you declare any variable as float, what the compiler has to actually do is to assign a double value to a float variable,
which is not possible. So, to tell the compiler to treat this value as a float, that 'F' is used.
public class MagicPower {
void castSpell(String spell) {}
}
new MagicPower().castSpell("expecto patronum");
MagicPower magicPower = new MagicPower();
magicPower.castSpell();
MagicPower.castSpell("expelliarmus");
new MagicPower.castSpell();
public static void main(String[] args) {
int x=5,y=10;
swapsies(x,y);
System.out.println(x+" "+y);
}
static void swapsies(int a, int b) {
int temp=a;
a=b;
b=temp;
}
try {
System.out.println("Hello World");
} catch (Exception e) {
System.out.println("e");
} catch (ArithmeticException e) {
System.out.println("e");
} finally {
System.out.println("!");
}
Explanation: native
is a part of JNI interface.
%
//
/
DIV
Array<Integer> numbers = new Array<Integer>(10);
Array[int] numbers = new Array[int](10);
int[] numbers = new int[10];
int numbers[] = int[10];
groucyButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Press me one more time..");
}
});
groucyButton.addActionListener(ActionListener listener -> System.out.println("Press me one more time..."));
groucyButton.addActionListener((event) -> System.out.println("Press me one more time..."));
groucyButton.addActionListener(new ActionListener(ActionEvent e) {() -> System.out.println("Press me one more time...");});
groucyButton.addActionListener(() -> System.out.println("Press me one more time..."));
a -> false;
(a) -> false;
String a -> false;
(String a) -> false;
"21".intValue()
String.toInt("21")
Integer.parseInt("21")
String.valueOf("21")
public class Duck {
private String name;
Duck(String name) {
this.name = name;
}
public static void main(String[] args) {
System.out.println(new Duck("Moby"));
}
}
public String toString() { return name; }
public void println() { System.out.println(name); }
String toString() { return this.name; }
public void toString() { System.out.println(this.name); }
+
&
.
-
for (int i = 44; i > 40; i--) {
System.out.println("exterminate");
}
1: public class Main {
2: public static void main (String[] args) {
3: char myCharacter = "piper".charAt(3);
4: }
5: }
public class Main {
public static void main (String[] args) {
int[] sampleNumbers = {8, 5, 3, 1};
System.out.println(sampleNumbers[2]);
}
}
1: public class Main {
2: String MESSAGE ="Hello!";
3: static void print(){
4: System.out.println(message);
5: }
6: void print2(){}
7: }
public static final String message
public void print2(){}
print2
method and add a semicolon.
print
method.Explanation: Changing line 2 to public static final String message
raises the error
message not initialized in the default constructor
.
import java.util.*;
class Main {
public static void main(String[] args) {
String[] array = new String[]{"A", "B", "C"};
List<String> list1 = Arrays.asList(array);
List<String> list2 = new ArrayList<>(Arrays.asList(array));
List<String> list3 = new ArrayList<>(Arrays.asList("A", new String("B"), "C"));
System.out.print(list1.equals(list2));
System.out.print(list1.equals(list3));
}
}
ArrayList<String> words = new ArrayList<String>(){"Hello", "World"};
ArrayList words = Arrays.asList("Hello", "World");
ArrayList<String> words = {"Hello", "World"};
ArrayList<String> words = new ArrayList<>(Arrays.asList("Hello", "World"));
class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("hello");
sb.deleteCharAt(0).insert(0, "H")." World!";
System.out.println(sb);
}
}
class TaxCalculator {
static calculate(total) {
return total * .05;
}
}
Note: This code won't compile, broken code sample.
Explanation: HashSet makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.
import java.util.*;
public class Main {
public static void main(String[] args)
{
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.add(4);
queue.add(3);
queue.add(2);
queue.add(1);
while (queue.isEmpty() == false) {
System.out.printf("%d", queue.remove());
}
}
}
System.out.println("hello my friends".split(" ")[0]);
Explanation: HashMap class implements Map interface.
employees
of type List<Employee>
containing
multiple entries. The Employee
type has a method getName()
that returns the employee
name.
Which statement properly extracts a list of employee names?employees.collect(employee -> employee.getName());
employees.filter(Employee::getName).collect(Collectors.toUnmodifiableList());
employees.stream().map(Employee::getName).collect(Collectors.toList());
employees.stream().collect((e) -> e.getName());
public enum Direction {
EAST("E"),
WEST("W"),
NORTH("N"),
SOUTH("S");
private final String shortCode;
public String getShortCode() {
return shortCode;
}
}
String
parameter
and assigns it to the field shortCode
.final
keyword for the field
shortCode
.
shortCode
.AutoCloseable
interface are
closed
when it completes?1: class Main {
2: public static void main(String[] args) {
3:
4: array[0] = new int[]{1, 2, 3};
5: array[1] = new int[]{4, 5, 6};
6: array[2] = new int[]{7, 8, 9};
7: for (int i = 0; i < 3; i++)
8: System.out.print(array[i][1]); //prints 258
9: }
10: }
int[][] array = new int[][];
int[][] array = new int[3][3];
int[][] array = new int[2][2];
int[][] array = [][];
class Car {
public void accelerate() {}
}
class Lambo extends Car {
public void accelerate(int speedLimit) {}
public void accelerate() {}
}
this
or
super
.
public class Berries{
String berry = "blue";
public static void main(String[] args) {
new Berries().juicy("straw");
}
void juicy(String berry){
this.berry = "rasp";
System.out.println(berry + "berry");
}
}
forestCount
after this code executes?
Map<String, Integer> forestSpecies = new HashMap<>();
forestSpecies.put("Amazon", 30000);
forestSpecies.put("Congo", 10000);
forestSpecies.put("Daintree", 15000);
forestSpecies.put("Amazon", 40000);
int forestCount = forestSpecies.size();
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Main {
public static void main(String[] args) {
List<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c"));
for(String value :list) {
if(value.equals("a")) {
list.remove(value);
}
}
System.out.println(list); // outputs [b,c]
}
}
public int square(int x) {
return x * x;
}
Function<Integer, Integer> squareLambda = (int x) -> { x * x };
Function<Integer, Integer> squareLambda = () -> { return x * x };
Function<Integer, Integer> squareLambda = x -> x * x;
Function<Integer, Integer> squareLambda = x -> return x * x;
interface MyInterface {
int foo(int x);
}
public class MyClass implements MyInterface {
// ....
public void foo(int x){
System.out.println(x);
}
}
public class MyClass implements MyInterface {
// ....
public double foo(int x){
return x * 100;
}
}
public class MyClass implements MyInterface {
// ....
public int foo(int x){
return x * 100;
}
}
public class MyClass implements MyInterface {
// ....
public int foo(){
return 100;
}
}
interface Foo {
int x = 10;
}
public class Main{
public static void main(String[] args) {
Foo.x = 20;
System.out.println(Foo.x);
}
}
1:
2: Optional<String> opt = Optional.of(val);
3: System.out.println(opt.isPresent());
Integer val = 15;
String val = "Sam";
String val = null;
Optional<String> val = Optional.empty();
System.out.println(true && false || true);
System.out.println(false || false && true);
List<String> list1 = new ArrayList<>();
list1.add("One");
list1.add("Two");
list1.add("Three");
List<String> list2 = new ArrayList<>();
list2.add("Two");
list1.remove(list2);
System.out.println(list1);
[Two]
[One, Two, Three]
[One, Three]
Two
time
and money
, are the same?if(time <> money){}
if(time.equals(money)){}
if(time == money){}
if(time = money){}
class Unicorn {
_____ Unicorn(){}
}
List[] myLists = {
new ArrayList<>(),
new LinkedList<>(),
new Stack<>(),
new Vector<>(),
};
for (List list : myLists){
list.clear();
}
Explanation: switch between different implementations of the List
interface.
String a = "bikini";
String b = new String("bikini");
String c = new String("bikini");
System.out.println(a == b);
System.out.println(b == c);
Explanation: == operator
compares the object reference.
String a = "bikini"; String b = "bikini";
would result in True. Here new
creates a
new object, so false. Use equals() method
to compare the content.
_____ oddOrEven = x -> {
return x % 2 == 0 ? "even" : "odd";
};
Function<Integer, Boolean>
Function<String>
Function<Integer, String>
Function<Integer>
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> pantry = new HashMap<>();
pantry.put("Apples", 3);
pantry.put("Oranges", 2);
int currentApples = pantry.get("Apples");
pantry.put("Apples", currentApples + 4);
System.out.println(pantry.get("Apples"));
}
}
List<String> songTitles = Arrays.asList("humble", "element", "dna");
_______ capitalize = (str) -> str.toUpperCase();
songTitles.stream().map(capitalize).forEach(System.out::println);
Function<String, String>
Stream<String>
String<String, String>
Map<String, String>
_____ processFunction(Integer number, Function<Integer, String> lambda) {
return lambda.apply(number);
}
Integer
String
Consumer
Function<Integer, String>
List<String> dates = new ArrayList<String>();
// missing code
dates.replaceAll(replaceSlashes);
UnaryOperator<String> replaceSlashes = date -> date.replace("/", "-");
Function<String, String> replaceSlashes = dates -> dates.replace("-", "/");
Map<String, String> replaceSlashes = dates.replace("/", "-");
Consumer<Date> replaceSlashes = date -> date.replace("/", "-");
Explanation: replaceAll
method for any List
Object
Main
Java
Class
import java.util.date;
public class CurrentDateRunnable implements Runnable {
@Override
public void run () {
while (true) {
System.out.println("Current date: " + new Date());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
Thread thread = new Thread(new CurrentDateRunnable()); thread.start();
new Thread(new CurrentDateRunnable()).join();
new CurrentDateRunnable().run();
new CurrentDateRunnable().start();
List<Integer> numbers = List.of(1,2,3,4);
int total = 0;
for (Integer x : numbers) {
if (x % 2 == 0)
total += x * x;
}
int total = numbers.stream()
.transform(x -> x * x)
.filter(x -> x % 2 == 0)
.sum ();
int total = numbers.stream()
.filter(x -> x % 2 == 0)
.collect(Collectors.toInt());
int total = numbers.stream()
.mapToInt (x -> {if (x % 2 == 0) return x * x;})
.sum();
int total = numbers.stream()
.filter(x -> x % 2 == 0)
.mapToInt(x -> x * x)
.sum();
Explanation: The given code in the question will give you the output 20 as total:
numbers // Input `List<Integer>` > [1, 2, 3, 4]
.stream() // Converts input into `Stream<Integer>`
.filter(x -> x % 2 == 0) // Filter even numbers and return `Stream<Integer>` > [2, 4]
.mapToInt(x -> x * x) // Square the number, converts `Integer` to an `int`, and returns `IntStream` > [4, 16]
.sum() // Returns the sum as `int` > 20
double pickle = 2;
int jar = pickle;
for(int i=0; i<30; i+=x) {}
String buy = "bitcoin";
System.out.println(buy.substring(x, x+1) + buy.substring(y, y+2))
int yearsMarried = 2;
switch (yearsMarried) {
case 1:
System.out.println("paper");
case 2:
System.out.println("cotton");
case 3:
System.out.println("leather");
default:
System.out.println("I don't gotta buy gifts for nobody!");
}
System.out::println
Doggie::fetch
List<String> horses = new ArrayList<String>();
horses.add (" Sea Biscuit ");
System.out.println(horses.get(1).trim());
Explanation:
from @yktsang01 in #3915 thread
Map because map is a key/value pair without creating new classes/objects. So can store the rainfall per month
like
Map<java.time.Month, Double>
.
The other options will most likely need some new class to be meaningful:
public class Rainfall {
private java.time.Month month;
private double rainfall;
}
Vector<Rainfall>
LinkedList<Rainfall>
Queue<Rainfall>
Explanation: After a thread is started, via its start()
method of the Thread class,
the
JVM invokes the thread's run()
method when the thread is initially executed.
Explanation: Final classes are created so the methods implemented by that class cannot be
overridden. It can't be inherited. These classes are declared final
.
void accept(T t)
is method of -?Stream filter()
operates on?Stream map()
operates
on?1: class Main {
2: public static void main(String[] args) {
3: Map<String, Integer> map = new HashMap<>();
4: map.put("a", 1);
5: map.put("b", 2);
6: map.put("c", 3);
7: int result = 0;
8:
9: result += entry.getValue();
10: }
11: System.out.println(result); // outputs 6
12: }
13: }
class Car {
String color = "blue";
}
class Lambo extends Car {
String color = "white";
public Lambo() {
System.out.println(super.color);
System.out.println(this.color);
System.out.println(color);
}
}
class variable_scope {
public static void main(String args[]) {
int x;
x = 5;
{
int y = 6;
System.out.print(x + " " + y);
}
System.out.println(x + " " + y);
}
}
Explanation: Scope of variable Y is limited.
import java.util.Formatter;
public class Course {
public static void main(String[] args) {
Formatter data = new Formatter();
data.format("course %s", "java ");
System.out.println(data);
data.format("tutorial %s", "Merit campus");
System.out.println(data);
}
}
void printUnorderedPairs(int[] arrayA, int[] arrayB){
for(int i = 0; i < arrayA.length; i++){
for(int j = 0; j < arrayB.length; j++){
if(arrayA[i] < arrayB[j]){
System.out.println(arrayA[i] + "," + arrayB[j]);
}
}
}
}
1. true && false
2. true && false || true
Reference //check page number 47 and example number 4.:-}