Showing posts with label Core Java Interview Questions. Show all posts
Showing posts with label Core Java Interview Questions. Show all posts

13 July, 2019

Find all palindrome strings in a java array.


In this article, we will see how to find all palindrome strings from an array. This is a very frequently asked questions in interview.  Also there is a question to find all palindrome number from an array.  Find few more collection interview question.  


PalindromeStrings.java


package com.javadevelopersguide.lab.basic;
/**
 * This program illustrates find all palindrome strings from array.
 *
 * @author manoj.bardhan
 *
 */
public class PalindromeStrings {
public static void main(String[] args) {
String stringArray[] = { "eye", "jdg", "javadevelopersguide", "aabaa", "hello", "pip" };
for (int i = 0; i < stringArray.length; i++) {
printOnlyPalindrom(stringArray[i]);
}
}
private static void printOnlyPalindrom(String str) {
String oldString = str;
StringBuilder builder = new StringBuilder(str);
if (builder.reverse().toString().equals(oldString)) {
System.out.println(oldString + " is a Palindrome.");
}
}
}


Output -

Find all possible palindromes in an array

In this article, we will see how to find all palindrome from an array. This is a very basic questions in interview, the interviewer will ask the same questions in different way. So, its good to know all possible questions from palindrome. Also there is a question to find all palindrome number from a list.  Find few more collection interview question.  Today we will see how to check a number is palindrome or not. 


FindAllPalindrome.java

package com.javadevelopersguide.lab.basic;
/**
 * This program illustrates find all palindrome from array.
 *
 * @author manoj.bardhan
 *
 */
public class FindAllPalindrome {
public static void main(String[] args) {
int numberArray[] = { 120, 990, 121, 777, 808, 1280 };
for (int i = 0; i < numberArray.length; i++) {
printOnlyPalindrom(numberArray[i]);
}
}
private static void printOnlyPalindrom(int number) {
int finalNumber = 0;
int oldNumber = number;
// Repeat the loop until the number became zero.
while (number != 0) {
// Get the First Digit (i.e. 1)
int firstDigit = number % 10;
// Get the Result number.
finalNumber = (finalNumber * 10) + firstDigit;
// Now get the remaining digits , after finding the first digit
number = number / 10;
}
// Now compare the finalNumber and oldNumber both are same or not.
if (finalNumber == oldNumber)
System.out.println(finalNumber + " is a Palindrome.");
}
}

Output -

121 is a Palindrome.
777 is a Palindrome.
808 is a Palindrome.


Find the number is palindrome or not


In this article, we will see how to check if a number is palindrome or not. This is a very basic questions in interview. But, you never know about what kind of question the interviewer will ask. So, better you prepare for every certain questions. Also there is a question to find all palindrome number from a list.  Find few more collection interview question.  Today we will see how to check a number is palindrome or not. 


Palindrom.java


package com.javadevelopersguide.lab.basic;
/**
 * This program illustrates how to check a number is palindrome or not.
 *
 * @author manoj.bardhan
 *
 */
public class Palindrom {
public static void main(String[] args) {
int number = 121;
int temp = number;
int finalNumber = 0;
// Repeat the loop until the number became zero.
while (number != 0) {
// Get the First Digit (i.e. 1)
int firstDigit = number % 10;
// Get the Result number.
finalNumber = (finalNumber * 10) + firstDigit;
// Now get the remaining digits , after finding the first digit
number = number / 10;
}
// Now compare the finalNumber and number both are same or not.
if (finalNumber == temp) {
System.out.println("This number is a Palindrome.");
} else {
System.out.println("This number is not a Palindrome.");
}
}
}


Output -

This number is a Palindrome.

11 July, 2019

Find the largest number from an array using java

In this article, we will see how to find the largest number from an array using java.  This is one of basic questions in technical interviews. Earlier post we had seen how to find the smallest element from array. Now we will see how to find the largest number from integer array using java. 


The logic is very simple here, see the below.

  • At first we need to assume any element as largest value. Example - 0th location.
  • Then iterate over the array and compare with each element , whether its larger than the assumed larger value or not. If array element is larger then assign the array element value to assumed variable. Repeat the entire until end. 


