C Pro PDF
C Pro PDF
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Coding is an integral part of any programming job interviews, and Java development
interviews are no exception. I would even suggest you should never hire anyone
without testing their coding skill, coding is also an art, and more often than a good
code is an excellent developer as well. If you look at tech giants like Amazon,
Facebook, and Google they thoroughly test the coding skill of any developer they
hire, notably Amazon who first send online coding exercises to filter Java
programmers who can code. This online test usually gives you requirements and ask
you to write a program in a limited time, usually 2 to 3 hours. The application should
meet the output provided by the exercise itself. These type of tasks are very tough to
crack if you don't have excellent coding skill.
Btw, the most crucial question is how do you develop that kind of coding skill in the
first place? Well, things always start small, and if you pay attention, there are many
Java job interviews where you would have been asked to write small programs.
They are simple, but yet they give a good indication of the coding skill of prospective
candidates. They are usually preferred by many companies because it often requires
10 to 20 minutes to write the solution and discuss them.
In this list, I am going to share 50 of such small programs from Java Programming
interviews. These programs are from various Data Structure and Algorithm topics
like an array, string, linked list, binary tree, etc. If you don't have a good knowledge
of Data structure and algorithm, I suggest you to first read a good book on Data
Structure and Algorithms like Introduction to Algorithms by Thomas H. Cormen.
But, If you find the book challenging, you can also join a comprehensive online
course on Data structure and algorithms like Data Structures and Algorithms:
Deep Dive Using Java on Udemy to learn better and more comfortable.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
7. Factorial (solution)
This is one of the simplest programs you can expect in interviews. It is generally
asked to see if you can code or not. Sometimes interviewer may also ask about
changing a recursive solution to iterative one or vice-versa.
Java interviews.
operators and functions, but sorting functions from Java API is not allowed.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Write a program to check if given linked list has a loop or not. Sometimes a linked list
get corrupt, and two nodes point to the same node, which forms the loop or cycle in
the linked list.
44. Find the 3rd element from the tail linked list (solution)
You need to write a program to find the 3rd element from the tail of a singly linked
list. You need to solve this problem without iterating twice. If you want more linked
list questions, you can see the article about frequently asked linked list interview
questions.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
That's all about top 50 programs from Java interviews. You can practice these
Java programs even if you are not preparing for any Job interview. They not only
help you to do well on your programming job interviews but also on learning how to
code and developing your programming skill and coding sense.
These small programs touch several important areas, e.g. popular data structures
like an array, linked list, binary tree, binary search tree, string, etc., popular
algorithms, e.g. sieve of the Eratosthenes algorithm for generating primes, the
Euclidean algorithm for calculating LCM and GCF, Fibonacci sequence, printing
patterns and so on.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
These programs also touch base on useful operators like bit-shift and bitwise
operators, modulus operators, and others. Overall, you get a good understanding of
the Java programming world by practicing these Java programs from coding
interviews.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
This has now become a general practice by the interviewers to ask basic Java Programs in
interviews rather than just focusing on theoretical aspects.
For this, we have come up with an idea of listing down a few very important Java Programs
along with the proper explanation of each program.
Moreover, we have also included the respective outputs which will give you a fair idea about
how that program worked. The flow of the program and the concepts are properly explained
wherever possible throughout this article.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Q #2) Write a Java Program to reverse a string without using String inbuilt function
reverse().
Answer:
Method 1:
There are several ways with which you can reverse your string if you are allowed to use the
other string inbuilt functions.
In this method, we are initializing a string variable called str with the value of your given
string. Then, we are converting that string into character array with toCharArray() function.
Thereafter, we are using for loop to iterate between each character in reverse order and
printing each character.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Method 2:
This is another method in which you are declaring your string variable str and then using
Scanner class to declare an object with predefined standard input object.
This program will accept the string value through the command line (when executed).
We have used nextLine() which will read the input with the spaces between the words of a
string. Thereafter, we have used a split() method to split the string into its substrings(no
delimiter given here). Finally, we have printed the string in reverse order using for loop.
1 import java.util.Scanner;
2
3 public class ReverseSplit {
4
5 public static void main(String[] args) {
// TODO Auto-generated method
6
stub
7 String str;
8 Scanner in = new Scanner(System.in);
9 System.out.println("Enter your String");
10 str = in.nextLine();
String[] token = str.split(""); //used split method to print
11
in reverse order
12 for(int i=token.length-1; i>=0; i--)
13 {
14 System.out.print(token[i] + "");
15 }
16
17 }
18
19 }
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Output:
Enter your String
Softwaretestinghelp
plehgnitseterawtfoS
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Method 3:
This is almost like method 2, but here we did not use the split() method. We have used the
scanner class and nextLine() for reading the input string. Then, we have declared an integer
length which has the length of the input string.
Thereafter, we have printed the string in the reverse order using for loop. However, we have
used charAt(index) method which will return the character at any specific index. After each
iteration, the character will be concatenated to reverse the string variable.
1 import java.util.Scanner;
2
3 public class Reverse {
4
5 public static void main(String[] args) {
// TODO Auto-generated method
6
stub
7 String original, reverse = "";
8 System.out.println("Enter the string to be reversed");
9 Scanner in = new Scanner(System.in);
10 original = in.nextLine();
11 int length = original.length();
12 for(int i=length-1; i>=0; i--) {
reverse = reverse + original.charAt(i); //used inbuilt
13
method charAt() to reverse the string
14 }
15 System.out.println(reverse);
16 }
17
18 }
Output:
Enter the string to be reversed
automation testing
gnitset noitamotua
Q #3) Write a Java Program to swap two numbers with using the third variable.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Answer: In this Example, we have made use of the Scanner class to declare an object with a
predefined standard input object. This program will accept the values of x and y through the
command line (when executed).
We have used nextInt() which will input the value of an integer variable ‘x' and ‘y' from the
user. A temp variable is also declared.
Now, the logic of the program goes like this – we are assigning temp or third variable with
the value of x, and then we are assigning x with the value of y and again we are assigning y
with the value of temp. So, after the first complete iteration, the temp will have a value of x, x
will have a value of y and y will have a value of temp (which is x).
1 import java.util.Scanner;
2
3 public class SwapTwoNumbers {
4
5 public static void main(String[] args) {
// TODO Auto-generated method
6
stub
7 int x, y, temp;
8 System.out.println("Enter x and y");
9 Scanner in = new Scanner(System.in);
10 x = in.nextInt();
11 y = in.nextInt();
12 System.out.println("Before Swapping" + x + y);
13 temp = x;
14 x = y;
15 y = temp;
16 System.out.println("After Swapping" + x + y);
17
18 }
19
20 }
Output:
Enter x and y
45
98
Before Swapping4598
After Swapping9845
Q #4) Write a Java Program to swap two numbers without using the third variable.
Answer: Rest all things will be the same as the above program. Only the logic will change.
Here, we are assigning x with the value x + y which means x will have a sum of both x and y.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Then, we are assigning y with the value x – y which means we are subtracting the value of y
from the sum of (x + y). Till here, x still has the sum of both x and y. But y has the value of
x.
Finally, in the third step, we are assigning x with the value x – y which means we are
subtracting y (which has the value of x) from the total (x + y). This will assign x with the
value of y and vice versa.
1 import java.util.Scanner;
2
3 class SwapTwoNumberWithoutThirdVariable
4{
5 public static void main(String args[])
6 {
7 int x, y;
8 System.out.println("Enter x and y");
9 Scanner in = new Scanner(System.in);
10
11 x = in.nextInt();
12 y = in.nextInt();
13
14 System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
15
16 x = x + y;
17 y = x - y;
18 x = x - y;
19
System.out.println("After Swapping without third variable\nx =
20
"+x+"\ny = "+y);
21 }
22 }
Output:
Enter x and y
45
98
Before Swapping
x = 45
y = 98
After Swapping without a third variable
x = 98
y = 45
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Q #5) Write a Java Program to count the number of words in a string using HashMap.
Answer: This is a collection class program where we have used HashMap for storing the
string.
First of all, we have declared our string variable called str. Then we have used split() function
delimited by single space so that we can split multiple words in a string.
Thereafter, we have declared HashMap and iterated using for loop. Inside for loop, we have
an if else statement
in which wherever at a particular position, the map contains a key, we set the counter at that
position and add the object to the map.
Note: The same program can be used to count the number of characters in a string. All you
need to do is to remove one space (remove space delimited in split method) in String[] split =
str.split(“”);
1 import java.util.HashMap;
2
3 public class FinalCountWords {
4
5 public static void main(String[] args) {
// TODO Auto-generated method
6
stub
7 String str = "This this is is done by Saket Saket";
8 String[] split = str.split(" ");
9 HashMap<String,Integer> map = new HashMap<String,Integer>();
10 for (int i=0; i<split.length-1; i++) {
11 if (map.containsKey(split[i])) {
12 int count = map.get(split[i]);
13 map.put(split[i], count+1);
14 }
15 else {
16 map.put(split[i], 1);
17 }
18 }
19 System.out.println(map);
20 }
21
22 }
Output:
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Q #6) Write a Java Program to iterate HashMap using While and advance for loop.
Answer: Here we have inserted three elements in HashMap using put() function.
The size of the map can get using size() method. Thereafter, we have used While loop for
iterating through the map which contains one key-value pair for each element. Keys and
Values can be retrieved through getKey() and getValue().
Likewise, we have used advanced for loop where we have “me2” object for the HashMap.
1 import java.util.HashMap;
2 import java.util.Iterator;
3 import java.util.Map;
4
5 public class HashMapIteration {
6
7 public static void main(String[] args) {
// TODO Auto-generated method
8
stub
9 HashMap<Integer,String> map = new HashMap<Integer,String>();
10 map.put(2, "Saket");
11 map.put(25, "Saurav");
12 map.put(12, "HashMap");
13 System.out.println(map.size());
14 System.out.println("While Loop:");
15 Iterator itr = map.entrySet().iterator();
16 while(itr.hasNext()) {
17 Map.Entry me = (Map.Entry) itr.next();
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
3
While Loop:
Key is 2 Value is Saket
Key is 25 Value is Saurav
Key is 12 Value is HashMap
For Loop:
Key is: 2 Value is: Saket
Key is: 25 Value is: Saurav
Key is: 12 Value is: HashMap
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Based on isPrime value, we are coming to the conclusion that whether our number is prime or
not.
1 import java.util.Scanner;
2
3 public class Prime {
4
5 public static void main(String[] args) {
// TODO Auto-generated method
6
stub
7 int temp, num;
8 boolean isPrime = true;
9 Scanner in = new Scanner(System.in);
10 num = in.nextInt();
11 in.close();
12 for (int i = 2; i<= num/2; i++) {
13 temp = num%i;
14 if (temp == 0) {
15 isPrime = false;
16 break;
17 }
18 }
19 if(isPrime)
20 System.out.println(num + "number is prime");
21 else
22 System.out.println(num + "number is not a prime");
23
24
25 }
26
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
27 }
Output:
445
445number is not a prime
Q #8) Write a Java Program to find whether a string or number is palindrome or not.
Answer: You can use any of the reverse string program explained above to check whether
the number or string
is palindrome or not.
What you need to do is to include one if-else statement. If the original string is equal to a
reversed string then the number is a palindrome, otherwise not.
1 import java.util.Scanner;
2
3 public class Palindrome {
4 public static void main (String[] args) {
5 String original, reverse = "";
6 Scanner in = new Scanner(System.in);
7 int length;
8 System.out.println("Enter the number or String");
9 original = in.nextLine();
10 length = original.length();
11 for (int i =length -1; i>=0; i--) {
12 reverse = reverse + original.charAt(i);
13 }
14 System.out.println("reverse is:" +reverse);
15
16 if(original.equals(reverse))
17 System.out.println("The number is palindrome");
18 else
19 System.out.println("The number is not a palindrome");
20
21 }
22 }
Output:
For String-
Enter the number or String
vijay
reverse is:yajiv
The number is not a palindrome
For Number-
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
The logic goes like a is set with the value of b which is 0, then b is set with the value of c
which is 1. Then, c is set with the sum of both a and b.
1 import java.util.Scanner;
2
3 public class Fibonacci {
4 public static void main(String[] args) {
5 int num, a = 0,b=0, c =1;
6 Scanner in = new Scanner(System.in);
7 System.out.println("Enter the number of times");
8 num = in.nextInt();
9 System.out.println("Fibonacci Series of the number is:");
10 for (int i=0; i<=num; i++) {
11 a = b;
12 b = c;
13 c = a+b;
System.out.println(a + ""); //if you want to print on
14
the same line, use print()
15 }
16 }
17 }
Output:
Enter the number of times
9
Fibonacci Series of the number is:
0
1
1
2
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
3
5
8
13
21
34
Q #10) Write a Java Program to iterate ArrayList using for-loop, while-loop, and
advance for-loop.
Answer: In this program, we have inserted three elements and printed the size of the
ArrayList.
Then, we have used While Loop with an iterator. Whenever the iterator has (next) element, it
will display that element until we reach the end of the list. So it will iterate three times.
Likewise, we have done for Advanced For Loop where we have created an object called obj
for the ArrayList called list. Then printed the object.
Thereafter, we have put the condition of For Loop where the iterator i is set to 0 index, then it
is incremented by 1 until the ArrayList limit or size is reached. Finally, we have printed each
element using a get(index) method for each iteration of For Loop.
1 import java.util.*;
2
3 public class arrayList {
4 public static void main(String[] args) {
5 ArrayList list = new ArrayList();
6 list.add("20");
7 list.add("30");
8 list.add("40");
9 System.out.println(list.size());
10 System.out.println("While Loop:");
11 Iterator itr = list.iterator();
12 while(itr.hasNext()) {
13 System.out.println(itr.next());
14 }
15 System.out.println("Advanced For Loop:");
16 for(Object obj : list) {
17 System.out.println(obj);
18 }
19 System.out.println("For Loop:");
20 for(int i=0; i<list.size(); i++) {
21 System.out.println(list.get(i));
22 }
23 }
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
24 }
Output:
3
While Loop:
20
30
40
Advanced For Loop:
20
30
40
For Loop:
20
30
40
The condition is set in such a way that webdriver will have to wait until we see the link
“Software testing – Wikipedia” on a web page. It won't execute if it does not find this link. If
it does, then it will do a mouse click on that link.
1 package Codes;
2 import java.util.concurrent.TimeUnit;
3 import org.openqa.selenium.By;
4 import org.openqa.selenium.WebDriver;
5 import org.openqa.selenium.WebElement;
6 import org.openqa.selenium.chrome.ChromeDriver;
7 import org.openqa.selenium.chrome.ChromeOptions;
8 import org.openqa.selenium.support.ui.ExpectedConditions;
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
9 import org.openqa.selenium.support.ui.WebDriverWait;
10
11 public class explicitWaitConditionCheck {
12
13 public static void main(String[] args) {
14 // TODO Auto-generated method stub
1 System.setProperty("webdriver.chrome.driver", "C:\\w
5 ebdriver\\chromedriver.exe");
1
6 ChromeOptions options = new ChromeOptions();
17 options.addArguments("--disable-arguments");
18 WebDriver driver = new ChromeDriver();
19 driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20,
20
TimeUnit.SECONDS);
21 driver.navigate().to("https://www.google.com");
WebElement element =
22
driver.findElement(By.name("q"));
23 element.sendKeys("Testing");
24 element.submit();
25 WebDriverWait wait = new WebDriverWait(driver, 20);
26
WebElement element2 =
2
wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkT
7
ext("Software testing - Wikipedia")));
2
element2.click();
8
29 }}
Q #12) Write a Java Program to demonstrate Scroll up/ Scroll down.
Answer: All the lines of codes are easily relatable as we have discussed in our previous
example.
However, in this program, we have included our JavascriptExecutor js which will do the
scrolling. If you see the last line of the code, we have passed window.scrollBy(arg1,arg2).
If we want to scroll up then pass some value in arg1 if you want to scroll down then pass
some value in arg2.
1 package Codes;
2
3 import java.util.concurrent.TimeUnit;
4
5 import org.openqa.selenium.By;
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
6 import org.openqa.selenium.JavascriptExecutor;
7 import org.openqa.selenium.Keys;
8 import org.openqa.selenium.WebDriver;
9 import org.openqa.selenium.WebElement;
10 import org.openqa.selenium.chrome.ChromeDriver;
11
12 public class ScrollDown {
13
14 public static void main(String[] args) {
1
// TODO Auto-generated method stub
5
1 System.setProperty("webdriver.chrome.driver", "C:\\we
6 bdriver\\chromedriver.exe");
17 WebDriver driver = new ChromeDriver();
18 JavascriptExecutor js = (JavascriptExecutor) driver;
19 driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20,
20
TimeUnit.SECONDS);
21 driver.get("https://www.google.com");
WebElement element =
22
driver.findElement(By.name("q"));
23 element.sendKeys("SoftwareTestingHelp");
24 element.sendKeys(Keys.ENTER);
25 js.executeScript("window.scrollBy(0,1000)");
26
27 }
28
29 }
Q #13) Write a Java Program to open all links of gmail.com.
Answer: It is a typical example of advanced for loop which we have seen in our previous
programs.
Once you have opened a website such as Gmail using get() or navigate().to(), you can use a
tagName locator to find the tag name of a website which will return all the tags.
We have advanced for loop where we have created a new WebElement link2 for a link(which
already has located
all the tags), then we have got all the links through getAttribute(“href”) and got all the texts
through getText().
1 package Codes;
2
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
3 import java.util.concurrent.TimeUnit;
4
5 import org.openqa.selenium.By;
6 import org.openqa.selenium.WebDriver;
7 import org.openqa.selenium.WebElement;
8 import org.openqa.selenium.chrome.ChromeDriver;
9
10 public class openAllLinks {
11
12 public static void main(String[] args) {
1
// TODO Auto-generated method stub
3
1 System.setProperty("webdriver.chrome.drive", "C:\\webdriver\\chr
4 omedriver.exe");
15 WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20,
16
TimeUnit.SECONDS);
17 driver.manage().window().maximize();
18 driver.get("https://www.gmail.com/");
java.util.List<WebElement> link =
19
driver.findElements(By.tagName("a"));
20 System.out.println(link.size());
21
22 for (WebElement link2: link) {
23
//print the links i.e. http://google.com or
24
https://www.gmail.com
25 System.out.println(link2.getAttribute("href"));
26
27 //print the links text
28 System.out.println(link2.getText());
29 }
30 }
31 }
Output:
Starting ChromeDriver 2.38.551601 (edb21f07fc70e9027c746edd3201443e011a61ed) on
port 16163
Only local connections are allowed.
4
https://support.google.com/chrome/answer/6130773?hl=en-GB
Learn more
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
https://support.google.com/accounts?hl=en-GB
Help
https://accounts.google.com/TOS?loc=IN&hl=en-GB&privacy=true
Privacy
https://accounts.google.com/TOS?loc=IN&hl=en-GB
Terms
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
1 package Codes;
2
3 import java.awt.AWTException;
4 import java.awt.Robot;
5 import java.awt.event.KeyEvent;
6 import java.util.concurrent.TimeUnit;
7 import org.openqa.selenium.By;
8 import org.openqa.selenium.Keys;
9 import org.openqa.selenium.WebDriver;
10 import org.openqa.selenium.WebElement;
11 import org.openqa.selenium.chrome.ChromeDriver;
12 public class PreviousTab {
13 public static void main(String[] args) throws AWTException {
14 // TODO Auto-generated method stub
1 System.setProperty("webdriver.chrome.driver", "C:\\webdriv
5 er\\chromedriver.exe");
1
6 WebDriver driver = new ChromeDriver();
17 driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20,
18
TimeUnit.SECONDS);
19 driver.get("https://www.google.com");
20 WebElement element1 = driver.findElement(By.name("q"));
21 element1.sendKeys("software testing help");
22 element1.sendKeys(Keys.ENTER);
23 String a = Keys.chord(Keys.CONTROL,Keys.RETURN);
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
driver.findElement(By.partialLinkText("Software Testing
24
Help - A Must Visit Software Testing Portal")).sendKeys(a);
25 Robot robot = new Robot(); // instantiated robot class
robot.keyPress(KeyEvent.VK_CONTROL); // with robot class
26
you can easily achieve anything if you know the shortcut keys
robot.keyPress(KeyEvent.VK_2); // here, we have just
27
pressed ctrl+2
robot.keyRelease(KeyEvent.VK_CONTROL); // once we press
28
and release ctrl+2, it will go to the second tab.
robot.keyRelease(KeyEvent.VK_2); //if you again want to go
29
back to first tab press and release vk_1
30 }
31 }
Q #15) Write a Java Program to find the duplicate characters in a string.
Answer: In this program, we have created a string variable str and initialized an integer count
with zero.
Then, we have created a character array to convert our string variable to the character. With
the help of for loop, we are performing a comparison between different character at different
indexes.
If two character of consecutive index matches, then it will print that character and the counter
will be incremented by 1 after each iteration.
10 for(int j=i+1;
j<str.length();j++) {
11 if (chars[i] == chars[j]) {
1 System.out.println(c
2 hars[j]);
13 count++;
14 break;
15 }
16 }
17 }
18 }
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
19
20 }
Output:
Duplicate characters are:
k
t
Q #16) Write a Java Program to find the second highest number in an array.
Answer: In this program, we have initialized an array with 10 random elements out of which
we are going to
find the second highest number. Here, we have two integers- the largest and second largest.
Both set to the first
index of the element. Then, we have printed all the elements using for loop.
Now the logic is when the element at the 0th index is greater than the largest, then assign
arr[0] to largest
and secondLargest to largest. Again, if the element at the 0th index is greater than the
secondLargest, then
assign secondLargest to arr[0].
This will be repeated for each iteration and ultimately after comparing or completing
iterations up to array length will give you the secondLargest element.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
21 secondLargest = arr[i];
22 }
23 }
Now, in this program, we have a temp and integers declared. We have initialized c with value
0. Then, we need to
assign the integer value which we are going to check for Armstrong (in our case, let us say
153). Then we have assigned our temp variable with that number which we are going to
check.
Thereafter, we have used while conditional check where the remainder is assigned to a and
the number is divided by 10 and assigned to n. Now, our c variable which was set to zero
initially is assigned with c+(a*a*a). Suppose we have to evaluate a four-digit number then c
should be assigned with c + (a*a*a*a).
Lastly, we have put an if-else statement for conditional checking where we have compared
the value contained in c against temp(which has the actual number stored at this point). If it
matches, then the number is Armstrong otherwise not.
1 class Armstrong{
2 public static void main(String[] args) {
3 int c=0,a,temp;
4 int n=153;//It is the number to check Armstrong
5 temp=n;
6 while(n>0)
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
7 {
8 a=n%10;
9 n=n/10;
10 c=c+(a*a*a);
11 }
12 if(temp==c)
13 System.out.println("armstrong number");
14 else
15 System.out.println("Not armstrong number");
16 }
17 }
Output:
armstrong number
Q #18) Write a Java Program to remove all white spaces from a string with using
replace().
Answer: This is a simple program where we have our string variable str1.
Another string variable str2 is initialized with the replaceAll option which is an inbuilt
method to remove n number of whitespaces. Ultimately, we have printed str2 which has no
whitespaces.
1 class RemoveWhiteSpaces
2{
3 public static void main(String[] args)
4 {
5 String str1 = "Saket Saurav is a QualityAna list";
6
7 //1. Using replaceAll() Method
8
9 String str2 = str1.replaceAll("\\s", "");
10
11 System.out.println(str2);
12
13 }
14 }
15 }
Output:
SaketSauravisaQualityAnalist
Q #19) Write a Java Program to remove all white spaces from a string without using
replace().
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Answer: This is another approach to removing all white spaces. Again, we have one string
variable str1 with some
value. Then, we have converted that string into a character array using toCharArray().
Then, we have one StringBuffer object sb which will be used to append the value stored at
chars[i] index after we have included for loop and one if condition.
If the condition is set such that then the element at i index of the character array should not be
equal to space or tab. Finally, we have printed our StringBuffer object sb.
1 class RemoveWhiteSpaces
2{
3 public static void main(String[] args)
4 {
String str1 = "Saket Saurav is an Autom ation Engi
5
ne er";
6
7 char[] chars = str1.toCharArray();
8
9 StringBuffer sb = new StringBuffer();
10
11 for (int i = 0; i < chars.length; i++)
12 {
13 if( (chars[i] != ' ') && (chars[i] != '\t') )
14 {
15 sb.append(chars[i]);
16 }
17 }
System.out.println(sb); //Output :
18
CoreJavajspservletsjdbcstrutshibernatespring
19 }
20 }
Output:
SaketSauravisanAutomationEngineer
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Then we are setting the type of cell to string. Thereafter we are carrying out a normal web
element locator operation (By.id) where we have passed unique locator values such as
“email” and “password” which will identify these elements.
1 @Test
2 public void ReadData() throws IOException
3 {
// Import excel sheet from a webdriver directory which is inside c
4
drive.
5 //DataSource is the name of the excel
6 File src=new File("C:\\webdriver\\DataSource.xls");
7
//This step is for loading the file. We have used FileInputStream
8
as
//we are reading the excel. In case you want to write into the
9
file,
//you need to use FileOutputStream. The path of
10
the file is passed as an argument to FileInputStream
11 FileInputStream finput = new FileInputStream(src);
12
//This step is to load the workbook of the excel which is done by
13
global HSSFWorkbook in which we have
14 //passed finput as an argument.
15 workbook = new HSSFWorkbook(finput);
16
17 //This step is to load the sheet in which data is stored.
18 sheet= workbook.getSheetAt(0);
19
20 for(int i=1; i<=sheet.getLastRowNum(); i++)
21 {
22 // Import data for Email.
23 cell = sheet.getRow(i).getCell(1);
24 cell.setCellType(Cell.CELL_TYPE_STRING);
2 driver.findElement(By.id("email")).sendKeys(cell.getStringCellV
5 alue());
26
27 // Import data for the password.
28 cell = sheet.getRow(i).getCell(2);
29 cell.setCellType(Cell.CELL_TYPE_STRING);
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
3 driver.findElement(By.id("password")).sendKeys(cell.getStringCe
0 llValue());
31
32 }
33 }
Summary
In this article, we have discussed all the important basic Java Interview Programs with
code examples that are being asked in any Java Programming Interviews.
We have learned all the Java Tricks like basic manipulation of String, Integer and Characters,
Selenium Codes, Reading Data from a File, Mathematical Series through codes and now you
do have ample idea of how to go about any Java Interview.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Platform independence means that execution of your program does not dependent
on type of operating system(it could be any : Linux, windows, Mac ..etc). So compile
code only once and run it on any System (In C/C++, we need to compile the code for
every machine on which we run it). Java is both compiler(javac) and interpreter(jvm)
based lauguage. Your java source code is first compiled into byte code using javac
compiler. This byte code can be easily converted to equivalent machine code using
JVM. JVM(Java Virtual Machine) is available in all operating systems we install.
Hence, byte code generated by javac is universal and can be converted to machine
code on any operating system, this is the reason why java is platform independent.
Final keyword in java is used to restrict usage of variable, class and method.
Variable: Value of Final variable is constant, you can not change it.
Method: you can’t override a Final method.
Class: you can’t inherit from Final class.
Refer this for details
String is an Immutable class, i.e. you can not modify its content once created. While
StringBuffer is a mutable class, means you can change its content later. Whenever
we alter content of String object, it creates a new string and refer to that,it does not
modify the existing one. This is the reason that the performance with StringBuffer is
better than with String.
Refer this for details.
Java supports multiple inheritance but not through classes, it supports only through
its interfaces. The reason for not supporting multiple inheritance is to avoid the
conflict and complexity arises due to it and keep Java a Simple Object Oriented
Language. If we recall this in C++, there is a special case of multiple inheritance
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
(diamond problem) where you have a multiple inheritance with two classes which
have methods in conflicts. So, Java developers decided to avoid such conflicts and
didn’t allow multiple inheritance through classes at all.
Top level classes in java can’t be private or protected, but inner classes in java can.
The reason for not making a top level class as private is very obvious, because
nobody can see a private class and thus they can not use it. Declaring a class as
protected also doesn’t make any sense. The only difference between default visibility
and protected visibility is that we can use it in any package by inheriting it. Since in
java there is no such concept of package inheritance, defining a class as protected is
no different from default.
Unlike c++ , we don’t need to destroy objects explicitly in Java. ‘Garbage Collector‘
does that automatically for us. Garbage Collector checks if no references to an
object exist, that object is assumed to be no longer required, and the memory
occupied by the object can be freed. Sometimes an object can hold non-java
resources such as file handle or database connection, then you want to make sure
these resources are also released before object is destroyed. To perform such
operation Java provide protected void finalize() in object class. You can override this
method in your class and do the required tasks. Right before an object is freed, the
java run time calls the finalize() method on that object. Refer this for more details.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Set and List both are child interface of Collection interface. There are following two
main differences between them
• List can hold duplicate values but Set doesn’t allow this.
• In List interface data is present in the order you inserted but in the case of Set
insertion order is not preserved.
What will happen if you put System.exit(0) on try or catch block? Will finally
block execute?
By Calling System.exit(0) in try or catch block, we can skip the finally block.
System.exit(int) method can throw a SecurityException. If Sysytem.exit(0) exits the
JVM without throwing that exception then finally block will not execute. But, if
System.exit(0) does throw security exception then finally block will be executed.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
// ptr is a dangling pointer now and operations like following are invalid
*ptr = 10; // or printf("%d", *ptr);
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
filter_none
edit
play_arrow
brightness_4
// EXAMPLE 2
int* ptr = NULL
{
int x = 10;
ptr = &x;
}
// x goes out of scope and memory allocated to x is free now.
// So ptr is a dangling pointer now.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
void f()
{
int* ptr = (int*)malloc(sizeof(int));
/* Do some work */
int main()
{
fun();
fun();
return 0;
}
// Output: 0 1
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Let us start by taking a look at some of the most frequently asked Java interview questions,
Edureka 2019 Tech Career Guide is out! Hottest job roles, precise learning paths, industry
outlook & more in the guide. Download now.
We have compiled a list of top Java interview questions which are classified into 7 sections,
namely:
1.
2.
3.
4.
5.
6.
7.
As a Java professional, it is essential to know the right buzzwords, learn the right
technologies and prepare the right answers to commonly asked Java Interview
Questions. Here’s a definitive list of top Java Interview Questions that will guarantee a
breeze-through to the next level.
In case you attended any Java interview recently, or have additional questions beyond what
we covered, we encourage you to post them in our QnA Forum. Our expert team will get
back to you at the earliest.
So let’s get started with the first set of basic Java Interview Questions.
• public: Public is an access modifier, which is used to specify who can access this
method. Public means that this Method will be accessible by any Class.
• static: It is a keyword in java which identifies it is class-based. main() is made static in
Java so that it can be accessed without creating the instance of a Class. In case, main
is not made static then the compiler will throw an error as main() is called by the
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
JVM before any objects are made and only static methods can be directly invoked via
the class.
• void: It is the return type of the method. Void defines the method which will not
return any value.
• main: It is the name of the method which is searched by JVM as a starting point for
an application with a particular signature only. It is the method where the main
execution occurs.
• String args[]: It is the parameter passed to the main method.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Java is not 100% Object-oriented because it makes use of eight primitive data types such as
63ehavio, byte, char, int, float, double, long, short which are not objects.
1. Default Constructor: In Java, a default constructor is the one which does not take
any inputs. In other words, default constructors are the no argument constructors
which will be created by default in case you no other constructor is defined by the
user. Its main purpose is to initialize the instance variables with the default values.
Also, it is majorly used for object creation.
2. Parameterized Constructor: The parameterized constructor in Java, is the
constructor which is capable of initializing the instance variables with the provided
values. In other words, the constructors which take the arguments are called
parameterized constructors.
Q7. What is singleton class in Java and how can we make a class singleton?
Singleton class is a class whose only one instance can be created at any given time, in one
JVM. A class can be made singleton by making its constructor private.
Q8. What is the difference between Array list and vector in Java?
ArrayList Vector
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Q10. What are the differences between Heap and Stack Memory in Java?
The major difference between Heap and Stack memory are:
1. Default
2. Private
3. Protected
4. Public
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
1 class Abc {
2 member variables
3 methods}
1. State
2. Behavior
3. Identity
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Example
2 {
4 }
Whereas, an instance variable in Java, is a variable which is bounded to its object itself.
These variables are declared within a class, but outside a method. Every object of that class
will create it’s own copy of the variable while using it. Thus, any changes made to the
variable won’t reflect in any other instances of that class and will be bound to that particular
instance only.
1 class Test{
4 }
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
• final variable
When the final keyword is used with a variable then its value can’t be changed once assigned.
In case the no value has been assigned to the final variable then using only the class
constructor a value can be assigned to it.
• final method
When a method is declared final then it can’t be overridden by the inheriting class.
• final class
When a class is declared as final in Java, it can’t be extended by any subclass class but it can
extend other class.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Example break:
2 {
3 if (i == 3)
4 {
5 break;
6 }
7 System.out.println(i);
8 }
Example continue:
2 {
3 if(i == 2)
4 {
5 continue;
6 }
7 System.out.println(i);
}
8
For example:
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
2 {
4 for(;;)
5 System.out.println("Welcome to Edureka!");
}
6
}
7
this() super()
1. this() represents the current instance of a 1. super() represents the current instance of a
class parent/base class
2. Used to call the default constructor of the 2. Used to call the default constructor of the
same class parent/base class
3. Used to access methods of the current
3. Used to access methods of the base class
class
4. Used for pointing the current class
4. Used for pointing the superclass instance
instance
5. Must be the first line of a block 5. Must be the first line of a block
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
1. Bootstrap ClassLoader
2. Extension ClassLoader
3. System/Application ClassLoader
Q33. What is collection class in Java? List down its methods and interfaces.
In Java, the collection is a framework that acts as an architecture for storing and manipulating
a group of objects. Using Collections you can perform various tasks like searching, sorting,
insertion, manipulation, deletion, etc. Java collection framework includes the following:
• Interfaces
• Classes
• Methods
The below image shows the complete hierarchy of the Java Collection.
In case you are facing any challenges with these java interview questions, please comment on
your problems in the section below.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
polymorphism:
1 class Car {
2 void run()
3 {
4 System.out.println(“car is running”);
5 }
6 }
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
8 void run()
9 {
11 }
13 {
15 b.run();
}
16
}
17
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Inheritance in Java is the concept where the properties of one class can be inherited by the
other. It helps to reuse the code and establish a relationship between different classes.
Inheritance is performed between two types of classes:
A class which inherits the properties is known as Child Class whereas a class whose
properties are inherited is known as Parent class.
1. Single Inheritance: In single inheritance, one class inherits the properties of another
i.e there will be only one parent as well as one child class.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
2. Multilevel Inheritance: When a class is derived from a class which is also derived
from another class, i.e. a class having more than one parent class but at different
levels, such type of inheritance is called Multilevel Inheritance.
3. Hierarchical Inheritance: When a class has more than one child classes (subclasses)
or in other words, more than one child classes have the same parent class, then such
kind of inheritance is known as hierarchical.
4. Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of
inheritance.
• In Method Overloading, Methods of the same class shares the same name but each
method must have a different number of parameters or parameters having different
types and order.
• Method Overloading is to “add” or “extend” more to the method’s behavior.
• It is a compile-time polymorphism.
• The methods must have a different signature.
• It may or may not need inheritance in Method Overloading.
1 class Adder {
3 {
4 return a+b;
5 }
7 {
8 return a+b;
9 }
11 {
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
12 System.out.println(Adder.add(11,11));
13 System.out.println(Adder.add(12.3,12.6));
14 }}
Method Overriding:
• In Method Overriding, the subclass has the same method with the same name and
exactly the same number and type of parameters and same return type as a
superclass.
• Method Overriding is to “Change” existing behavior of the method.
• It is a run time polymorphism.
• The methods must have the same signature.
• It always requires inheritance in Method Overriding.
1 class Car {
2 void run(){
3 System.out.println(“car is running”);
4 }
6 void run()
7 {
9 }
11 {
13 b.run();
14 }
15 }
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
1 class Base {
4 }
7 }
11 }
14 }
17 {
19 obj1.display();
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
20 obj1.print();
21 }
22 }
The problem with multiple inheritance is that if multiple parent classes have the same method
name, then at runtime it becomes difficult for the compiler to decide which method to
execute from the child class.
Therefore, Java doesn’t support multiple inheritance. The problem is commonly referred to as
Diamond Problem.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
A Marker interface can be defined as the interface having no data member and member
functions. In simpler terms, an empty interface is called the Marker interface. The most
common examples of Marker interface in Java are Serializable, Cloneable etc. The marker
interface can be declared as follows.
2 }
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Object cloning in Java is the process of creating an exact copy of an object. It basically
means the ability to create an object with a similar state as the original object. To achieve
this, Java provides a method clone() to make use of this functionality. This method creates a
new instance of the class of the current object and then initializes all its fields with the exact
same contents of corresponding fields. To object clone(), the marker
interface java.lang.Cloneable must be implemented to avoid any runtime exceptions. One
thing you must note is Object clone() is a protected method, thus you need to override it.
1
class Demo
2
{
3
int i;
4
public Demo(int a)
5
{
6
i=k;
7
}
8
public Demo(int a, int b)
9
{
10
}
11
}
12
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
In case you are facing any challenges with these java interview questions, please comment on
your problems in the section below. Apart from this Java Interview Questions Blog, if you
want to get trained from professionals on this technology, you can opt for a structured
training from edureka!
Q2. What are the differences between Get and Post methods?
Get Post
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Limited amount of data can be sent because Large amount of data can be sent because
data is sent in header. data is sent in body.
Not Secured because data is exposed in URL Secured because data is not exposed in URL
bar. bar.
Can be bookmarked Cannot be bookmarked
Idempotent Non-Idempotent
It is more efficient and used than Post It is less efficient and used
1.void forward()
2.void include()
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
servlet:
1. Servlet is loaded
2. Servlet is instantiated
3. Servlet is initialized
4. Service the request
5. Servlet is destroyed
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
ServletConfig ServletContext
It represent whole web application running on
Servlet config object represent single servlet
particular JVM and common for all the servlet
Its like local parameter associated with Its like global parameter associated with whole
particular servlet application
It’s a name value pair defined inside the
ServletContext has application wide scope so
servlet section of web.xml file so it has
define outside of servlet tag in web.xml file.
servlet wide scope
getServletConfig() method is used to get the getServletContext() method is used to get the
config object context object.
for example shopping cart of a user is a To get the MIME type of a file or application
specific to particular user so here we can use session related information is stored using servlet
servlet config context object.
1. User Authentication
2. HTML Hidden Field
3. Cookies
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
4. URL Rewriting
5. Session Management API
In case you are facing any challenges with these java interview questions, please comment
your problems in the section below. Apart from this Java Interview Questions Blog, if you
want to get trained from professionals on this technology, you can opt for a structured
training from edureka! Click below to know more.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
4. Thin driver
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
5.
6. (fully java driver)
Interfaces:
• Connection
• Statement
• PreparedStatement
• ResultSet
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
• ResultSetMetaData
• DatabaseMetaData
• CallableStatement etc.
Classes:
• DriverManager
• Blob
• Clob
• Types
• SQLException etc.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Statement executeQuery(String query) is used to execute Select queries and returns the
ResultSet. ResultSet returned is never null even if there are no records matching the query.
When executing select queries we should use executeQuery method so that if someone tries
to execute insert/update statement it will throw java.sql.SQLException with message
“executeQuery method can not be used for update”.
You should use execute() method only when you are not sure about the type of statement else
use executeQuery or executeUpdate method.
1. Statement: Used for general purpose access to the database and executes a static
SQL query at runtime.
2. PreparedStatement: Used to provide input parameters to the query during
execution.
3. CallableStatement: Used to access the database stored procedures and helps in
accepting runtime parameters.
In case you are facing any challenges with these java interview questions, please comment
your problems in the section below. Apart from this Java Interview Questions Blog, if you
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
want to get trained from professionals on this technology, you can opt for a structured
training from edureka!
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
• @Required
• @Autowired
• @Qualifier
• @Resource
• @PostConstruct
• @PreDestroy
Q4. Explain Bean in Spring and List the different Scopes of Spring bean.
Beans are objects that form the backbone of a Spring application. They are managed by the
Spring IoC container. In other words, a bean is an object that is instantiated, assembled, and
managed by a Spring IoC container.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
• Singleton: Only one instance of the bean will be created for each container. This is
the default scope for the spring beans. While using this scope, make sure spring
bean doesn’t have shared instance variables otherwise it might lead to data
inconsistency issues because it’s not thread-safe.
• Prototype: A new instance will be created every time the bean is requested.
• Request: This is same as prototype scope, however it’s meant to be used for web
applications. A new instance of the bean will be created for each HTTP request.
• Session: A new bean will be created for each HTTP session by the container.
• Global-session: This is used to create global session beans for Portlet applications.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
ContextLoaderListener, on the other hand, is the listener to start up and shut down the
WebApplicationContext in Spring root. Some of its important functions includes tying up the
lifecycle of Application Context to the lifecycle of the ServletContext and automating the
creation of ApplicationContext.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Q6. What are the differences between constructor injection and setter
injection?
No. Constructor Injection Setter Injection
1) No Partial Injection Partial Injection
Overrides the constructor property if both are
2) Doesn’t override the setter property
defined.
Creates a new instance if any Doesn’t create a new instance if you change the
3)
modification occurs property value
4) Better for too many properties Better for a few properties.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Controller Based:
We can define exception handler methods in our controller classes. All we need is to annotate
these methods with @ExceptionHandler annotation.
HandlerExceptionResolver implementation:
For generic exceptions, most of the times we serve static pages. Spring Framework provides
HandlerExceptionResolver interface that we can implement to create global exception
handler. The reason behind this additional way to define global exception handler is that
Spring framework also provides default implementation classes that we can define in our
spring bean configuration file to get spring framework exception handling benefits.
Q9. What are some of the important Spring annotations which you have
used?
Some of the Spring annotations that I have used in my project are:
@ResponseBody – for sending Object as response, usually for sending XML or JSON data
as response.
@PathVariable – for mapping dynamic values from the URI to handler method arguments.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
AspectJ annotations for configuring aspects and advices , @Aspect, @Before, @After,
@Around, @Pointcut, etc.
Also, Spring ORM provides support for using Spring declarative transaction management, so
you should utilize that rather than going for hibernate boiler-plate code for transaction
management.
In case you are facing any challenges with these java interview questions, please comment
your problems in the section below. Apart from this Java Interview Questions Blog, if you
want to get trained from professionals on this technology, you can opt for structured training
from edureka!
Hibernate provides a reference implementation of Java Persistence API, that makes it a great
choice as ORM tool with benefits of loose coupling. We can use the Hibernate persistence
API for CRUD operations. Hibernate framework provide option to map plain old java objects
to traditional database tables with the use of JPA annotations as well as XML based
configuration.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Similarly, hibernate configurations are flexible and can be done from XML configuration file
as well as programmatically.
1. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care
of managing resources, so we can focus on business logic.
2. Hibernate framework provides support for XML as well as JPA annotations, that
makes our code implementation independent.
3. Hibernate provides a powerful query language (HQL) that is similar to SQL. However,
HQL is fully object-oriented and understands concepts like inheritance,
polymorphism, and association.
4. Hibernate is an open source project from Red Hat Community and used worldwide.
This makes it a better choice than others because learning curve is small and there
are tons of online documentation and help is easily available in forums.
5. Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that
Spring Framework provides built-in support for integrating hibernate with Spring
applications.
6. Hibernate supports lazy initialization using proxy objects and perform actual
database queries only when it’s required.
7. Hibernate cache helps us in getting better performance.
8. For database vendor specific feature, hibernate is suitable because we can also
execute native sql queries.
Overall hibernate is the best choice in current market for ORM tool, it contains all the
features that you will ever need in an ORM tool.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
1. Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code
looks cleaner and readable.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
2. Hibernate supports inheritance, associations, and collections. These features are not
present with JDBC API.
3. Hibernate implicitly provides transaction management, in fact, most of the queries
can’t be executed outside transaction. In JDBC API, we need to write code for
transaction management using commit and rollback.
4. JDBC API throws SQLException that is a checked exception, so we need to write a lot
of try-catch block code. Most of the times it’s redundant in every JDBC call and used
for transaction management. Hibernate wraps JDBC exceptions and
throw JDBCException or HibernateException un-checked exception, so we don’t
need to write code to handle it. Hibernate built-in transaction management removes
the usage of try-catch blocks.
5. Hibernate Query Language (HQL) is more object-oriented and close to Java
programming language. For JDBC, we need to write native SQL queries.
6. Hibernate supports caching that is better for performance, JDBC queries are not
cached hence performance is low.
7. Hibernate provides option through which we can create database tables too, for
JDBC tables must exist in the database.
8. Hibernate configuration helps us in using JDBC like connection as well as JNDI
DataSource for the connection pool. This is a very important feature in enterprise
application and completely missing in JDBC API.
9. Hibernate supports JPA annotations, so the code is independent of the
implementation and easily replaceable with other ORM tools. JDBC code is very
tightly coupled with the application.
In case you are facing any challenges with these Java interview questions, please comment on
your problems in the section below. Apart from this Java Interview Questions Blog, if you
want to get trained from professionals on this technology, you can opt for structured training
from edureka!
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Object Type
1) out JspWriter
2) request HttpServletRequest
3) response HttpServletResponse
4) config ServletConfig
5) session HttpSession
6) application ServletContext
7) pageContext PageContext
8) page Object
9) exception Throwable
3. What are the differences between include directive and include action?
include directive include action
The include directive includes the content The include action includes the content at request
at page translation time. time.
The include directive includes the original The include action doesn’t include the original
content of the page so page size increases content rather invokes the include() method of
at runtime. Vendor provided class.
It’s better for static pages. It’s better for dynamic pages.
1. core tags
2. sql tags
3. xml tags
4. internationalization tags
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
5. functions tags
3
Cookie mycook = new Cookie("name1","value1");
4
response.addCookie(mycook1);
5
Cookie killmycook = new Cookie("mycook1","value1");
6
killmycook . set MaxAge ( 0 );
7
killmycook . set Path ("/");
8
killmycook . addCookie ( killmycook 1 );
9
10
11
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
11. How will you use JSP EL in order to get the HTTP method name?
Using pageContext JSP EL implicit object you can get the request object reference and make
use of the dot operator to retrieve the HTTP method name in the JSP page. The JSP EL code
for this purpose will look like ${pageContext.request.method}.
In case you are facing any challenges with these java interview questions, please comment on
your problems in the section below. Apart from this Java Interview Questions Blog, if you
want to get trained from professionals on this technology, you can opt for structured training
from edureka!
While exceptions are conditions that occur because of bad input or human error etc. e.g.
FileNotFoundException will be thrown if the specified file does not exist. Or a
NullPointerException will take place if you try using a null reference. In most of the cases it
is possible to recover from an exception (probably by giving the user feedback for entering
proper values etc.
1. try
2. catch
3. finally
4. throw
5. throws
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Q3. What are the differences between Checked Exception and Unchecked
Exception?
Checked Exception
• The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions.
• Checked exceptions are checked at compile-time.
• Example: IOException, SQLException etc.
Unchecked Exception
Q4. What purpose do the keywords final, finally, and finalize fulfill?
Final:
Final is used to apply restrictions on class, method, and variable. A final class can’t be
inherited, final method can’t be overridden and final variable value can’t be changed. Let’s
take a look at the example below to understand it better.
1 class FinalVarExample {
3 {
5 a=50;
6 }
Finally
Finally is used to place important code, it will be executed whether the exception is handled
or not. Let’s take a look at the example below to understand it better.
1 class FinallyExample {
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
3 try {
4 int x=100;
5 }
6 catch(Exception e) {
7 System.out.println(e);
8 }
9 finally {
Finalize
Finalize is used to perform clean up processing just before the object is garbage collected.
Let’s take a look at the example below to understand it better.
1 class FinalizeExample {
3 System.out.println("Finalize is called");
4 }
6 {
9 f1= NULL;
10 f2=NULL;
11 System.gc();
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
12 }
13 }
Throwable is a parent class of all Exception classes. There are two types of Exceptions:
Checked exceptions and UncheckedExceptions or RunTimeExceptions. Both type of
exceptions extends Exception class whereas errors are further classified into Virtual Machine
error and Assertion error.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
1. String getMessage() – This method returns the message String of Throwable and the
message can be provided while creating the exception through it’s constructor.
2. String getLocalizedMessage() – This method is provided so that subclasses can
override it to provide locale specific message to the calling program. Throwable class
implementation of this method simply use getMessage() method to return the
exception message.
3. Synchronized Throwable getCause() – This method returns the cause of the
exception or null id the cause is unknown.
4. String toString() – This method returns the information about Throwable in String
format, the returned String contains the name of Throwable class and localized
message.
5. void printStackTrace() – This method prints the stack trace information to the
standard error stream, this method is overloaded and we can pass PrintStream or
PrintWriter as an argument to write the stack trace information to the file or stream.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Q10. What is a finally block? Is there a case when finally will not execute?
Finally block is a block which always executes a set of statements. It is always associated
with a try block regardless of any exception that occurs or not.
Yes, finally will not be executed if the program exits either by calling System.exit() or by
causing a fatal error that causes the process to abort.
Q12. Can we write multiple catch blocks under single try block?
Yes we can have multiple catch blocks under single try block but the approach should be
from specific to general. Let’s understand this with a programmatic example.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
3 try {
5 a[10]= 10/0;
6 }
7 catch(ArithmeticException e)
8 {
10 }
11 catch(ArrayIndexOutOfBoundsException e)
{
12
System.out.println("Array index out of bounds in second catch
13 block");
14 }
15 catch(Exception e)
16 {
18 }
19 }
1. String getMessage() – This method returns the message String about the exception.
The message can be provided through its constructor.
2. public StackTraceElement[] getStackTrace() – This method returns an array
containing each element on the stack trace. The element at index 0 represents the
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
top of the call stack whereas the last element in the array represents the method at
the bottom of the call stack.
3. Synchronized Throwable getCause() – This method returns the cause of the
exception or null id as represented by a Throwable object.
4. String toString() – This method returns the information in String format. The
returned String contains the name of Throwable class and localized message.
5. void printStackTrace() – This method prints the stack trace information to the
standard error stream.
In case you are facing any challenges with these java interview questions, please comment
your problems in the section below. Apart from this Java Interview Questions Blog, if you
want to get trained from professionals on this technology, you can opt for structured training
from edureka!
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
So this brings us to the end of the Java interview questions blog. The topics that you learned
in this Java Interview Questions blog are the most sought-after skill sets that recruiters look
for in a Java Professional. These set of Java Interview Questions will definitely help you ace
your job interview. Good luck with your interview!
Check out the Java Training by Edureka, a trusted online learning company with a network
of more than 250,000 satisfied learners spread across the globe. We are here to help you
with every step on your journey, for becoming a besides this java interview questions, we
come up with a curriculum which is designed for students and professionals who want to be a
Java Developer. The course is designed to give you a head start into Java programming and
train you for both core and advanced Java concepts along with various Java frameworks like
Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this “Java Interview
Questions” and we will get back to you as soon as possible.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Ans: An Inner class is a class which is nested within another class. An Inner class has access
rights for the class which is nesting it and it can access all variables and methods defined in
the outer class.
A sub-class is a class which inherits from another class called super class. Sub-class can
access all public and protected methods and fields of its super class.
Q2. What are the various access specifiers for Java classes?
Ans: In Java, access specifiers are the keywords used before a class name which defines the
access scope. The types of access specifiers for classes are:
2. Protected:Method,Field can be accessed from the same class to which they belong or from
the sub-classes,and from the class of same package,but not from outside.
3. Default: Method,Field,class can be accessed only from the same package and not from
outside of it's native package.
4. Private: Method,Field can be accessed from the same class to which they belong.
Ans: When there is a requirement to share a method or a variable between multiple objects of
a class instead of creating separate copies for each object, we use static keyword to make a
method or variable shared for all objects.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
A singleton class in java can have only one instance and hence all its methods and variables
belong to just one instance. Singleton class concept is useful for the situations when there is a
need to limit the number of objects for a class.
The best example of singleton usage scenario is when there is a limit of having only one
connection to a database due to some driver limitations or because of any licensing issues.
Q6. What are Loops in Java? What are three types of loops?
1) For Loops
For loops are used in java to execute statements repeatedly for a given number of times. For
loops are used when number of times to execute the statements is known to programmer.
2) While Loops
While loop is used when certain statements need to be executed repeatedly until a condition
is fulfilled. In while loops, condition is checked first before execution of statements.
3) Do While Loops
Do While Loop is same as While loop with only difference that condition is checked after
execution of block of statements. Hence in case of do while loop, statements are executed at
least once.
Ans: An infinite loop runs without any condition and runs infinitely. An infinite loop can be
broken by defining any breaking logic in the body of the statement blocks.
for (;;)
{
// Statements to execute
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Ans: break and continue are two important keywords used in Loops. When a break keyword
is used in a loop, loop is broken instantly while when continue keyword is used, current
iteration is broken and loop continues with next iteration.
if (counter == 4) {
break;
}
In the below example when counter reaches 4, loop jumps to next iteration and any
statements after the continue keyword are skipped for current iteration.
if (counter == 4) {
continue;
}
system.out.println("This will not get printed when counter is 4");
}
Q9. What is the difference between double and float variables in Java?
Ans: In java, float takes 4 bytes in memory while Double takes 8 bytes in memory. Float is
single precision floating point decimal number while Double is double precision decimal
number.
Ans: In java, a constant is declared using the keyword Final. Value can be assigned only once
and after assignment, value of a constant can't be changed.
In below example, a constant with the name const_val is declared and assigned avalue:
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
When a method is declared as final,it can NOT be overridden by the subclasses.This method
are faster than any other method,because they are resolved at complied time.
When a class is declares as final,it cannot be subclassed. Example String,Integer and other
wrapper classes.
Ans: Ternary operator , also called conditional operator is used to decide which value to
assign to a variable based on a Boolean value evaluation. It's denoted as ?
In the below example, if rank is 1, status is assigned a value of "Done" else "Pending".
Ans:
• Using Math.random() you can generate random numbers in the range greater than or
equal to 0.1 and less than 1.0
• Using Random class in package java.util
Ans: In a switch statement, default case is executed when no other switch condition matches.
Default case is an optional case .It can be declared only once all other switch cases have been
coded.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
case 2:
system.out.println("Score is 2");
break;
default:
system.out.println("Default Case");
}
}
}
Q14. What's the base class in Java from which all classes are derived?
Ans: java.lang.object
Ans: In java, main() method can't return any data and hence, it's always declared with a void
return type.
Ans: In Java, package is a collection of classes and interfaces which are bundled together as
they are related to each other. Use of packages helps developers to modularize the code and
group the code for proper re-use. Once code has been packaged in Packages, it can be
imported in other classes and used.
Q17. Can we declare a class as Abstract without having any abstract method?
Ans: Yes we can create an abstract class by using abstract keyword before class name even if
it doesn't have any abstract method. However, if a class has even one abstract method, it must
be declared as abstract otherwise it will give an error.
Q18. What's the difference between an Abstract Class and Interface in Java?
Ans: The primary difference between an abstract class and interface is that an interface can
only possess declaration of public static methods with no concrete implementation while an
abstract class can have members with any access specifiers (public, private etc) with or
without concrete implementation.
Another key difference in the use of abstract classes and interfaces is that a class which
implements an interface must implement all the methods of the interface while a class which
inherits from an abstract class doesn't require implementation of all the methods of its super
class.
A class can implement multiple interfaces but it can extend only one abstract class.
Q19. What are the performance implications of Interfaces over abstract classes?
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Use of interfaces also puts an extra burden on the developers as any time an interface is
implemented in a class; developer is forced to implement each and every method of
interface.
Ans: In java, when a package is imported, its sub-packages aren't imported and developer
needs to import them separately if required.
For example, if a developer imports a package university.*, all classes in the package named
university are loaded but no classes from the sub-package are loaded. To load the classes
from its sub-package ( say department), developer has to import it explicitly as follows:
Import university.department.*
Ans: In java, main method must be public static in order to run any application correctly. If
main method is declared as private, developer won't get any compilation error however, it
will not get executed and will give a runtime error.
Q22. How can we pass argument to a function by reference instead of pass by value?
Ans: In java, we can pass argument to a function only by value and not by reference.
Ans: In java, to convert an object into byte stream by serialization, an interface with the name
Serializable is implemented by the class. All objects of a class implementing serializable
interface get serialized and their state is saved in byte stream.
Ans: Serialization is used when data needs to be transmitted over the network. Using
serialization, object's state is saved and converted into byte stream .The byte stream is
transferred over the network and the object is re-created at destination.
Q25. Is it compulsory for a Try Block to be followed by a Catch Block in Java for
Exception handling?
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Ans: Try block needs to be followed by either Catch block or Finally block or both. Any
exception thrown from try block needs to be either caught in the catch block or else any
specific tasks to be performed before code abortion are put in the Finally block.
Q26. Is there any way to skip Finally block of exception even if some exception occurs in
the exception block?
Ans: If an exception is raised in Try block, control passes to catch block if it exists otherwise
to finally block. Finally block is always executed when an exception occurs and the only way
to avoid execution of any statements in Finally block is by aborting the code forcibly by
writing following line of code at the end of try block:
System.exit(0);
Ans: The constructor of a class is invoked every time an object is created with new keyword.
For example, in the following class two objects are created using new keyword and hence,
constructor is invoked two times.
const_example() {
system.out.println("Inside constructor");
}
public static void main(String args[]) {
Ans: Yes, a class can have multiple constructors with different parameters. Which
constructor gets used for object creation depends on the arguments passed while creating the
objects.
Ans: We cannot override static methods. Static methods belong to a class and not to
individual objects and are resolved at the time of compilation (not at runtime).Even if we try
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
to override static method,we will not get an complitaion error,nor the impact of overriding
when running the code.
super.displayResult();
obj.displayResult();
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Ans: String is not a primitive data type in java. When a string is created in java, it's actually
an object of Java.Lang.String class that gets created. After creation of this string object, all
built-in methods of String class can be used on the string object.
Q32. In the below example, how many String Objects are created?
Ans: In the above example, two objects of Java.Lang.String class are created. s1 and s3 are
references to same object.
Ans: In java, string objects are called immutable as once value has been assigned to a string,
it can't be changed and if changed, a new object is created.
In below example, reference str refers to a string object having value "Value one".
When a new value is assigned to it, a new String object gets created and the reference is
moved to the new object.
str="New Value";
Ans: An array groups data of same primitive type and is static in nature while vectors are
dynamic in nature and can hold data of different data types.
Ans: Multi threading is a programming concept to run multiple tasks in a concurrent manner
within a single program. Threads share same process stack and running in parallel. It helps in
performance improvement of any program.
Ans: Runnable interface is used in java for implementing multi threaded applications.
Java.Lang.Runnable interface is implemented by a class to support multi threading.
Ans: Multi threaded applications can be developed in Java by using any of the following two
methodologies:
Q38. When a lot of changes are required in data, which one should be a preference to be
used? String or StringBuffer?
Ans: Since StringBuffers are dynamic in nature and we can change the values of StringBuffer
objects unlike String which is immutable, it's always a good choice to use StringBuffer when
data is being changed too much. If we use String in such a case, for every data change a new
String object will be created which will be an extra overhead.
Q39. What's the purpose of using Break in each case of Switch Statement?
Ans: Break is used after each case (except the last one) in a switch so that code breaks after
the valid case and doesn't flow in the proceeding cases too.
If break isn't used after each case, all cases after the valid case also get executed resulting in
wrong results.
Ans: In java, when an object is not referenced any more, garbage collection takes place and
the object is destroyed automatically. For automatic garbage collection java calls either
System.gc() method or Runtime.gc() method.
Q41. How we can execute any code even before main method?
Ans: If we want to execute any statements before even creation of objects at load time of
class, we can use a static block of code in the class. Any statements inside this static block of
code will get executed once at the time of loading the class even before creation of objects in
the main method.
Q42. Can a class be a super class and a sub-class at the same time? Give example.
Ans: If there is a hierarchy of inheritance used, a class can be a super class for another class
and a sub-class for another one at the same time.
In the example below, continent class is sub-class of world class and it's super class of
country class.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
..........
}
public class continenet extends world {
............
}
public class country extends continent {
......................
Q43. How objects of a class are created if no constructor is defined in the class?
Ans: Even if no explicit constructor is defined in a java class, objects get created successfully
as a default constructor is implicitly used for object creation. This constructor has no
parameters.
Q44. In multi-threading how can we ensure that a resource isn't used by multiple
threads simultaneously?
Ans: In multi-threading, access to the resources which are shared among multiple threads can
be controlled by using the concept of synchronization. Using synchronized keyword, we can
ensure that only one thread can use shared resource at a time and others can get control of the
resource only once it has become free from the other one using it.
Q45. Can we call the constructor of a class more than once for an object?
Ans: Constructor is called automatically when we create an object using new keyword. It's
called only once for an object at the time of object creation and hence, we can't invoke the
constructor again for an object after its creation.
Q46. There are two classes named classA and classB. Both classes are in the same
package. Can a private member of classA can be accessed by an object of classB?
Ans: Private members of a class aren't accessible outside the scope of that class and any other
class even in the same package can't access them.
Q47. Can we have two methods in a class with the same name?
Ans: We can define two methods in a class with the same name but with different
number/type of parameters. Which method is to get invoked will depend upon the parameters
passed.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
For example in the class below we have two print methods with same name but different
parameters. Depending upon the parameters, appropriate one will be called:
obj1.print();
obj1.print("xx");
Ans: We can use the concept of cloning to create copy of an object. Using clone, we create
copies with the actual state of an object.
Ans: Key benefit of using inheritance is reusability of code as inheritance enables sub-classes
to reuse the code of its super class. Polymorphism (Extensibility ) is another great benefit
which allow new functionality to be introduced without effecting existing derived classes.
Q50. What's the default access specifier for variables and methods of a class?
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Ans: Default access specifier for variables and method is package protected i.e variables and
class is available to any other class but in the same package,not outside the package.
Ans: There are no pointers in Java. So we can't use concept of pointers in Java.
Q52. How can we restrict inheritance for a class so that no class can be inherited from
it?
Ans: If we want a class not to be extended further by any class, we can use the
keyword Final with the class name.
Ans: When a method or a variable is declared with Protected access specifier, it becomes
accessible in the same class,any other class of the same package as well as a sub-class.
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Ans: Stack and Queue both are used as placeholder for a collection of data. The primary
difference between a stack and a queue is that stack is based on Last in First out (LIFO)
principle while a queue is based on FIFO (First In First Out) principle.
Ans: If we want certain variables of a class not to be serialized, we can use the
keyword transient while declaring them. For example, the variable trans_var below is a
transient variable and can't be serialized:
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Ans: Primitive data types like int can be handled as objects by the use of their respective
wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can
apply different methods to a wrapper class, just like any other object.
Ans: Checked exceptions can be caught at the time of program compilation. Checked
exceptions must be handled by using try catch block in the code in order to successfully
compile the code.
Q60. Can we override a method by using same method name and arguments but
different return types?
Ans: The basic condition of method overriding is that method name, arguments as well as
return type must be exactly same as is that of the method being overridden. Hence using a
different return type doesn't override a method.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
int x = 4;
system.out.println(x++);
}
}
Ans: In this case postfix ++ operator is used which first returns the value and then
increments. Hence it's output will be 4.
Q61. A person says that he compiled a java class successfully without even having a
main method in it? Is it possible?
Ans: main method is an entry point of Java class and is required for execution of the program
however; a class gets compiled successfully even if it doesn't have a main method. It can't be
run though.
Ans: Non-Static methods are owned by objects of a class and have object level scope and in
order to call the non-Static methods from a static block (like from a static main method), an
object of the class needs to be created first. Then using object reference, these methods can
be invoked.
Q63. What are the two environment variables that must be set in order to run any Java
programs?
Ans: Java programs can be executed in a machine only once following two environment
variables have been properly set:
1. PATH variable
2. CLASSPATH variable
Ans: In Java, if a variable is used in a code without prior initialization by a valid value,
program doesn't compile and gives an error as no default value is assigned to variables in
Java.
Q65. Can a class in Java be inherited from more than one class?
Ans: In Java, a class can be derived from only one class and not from multiple classes.
Multiple inheritances is not supported by Java.
Q66. Can a constructor have different name than a Class name in Java?
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Ans: Constructor in Java must have same name as the class name and if the name is different,
it doesn't act as a constructor and compiler thinks of it as a normal method.
Ans: In Java, there is not goto keyword and java doesn't support this feature of going to a
particular labeled line.
Ans: In java, a thread which is in dead state can't be started again. There is no way to restart a
dead thread.
Ans:
Ans: The above class declaration is incorrect as an abstract class can't be declared as Final.
Ans: JDK is development Kit of Java and is required for development only and to run a Java
program on a machine, JDK isn't required. Only JRE is required.
Q72. What's the difference between comparison done by equals method and ==
operator?
Ans: In Java, equals() method is used to compare the contents of two string objects and
returns true if the two have same value while == operator compares the references of two
string objects.
In the following example, equals() returns true as the two string objects have same values.
However == operator returns false as both string objects are referencing to different objects:
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
if (str1.equals(str2))
if (str1 == str2) {
} else
Q73. Is it possible to define a method in Java class but provide it's implementation in
the code of another language like C?
Ans: Yes, we can do this by use of native methods. In case of native method based
development, we define public static methods in our Java class without its implementation
and then implementation is done in another language like C separately.
Ans: In Java, there are no destructors defined in the class as there is no need to do so. Java
has its own garbage collection mechanism which does the job automatically by destroying the
objects when no longer referenced.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Ans: No a variable can't be static as well as local at the same time. Defining a local variable
as static gives compilation error.
Ans: Static methods can't be overridden in any class while any methods in an interface are by
default abstract and are supposed to be implemented in the classes being implementing the
interface. So it makes no sense to have static methods in an interface in Java.
Q77. In a class implementing an interface, can we change the value of any variable
defined in the interface?
Ans: No, we can't change the value of any variable of an interface in the implementing class
as all variables defined in the interface are by default public, static and Final and final
variables are like constants which can't be changed later.
Q78. Is it correct to say that due to garbage collection feature in Java, a java program
never goes out of memory?
Ans: Even though automatic garbage collection is provided by Java, it doesn't ensure that a
Java program will not go out of memory as there is a possibility that creation of Java objects
is being done at a faster pace compared to garbage collection resulting in filling of all the
available memory resources.
So, garbage collection helps in reducing the chances of a program going out of memory but it
doesn't ensure that.
Q79. Can we have any other return type than void for main method?
Ans: No, Java class main method can have only void return type for the program to get
successfully executed.
Nonetheless , if you absolutely must return a value to at the completion of main method , you
can use System.exit(int status)
Q80. I want to re-reach and use an object once it has been garbage collected. How it's
possible?
Ans: Once an object has been destroyed by garbage collector, it no longer exists on the heap
and it can't be accessed again. There is no way to reference it again.
Q81. In Java thread programming, which method is a must implementation for all
threads?
Ans: Run() is a method of Runnable interface that must be implemented by all threads.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Q82. I want to control database connections in my program and want that only one
thread should be able to make database connection at a time. How can I implement this
logic?
Ans: This can be implemented by use of the concept of synchronization. Database related
code can be placed in a method which hs synchronized keyword so that only one thread can
access it at a time.
Ans: In order to throw an exception in a block of code manually, throw keyword is used.
Then this exception is caught and handled in the catch block.
Q84. I want my class to be developed in such a way that no other class (even derived
class) can create its objects. How can I do so?
Ans: If we declare the constructor of a class as private, it will not be accessible by any other
class and hence, no other class will be able to instantiate it and formation of its object will be
limited to itself only.
Ans: In java, each object when created gets a memory space from a heap. When an object is
destroyed by a garbage collector, the space allocated to it from the heap is re-allocated to the
heap and becomes available for any new objects.
Q86. How can we find the actual size of an object on the heap?
Ans: In java, there is no way to find out the exact size of an object on the heap.
Q87. Which of the following classes will have more memory allocated?
Ans: Memory isn't allocated before creation of objects. Since for both classes, there are no
objects created so no memory is allocated on heap for any class.
Ans: If an exception is not handled in a program using try catch blocks, program gets aborted
and no statement executes after the statement which caused exception throwing.
Ans: If a class has multiple constructors, it's possible to call one constructor from the body of
another one using this().
Ans: An anonymous class is a class defined without any name in a single line of code using
new keyword.
For example, in below code we have defined an anonymous class in one line of code:
@Override
return false;
@Override
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
return null;
Q91. Is there a way to increase the size of an array after its declaration?
Ans: Arrays are static and once we have specified its size, we can't change it. If we want to
use such collections where we may require a change of size ( no of items), we should prefer
vector over array.
Q92. If an application has multiple classes in it, is it okay to have a main method in
more than one class?
Ans: If there is main method in more than one classes in a java application, it won't cause any
issue as entry point for any application will be a specific class and code will start from the
main method of that particular class only.
Q93. I want to persist data of objects for later use. What's the best approach to do so?
Ans: The best way to persist data for future use is to use the concept of serialization.
Ans: In Java, if we define a new class inside a particular block, it's called a local class. Such a
class has local scope and isn't usable outside the block where its defined.
Q95. String and StringBuffer both represent String objects. Can we compare String
and StringBuffer in Java?
Ans: Although String and StringBuffer both represent String objects, we can't compare them
with each other and if we try to compare them, we get an error.
Ans: Java provides a Collection API which provides many useful methods which can be
applied on a set of objects. Some of the important classes provided by Collection API include
ArrayList, HashMap, TreeSet and TreeMap.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Q97. Can we cast any other type to Boolean Type with type casting?
Ans: No, we can neither cast any other primitive type to Boolean data type nor can cast
Boolean data type to any other primitive data type.
Q98. Can we use different return types for methods when overridden?
Ans: The basic requirement of method overriding in Java is that the overridden method
should have same name, and parameters.But a method can be overridden with a different
return type as long as the new return type extends the original.
Class B extends A {
A method(int x) {
//original method
B method(int x) {
//overridden method
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Ans: In Java, Java.lang.Throwable is the super class of all exception classes and all
exception classes are derived from this base class.
Ans: In case of inheritance, when a new object of a derived class is created, first the
constructor of the super class is invoked and then the constructor of the derived class is
invoked.
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS
Join the telegram channel for more placement materials:
https://t.me/ajPlacementMaterials
Crack the coding interview in Product Based Company. Buy data structure book 90+
chapters covering Stack, Queue, Graph, Trees, Dynamic Programming:
https://imojo.in/ajGuideAlgoDS