55 Java Interview Questions PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Sign in Get started

WRIT E FOR US CODING INT ERVIEW COURS E →

You have 2 free stories left this month. Sign up and get an extra one for free.

55 Java Interview Questions


Marc Fichtel Follow
Jan 26 · 8 min read

For Junior and Intermediate Developers. Answers included!

Photo by Joshua Ness on Unsplash

Below you’ll find a list of Java interview questions and answers I’ve
gathered during my own job hunts. Before you continue, please note that
answers may not be 100% complete, up to date, or optimized, but are in
my experience sufficient for interview situations.

OOP Questions
These questions apply not only to Java, but object oriented languages in
general.

1. Compare interfaces and abstract classes

Both are used to achieve abstraction. Neither can be instantiated. An


abstract class can have concrete implementations, an interface cannot.
An interface is like a contract — a structure that classes implementing it
must adhere to. Abstract classes are used to hide internals and expose
relevant functionality — one doesn’t have to know how an abstract class
does something in order to use it.

2. Explain inheritance

Making one object the child of another gives the child all properties and
methods (with respect to access modifiers) of its parent and ancestors.
That is inheritance — it is used to achieve code reusability and
polymorphism. In Java, as in most modern languages, an object can
only have one parent — Java does not support multiple inheritance.
Inheritance creates tight coupling between the parent and its children,
which is why dependency injection is often a preferred alternative, as it
allows related pieces of code to be decoupled.

3. Explain polymorphism

Polymorphism means an object can belong to two or more types. It can


be achieved through inheritance and interfaces. For example, a Cat

object extending Mammal and implementing LandAnimal is an instance of


all three of those types. Method overloading and overriding is used to
achieve flexible behavior when implementing a polymorphic class
hierarchy.

4. Compare association, aggregation, and composition

These terms are used to describe relational structures in a class


hierarchy. Association describes how objects relate to/are associated
with each other (1–1, 1-N, N-1, N-M). It can be achieved through
aggregation and composition. Aggregation describes “is-a” relationships
— Each object can exist independently. Composition describes “has-a”
relationships — Objects cannot exist independently.

5. How would you model an ER Diagram for a social media website?

There are many ways to answer this one. A first approach could look
something like this:

User
* Id: Long
* Name: String

Post
* Id: Long
* Likes: Integer

Thread
* Id: Long
* Post: ForeignKey<Post>

Java Questions
6. What can you tell me about memory management and garbage collection
in Java?

Both are automatically handled by the JVM. The garbage collector


periodically collects variables without any references. Programmers can
tell the garbage collector to schedule garbage collection with
System.gc() , but it’s not guaranteed when that will happen. The two
most important memory areas in the JVM are the stack and the heap.
They are used for different purposes. The stack is used to hold method
frames and local variables, and is not shared between threads. Objects
are always allocated memory from the heap, which is shared between all
threads in the JVM. The stack is usually much smaller than heap
memory.

7. What can you tell me about Generics in Java?

Generics can be used in conjunction with classes and methods. They’re


used to specify a single declaration for a set of related methods, or a
single class declaration for a set of related types. Generics are checked at
compile-time for type safety. Two examples are ArrayList<T> and three
classes representing daily, monthly, and yearly charts that extend an
abstract Chart and can be specified with <? extends Chart> .

8. What can you tell me about Java Optionals?

They encapsulate optional values, and are used to make code more
readable, stable, and avoid having to deal with null values, thus avoiding
NullPointerExceptions .

9. Explain the difference between stream() and parallelStream() .

A regular stream is always synchronized, whereas a parallel stream can


execute operations asynchronously across CPU cores. Unless running a
heavy operation on a lot of objects, one should use regular streams, as
parallel streams have a high overhead for setting up multithreading.

10. What is ClassLoader in Java?

The part of the JVM that loads bytecodes for classes at runtime.

11. When is it appropriate to use a transient variable in Java?

Use transient variables, when you want to make a variable non-


serializable in a class that implements the Serializable interface.

12. Can private methods be overwritten in Java?

No, because private methods are not visible in the subclass.

13. What is the difference between lists and sets in Java?

They differ in how their items’ ordering and uniqueness. Lists are
ordered and allow duplicate values. Sets are unordered and do not allow
duplicate elements.

14. Which two methods do you have to override for an object to be usable as
a key in a hash map?

To be usable as a key in a hash map, an object needs to be comparable


and define a hash function. You have to overwrite equals() and
hashCode() .

15. What’s the difference between method overloading and overriding in


Java?

