Q11 What Is Encapsulation In Java
Encapsulation is a mechanism where you bind your data and code together as a single unit. Here, the data is hidden from the outer world and can be accessed only via current class methods. This helps in protecting the data from any unnecessary modification. We can achieve encapsulation in Java by:
- Providing public setter and getter methods to modify and view the values of the variables.
How Do You Make This Code Print 05 Instead Of 0
finaldouble d = 1 / 2 System.out.println
prints 0. Why? How do you make this code print 0.5 instead?
The problem here is that this expression:
1 / 2
has integer literals on both sides of the operator: 1 and 2. As a consequence, an integer division will be performed, and the result of 1 divided by 2 in an integer division is 0.
In order for the result to be a double as expected, at least one operand of the operation needs to be a double. For instance:
finaldouble d = 1 / 2.0
finaldouble d = 1.0 / 2
Core Java Interview Questions For Senior Developers And Tech Lead
Hashtable and ConcurrentHashMap4. What is CountDownLatch in Java?5. What is CyclicBarrier in Java?6. What is the difference between CountDownLatch and CyclicBarrier in Java?CountDownLatch in JavaDifference between CountDowntLatch and CyclicBarrier in Java8. What is deadLock in Java? Write code to avoid deadlock in Java?how to avoid deadlock in JavaWhat is a race condition in JavaOutOfMemoryError in PermGen or MetaSpace mens
Read Also: How To Thank An Employer For An Interview
Contiguous Memory Locations Are Usually Used For Storing Actual Values In An Array But Not In Arraylist Explain
In the case of ArrayList, data storing in the form of primitive data types is not possible. The data members/objects present in the ArrayList have references to the objects which are located at various sites in the memory. Thus, storing of actual objects or non-primitive data types takes place in various memory locations.
However, the same does not apply to the arrays. Object or primitive type values can be stored in arrays in contiguous memory locations, hence every element does not require any reference to the next element.
Question : What Is The Difference Between Factory And Abstract Factory Pattern
Answer: Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for the creation of different hierarchies of objects based on the type of factory. E.g., AbstractFactory extended by AutomobileFactory, UserFactory, RoleFactory, etc. Each factory would be responsible for the creation of objects in that genre.
If you want to learn more about the Abstract Factory design pattern, then I suggest you check out the Design Pattern in Java course, which provides excellent, real-world examples to understand patterns better.
Here is the UML diagram of the factory and abstract factory pattern:
If you need more choices, then you can also check out my list of Top 5 Java Design Pattern courses.
Question 9: What is Singleton? is it better to make the whole method synchronized or only critical section synchronized? Singleton in Java is a class with just one instance in the entire Java application, for example, java.lang.Runtime is a Singleton class.
Creating Singleton was tricky before Java 4, but once Java 5 introduced Enum, its straightforward.
You can see my article How to create thread-safe Singleton in Java for more details on writing Singleton using the enum and double-checked locking, which is the purpose of this Java interview question.
Don’t Miss: How To Write A Letter After An Interview
Can The Static Methods Be Overridden
- No! Declaration of static methods having the same signature can be done in the subclass but run time polymorphism can not take place in such cases.
- Overriding or dynamic polymorphism occurs during the runtime, but the static methods are loaded and looked up at the compile time statically. Hence, these methods cant be overridden.
Why Is It Said That The Length Method Of String Class Doesn’t Return Accurate Results
- The length method returns the number of Unicode units of the String. Let’s understand what Unicode units are and what is the confusion below.
- We know that Java uses UTF-16 for String representation. With this Unicode, we need to understand the below two Unicode related terms:
- Code Point: This represents an integer denoting a character in the code space.
- Code Unit: This is a bit sequence used for encoding the code points. In order to do this, one or more units might be required for representing a code point.
Now if a string contained supplementary characters, the length function would count that as 2 units and the result of the length function would not be as per what is expected.
In other words, if there is 1 supplementary character of 2 units, the length of that SINGLE character is considered to be TWO – Notice the inaccuracy here? As per the java documentation, it is expected, but as per the real logic, it is inaccurate.
Recommended Reading: What Questions To Prepare For An Interview
How Do You Find If Your Java Application Has A Deadlock
The Deadlock in Java is a situation in which two threads are waiting for each other to finish the process and release the lock. Deadlock detection is a complicated process. Usually, we need to restart the applications, but sometimes we may lose our work. So to avoid this problem, we can use some Deadlock detector classes in Java. One of the most used classes to detect the Deadlock is ThreadMXBean class.
What Is The Problem With This Code:
final bytes = someString.getBytes
There are, in fact, two problems:
- the code relies on the default Charset of the JVM
- it supposes that this default Charset can handle all characters.
While the second problem is rarely a concern, the first certainly is a concern.
For instance, in most Windows installations, the default charset is CP1252 but on Linux installations, the default charset will be UTF-8.
As such, such a simple string as é will give a different result for this operation depending on whether this code is run on Windows or Linux.
The solution is to always specify a Charset, as in, for instance:
final byte bytes = someString.getBytes
The what is the problem with this code? question is one of the most popular Java interview questions, but its not necessarily going to be this one above, of course. Be prepared to do some detective work to identify the issue.
Also, keep in mind: while the problem may be exception handling, method overloading, an access specifier issue, or something else, it could also be nothing at all! This is one of those trick Java interview questions where the answer will rely on your gut that everything is perfect with the code already.
Don’t Miss: Free Online Interview And Interrogation Courses
Is This Program Giving A Compile
abstractfinalclassInterviewBit4.classScalarAcademyextendsInterviewBit8. }9.classScalarTopicsextendsScalarAcademy13. }publicclassMain}
The above program will give a compile-time error. The compiler will throw 2 errors in this.
It is because abstract classes are incomplete classes that need to be inherited for making their concrete classes. And on the other hand, the final keywords in class are used for avoiding inheritance. So these combinations are not allowed in java.
Q100 Whats The Order Of Call Of Constructors In Inheritance
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.
Prep Up For your Job Interview!!! Go through Java Tutorial to be better prepared.
This detailed Java Mock Test Quiz will help you to clear the doubts about Java interview questions and will also help you to crack the interview.
These interview questions will also help in your viva
You May Like: How To Prepare For Hr Manager Interview
What Is The Use Of System Class
Java System Class is one of the core classes. One of the easiest ways to log information for debugging is System.out.print method.
System class is final so that we canât subclass and override its behavior through inheritance. System class doesnât provide any public constructors, so we canât instantiate this class and thatâs why all of its methods are static.
Some of the utility methods of System class are for array copy, get the current time, reading environment variables. Read more at Java System Class.
Also Check: What Questions Do You Get Asked In An Interview
Tech Lead Interview Questions
The Indeed Editorial Team comprises a diverse and talented team of writers, researchers and subject matter experts equipped with Indeed’s data and insights to deliver useful tips to help guide your career journey.
When hiring for a technical lead position, employers are looking for someone with a strong technical and leadership background. Show employers that you are qualified for this type of role by preparing for your interview. Many employers ask similar tech lead interview questions to get a better idea of your skills, background and experience in this field. In this article, we share 35 common tech lead interview questions and provide a few sample answers.
Read Also: What To Wear For An Interview Female 2021
Why Is The Main Method Static In Java
The main method is always static because static members are those methods that belong to the classes, not to an individual object. So if the main method will not be static then for every object, It is available. And that is not acceptable by JVM. JVM calls the main method based on the class name itself. Not by creating the object.
Because there must be only 1 main method in the java program as the execution starts from the main method. So for this reason the main method is static.
What Are The Advantages Of Hibernate Over Jdbc
Some of the important advantages of Hibernate framework over JDBC are:
Also Check: How To Interview For A Sales Job
First Things First: Select Your Job Requirements
Ultimately, an interview is about finding someone capable of producing the Java code you need while working effectively with your team. To do that, you need to figure out your unique job requirements.
Some example requirements include:
- Programming skills E.g. Object-Oriented Design
- Java-specific skills
- Design skills Performance optimization, building scalable applications, concurrency
- Communication skills Discussing problems and constraints
- Being a self-starter if theyll have to figure out solutions by themselves
Avoid making a shopping list of your perfect Java developer. Instead, focus on what your candidate will really be doing day-to-day. You should keep your requirements list as short as possible. Cut anything they can do without or learn on the job.
With clearly stated requirements, youll be able to choose the right Java coding interview questions and have a much better idea of what kinds of responses you are looking for.
What Does The Term Method Reference Mean In The Context Of Java 8
Method reference is a Java 8 construct used to reference a method without having to invoke it. It is a compact method of Lambda expression.
Now that we know basic java 8 interview questions, lets check the intermediate level questions.
Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.
Also Check: How To Prepare For Zoom Interview
Explain The Difference Between Path And Classpath
The Path is used to define the executables files, where the system can find them, whereas the classpath is used to specify the location.
In Java, we define the path variable to set the path for all Java tools like javac.exe, java.exe, javadoc.exe, and so on, and the classpath is used to set the path for Java classes.
What Is The Thread Dump Of Java Process How Do You Take It
A Thread dump is a state of all the threads presented in a Java process at the moment. Each thread’s state is available with a stack trace. It is useful for diagnosing thread activity problems. Usually, they are written in plain text, so we can save the data of a thread data in a file and analyze them later. There are different tools available in Java, such as jstack and JMC, to take the Thread dump of a process.
You May Like: Best Way To Conduct An Interview
Write A Function To Detect If Two Strings Are Anagrams
This is my go-to first interview question. It helps me gauge a candidates ability to understand a problem and write an algorithm to solve it.
If someone has not solved the problem before, I expect to see some code with loops and if/thens. Maybe some HashMaps. The things I look for are the ability to break down the problem to see what you need to check, what the edge cases are, and whether the code meets those criteria.
The naive solution is often to loop through the letters of the first string and see if theyre all in the second string. The next thing to look for is that the candidate should also do that in reverse too ? The next thing to look for is, what about strings with duplicate letters, like VASES?
If you can realize that these are all required and create a functional, non-ridiculous solution, I am happy.
Of course, one can solve it trivially by sorting both strings and comparing them. If someone catches this right away, usually they have seen the problem before. But thats a good sign that someone cares enough to do prep work. Then we can tackle a harder problem.
publicstaticbooleanisAcronym else }// Compare counts with characters in s2for i++) else }// Check all letters matchedfor ) returntrue }
The details of the implementation are not important whats important is someone understanding what they need to do, and then understanding why their solution works or doesnt work. If you can demonstrate this, youre on the right track.
Q17 What Are The Important Methods Of Java Exception Class
Methods are defined in the base class Throwable. Some of the important methods of Java exception class are stated below.
Synchronized Throwable getCause This method returns the cause of the exception or null id as represented by a Throwable object.
Read Also: Top 10 Coding Interview Questions
Q9 What Are The Differences Between Throw And Throws
|Throw is used to explicitly throw an exception.
|Throws is used to declare an exception.
|Checked exceptions can not be propagated with throw only.
|Checked exception can be propagated with throws.
|Throw is followed by an instance.
|Throws is followed by class.
|Throw is used within the method.
|Throws is used with the method signature.
|You cannot throw multiple exception
|You can declare multiple exception e.g. public void methodthrows IOException,SQLException.
In case you are facing any challenges with these java interview questions, please comment on your problems in the section below.
What Is An Intent
An intent is a messaging object that is used to request an action from other components of an application. It can also be used to launch an activity, send SMS, send an email, display a web page, etc.
It shows notification messages to the user from within an Android-enabled device. It alerts the user of a particular state that occurred. There are two types of intents in Android:
- Implicit Intent- Used to invoke the system components.
- Explicit Intent- Used to invoke the activity class.
Also Check: How To Prepare For A Nursing Job Interview