What Is The Benefit Of Composition Over Inheritance
One of the best practices of Java programming is to âfavor composition over inheritanceâ. Some of the possible reasons are:
- Any change in the superclass might affect subclass even though we might not be using the superclass methods. For example, if we have a method test in the subclass and suddenly somebody introduces a method test in the superclass, we will get compilation errors in the subclass. The composition will never face this issue because we are using only what methods we need.
- Inheritance exposes all the superclass methods and variables to the client and if we have no control in designing superclass, it can lead to security holes. Composition allows us to provide restricted access to the methods and hence more secure.
- We can get runtime binding in composition where inheritance binds the classes at compile time. So composition provides flexibility in the invocation of methods.
You can read more about above benefits of composition over inheritance at java composition vs inheritance.
Q What Do You Mean Run Time Polymorphism
Polymorphism in Java is a concept by which we can perform a single action in different ways.There are two types of polymorphism in java:
- Static Polymorphism also known as compile time polymorphism
- Dynamic Polymorphism also known as runtime polymorphism
Example: Static Polymorphism
classSimpleCalculator intadd }publicclassMainClass}
Example: Runtime polymorphism
classABC }publicclassXYZextendsABC publicstaticvoidmain }
Explain The Use Of Final Keyword In Variable Method And Class
In Java, the final keyword is used as defining something as constant /final and represents the non-access modifier.
- final variable:
- When a variable is declared as final in Java, the value cant be modified once it has been assigned.
- If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class.
Recommended Reading: How To Answer Interview Questions For Manager Position
Core Java Interview Questions And Answers
I have already written a lot about java interview questions for specific topics such as String, Collections, and Multithreading.
Here I am providing some of the important core java interview questions with answers that you should know. You can bookmark this post to brush up on your knowledge before heading for an interview.
Name The Methods Of An Object Class
- clone: This method helps create and return a copy of an object.
- equals: This method helps compare.
- finalize: It is called by the garbage collector on the object.
- getClass: It allows us to return the runtime class of the object.
- hashCode: This method helps return a hash code value for the object.
- toString: It lets us return a string representation of the object.
- notify, notifyAll, and wait: These help in synchronizing the activities of the independently running threads in a program.
Read this tutorial to learn more about Java Methods!
Also Check: Amazon Problem Solving Interview Questions
Why Do You Want A Leadership Position
Since this is a leadership role, employers ask this question to make sure you’ve thought about why you want to be a leader. Being a leader requires a lot of reasonability, so this question helps an employer determine if you have the skills to manage a team and prioritize tasks. Prepare for this question by thinking about what leadership skills and experience you have. Figure out why a leadership position would be a good fit for your abilities.
Example:”I want a leadership position because I have the skills to effectively motivate and inspire a team of developers. In my previous role, I became more confident in my coding abilities, and now I have the expertise to offer support and advice to developers who are still perfecting their coding methods. I have always been someone who meets deadlines and is comfortable talking to clients, so I think I am ready for a leadership position at this point in my career.”
Q What Is Classloader In Java What Are Different Types Of Classloaders
The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Java code is compiled into class file by javac compiler and JVM executes Java program, by executing byte codes written in class file. ClassLoader is responsible for loading class files from file system, network or any other source.
Types of ClassLoader:
a) Bootstrap Class Loader:
It loads standard JDK class files from rt.jar and other core classes. It loads class files from jre/lib/rt.jar. For example, java.lang package class.
b) Extensions Class Loader:
It loads classes from the JDK extensions directly usually JAVA_HOME/lib/ext directory or any other directory as java.ext.dirs.
c) System Class Loader:
It loads application specific classes from the CLASSPATH environment variable. It can be set while invoking program using -cp or classpath command line options.
What Is The Difference Between A Nested Static Class And Top
A public top-level class must have the same name as the name of the source file, there is no such requirement for a nested static class. A nested class is always inside a top-level class and you need to use the name of the top-level class to refer nested static class e.g. HashMap.Entry is a nested static class, where HashMap is a top-level class and Entry is nested, static class.
Q What Is Difference Between String Stringbuffer And Stringbuilder
Mutability Difference:String is immutable, if you try to alter their values, another object gets created, whereas StringBuffer and StringBuilder are mutable so they can change their values.
Thread-Safety Difference: The difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.
You May Like: How To Prepare For A Machine Learning Interview
Describe The More Commonly Found Functional Interfaces In The Standard Library
Although many functional interfaces exist, these are the one’s users most likely encounter:
- Function. Takes one argument and returns a result
- Consumer. Takes one argument and returns no result
- Supplier. Takes a not argument and returns a result
- Predicate. Takes one argument and returns a boolean
- BiFunction. Takes two arguments and returns a result
- BinaryOperator. Its like a BiFunction, except it takes two arguments and returns a result, and they are all the same type
- UnaryOperator. Its like a Function, but it takes a single argument and returns a result of the same type
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
What Are Wrapper Classes In Java
Wrapper Classes in Java offers a mechanism to convert the primitive data types into reference or object types and vice-versa. Each primitive data type in Java has a dedicated class known as the wrapper class, which wraps the primitive types into an object of that particular class. Converting primitive data types into objects is known as autoboxing and converting from an object to primitive data types called unboxing.
One of the major applications of wrapper classes is changing the value inside the methods. Java does not support the call by reference, which means changes done inside a method will not change the original value. So, after converting the types into objects, the original values will also change. Also, the wrapper classes help to perform serialization by converting objects into streams.
What Is Inheritance In Java
The process by which one class acquires the properties and functionalities of another class are called inheritance. The aim of inheritance in java is to provide the reusability of code so that a class has to write only the unique features and the rest of the common properties and functionalities can be extended from another class.
Child Class: The class that extends the features of another class is known as a child class, subclass, or derived class. Parent Class: The class whose properties and functionalities are used by another class is known as the parent class, superclass, or Base class.
Also Check: How To Give A Perfect Interview
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.
What Will Be The Output Of Following Programs
Context: static method in class
Answer: The code wonât compile because we canât have an Object class method with the static keyword. Note that the Object class has toString method. You will get a compile-time error as âThis static method cannot hide the instance method from Objectâ. The reason is that the static method belongs to the class and since every class base is an Object, we canât have the same method in the instance as well as in class. You wonât get this error if you change the method name from toString to something else that is not present in the superclass Object.
Context: static method invocation
Answer: Well this is a strange situation. We all have seen NullPointerException when we invoke a method on the object that is NULL. But here this program will work and prints âTest foo calledâ.
The reason for this is the java compiler code optimization. When the java code is compiled to produced byte code, it figures out that foo is a static method and should be called using class. So it changes the method call obj.foo to Test.foo and hence no NullPointerException.
I must admit that itâs a very tricky question and if you are interviewing someone, this will blow his mind off. ð
Don’t Miss: What Should You Say In A Job Interview
Q7 What Are The Differences Between Servletcontext Vs Servletconfig
The difference between ServletContext and ServletConfig in Servlets JSP is in below tabular format.
|Servlet config object represent single servlet||It represent whole web application running on particular JVM and common for all the servlet|
|Its like local parameter associated with particular servlet||Its like global parameter associated with whole application|
|Its a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope||ServletContext has application wide scope so define outside of servlet tag in web.xml file.|
|getServletConfig method is used to get the config object||getServletContext method is used to get the context object.|
|for example shopping cart of a user is a specific to particular user so here we can use servlet config||To get the MIME type of a file or application session related information is stored using servlet context object.|
What Is The Importance Of Reflection In Java
- The term reflection is used for describing the inspection capability of a code on other code either of itself or of its system and modify it during runtime.
- Consider an example where we have an object of unknown type and we have a method fooBar which we need to call on the object. The static typing system of Java doesn’t allow this method invocation unless the type of the object is known beforehand. This can be achieved using reflection which allows the code to scan the object and identify if it has any method called fooBar and only then call the method if needed.
Method methodOfFoo = fooObject.getClass.getMethod methodOfFoo.invoke
- Using reflection has its own cons:
- Speed Method invocations due to reflection are about three times slower than the direct method calls.
- Type safety When a method is invoked via its reference wrongly using reflection, invocation fails at runtime as it is not detected at compile/load time.
- Traceability Whenever a reflective method fails, it is very difficult to find the root cause of this failure due to a huge stack trace. One has to deep dive into the invoke and proxy method logs to identify the root cause.
Also Check: How To Reject An Interview Candidate
Java Interview Questions Faqs
1. What should I prepare for the Java interview?
There is no fixed method through which you can prepare for your upcoming Java Interview. However, understanding the basic concepts of Java is important for you to do well. The next step would be to take up a Java Beginners Course that will help you understand the concepts well, or read the top books for self-learning. Apart from learning the basic concepts through courses, books, and blogs, you can also work on projects that will help you gain hands-on experience.
2. What are the basics of Java?
Java is an object-oriented general-purpose programming language. It is a popular programming language because of its easy-to-use syntax. The basics of Java include understanding what Java is, how to install Java and Java IDE, variables and data types in Java, Operators in Java, Arrays, Functions, Flow Control Statements, and basic programs. To learn the basics of Java, you can take up a Java for Beginners Course and understand the concepts required for you to build a successful career in Java Programming.
3. Is Java 100% object-oriented language?
No. Java is not a 100% object-oriented language. It follows some principles of an object-oriented language, but not all.
4. What are the features of Java?
The main features of Java include: multithreaded, platform-independent, simple, secure, architecture-neutral, portable, robust, dynamic, high-performance, and interpreted.
5. How can I learn Java easily?
Date Types And Basic Java Interview Questions
17) What is the right data type to represent a price in Java? 18) How do you convert bytes to String?19) How do you convert bytes to long in Java?20) Can we cast an int value into byte variable? what will happen if the value of int is larger than byte?21) There are two classes B extends A and C extends B, Can we cast B into C e.g. C = B 22) Which class contains clone method? Cloneable or Object?23) Is ++ operator is thread-safe in Java?24) Difference between a = a + b and a += b ?
25) Can I store a double value in a long variable without casting? 26) What will this return 3*0.1 == 0.3? true or false? 27) Which one will take more memory, an int or Integer? 28) Why is String Immutable in Java?29) Can we use String in the switch case?30) What is constructor chaining in Java?
Don’t Miss: How To Crack Behavioral Interview
Java Technical Lead Interview Questions
A Java technical lead provides solutions to technical challenges. Java technical leads are responsible for meeting development schedules, ensuring that solutions meet technical specifications, and reviewing the work of other team members.
When interviewing Java technical leads, the most suitable candidate should demonstrate good insight into anticipating issues and formulating resolutions and remedial actions. Be wary of candidates who lack teamwork skills, and display poor problem-solving skills and underwhelming IT knowledge.
- Completely free trial, no card required.
- Reach over 250 million candidates.
What Is A Constructor In Java
"A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:ExampleCreate a constructor:// Create a MyClass classpublic class MyClass public static void main }// Outputs 5
Read Also: How To Make Money Doing Interviews
Q44 What Is A Map In Java
In Java, Map is an interface of Util package which maps unique keys to values. The Map interface is not a subset of the main Collection interface and thus it behaves little different from the other collection types. Below are a few of the characteristics of Map interface:
Each key can map at max one value.