Core Java Questions For 5 To 6 Years Experienced
1. What is Busy Spinning? Why Should You Use It in Java? waiting strategysleepsuspending the thread50+ advanced thread interview questions2. What is Read-Write Lock? Does ConcurrentHashMap in Java Use The ReadWrite Lock?lock strippingread and write lockonly a portion of the ConcurrentHashMap is lockedhow ConcurrentHashMap internally works in JavaJava Concurrency in Practice3. How to Make an Object Immutable in Java? Why Should You Make an Object Immutable?here Why String is Immutable in Java4. Which Design Patterns have You Used in Your Java Project?Dependency Injection Patternactuallyhave you used this pattern in your project?this5. Do you know about Open Closed Design Principle or Liskov Substitution Principle?object-oriented design principlesClean Code6. Which Design Pattern Will You Use to Shield Your Code From a Third Party library Which Will Likely to be Replaced by Another in a Couple of Months?code against an interface rather than implementationJava developers with 5 to 7 years of experienceQuestion 7. How do you prevent SQL Injection in Java Code?use PreparedStatement to avoid SQL injectionSession Fixation attacksCross-Site ScriptingQuestion 8) Tell me about different Reference types available in Java, e.g. WeakReference, SoftReference, or PhantomReference? and Why should you use them? WeakReferenceJava Performance The Definitive GuideQuestion 9) How does get method of HashMap works in Java? how does HashMap work in Javahereequals
Q4 What Is Data Encapsulation And Whats Its Significance
Ans: Encapsulation is a concept in Object Oriented Programming for combining properties and methods in a single unit.
Encapsulation helps programmers to follow a modular approach for software development as each object has its own set of methods and variables and serves its functions independent of other objects. Encapsulation also serves data hiding purpose.
Write A Java Program That Illustrates Merge Sort
Merge sort is one of the most efficient sorting algorithms. It works on the principle of âdivide and conquerâ. It is based on the idea of breaking down a list into several sub-lists until each sub-list consists of a single element, and then merging those sub-lists in a manner that results in a sorted list. The following example code shows one way to use merge sort:
publicclassMergeSort int merged =mergeSort for}publicstaticintmergeTwoSortedArrayselse}if}if}return sorted }publicstaticintmergeSortint mid =/2 int fh =mergeSort int sh =mergeSort int merged =mergeTwoSortedArrays return merged }}
Recommended Reading: What Are Some Questions To Ask In An Interview
Write A Java Program To Rotate Arrays 90 Degree Clockwise By Taking Matrices From User Input
mport java.util.Scanner publicclassInterviewBit } System.out.print for System.out.println } System.out.println //Rotation//Transposefor }//Reverse Each rowfor } System.out.println for System.out.println } }}
In the above code, for rotating the matrix to 90 degrees we are first transposing the matrix so the row becomes the column. And after that, we are reversing each row in the matrix. So this is how the matrix got rotated.
How Do You Implement A Binary Search In Java
The array elements must be sorted to implement binary search. The binary search algorithm is based on the following conditions:
- If the key is less than the middle element, then you now need to search only in the first half of the array.
- If the key is greater than the middle element, then you need to search only in the second half of the array.
- If the key is equal to the middle element in the array, then the search ends.
- Finally, if the key is not found in the whole array, then it should return -1. This indicates that the element is not present.
The following example code implements a binary search:
publicstaticintbinarySearchelseifelsemid =/2 }ifreturn-1 }
Don’t Miss: Google Interview System Design Questions
Q2 Name The Different Modules Of The Spring Framework
Some of the important Spring Framework modules are:
- Spring Context for dependency injection.
- Spring AOP for aspect oriented programming.
- Spring DAO for database operations using DAO pattern
- Spring JDBC for JDBC and DataSource support.
- Spring ORM for ORM tools support such as Hibernate
- Spring Web Module for creating web applications.
- Spring MVC Model-View-Controller implementation for creating web applications, web services etc.
What Is The Benefit Of A Multi
Multi-catch block is an improvement that came with the Java 7 release. Be ready to answer questions on this critical part of the programming language.
Example answer:”With multi-catch blocks, code is shorter. This makes code easier to create and easier for others to interpret. Also, making exception parameters final is less complex with this format.”
Don’t Miss: Do You Have Any Questions Interview
What Are The Different Types Of Thread Priorities In Java And What Is The Default Priority Of A Thread Assigned By Jvm
There are a total of 3 different types of priority available in Java.
MIN_PRIORITY: It has an integer value assigned with 1.MAX_PRIORITY: It has an integer value assigned with 10.NORM_PRIORITY: It has an integer value assigned with 5.
In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default priority for any thread is NORM_PRIORITY assigned by JVM.
Advanced Java Interview Questions For 5 To 7 Years Experienced Programmers
Without wasting anymore of your time, here is a list of my favorite advanced Java questions related to debugging, profiling, coding, performance improvement and on many practical topics which only a senior Java developer can be familiar.
1) How do you measure execution time of a code or method in Java?
hint, – you can use System.nanoTime or System.currentTimeInMillis method to track start time and end time and then calculate difference.
2) What are the tools to profile a Java application?
You can use profilers like JProbe, YourKit, as well NetBeans profiler to profile your Java application.
3) What do you mean by latency and throughput of Java application?
Latency is time related like how much time it take to do certain task like sending order to exchange and throughput is about how many orders you can do per second, minute or hours. Generally speaking, low latency and high throughput is desired in Java application for better performance.
4) How do you measure latency and throughput of Java program?
hint – by tracking time it take to complete certain task.
5) What are some common problem performance areas in Java web application?
6) How do you find the time spent in Garabage collection by your application?
7) How do you deal with OutOfMemoyrError in Java?
8) How do you deal with NoClassDefFoundError in Java?
9) What is the maximum memory you can provide to a 32-bit JVM?
10) What is difference between serial and parallel garbage collector?
disk space, OutOfMemory, DeadLock
Read Also: How To Ask For Interview Feedback
Q4 What Are The Differences Between Forward Method And Sendredirect Methods
|forward sends the same request to another resource.||sendRedirect method sends new request always because it uses the URL bar of the browser.|
|forward method works at server side.||sendRedirect method works at client side.|
|forward method works within the server only.||sendRedirect method works within and outside the server.|
Question 1: What Is Immutable Object Can You Write Immutable Class
Immutable classes are Java classes whose objects cannot be modified once created. Any modification in an Immutable object results in a new purpose for example, String is immutable in Java.
Mostly Immutable classes are also final in Java to prevent subclasses from overriding methods, which can compromise Immutability.
You can achieve the same functionality by making member as non-final but private and not modifying them except in constructor.
Apart from obvious, you also need to make sure that you should not expose the internals of an Immutable object, mainly if it contains a mutable member.
Similarly, when you accept the value for the mutable member from client e.g. java.util.Date, use the clone method to keep a separate copy for yourself to prevent the risk of malicious client modifying mutable reference after setting it.
The Same precaution needs to be taken while returning value for a mutable member, return another separate copy to the client, never return original reference held by Immutable class. You can also see my post How to create an Immutable class in Java for step by step guide and code examples.
Read Also: How To Answer Questions During An Interview
What Are Oops Concepts In Java
The OOPs concepts stand for Object-Oriented Programming in Java and cover the following elements: class, object, encapsulation, inheritance, polymorphism, and abstraction. All these assist in ensuring the applications reusability, security, and flexibility, and allows developers to create the working methods and variables, then reuse them all or part of them without compromising the system security.
What Is Hibernate Framework
Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is Java-based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa.
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.
Similarly, hibernate configurations are flexible and can be done from XML configuration file as well as programmatically.
You May Like: How To Prepare For Google Non Technical Interview
What Is The Inheritance
Inheritance is a mechanism by which one object acquires all the properties and behavior of another object of another class. It is used for Code Reusability and Method Overriding. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
There are five types of inheritance in Java.
- Single-level inheritance
Using Relevant Properties Highlight The Differences Between Interfaces And Abstract Classes
- Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes.
- Variable types: Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables.
- Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.
- Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also.
- Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true
Abstract class example:
Read Also: Best Way To Record Video Interviews
How Do You Create An Object In Java What Is An Object Used For
This question tests your skills with creating and integrating Java code into various processes. Use examples from past experiences and your knowledge of programming concepts using Java functions.
Example:”Objects in Java are real-world entities that have three key characteristics: a state, behavior and identity. This can be anything from an image display to a title on a web application, but essentially, I initiate the ‘new’ keyword under the programming code so it appears as ClassName obj = new ClassName . This makes it easy to categorize and define specific objects, such as what you would see in an online shopping process where I would create objects for this system, like a shopping cart, product or customer.”
What Is A Final Class In Java
This is a question regarding Java’s architecture. Answer it by defining what final means and explaining why it is useful.
Example answer:”This is a designation that says a class cannot be extended or overridden by a subclass. Declaring a class final helps prevent inheritance and keeps information secure.”
Recommended Reading: What Is The Good Question To Ask In Interviews
Explain Semantic Html With An Example And Why We Should Use It
In web design, the idea of using HTML elements to indicate what they actually are. It is known as semantic HTML or semantic markup.
Semantic HTML is HTML that represents meaning to the web page rather than just presentation. For example, tag < p> indicates that a paragraph is enclosed in it. It is both semantic and presentational because the user know what paragraph are and the browser also know how to display them. On the other hand, tags such as < b> and < i> are not semantic. They only represent how text should look. These tags do not provide any additional meaning to the markup.
Example of semantic HTML tags are header tags< h1> to < h6> , < abbr> , < cite> , < tt> , < code> , < blockquote> , < em> , etc. There are some other semantic HTML tags that are used to build a standards-compliant website.
We should use the semantic HTML for the following reasons:
- It provides additional information about the document in which it is used. It also aids in communication.
- Semantic tags make it clear to the browser what the meaning of a page and its content is.
- It provides information about the contents of those tags that goes beyond just how they look on a page.
- It gives us many more hooks for styling the content of the page.
- The clarity of semantic tag is also communicated with search engines that ensure the right pages are delivered for the right queries.
Q 59 Explain The Different Authentications In Java Servlets
Authentication options are available in Servlets: There are four different options for authentication in servlet:
- Basic Authentication:
Usernames and passwords are given by the client to authenticate the user.
- Form-based authentication:
In this, the login form is made by the programmer by using HTML.
- Digest Authentication:
It is similar to basic authentication, but the passwords are encrypted using the Hash formula. Hash Formula makes digest more secure.
- Client certificate Authentication:
It requires that each client accessing the resource has a certificate that it sends to authenticate itself. Client Authentication requires the SSL protocol.
Recommended Reading: What Are Some Good Questions To Ask The Interviewer
Q1 What Is The Difference Between Error And Exception
An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors you cannot repair them at runtime. Though error can be caught in the catch block but the execution of application will come to a halt and is not recoverable.
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.
How Many Ways To Handle Exceptions In The Spring Mvc Framework
Spring MVC Framework provides the following ways to handle exceptions:
- Controller-Based: We can define the exception handler method in our controller class.
- Global Exception Handler:Exception handling is a cross-cutting concern that Spring
- HandlerExceptionResolver: Any Spring Bean declared in the DispatcherServlet’s application context that implements HandlerExceptionResolver will be used to intercept and process any exception raised in the MVC system and not handled by a Controller.
Also Check: What To Wear For A Video Interview
Can You Prove That A String Object In Java Is Immutable Programmatically
The following example code shows how to prove that a String object is immutable and the comments in the code explain each step:
String s1 ="Java" // "Java" String created in pool and reference assigned to s1String s2 = s1 //s2 also has the same reference to "Java" in the poolSystem.out.println // proof that s1 and s2 have the same references1 ="Python" //s1 value got changed above, so how String is immutable?//in the above case a new String "Python" got created in the pool//s1 is now referring to the new String in the pool //BUT, the original String "Java" is still unchanged and remains in the pool//s2 is still referring to the original String "Java" in the pool// proof that s1 and s2 have different referenceSystem.out.println System.out.println // prints "Java" supporting the fact that original String value is unchanged, hence String is immutable
Can You Tell Me What The Four Access Modifiers Are In Java And Explain Why We Use Them
When answering this question, list all four access modifiers and show your understanding by giving a clear and efficient description of why programmers use them.
Example answer:”The four access modifiers are public, private, protected and default. We use them to determine who has access to information or keywords within a class.”
You May Like: Interview Questions For Territory Sales Manager
How Can Constructor Chaining Be Done Using This Keyword
Constructor chaining enables us to call one constructor from another constructor of the class with respect to the current class object. We can use this keyword to perform constructor chaining within the same class. Consider the following example which illustrates how can we use this keyword to achieve constructor chaining.
ID: 105 Name:Vikas age:22 address: Delhi
How We Can Set The Spring Bean Scope And What Supported Scopes Does It Have
A scope can be set by an annotation such as the @Scope annotation or the “scope” attribute in an XML configuration file. Spring Bean supports the following five scopes:
- Step 1: 163 => 1+6+3 = 10
- Step 2: 10 => 1+0 = 1 => Hence 163 is a magic number
publicclassIBMagicNumber sumOfDigits += num % 10 num /= 10 } // If sum is 1, original number is magic number if else }}
Also Check: How To Prepare For Java Coding Interview