FindLarestNumerInArray.java



package com.javadevelopersguide.lab.basic;
/**
 * This program illustrate how to find the Largest number from an array.
 *
 * @author manoj.bardhan
 *
 */
public class FindLarestNumerInArray {
// Find the largest value from an array.
public static void main(String[] args) {
int[] arr = { 200, 3, 4, 24, 33, 24, 22, 55, 90, 103, 150 };
// Assume the largest value is 0th Index
int largest = arr[0];
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] >= largest) {
largest = arr[i];
}
}
System.out.println("Largest Number is ::" + largest);
}
}


Output - 

Largest Number is ::200


Using Java 8

int largest = IntStream.of(arr).boxed().max(Comparator.naturalOrder()).get().intValue() ;


 Happy Learning.

10 July, 2019

Find the Missing Number in a list


In this article, we will see how to find the missing number from a list using java.  This is one of important common interview question asked in interview. You can see, how to find all missing numbers from a list. In this program we will use core java or the traditional way using for loop for finding the miss number from a list. Earlier post we had seen how to use stream for finding the missing number. Now we will see how to find one missing number using traditional core java style. 


The logic is very simple here, see the below.

  • At first we need to find the MAX number from the list. We need this MAX number because , we need to calculate the SUM of all natural number up to that max number. 
  • Then , we need to calculate the sum of all those natural number.
  • Then we will subtract each element from the given list from sumOfNaturalNumbers.
  • Now, the at the last  the value inside sumOfNaturalNumbers is the missing number.



FindOneMissingNumber.java


package com.javadevelopersguide.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
/**
 * This program finds the missing number from a list. This is only for one
 * missing number using core java before jdk 8.
 *
 * @author manoj.bardhan
 *
 */
public class FindOneMissingNumber {
public static void main(String[] args) {
ArrayList<Integer> numberList = new ArrayList<Integer>(
Arrays.asList(10, 3, 2, 4, 5, 6, 7, 9, 8, 14, 1, 11, 13));
int sumOfNaturalNumbers = getSumUptoMax(findMax(numberList));
for (int i = 0; i < numberList.size(); i++) {
/*
* Substract each elements from list from sumOfNaturalNumbers and
* the final value will be the missing.
*/
sumOfNaturalNumbers = sumOfNaturalNumbers - numberList.get(i);
}
int missingNumber = sumOfNaturalNumbers;
System.out.println("Missing Number is :: " + missingNumber);
}
// Find the sum of all natural numbers up to limitNumber.
private static int getSumUptoMax(int limitNumber) {
int sum = 0;
for (int i = 1; i <= limitNumber; i++) {
sum = sum + i;
}
return sum;
}
// Find the greatest value from the list
private static int findMax(ArrayList<Integer> numberList) {
int largest = 0;
for (int i = 0; i < numberList.size() - 1; i++) {
if (numberList.get(i) >= largest) {
largest = numberList.get(i);
}
}
return largest;
}
}


Output -

Missing Number is :: 12



Find one missing number from a list of numbers

In this article, we will find the missing number from a list of numbers using java 8.  This is one of important questions asked in interview. This program is to find the only one missing number. Check how to find all missing numbers from a list. In this program we will use only java 8 stream to find the missing number. Earlier post we had seen how to use stream to sort the employee. Check more how find one missing number using traditional core java style


FindMissingNumber.java

package com.javadevelopersguide.lab.basic;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
/**
 * This program finds the missing number from a list. This is only for one
 * missing number. Used the java 8 for this program.
 *
 * @author manoj.bardhan
 *
 */
public class FindMissingNumber {
public static void main(String[] args) {
ArrayList<Integer> numberList = new ArrayList<Integer>(Arrays.asList(1, 3, 2, 4, 5, 6, 7, 9, 10));
// Get the Max value from the List.
int maxValue = numberList.stream().max(Comparator.naturalOrder()).get().intValue();
// Get sum of all natural numbers - upto the above maxvalue
int sumOfAllNumber = IntStream.range(1, maxValue + 1).sum();
// Get the sum of all number inside List.
int sumofList = numberList.stream().mapToInt(Integer::intValue).sum();
// Now print the missing number.
System.out.println("The Missing Number is:: " + (sumOfAllNumber - sumofList));
}
}