Overriding happens in a subclass. Overloading happens in the same


class.

16. How do you prevent a class from being sub-classed in Java?

You can either make the constructor of the class private, or mark the Top highlight

class as final .

17. What’s the difference between this and super in Java?

this refers to the current instance of an object. super refers to an


instance of the parent/superclass.

18. Will 3*0.1 == 0.3 return true or false?

This will return false, because some floating point numbers cannot be
represented exactly.

19. What is the right data type to represent a price in Java?

BigDecimal if memory is not a concern and performance is not critical,


otherwise double with a predefined precision.

20. Why is String immutable in Java?

Because Java was designed on the assumption that strings will be heavily
used. Making it immutable allows for some optimization around easily
sharing the same string between multiple clients.

21. What are some ways that you could sort a collection?

You could use an inherently sorted collection like TreeMap , or

Collections.sort() , or the Stream API.

22. Write a Java program for the Fizz Buzz problem.

1 for (int i = 0; i < 100; i++) {


2 if (i % 15 == 0) System.out.println("FizzBuzz");
3 else if (i % 3 == 0) System.out.println("Fizz");
4 else if (i % 5 == 0) System.out.println("Buzz");
5 else print(i);
6 }

interview.java hosted with ❤ by GitHub view raw

Fizz buzz

23. Write an algorithm to check, if a string is a palindrome in Java.

1 public Boolean isPalindrome(String s) {


2 return s.equals(new StringBuilder(s).reverse().toString());
3 }

interview.java hosted with ❤ by GitHub view raw

Palindromes

24. Write a Java program to check, if a number is even or odd.

1 public Boolean isEven(int num) {


2 return (num & 1) == 0;
3 }

interview.java hosted with ❤ by GitHub view raw

Even or Odd

25. Write a Java program with a memory overflow.

1 public int fib(int n) {


2 if (i <= 1) return i;
3 return fib(n-1) + fib(n-2);
4 }
5
6 ...
7
8 fib(10000000);

interview.java hosted with ❤ by GitHub view raw

Naive Fibonacci

or

1 Map map = new HashMap<int, int>();


2 int i = 0;
3 while(true) {
4 map.put(i++, i);
5 }

interview.java hosted with ❤ by GitHub view raw

Endless Loop

26. Write a Java program to check, if a number is prime.

1 bool isPrime(int n) {
2 if (n % 2 == 0) return false;
3 for (int i = 3; i*i <= n; i += 2) {
4 if (n % i == 0) return false;
5 }
6 return true;
7 }

interview.java hosted with ❤ by GitHub view raw

Primes

27. Implement a stack in Java.

1 public class MyStack<T> {


2 private List<T> stackList;
3 private int top;
4
5 public MyStack() {
6 stackList = new ArrayList<T>();
7 top = -1;
8 }
9
10 public void push(final T value) {
11 stackList.add(value);
12 top++;
13 }
14
15 public T pop() { return stackList.remove(top--); }
16 public T peek() { return stackList.get(top); };
17 public Boolean isEmpty() { return top == -1; };
18 }

interview.java hosted with ❤ by GitHub view raw

Stacks

28. In a stack, peek() is O(1). How would you achieve O(1) lookup for
peek() in a linked list?

Linked lists typically keep a reference to the head node. In peek() just

return head.value .

29. Implement a queue in Java using a linked list.

1 public class QueueLinkedList<T> implements Queue<T> {


2 private int total;
3 private Node first, last;
4
5 private class Node {
6 private T data;
7 private Node next;
8 }
9
10 public QueueLinkedList<T> enqueue(T data) {
11 Node current = last;
12 last = new Node();
13 last.data = data;
14 if (total++ == 0) first = last;
15 else current.next = last;
16 return this;
17 }
18
19 public T dequeue() {
20 if (total == 0) throw new java.util.IllegalArgumentException('Queue is empty');
21 T data = first.data;
22 first = first.next;
23 total--;
24 if (total == 0) last = null;
25 return data;
26 }
27 }

interview.java hosted with ❤ by GitHub view raw

Queues using Linked Lists

30. Implement a queue in Java using arrays.

