0% found this document useful (0 votes)
4 views2 pages

Java Interview Questions & Answers Guide

The document provides a collection of Java walk-in interview questions and answers covering various topics such as string manipulation, prime number checking, recursion, encapsulation, inheritance, and differences between interfaces and abstract classes. It also includes a SQL query example for retrieving the top 3 salaries from an employee table. Each question is accompanied by a code snippet demonstrating the solution.

Uploaded by

Nirmal Mali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Java Interview Questions & Answers Guide

The document provides a collection of Java walk-in interview questions and answers covering various topics such as string manipulation, prime number checking, recursion, encapsulation, inheritance, and differences between interfaces and abstract classes. It also includes a SQL query example for retrieving the top 3 salaries from an employee table. Each question is accompanied by a code snippet demonstrating the solution.

Uploaded by

Nirmal Mali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Walk-in Interview Questions and Answers

1. Reverse a string without using in-built reverse()

String str = "hello";

String reversed = "";

for(int i = [Link]()-1; i >= 0; i--)

reversed += [Link](i);

[Link](reversed);

2. Check if a number is prime

int num = 29, flag = 0;

for (int i = 2; i <= num / 2; ++i) {

if (num % i == 0) {

flag = 1;

break;

[Link](flag == 0 ? "Prime" : "Not Prime");

3. Palindrome string check

String str = "madam";

String rev = new StringBuilder(str).reverse().toString();

[Link]([Link](rev) ? "Palindrome" : "Not Palindrome");

4. Factorial using recursion

int factorial(int n) {

if (n == 0) return 1;

return n * factorial(n - 1);

5. Find duplicate elements in array

int[] arr = {1, 2, 3, 2, 4, 3};


Java Walk-in Interview Questions and Answers

Set<Integer> set = new HashSet<>();

for(int n : arr) {

if (![Link](n)) [Link]("Duplicate: " + n);

6. Difference between == and .equals()

== checks reference equality (same object).

.equals() checks value equality (same content).

7. Create a class with encapsulation

public class Person {

private String name;

public String getName() { return name; }

public void setName(String name) { [Link] = name; }

8. Inheritance example

class Animal {

void sound() { [Link]("Animal sound"); }

class Dog extends Animal {

void sound() { [Link]("Bark"); }

9. Interface vs Abstract class

Interface: all methods are abstract, no state.

Abstract class: can have both abstract and concrete methods, with state.

10. SQL: Top 3 salaries from employee table

SELECT DISTINCT salary FROM employee ORDER BY salary DESC LIMIT 3;

Common questions

Powered by AI

Encapsulation in Java is a concept of wrapping the data (variables) and code acting on the data (methods) together as a single unit and restricting access to some of the object's components. It is achieved using access modifiers. For example, consider the 'Person' class where the field 'name' is private, but the class provides public methods to get and set the 'name'. This prevents external classes from directly accessing the 'name' field, thus encapsulating it: public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } .

The key differences between an interface and an abstract class in Java include that interfaces can have only abstract methods (until Java 8 and above, which allows default and static methods), whereas abstract classes can have a mix of abstract and concrete methods. Interfaces cannot maintain any state while abstract classes can have fields and constructors. You would use an interface when you need to define a contract that multiple classes can implement, allowing for different implementations, such as multiple inheritance scenarios which is not possible with abstract classes. An abstract class is preferable when you want to share common code among closely related classes, provide shared state, or require the use of constructors .

To retrieve the top 3 unique salaries from an 'employee' table, the SQL query would be: SELECT DISTINCT salary FROM employee ORDER BY salary DESC LIMIT 3;. The 'DISTINCT' keyword is essential here to ensure that only unique salary values are considered when ordering and selecting the top results. Without 'DISTINCT', the query might return duplicate salaries, which wouldn't provide the true top unique salaries as required .

Polymorphism in Java allows objects to be treated as instances of their parent class rather than their actual class. It manifests in two main forms: method overriding and interface implementation. In real-life examples, method overriding is commonly showcased where a subclass extends a parent class and provides a specific implementation of a method that is already defined in the parent class. For instance, a 'Dog' class extending an 'Animal' class could override a generic 'sound' method from the 'Animal' class to specify a dog-specific 'bark'. This polymorphic behavior ensures that when invoking the 'sound' method on an 'Animal' reference, the program decides which version of the method to execute at runtime based on the actual object's class, illustrating dynamic method dispatch .

To reverse a string in Java without using the built-in reverse() function, you can iterate through the string from the end to the beginning and construct a new string. Here's a sample implementation: String str = "hello"; String reversed = ""; for(int i = str.length()-1; i >= 0; i--) reversed += str.charAt(i); This constructs the reversed string by appending each character from the end of the original string to the new string .

In Java, '==' checks for reference equality, meaning it determines if two references point to the exact same object in memory. This is appropriate when checking if two variables reference the same memory location, such as when checking for nulls or using primitive data types. The '.equals()' method, however, checks for value equality, which means it determines if two objects are logically equivalent in terms of their content. This is appropriate when comparing the data within objects, such as strings or user-defined objects that override the '.equals()' method to compare their fields for equivalence .

To check if a number is prime using iteration, you typically start by checking for divisibility from 2 up to the square root of the number. This is because a larger factor of a number will necessarily be a multiple of a smaller factor that has already been checked. Here’s a basic implementation: int num = 29, flag = 0; for (int i = 2; i <= num / 2; ++i) { if (num % i == 0) { flag = 1; break; } } This checks divisibility by numbers up to num/2 for simplicity, but checking up to the square root of the number would be more optimal in terms of performance .

Inheritance in Java is a mechanism where a new class is derived from an existing class. It allows for method overriding, where a subclass provides a specific implementation of a method that is already defined by its superclass. For example, consider the following classes: class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { void sound() { System.out.println("Bark"); } } In this case, the 'Dog' class extends 'Animal' and overrides the 'sound' method to provide its implementation, demonstrating polymorphism .

The recursive technique for calculating factorial involves a function that calls itself with decremented arguments until it reaches a base case. Here's a simple Java implementation: int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } In this approach, the factorial function keeps calling itself with n-1, n-2, etc., until n equals 0, at which point it starts returning and multiplying the results. While recursion provides a simple way to solve problems with nested subproblems, it can be inefficient due to the overhead of function call stack management, especially for large input sizes, potentially leading to stack overflow errors .

To find duplicate elements in an integer array, you can use a HashSet to track the elements that have been seen before. As you iterate through the array, you attempt to add each element to the HashSet; if the addition fails, the element is a duplicate. For example: int[] arr = {1, 2, 3, 2, 4, 3}; Set<Integer> set = new HashSet<>(); for(int n : arr) { if (!set.add(n)) System.out.println("Duplicate: " + n); } The HashSet is effective for this purpose because it provides constant-time performance for the add operation and automatically handles duplicates by not allowing them to be added more than once .

You might also like