Output - 

The Missing Number is:: 8




Happy Learning.



Follow for more details on @Facebook!!!

Find More  :-

01 July, 2019

Top 5 interview questions on BlockingQueue


1) What is BlockingQueue ? Under which package of JDK its available ?

Ans- A blocking queue is an interface. BlockingQueue implementations are thread-safe. It helps to handle multi threaded execution , specially its for producer and consumer problem.
The queue that blocks when you try to dequeue from it and the queue is empty, or if you try to enqueue items to it and the queue is already full. 

A thread trying to dequeue from an empty queue is blocked until some other thread inserts an item into the queue. 

There are few implementation for this BlockingQueue as below, all these classes available under java.util.concurrent package.
  • ArrayBlockingQueue
  • SyncronousBlockingQueue
  • PriorityBlockingQueue
  • LinkedBlockingQueue
  • DelayQueue


2) What is the use of these methods peek(), poll(), take() and remove() ?

Ans - 
peek() :- This retrieves, but does not remove, the head of this queue,or returns null if this queue is empty. It doesn't throw any exception.

poll() :- This retrieves and removes the head of this queue,or returns null if this queue is empty.It doesn't throw any exception.

take() :- This retrieves and removes the head of this queue, waiting if necessary until an element becomes available. This method waits for certain time , if its interrupted then it throws InterruptedException. 

remove() :- This retrieves and removes the head of this queue. This method differs from poll() only in that it throws an exception (NoSuchElementException ) if this queue is empty.

Apart from the above difference take() method is provided by BlockingQueue i.e. java.util.concurrent.BlockingQueue.take(). Where as other methods provided by Queue i.e.  java.util.Queue.poll(), java.util.Queue.peek(), java.util.Queue.remove()


3) Is this possible to declare BlockingQueue implementation with ZERO/0 size?

Ans- Yes, if its unbounded implementation. But,if its bounded then we have to provide a capacity. The capacity must be greater than ZERO (i.e. capacity > 0).If we create a BlockingQueue with ZERO capacity then this will throw java.lang.IllegalArgumentException.


4) Write a program for demonstrating producer & consumer problem using blocking
 queue.

Ans- Find the answer here.


5) What is the difference between ArrayBlockingQueue and LinkedBlockingQueue ?

Ans- ArrayBlockingQueue is a bounded blocking queue backed by an array of objects. LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. 
Linked queues typically have higher throughput than array-based queues but less predictable performance in most concurrent applications.Linked nodes are dynamically 
created upon each insertion unless this would bring the queue capacity (Integer.MAX_VALUE). 



Follow for more details on @Facebook!!!


Find More Questions & Answers Below.

11 March, 2018

Write a program to reverse a string using recursive method


The below example is to reverse string in java using recursive method.



package com.javadevelopersguide.www;
/**
 *
 * This Program will help you to reverse the string using recursive manner.
 *
 * @author manojkumar.bardhan
 *
 */
public class ReverseStringRecursive {
String resultString = "";
public static void main(String[] args) {
ReverseStringRecursive rec = new ReverseStringRecursive();
String inputString = "javadevelopersguide";
System.out.println("Input String::" + inputString);
String stringRev = rec.callReverse(inputString);
System.out.println("New Result String::" + stringRev);
}
private String callReverse(final String str) {
if (str.length() == 1) {
return str;
} else {
resultString += str.charAt(str.length() - 1)
+ callReverse(str.substring(0, str.length() - 1));
return resultString;
}
}
}

11 February, 2015

Sapient Interview Questions and Answers for Java 2 - 6 Year Experience

Sapient Interview questions for Java experience candidate - 2 -6 years.....

Q1) Tell me about yourself!!!

Ans – Give your brief introduction with full confidence.

Q2) What are the types of class loaders in Java ?

Ans – View Answer. 

 Q3)  How to read and write image from a file ?

Ans – By the use of ImageIO.read() and ImageIO.write()  method of javax.imageio package.

 Q4) What is difference between static and init block in Java ?

Ans – View Answer.

Q5) What is ConcurrentMap and how it works?

Ans – It’s a Map which providing thread safety and atomicity guarantees. For Memory consistency it works with other concurrent collections, actions in a thread prior to placing an object into a ConcurrentMap as a key or value happen-before actions subsequent to the access or removal of that object from the ConcurrentMap in another thread.

       Q6) Can a static block throw exception?

Ans –  Yes. We can throw checked exception.

Q7) What is difference between iterator access and index access?

Ans - Basically iterator access process the traverse operation through each element, where index access process access direct the element by using the index.

Q8) Why character array is better than string for storing password in Java?

Ans – Security !!! Because, character array stores data in encrypted format which is not readable by human. But, the string stores the data in human readable format which is not secure.

Q9) What is the difference between Serializable and Externalizable interfaces ?

Ans - Both interfaces are used for implement serialization. But, the basic
difference is Serializable interface does not have any method (it’s a
marker interface ) and Externalizable interface having 2 methods such as
 readExternal() and writeExternal(). Serializable interface is the super
interface for Externalizable interface. 

 Q10)   Which Interface is used to make duplicate of Objects ?

Ans – Cloneable interface.

 Q11) What are some advantages and disadvantages of Java Sockets?

Ans – The main advantage is its flexible and very efficient during low network bandwidth. Also its helpful for debugging and some kind of testing. But, security is the most disadvantages. Its always recommended to be careful when authenticating.

Q12)  When can an object reference be cast to an interface reference?

Ans –Yes its possible, when that interface is implemented by that class.

Example – MyInterface obj=new MyClass();
                obj.callMethod();

Q13)  How does Java allocate stack and heap Memory?

Ans – As we know stack memory is not dynamic and its follows LIFO order. Java provides similar implementation for memory allocation. Normally all local variables are created in Stack area (memory) and objects (reference types) are created in heap memory (heap area) .Even all primitive types allocated in stack memory. Heap area is dynamic and handled by JVM runtime. Heap memory is cleaned by garbage collector at runtime.

Q14)   What is memory leak in Java?


Ans – Usually memory leak leads to waste of memory. In general memory leak defines the unavailability of referenced memory. It causes the Garbage collector to fail to collect that object.

Q15) Can we throw exception from finally block in Java?

Ans – Yes, but you need to mentioned “throws” on the method head.

Example
        
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
TestInterface2 interObj=new InterfaceObject();

try{
interObj.display();
}catch(Exception e){
System.out.println("Exception handled...");
}finally{
throw new Exception("This is exception");
}
}

Q16)  How does Java handle integer overflows and underflows?

Ans – Yes, java handles overflows and underflows very intelligently. When it overflows it will go to MIN_VALUE (i.e. -231 ) and when it underflows to will go to MAX_VALUE (i.e. 231-1) .

Q18)  What is casting?

Ans – Casting means conversion. Basically we need casting to type cast the type. There are two types of casting by java i.e. explicit casting and implicit casting.

Q19)  What is new in JSP?

Ans – As per my knowledge JSP 2.1 has many new functionalities. It support resource injection via annotation. It has few extended support for java standard tag library. Also literal expression is supported by JSP 2.1 EL  and many other additional features.

Q20) What do you mean by Java Reflection ?

Ans – It provides runtime access to JVM.  Reflection is one of the most powerful API  which help to work with classes, methods and variables dynamically at runtime. Basically it inspects the class attributes at runtime. Also we can say it provides a metadata about the class. 

Q21) Why does the InputStreamReader class has a read() ?

Ans – Because, an InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.  It has two overloaded read() method . Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.

Q22)   Describe a problem you faced and how did you solve that?

           Ans  - You can describe any issue you faced during your project work in the                          organization. And what the solution you have implemented for that issue.