1 public class QueueArray<T> implements Queue<T> {


2 private T[] arr;
3 private int total;
4 private int first;
5 private int next;
6
7 public QueueArray() {
8 arr = new T[2];
9 }
10
11 private void resize(int capacity) {
12 T[] tmp = new T[capacity];
13 for (int i = 0; i < total; i++) tmp[i] = arr[(first + i) % arr.length];
14 arr = tmp;
15 first = 0;
16 next = total;
17 }
18
19 public QueueArray<T> enqueue(T data) {
20 if (arr.length == total) resize(arr.length * 2);
21 arr[next++] = data;
22 if (next == arr.length) next = 0;
23 total++;
24 return this;
25 }
26
27 public T dequeue() {
28 if (total == 0) throw new java.util.IllegalArgumentException('Queue is empty');
29 T data = arr[first];
30 arr[first] = null;
31 first++;
32 total--;
33 if (first == arr.length) first = 0;
34 if (total > 0 && total == arr.length / 4) resize(arr.length / 2);
35 return data;
36 }
37 }

interview.java hosted with ❤ by GitHub view raw

Queues using Arrays

31. Implement a singly-linked list in Java.

1 public class MyLinkedList<T> {


2
3 private Integer size;
4 private MyNode head;
5
6 public MyLinkedList() {
7 size = 0;
8 head = new MyNode(null);
9 }
10
11 public void add(final T value) {
12 final MyNode node = new MyNode(value);
13 if (head.value == null) head = node;
14 else {
15 MyNode current = head;
16 while (current.next != null) current = current.next;
17 current.next = node;
18 }
19 size++;
20 }
21
22 public void addAtIndex(final T value, final Integer index) {
23 if (index > size) throw new IndexOutOfBoundsException("Some meaningful error message
24 final MyNode node = new MyNode(value);
25 if (size == 0) add(value);
26 else {
27 MyNode current = head;
28 for (int i = 0; i < index-1; i++) current = current.next;
29 MyNode after = current.next;
30 current.next = node;
31 node.next = after;
32 }
33 size++;
34 }
35
36 public T get(final Integer index) {
37 if (index >= size) throw new IndexOutOfBoundsException("Some other meaningful error
38 MyNode node = head;
39 for (int i = 0; i < index; i++)
40 node = node.next;
41 return node.value;
42 }
43
44 public void remove(final Integer index) {
45 if (index > size) throw new IndexOutOfBoundsException("Yet another meaningful error
46 if (index == 0) head = head.next;
47 else {
48 MyNode previous = head;
49 for (int i = 0; i < index - 1; i++) previous = previous.next;
50 previous.next = previous.next.next;
51 }
52 size--;
53 }
54
55 public Boolean isEmpty() { return size == 0; }
56 public Integer getSize() { return size; }
57
58 class MyNode {
59 public T value;
60 public MyNode next;
61 public MyNode(final T value) { this.value = value; }
62 }
63 }

interview.java hosted with ❤ by GitHub view raw

Singly-linked List

32. in Java, how fast is direct lookup in a hash map theoretically, and why is
it often slower in reality?

Lookup in hash maps is supposed to be constant time, O(1), as each


element is mapped to a key, which is computed using the key object’s
hash code. However, if the hash function returns the same result for two
or more inputs, collisions occur. In this case, each key is essentially
mapped to a linked list of N objects belonging to it, reducing lookup
speed to O(N).

33. Implement binary search in Java.

Arrays.binarySearch(sortedArray, key);

if you’re being sassy, or from scratch:

1 public int binarySearch(int[] sortedArray, int key) {


2 int low = 0;
3 int high = sortedArray.size;
4 int index = -1;
5
6 while (low <= high) {
7 int mid = (low + high) / 2;
8
9 // key must be higher
10 if (sortedArray[mid] < key) low = mid + 1;
11
12 // key must be lower
13 else if (sortedArray[mid] > key) high = mid - 1;
14
15 // found key
16 else if (sortedArray[mid] == key) {
17 index = mid;
18 break;
19 }
20 }
21
22 // if index = -1, array does not contain key
23 return index;
24 }

interview.java hosted with ❤ by GitHub view raw

Binary search

34. Implement bubble sort in Java.

1 // O(n^2) --> there are many better sorting alg's


2 public int[] bubbleSort(int array[]) {
3
4 // iterate over array backwards
5 for (int i = array.length; i >= 0; i--) {
6
7 // iterate over array forwards
8 for (int j = 0; j < array.length - 1; j++) {
9
10 // compare jth and next number
11 int k = j + 1;
12
13 // swap if necessary
14 if (array[j] > array[k]) {
15 int temp;
16 temp = array[j];
17 array[j] = array[k];
18 array[k] = temp;
19 }
20 }
21 }
22 return array;
23 }

interview.java hosted with ❤ by GitHub view raw

Bubble Sort

35. Given a string like a**hf*kl9* , write a function that returns a string with
all asterisks appearing first.

1 public String sortAsterisksInString(final String input) {


2 final StringBuilder sb1 = new StringBuilder();
3 final StringBuilder sb2 = new StringBuilder();
4 for (char c : input.toCharArray()) {
5 if (c == '*') sb1.append(c);
6 else sb2.append(c);
7 }
8 return sb1.toString() + sb2.toString();
9 }

interview.java hosted with ❤ by GitHub view raw

Sort String

. . .

Below you’ll find more general technical and nontechnical questions.


How you respond to these depends entirely on you, your experience, and
the position you’re applying for.

General Technical Questions


36. How long have you been programming professionally?

37. Tell us the details of an interesting problem you worked on. What made it
interesting?

38. What is something you’re proud to have contributed to?

39. What is something that didn’t go so well at work / while programming


and how did you handle it / how would you handle it in the future?

40. How do you feel about <insert language/framework/library/tool from


job posting>? What made you apply?

41. Tell us about a time when you had to make a trade-off between user
experience and optimization / technical design?

42. What’s an example of a time, when you had make a decision quickly?
What were the reasons behind that decision? Would you have done anything
differently?

43. What is your favorite thing you’ve worked on recently?

44. What is the biggest technical challenge you have faced?

45. Describe a bug you fixed / a feature you implemented.

46. What are your favorite and least favorite (Java)


frameworks/libraries/tools, and why?

Nontechnical Questions
47. Tell us about yourself. What are your career goals and past projects?
Where do you see yourself in 2 / 5 / 10 years?

48. Where did you hear about this role?

49. Which parts of our Creed / Mission / Vision resonate the most with you?
Why us? What do you like about our company?

50. Which of our products / projects would you be excited to work on and
why? Are there technologies you don’t want to work with and why not?

51. How do you use our and / or our competitors’ products? How would you
improve on them?

52. What is your dream job? What’s your perfect work day like?

53. How do you work with different teams/departments?

54. Do you have references?

55. Do you have any questions for us?

The last one is important. Here are some suggestions for questions you
may want to ask your interviewer:

How are you financed? (especially important for startups)

What do you like about working here?

How can I best prepare for this role before starting?

Could you describe a typical work week?

How big are teams?

What would my immediate responsibilities be?

Will there be opportunities to choose, what projects I work on?

What does the career path look like for this role?

How does your company promote personal growth?

Do you feel there are any skills currently lacking on the team?

What is the biggest change the company has gone through in the last
year?

What’s the style of leadership?

What is the rhythm of work here? Is there a particular time of year,


when it’s all hands on deck and we’re pulling long hours, or is it fairly
consistent throughout the year?

What type of background and experience are you looking for in this
position? What would your ideal candidate be like?

Is there anything that stands out to you that makes you think I might
not be the right fit for this position?

What is the timeline for making a decision on this position? When


should I get back in touch with you?

Sign up for "Top Stories" from Level Up Coding


A monthly summary of the best stories shared in Level Up Coding

Create a free Medium account to get "Top Stories" in


Get this newsletter your inbox.

Java Interview Questions Software Development Software Engineering Career Advice

469 claps

WRIT T EN BY

Marc Fichtel Follow

Software Engineer @ Unity Technologies ~


linkedin.com/in/ma chtel

Level Up Coding Follow

Coding tutorials and news. The developer homepage


gitconnected.com

See responses (3)

More From Medium

Linux user tries My Top 20 VS Code Tricky Java Interview 5 T hings T hat Are Hard
Windows, in 2020 Extensions Questions To Grasp When You
Dominik Tarnowski in Level Up Neo Hao Jun in Level Up Manusha Chethiyawardhana in Start Programming
Coding Coding Level Up Coding Daan in Level Up Coding

5 Lessons I’ve Learned Handling Authorization 4 JavaScript Tricks You 3 Habits T hat Will Help
on How to Structure In Clean Architecture Should Know You Become a Top
Code with ASP.NET Core and Anupam Chugh in Level Up Developer
Daan in Level Up Coding MediatR Coding Manish Jain in Level Up Coding
Austin Davies in Level Up
Coding

Discover Medium Make Medium yours Become a member


Welcome to a place where words matter. On Medium, smart Follow all the topics you care about, and we’ll deliver the Get unlimited access to the best stories on Medium — and
voices and original ideas take center stage - with no ads in best stories for you to your homepage and inbox. Explore support writers while you’re at it. Just $5/month. Upgrade
sight. Watch

About Help Legal

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy