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

Monday, September 7, 2026

Top 5 Interview Questions on BlockingQueue in Java


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). 

Birla Soft Interview Question and Answers for Java 2- 4 year experience

The below questions asked by Birla Soft for Java/J2EE. I tried to give the best answer , hope it will help you out to crack the interview.

Q. Tell me about your self?
 Ans:  Give your brief introduction.

Q. Is Java Pass by Reference or Pass by Value?
Ans : Its always pass by value .

Q. What is the difference between an Interface and an Abstract class?
Ans : Both are looks similar. But, the basic difference is abstract class can contain abstract and non abstract methods, where interface only contains abstract method (without method body). You can declare fields that are not static and final, and define public, protected, and private concrete methods in abstract class. But, in Interface all members are public, static and final , all methods are public.

Q. What is the purpose of garbage collection in Java, and when is it used?
Ans : Garbage collection is a special feature in java language. It helps developer to save time and extra mental tension for handling object allocation in memory. It automatically clean the unused object from memory which helps to allocate space at runtime. When there is no reference to an object found, it will clean that object from memory . You can run the garbage collection explicitly by using System.gc() .

Q. What is Marker interface? How is it used in Java?
Ans : Marker interface is an interface which help us to notify few information to JVM/Compiler. The marker interface does not have any body, it’s a empty interface. Ex. Cloneable, Serialization, etc.            

Q. Can you give few examples of final classes defined in Java API?
Ans: String, Integer ,Float ,etc. Basically all wrapper classed are final.

Q. What is the importance of init() method in Servlet?
Ans:  init() method is one of the life cycle method of servlet. This method runs once in total life. After servlet instance created and before it handles request the init() method will work. Its basically used for initializing values at the time of application startup.

Q. How to improve Servlet Performance ?
Ans: You need to do few tuning for this achievement. Few points below :-

1.     Use init() method for all expensive operation during initialization (may be static data or cached data ).
2.     Always avoid auto loading of servlet.
3.     Avoid SingleThreadModel.
4.     Use and control HttpSession properly.

Q. How can a Servlet refresh automatically if some new data has entered the database?
Ans :  Basically it depends on the scenario , how you can handle. You need  handle this in DAO layer, when doing insert operation you can call an utility method which will load the context ServletContextListener. Because, servlets are basically used for handling request and give the response.

Q. How does JSP handle run-time exceptions?
Ans: You can use isErrorPage=”true” in page attribute.

Q. What is an EJB Context?
Ans: The EJBContext interface provides an instance with access to the container-provided runtime context of an enterprise bean instance.

Accenture Java Interview Questions and Answers

Accenture interview question for Java 3-8 year experience.

Q1. Why do you want to work in this industry / company?

Ans: First you should try to convince that this company gives huge opportunity in many aspect i.e. new technologies implementation, the policy of company suits you like professionalism.   Also you can mention that you are big fan of this company and its your dream company. Basically show your all positive attitude towards company.

Q2. Which location do you want to work in and why?

Ans : Give your own choice. Also mention a valid reason for why you are interested for that location. The reason should be always positive and clear. Example :- you can support your family from this location,

Q3. Describe a problem you faced and how you deal with it ?

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.

Q4. What are the types of class loaders in Java?

Ans  :  As per my knowledge there are basically 3 types of class loader like bootstrap class-loader,extension class loader and system class loader.
  • Bootstrap Class Loader
    Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.
  •  Extensions Class Loader
    JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment property java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader
  • System Class Loader
                  Java classes that are available in the java class-path are loaded using System class loader

Q5. Write your own ArrayList in Java ?

      Your own code here .

Q6. How to read and write image from a file ?

Ans : You can use ImageIo.read() and ImageIO.write()  method of javax.imageio package.

Q7. What is difference between static and init block in java.

Q8. How ConcurrentHashMap works?

Ans : The basic design of ConcurrentHashMap is to handling threading. Basically it locks each of the box (by default 16) which can be locked independently and thread safe for operation. And it does not expose the internal lock process.

Q9. Can a static block throw exception?

Ans : Yes. We can throw checked exception.

Q10. 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.

Q11. Why character array is better than string for storing password in java?

Ans : 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.

Q12. what is daemon thread in java ?

Ans : A daemon thread is normally runs on background. And it does not prevent the JVM from exiting when the program finishes but the thread is still running.

Q13. What is Java Reflection API?

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

Q14. 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. 

Experienced Java/J2EE interview questions by MNC

Experienced Java/J2ee Interview questions asked by MNC.

1. Why main() in java is declared as public static void main? What if the main method is declared as
private?


Ans : Because, every program start execution from main function.The static method can directly call without creating the object of the class.So, before creating object the main function runs and then it creates object.

And, public in main method due to access by JVM. If the method is private then JVM cannot call that function.The program will compile but never run.It show the message  "Main method not public."


2.What is Externalization?

Ans : This interface is used for serialization.To save the state of an object in file. It provides two method
readExternal() and writeExternal().

3.What modifiers are allowed for methods in an Interface?
Ans : abstract and public

4.What are the different identifier states of a Thread?

Ans :
R- Running or Runnable
S- Suspended
MS- Thread Suspended on Monitor lock
MW- Thread waiting on monitor
CW- Thread waiting on condition variable


5.What are some alternatives to inheritance?

Ans : Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).

6.Why isn’t there operator overloading?

Ans : Because C++ has proven by example that operator overloading makes code almost impossible to maintain.

7.What does it mean that a method or field is “static”?

Ans : Static method or field are member of class.They do not need any object for call or access . We can directly call the static method and fields without using the object.

Tavant Technologies Java Interview Questions - Experienced

Tavant Technologies
Round 1:F2F
1) Tell about your technical skills
2) How to work with Ajax applications?
4) Asked about page factory design concepts.
5) What are the collections u used in your project?
6) Framework explanation
7) How to find no of rows or columns in a table?
8) Diff b/w interface and abstract class?
9) Various oops concepts used in the project?
10) Roles and responsibilities.
11) SQL queries a) how to find duplicate records in a table b) Display the name of the employee who is getting         10th maximum salary
12) Logical questions:
i) A 2l bottle and a 4l bottle, By this u have to give me 3l of water? Is it possible? If yes tell me how
ii) 8 balls, having same color and weight, out of that 1 is defective, a physical balance is given, using this how to find the defective one.

Round 2
1. What is run-time polymorphism? Explain with program? Where is it achieved?
2. SQL queriesemp table fieldsename,eid,age
a) Find the name of the employee who has 3rd max age
b) Having clause and where clause
3. Logical questions
a) Cake in round shape, u have to cut the cake by 3 times only, and u have to divide into 8 equal pieces
b) Using 5 zeros, how to make it as 120
c) He gave me a paper, asked me to tore the paper once, to make 3 equal pieces


Round 3- HR+ Managerial round

1. Tell about your self
2. Why u r looking for the job?
3. What are the difficulties you faced in your previous job?
4. He is asking the same questions in different ways for 15 min
5. Framework
6. Difference b/w abstract class and interface.
7. Scenario-an abstract class implements an interface, can the abstract class implement the methods of interface?
8. From that he asked that do u perform auto it scripts in parallel execution?
9. Difference B/w primary key and unique key
10. Can unique key column hold null values? If yes how many null values?
11. Use of super keyword, order of execution
12. Collections u used in the project
13. When array will be used ? and when array list will be used?



Saturday, August 9, 2014

Experienced Java Interview questions asked by CGI

3+ Year experienced java questions asked by CGI.

       1)  Tell me about your self ?

    Ans : Just describe yourself with cool & confidence.
    
2) What you know about our company?

   Ans : Remember , it’s a very crucial question. You must do one R&D before going to interview. You should know about their product, technical stuffs they are working, market value of the company and other important stuffs.

3) What is transient variable ?

   Ans : Transient variables are not serializable. It helps to avoid a variable to being serialization.

4) Write the code to initialize the inner class members.

Ans : Code here

public class InnerClassTest {

      class innerTest{
            private int age;
           
            public void display(){
                  System.out.println("Age="+age);
            }
      }
      /**
       * @param args
       */
      public static void main(String[] args) {
            InnerClassTest.innerTest innerObj=new InnerClassTest().new innerTest();
            innerObj.age=20;
            innerObj.display();
      }
}
 5) How to retrieve the elements from the collection write the code ?

Ans : Java provides certain interfaces by using that we can retrieve the elements from collection.Example – Iterator, ListIterator and Enumeration.

Example :- ArrayList data retrival

public class ArrayListRetrive {

      /**
       * @param args
       */
      public static void main(String[] args) {
            ArrayList<String> arList=new ArrayList<String>();
            arList.add("Java");
            arList.add("is");
            arList.add("Powerful!!!");
           
            //Retrive elements from ArrayList using Iterator
            Iterator iTer=arList.iterator();
            while(iTer.hasNext()){
                  System.out.println(iTer.next());
            }
      }

}
6) What is static and instance variables and methods ?

Ans : Static variables are per class but the instance variables are per object. All object share a single copy of static variable. In case of static method , no need of object creation for calling static method. The static method can directly call by using class name. Instance method need object for calling.
7) What is dynamic loading and static loading of java class ?

Ans : Dynamic class loading is by Class.forName() , which loads the class dynamically. Also you can use reflection for dynamic class loading. But, the static class loading is working by using ‘new’ keyword.

8) What type of loading is class.forname() ?

Ans : Its dynamically locate and loads the class.

9) What is Hibernate 3 best benefits ?

Ans : There are many benefits of hibernate. But the most benefits are below :-

1.     It reduces the developer effort to writing queries.
2.     Its easy to use with relational object which maps with java class and database relation.
3.     Query tuning is not required and it implements separates cache which is reason for better performance.

10) I have 100 tables and fields. I want to find one table name and  column names.  Write a quey .

Ans :  I have used MySQL database for this below query.
select TABLE_SCHEMA,TABLE_NAME,COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='EMPLOYEE';

 11) How to define a field name in hibernate using annotation ?


          Ans:- @Column  (Its provided by java persistent  API).

 12) What is Synchronization ?

          Ans:- Synchronization is a solution for concurrency issue. Java provide 'synchronized' keyword for implementing this.

  13) The most commonly used classes in collections ?

Ans : ArrayList, LinkedList, HashTable, HashMap and ConcurrentHashMap, etc.