Posted on: July 26, 2020 Posted by: India Hires Comments: 0
Java Developer Interview

When you’re a fresher and seriously planning for a Java Developer interview, you will also gain from the main Java Interview questions.

In this post, we ‘re trying to ask you a particular collection of questions from which you can really take advantage of the resources you need to get hired for Java Developer positions.

Cracking an interview to become a Java Developer is not an easy feat, but we’re here to direct you through every step of the interview process.

As part of your training, we ‘re providing you with Java Developer Interview Questions and Answers that will certainly help you secure your dream job and a competitive salary.

Interview Questions and Answers for Java Developer Interview

ArrayList and Vectors both implement the List interface and both use (dynamically resizable) arrays for their internal data structure, much like using a common array.

Syntax:

	
		ArrayList<T> al = new ArrayList<T>();
		Vector<T> v = new Vector<T>();
	
Major Differences between ArrayList and Vector:
  1. Synchronization:

    Vector is synchronized, which means that only one thread at a time can access the code, while arrayList is not synchronized, which means that several threads can operate on arrayList at the same time. For example, if one thread performs an add operation, another thread may perform a remove operation in a multi-threaded environment.

    If multiple threads access arrayList at the same time, then we need to synchronize the code block that modifies the list structurally or, alternatively, allow simple changes to the element. Structural modification means the addition or deletion of the item(s) from the list. Setting the value of an existing entity is not a structural change.

  2. Performance:

    ArrayList is faster because it is non-synchronized, while vector operations are slower because they are synchronized (thread-safe). If one thread is working on a vector, it has acquired a lock on it, which forces any other thread that wants to work on it to have to wait until the lock is released.

  3. Data Growth:

    ArrayList and Vector both grow and shrink dynamically to maintain optimal storage use – but the way they are resized is different. ArrayList increases the current array size by 50 percent if the number of elements exceeds its capacity, while the vector increases by 100 percent – essentially doubling the current array size.

  4. Traversal

    Vector can use both Enumeration and Iterator to pass through vector elements, while ArrayList can only use Iterator to pass through.

  5. Applications:

    Most of the time, programmers prefer ArrayList over Vector, because ArrayList can be explicitly synchronized using Collections.synchronizedList.

How do you choose between ArrayList and Vector?
  1. The ArrayList is non-synchronized and not thread-safe, whereas the vectors are. Only one thread can call Vector methods at a time that is a slight overhead, but useful when safety is a concern. Therefore, in a single-threaded case, arrayList is an obvious choice, but in the case of multithreading, vectors are often preferable.
  2. If we don’t know how much data we ‘re going to have, but know the rate at which it’s going to grow, Vector has an advantage, because we can set the increment value in vectors.
  3. The ArrayList is both newer and faster. If we don’t have any explicit requirements to use either of them, we use the ArrayList over the vector.
Difference between ArrayList and LinkedList in Java

ArrayList and LinkedList both implement the List interface and their methods and results are almost identical. Nevertheless, depending on the criteria, there are little variations between them, which make one better.

  1. Search:

    ArrayList search operation is quite fast compared to the LinkedList search operation. Get(int index) in the ArrayList gives the performance of O(1) while the LinkedList output is O(n).

    Reason: ArrayList maintains an index-based system for its elements, as it implicitly uses array data structure , which makes it faster to search for an element in the list. On the other hand, LinkedList implements a double-linked list that requires a crossover of all the elements to search for an element.

  2. Deletion:

    LinkedList delete operation gives O(1) performance while ArrayList gives variable performance: O(n) in the worst case (while removing the first element) and O(1) in the best case (while removing the last element).

    Conclusion: The deletion of the LinkedList element is faster than the ArrayList.

    Reason: Each element of LinkedList has two pointers (addresses) that point to the two neighboring elements in the list. Consequently, removal only requires a change in the location of the pointer in the two nearby nodes (elements) of the node that will be removed. While in ArrayList all the elements need to be moved to fill in the space created by the deleted element.

  3. Inserts Performance:

    LinkedList add method gives O(1) performance while ArrayList gives O(n) performance in the worst case. Reason is the same as explained for deletion.

  4. Memory Overhead:

    ArrayList maintains indexes and element data while LinkedList maintains element data and two pointers for neighboring nodes, so the memory consumption in LinkedList is relatively high.

How do you choose between ArrayList and LinkedList?
  1. As explained above, inserting and removing operations provides good performance (O(1)) in LinkedList compared to ArrayList(O(n)). Therefore, if there is a requirement for frequent addition and deletion in the application, then LinkedList is the best choice.
  2. Search (get method) operations are fast in Arraylist (O(1)) but not in LinkedList (O(n)) so if less add and remove operations and more search operations are required, ArrayList would be your best bet.

Difference between fail-fast and fail safe in Java

KeyFail-FastFail-Safe
ExceptionAny modifications to the array, such as adding , removing, and modifying the array during a thread, are iterating the collection, then Fail fast throwing the concurrent adjustment exception.The fail-safe collection doesn’t throw exception.
Type of collectionArrayList and hashmap collection are the examples of fail-fast iteratorCopyOnWrite and concurrent modification are the examples of a fail-safe iterator
Performance and MemoryInstead, it’s focusing on the actual album. So, this iterator doesn’t need extra time and memoryThis works on the replica of the set instead of the real version. It’s overhead in terms of time and memory
ModificationsIterators do not make adjustments to the set when iterating.Fail-Safe iterators make adjustments to the set while iterating.

Difference between throw and throws in Java

There are a lot of variations between throwing and throwing keywords. Here is a list of variations between throws and throws:

throwthrows
throw keyword is used to throw an exception explicitly.throws keyword is used to declare one or more exceptions, separated by commas.
Only single exception is thrown by using throw.Multiple exceptions can be thrown by using throws.
throw keyword is used within the method.throws keyword is used with the method signature.
Syntax wise throw keyword is followed by the instance variable.Syntax wise throws keyword is followed by exception class names.
Checked exception cannot be propagated using throw only.Unchecked exception can be propagated using throw.For the propagation checked exception must use throws keyword followed by specific exception class name.
Java throw example
	
		void m(){  
			throw new ArithmeticException("sorry");  
		}  					
	
Java throws example
	
		void m() throws ArithmeticException{  
			throw new ArithmeticException("sorry");  
		}  					
	
	
		void m()throws ArithmeticException{  
			throw new ArithmeticException("sorry");  
		} 
	

21 React js Interview Questions and Answers

A wait() only makes sense when there is also a notify(), so it’s always about communication between threads, and that needs synchronization to work correctly. One could argue that this should be implicit, but that would not really help, for the following reason:

Semantically, you never just wait(). You need some condition to be satsified, and if it is not, you wait until it is. So what you really do is

	
		if(!condition){
		    wait();
		}			
	

But the condition is set by a separate thread, so you need synchronization to get this job done correctly. A few more things are wrong with it, where just because your thread stops waiting doesn’t mean that the condition you ‘re looking for is true:

  1. You can get spurious wake-ups (meaning that a thread will wake up from waiting without ever getting a notification)
  2. The condition can be set, but the third thread can make the condition false again when the waiting thread wakes up (and reacquires the monitor).

When deal with these situations, what you really need is always some combination of the following:

	
		synchronized(lock){
		    while(!condition){
		        lock.wait();
		    }
		}		
	

Better yet, don’t mess with the synchronization primitives at all and work with the abstractions offered in the java.util.concurrent packages.

Within Java programming, for any occurrence of an exception, an exception object is created which holds all the details of the exception. The software must then check for its respective exception handler. When detected, the violation must be addressed or fixed, or the execution of the program must end.

Java generates two types of exceptions

  1. Checked exception
  2. Unchecked exception

Difference Between Checked and Unchecked Exceptions in Java

Checked ExceptionUnchecked Exception
Checked exceptions occur at compile time.Unchecked exceptions occur at runtime.
The compiler checks a checked exception.The compiler does not check these types of exceptions.
These types of exceptions can be handled at the time of compilation.These types of exceptions cannot be a catch or handle at the time of compilation, because they get generated by the mistakes in the program.
They are the sub-class of the exception class.They are runtime exceptions and hence are not a part of the Exception class.
Here, the JVM needs the exception to catch and handle.Here, the JVM does not require the exception to catch and handle.
Examples of Checked exceptions:
  1. File Not Found Exception
  2. No Such Field Exception
  3. Interrupted Exception
  4. No Such Method Exception
  5. Class Not Found Exception
Examples of Unchecked Exceptions:
  1. No Such Element Exception
  2. Undeclared Throwable Exception
  3. Empty Stack Exception
  4. Arithmetic Exception
  5. Null Pointer Exception
  6. Array Index Out of Bounds Exception
  7. Security Exception

Lambda expression is a new feature implemented in Java 8. The expression of the lambda is an anonymous function. A category that has no name and does not belong to any class. The definition of lambda expression was first implemented in the programming language of LISP.

Java Lambda Expression Syntax

To create a lambda expression, define the input parameters (if any) on the left side of the lambda operator->, and place the expression or sequence of the statements on the right side of the lambda operator. For example, the lambda expression (x, y)- > x + y specifies that the lambda expression takes two arguments, x and y, and returns the sum of those arguments.

	
		//Syntax of lambda expression
		(parameter_list) -> {function_body}				
	
The lambda expression in Java has the following key parts:

The Lambda expression only has a description of the body and parameter.

  1. No name-function is anonymous, so we don’t care about the name.
  2. List of parameters
  3. Body – that’s the key part of the body.
  4. No return type – the Java 8 compiler should be able to infer the return type by testing the code. You don’t need to mention it directly.

Where to use the Lambdas in Java

You need to either build your own functional interface or use the predefined functional interface given by Java to use the lambda expression. The interface with a single abstract method is called a functional interface (or a single abstract method interface), e.g.: Runable, Callable, ActionListener, etc.

Java Lambda expression Example

By using Lambda expression:

prior to Java 8 we used an anonymous inner class to implement the only abstract method of the functional interface.

	
		import java.awt.*;  
		import java.awt.event.*;  
		public class ButtonListenerOldWay {  
		    public static void main(String[] args) {  
		       Frame frame=new Frame("ActionListener Before Java8");  
		    
		       Button b=new Button("Click Here");  
		       b.setBounds(50,100,80,50);  
		  
		       b.addActionListener(new ActionListener(){  
		          public void actionPerformed(ActionEvent e){  
		    	     System.out.println("Hello World!"); 
		          }  
		       });  
		       frame.add(b);		    
		       frame.setSize(200,200);  
		       frame.setLayout(null);  
		       frame.setVisible(true);   
		    }  
		}				
	

Java Lambda expression Example

Without using Lambda expression:

Instead of creating an anonymous inner entity, we might create a lambda expression like this:

	
		import java.awt.*;  
		public class ButtonListenerNewWay {  
		   public static void main(String[] args) {  
		      Frame frame=new Frame("ActionListener java8");  
		     
		      Button b=new Button("Click Here");  
		      b.setBounds(50,100,80,50); 
		  
		      b.addActionListener(e -> System.out.println("Hello World!")); 
		      frame.add(b);
		  
		      frame.setSize(200,200);  
		      frame.setLayout(null);  
		      frame.setVisible(true);   
		   }  
		}				
	

Encapsulate:

Encapsulate covers variables or any kind of specification that can be modified very frequently in a class to prevent others from directly accessing it. They must have access to this through getter and setter methods.

Abstraction

Abstraction is used to cover something in a higher degree (class, interface). Clients are using an abstract class(or interface) that doesn’t matter who or what it was, they just need to know what it can do.

Difference between Encapsulation and Abstraction

AbstractionEncapsulation
Abstraction is the process or method of gaining the information.While encapsulation is the process or method to contain the information.
In abstraction, problems are solved at the design or interface level.While in encapsulation, problems are solved at the implementation level.
Abstraction is the method of hiding the unwanted information.Whereas encapsulation is a method to hide the data in a single entity or unit along with a method to protect information from outside.
We can implement abstraction using abstract class and interfaces.Whereas encapsulation can be implemented using by access modifier i.e. private, protected and public.
In abstraction, implementation complexities are hidden using abstract classes and interfaces.While in encapsulation, the data is hidden using methods of getters and setters.
The objects that help to perform abstraction are encapsulated.Whereas the objects that result in encapsulation need not be abstracted.

Polymorphism is one of the main principles of the OOPS model. The concept of polymorphism is that it exists in a variety of different ways.

What is Polymorphism?

Polymorphism is the tendency to do various actions in different circumstances. Often polymorphism is dependent on the input parameters of the function. Polymorphism can also be present in the case of inheritance. The functions behave differently on the basis of the actual implementation.

Polymorphism Real Life Example

  • It is one of the functions of a individual to write. When a person is faced with a pencil and a paper, he will write a few words on it. If a individual offers an oil painting and a coloring book, he will make a painting. Here, the method behaves differently on the basis of input arguments.
  • The delivery person shall deliver the items to the address in question. If he’s a postman, he’s going to deliver letters and packages to his house. If he’s a Pizza delivery guy, he’ll bring Pizza to you. Here, polymorphism in the distribution function is accomplished through various implementations.

Polymorphism in Java

Java supports polymorphism and it can be divided into two types.

  1. Compile Time Polymorphism: If the compiler is able to evaluate the actual function, it is called compile-time polymorphism. There are two types of compile-time polymorphisms.
    1. Method Overloading:

      When different functions in a class have the same name but a different signature, this is called overloading. The signature method includes the reasons for the name and process. So, overloaded methods have a number of arguments. The arguments can vary in number or form of argument. The form of return method is not part of the signature.

      Here’s a simple example of Java overloading process.

      	
      		import java.io.File;
      		class Printer{
      			
      			void print(String message) {
      				// printing string message
      			}
      			
      			void print(String message, int count) {
      				// printing message count times
      			}
      			
      			boolean print(Object obj, File f) {
      				//printing object to file
      				return true;
      			}
      		}					
      	
      

      When you’re looking for method overloading in the JDK modules, you’ll find a lot of them in the String and Primitive Wrapper groups. For example, String valuesOf() methods, Integer parseInt() methods, etc.

    2. Operator Overloading

      Java does not require us to override operators. Nevertheless, the additional (+) operator is overloaded for the String objects. If the add-on operator uses string objects, it concatenates them and returns a new string object.

      	
      		jshell> 10 + 5
      		$1 ==> 15
      
      		jshell> 10.5 + 20.1
      		$2 ==> 30.6
      
      		jshell> "ABC" + "abc"
      		$3 ==> "ABCabc"
      
      		jshell> new Object() + new Object()
      		|  Error:
      		|  bad operand types for binary operator '+'
      		|    first type:  java.lang.Object
      		|    second type: java.lang.Object
      		|  new Object() + new Object()
      		|  ^-------------------------^
      
      		jshell>			
      	
      
  2. Runtime Polymorphism:

    Runtime polymorphism is accomplished by an over-the-counter process. When the superclass method is overridden in the subclass, it is considered an overridden method. In this case, the compiler will not be able to decide if the superclass or subclass form will be named. The method of resolution occurs at runtime based on the particular object type. That’s why this is called runtime polymorphism. It’s also called the Dynamic Dispatch Process.

    Here’s an example of Java runtime polymorphism.

    	
    		package com.journaldev.examples;
    		import java.util.Random;
    
    		public class DeliveryBoy {
    			void deliver() {
    				System.out.println("Delivering Item");
    			}
    
    			public static void main(String[] args) {
    				DeliveryBoy db = getDeliveryBoy();
    				db.deliver();
    			}
    
    			private static DeliveryBoy getDeliveryBoy() {
    				Random rand = new Random();
    				int num = rand.nextInt(10);
    				return num % 2 == 0 ? new PizzaDeliveryBoy() : new Postman();
    			}
    		}
    
    		class PizzaDeliveryBoy extends DeliveryBoy {
    
    			@Override
    			void deliver() {
    				System.out.println("Delivering Pizza");
    			}
    		}
    
    		class Postman extends DeliveryBoy {
    			@Override
    			void deliver() {
    				System.out.println("Delivering Letters");
    			}
    		}		
    	
    

    The delivery() method is overridden in the PizzaDeliveryBoy and Postman sections. The compiler can not decide if PizzaDeliveryBoy or Postman will be returned to getDeliveryBoy). Therefore, the process of resolution is going to happen at runtime. If you run the program, the performance will differ between “Delivery Letters” and “Delivery Pizza.”

Simple example: Let’s say you’ve got a Students table and a Lockers table. For SQL, the first table you enter in the join, Students, is the LEFT table, and the second one, Lockers, is the RIGHT table.

Each student can be assigned to a locker, so there’s a Locker Number column in the Student Row. More than one student may possibly be in a single locker, but particularly at the beginning of the school year, you may have some incoming students without lockers and some lockers who are not assigned to students.

In this example , let’s assume that you have 100 students, 70 of whom have lockers. You have a total of 50 lockers, 40 of which have at least 1 student, and 10 lockers have no student at all.

Difference between Left, Right, Outer and Inner Joins?

  • INNER JOIN is similar to “showing all students with lockers to me.” Students without lockers or lockers without students are absent. Returns to 70 rows
  • LEFT OUTER JOIN will be “to show me all the teachers, with their respective lockers, if they have one.” It could be a general student list, or it could be used to classify students without a locker. Returns to 100 points
  • RIGHT OUTER JOIN would be “show me all lockers, and the students would be allocated to them if they had any.” This may be used to classify lockers that are not assigned to students, or lockers that have too many students. Returns 80 rows (list of 70 students in 40 lockers plus 10 lockers without a student)
  • Complete OUTER JOIN will be dumb and probably not very useful. Something like “Show me all the students and all the lockers and fit them where you can” Returns 110 rows (all 100 students, including those without lockers, plus 10 lockers without students)
  • CROSS JOIN is still pretty dumb in this case. It doesn’t use the related locker number field in the student table, so you essentially end up with a big list of all potential student-to-locker pairings, whether or not they actually exist

TCS Possible Technical Interview Questions and Answers

You must have seen public, private and secure keywords when running java programs, which are called access modifiers. The access modifier limits access to a class, constructor, data element, and process in another class. For Java, we have four access-modifiers:default, private, protected, public

Default

If we do not mention a change in access, it is called a default change in access. The scope of this amendment is limited to the kit only. This means that only those classes that are in this package can access this class if we have a class with the default access modifier in the package. No other class outside this package will be able to access this class. Similarly, if we have a default method or a data component in a module, it will not be available in another package module.

Private

The purpose of the private alteration is limited to the class only.

  1. Private Data Members and methods are only available inside the class.
  2. Class and Framework can not be considered private
  3. If a class has a private constructor, you can not create the object of that class from outside the class.

Protected

The covered data member and method can only be accessed by members of the same package and subclasses present in any package. You can also say that the protected Access Modifier is similar to the default Access Modifier, except that it has visibility in subclasses. Groups shall not be declared safe. This access change is generally used in a parent child relationship.

Public

Members, methods and classes that have been made public can be accessed from anywhere. This modifier does not impose any limits on access.

The scope of access modifiers in tabular form

------------+-------+---------+--------------+--------------+--------
            | Class | Package | Subclass     | Subclass     |Outside|
            |       |         |(same package)|(diff package)|Class  |
————————————+———————+—————————+——————————----+—————————----—+————————
public      | Yes   |  Yes    |    Yes       |    Yes       |   Yes |    
————————————+———————+—————————+—————————----—+—————————----—+————————
protected   | Yes   |  Yes    |    Yes       |    Yes       |   No  |    
————————————+———————+—————————+————————----——+————————----——+————————
default     | Yes   |  Yes    |    Yes       |    No        |   No  |
————————————+———————+—————————+————————----——+————————----——+————————
private     | Yes   |  No     |    No        |    No        |   No  |
------------+-------+---------+--------------+--------------+--------

The final keyword in Java can also be used for methods. The Java method with the final keyword is considered the final method and can not be overridden in the subclass. You will render the Java method final if you think it is complete and the behavior of the Java method will remain constant in subclasses.

In general, final methods are faster than non-final methods because they are not expected to be resolved during run-time and bind to compile time.

Here is an example of a final method in Java:

	
		class PersonalLoan{
			public final String getName(){
			    return "personal loan";
			}
		}
		class CheapPersonalLoan extends PersonalLoan{
		    @Override
		    public final String getName(){
		        return "cheap personal loan"; //compilation error: overridden method is final
		    }
		}		
	

RESTful web services are loosely coupled, lightweight web services that are especially well suited for building client APIs distributed around the internet. Representational State Transfer (REST) is an architectural form of client-server application based on the transfer of resource representations through requests and responses. Data and features are called tools in the REST architectural style and are accessed using Uniform Resource Identifiers (URIs), usually web links. Resources are expressed by documents and are accompanied by a set of simple, well-defined operations.

For example, the REST resource may be the current weather conditions for a city. This resource can be represented by an XML document, an image file, or an HTML page. A client can retrieve a particular representation, change the resource by updating its data, or remove the resource entirely.

The REST architectural style is designed to use stateless communication protocols, usually HTTP. In the REST architecture model, clients and servers share resource representation using a structured interface and protocol.

The following principles encourage RESTful applications to be simple, lightweight and quick:

  1. Identification of resources by URI: The RESTful web service provides a collection of resources to define the purposes of contact with its clients. Assets are defined by URIs, which provide a global resource and service discovery address space.
  2. Uniform interface: The resources are managed using a fixed set of four development, reading, updating, deleting operations: PUT, GET, Publish, and DELETE. PUT generates a new resource that can be removed using DELETE. For certain representations, GET retrieves the current state of the property. POST is passing a new state to a tool.
  3. Self-descriptive messages: Documents are decoupled from their representation so that they can be viewed in a variety of formats, such as HTML , XML, plain text, PDF, JPEG, JSON, and other document formats. Resource metadata is accessible and used, for example, to manage caching, detect transmission errors, negotiate an correct representation format, and perform authentication or access control.
  4. State-of-the-art interactions across links: any contact with a resource is stateless; that is, requests for messages are self-contained. Stateful relations are based on the principle of clear transition of state. There are many strategies for state exchange, such as URI rewriting, cookies, and secret type fields. State may be inserted in answer messages to suggest true future states of interaction.

Reflection is an API used to analyze or change the actions of methods, classes, interfaces at runtime.

  • The appropriate classes for reflection are given in the java.lang.reflect package.
  • Reflection provides us knowledge about the class to which the object belongs, as well as the methods of the class that can be implemented by using the object.
  • Through means of reflection, we can invoke methods at runtime irrespective of the access specifier used for them.

Reflection can be used to get information about –

  1. Class The getClass() method is used to get the name of the class the object belongs to.
  2. Constructors The getConstructors() method is used to get the public constructors of the class the object belongs to.
  3. Methods The getMethods() function is used to get the public methods of the class to which the objects belong.
Advantages of Using Reflection:
  • Extensibility Features: An application can use external, user-defined classes by creating extensibility object instances using their fully qualified names.
  • Debugging and testing tools: Debuggers use the reflection property to analyze classes for private members.
Drawbacks:
  • Performance Overhead: Reflective operations have slower performance than their non-reflective counterparts and should be avoided in code sections that are frequently referred to in performance-sensitive applications.
  • Exposure of internals: the reflective code removes abstractions and can therefore alter the behavior of the device upgrades.

Association mapping is always the most difficult thing to execute correctly. In this section , we discuss some canonical cases one by one, beginning with unidirectional mapping and then bidirectional mapping. In all the instances, we will use Person and Email.

Associations would be categorized by multiplicity and whether or not they correspond to the intermediate joint table.

Null foreign keys are not known to be good practice in conventional data modeling, so our examples do not use null foreign keys. It is not a prerequisite of Hibernate, and mappings will work if you remove the nullity constraints.

  1. one to one

    A one-to-one partnership on a joint table is probable, but highly rare.

    	
    		<class name="Person">
    		    <id name="id" column="personId">
    		        <generator class="native"/>
    		    </id>
    		    <join table="PersonAddress" 
    		        optional="true">
    		        <key column="personId" 
    		            unique="true"/>
    		        <many-to-one name="address"
    		            column="addressId" 
    		            not-null="true"
    		            unique="true"/>
    		    </join>
    		</class>
    
    		<class name="Address">
    		    <id name="id" column="addressId">
    		        <generator class="native"/>
    		    </id>
    		</class>	
    
    
    		create table Person ( personId bigint not null primary key )
    		create table PersonAddress ( personId bigint not null primary key, addressId bigint not null unique )
    		create table Address ( addressId bigint not null primary key )	
    	
    
  2. one to many

    The best choice is a one-to-many one-to-many partnership on a joint table. Specifying unique=”true, “switches the multiplicity from many to many to one-to-many.

    	
    		<class name="Person">
    		    <id name="id" column="personId">
    		        <generator class="native"/>
    		    </id>
    		    <set name="addresses" table="PersonAddress">
    		        <key column="personId"/>
    		        <many-to-many column="addressId"
    		            unique="true"
    		            class="Address"/>
    		    </set>
    		</class>
    
    		<class name="Address">
    		    <id name="id" column="addressId">
    		        <generator class="native"/>
    		    </id>
    		</class>		
    
    
    		create table Person ( personId bigint not null primary key )
    		create table PersonAddress ( personId not null, addressId bigint not null primary key )
    		create table Address ( addressId bigint not null primary key )		
    	
    
  3. many to one

    A many-to-one unidirectional association on a joint table is common when an association is optional. For instance:

    	
    		<class name="Person">
    		    <id name="id" column="personId">
    		        <generator class="native"/>
    		    </id>
    		    <join table="PersonAddress" 
    		        optional="true">
    		        <key column="personId" unique="true"/>
    		        <many-to-one name="address"
    		            column="addressId" 
    		            not-null="true"/>
    		    </join>
    		</class>
    
    		<class name="Address">
    		    <id name="id" column="addressId">
    		        <generator class="native"/>
    		    </id>
    		</class>		
    
    
    		create table Person ( personId bigint not null primary key )
    		create table PersonAddress ( personId bigint not null primary key, addressId bigint not null )
    		create table Address ( addressId bigint not null primary key )		
    	
    
  4. many to many

    Finally, here is an example of a unidirectional many-to-many association.

    	
    		<class name="Person">
    		    <id name="id" column="personId">
    		        <generator class="native"/>
    		    </id>
    		    <set name="addresses" table="PersonAddress">
    		        <key column="personId"/>
    		        <many-to-many column="addressId"
    		            class="Address"/>
    		    </set>
    		</class>
    
    		<class name="Address">
    		    <id name="id" column="addressId">
    		        <generator class="native"/>
    		    </id>
    		</class>	
    
    
    		create table Person ( personId bigint not null primary key )
    		create table PersonAddress ( personId bigint not null, addressId bigint not null, primary key (personId, addressId) )
    		create table Address ( addressId bigint not null primary key )	
    	
    

Selenium-RC operated the same way for each browser enabled. It inserted the JavaScript functions into the browser when the tab was loaded and then used the JavaScript to control the AUT in the tab. Selenium WebDriver plays the same function as Selenium-RC and implements the original 1.x bindings and contains the WebDriver API. It applies to both the language bindings and the implementations of the individual browser-control code. This is usually referred to as a Webdriver. In short, WebDriver is a remote control interface that enables user agents to be introspected and managed. WebDriver offers a forum and language-neutral wire protocol as a medium for out-of-process programs to remotely control the actions of web browsers.

Key points of WebDriver
  1. WebDriver is equipped with a simpler and more succinct programming interface, along with some limitations in the Selenium-RC API.
  2. WebDriver is a lightweight object-oriented API similar to Selenium1.0.
  3. It drives the browser even more efficiently and overcomes the shortcomings of Selenium 1.x that have plagued our usable test coverage, such as uploading or installing files, pop-ups and dialogs.
  4. WebDriver overcomes the limitation of the Single Host Origin Policy of Selenium RC.

ClassNotFoundException and NoClassDefFoundError both occur when the class is not found during runtime. They’re connected to the Java classpath.

ClassNotFoundException

ClassNotFoundException occurs when you attempt to load a class at runtime using either Class.forName) (or loadClass) (methods, and the requested classes are not found in the classpath. Most of the time this exception happens when you attempt to run an application without updating the JAR file classpath. This exception is a verified exception originating from the class java.lang. Exception and you need to have specific handling for it.

An exception often happens when you have two file loaders, and when a ClassLoader attempts to access a file that is loaded by another classloader in Java. You must be wondering what the Java classloader actually is. Java ClassLoader is a part of the Java Runtime Framework that dynamically loads Java classes into JVM(Java Virtual Machine). Because of classloaders, the Java Runtime System does not need to learn about the module and file system.

	
		// Java program to illustrate 
		// ClassNotFoundException 
		public class Example { 
		      
		    public static void main(String args[]) { 
		        try 
		        { 
		            Class.forName("India Hires"); 
		        } 
		        catch (ClassNotFoundException ex) 
		        { 
		            ex.printStackTrace(); 
		        } 
		    } 
		} 
	
NoClassDefFoundError

NoClassDefFoundError occurs when the class was present during compile time and the program was compiled and successfully connected, but the class was not present during runtime. This is an error that is derived from LinkageError. Linkage error occurs when a class has some dependency on another class, and the latter class changes after the previous class has been compiled. NoClassFoundError is the product of implicit class loading by calling a method or accessing a variable from that object. This error is more difficult to diagnose and to find the explanation why this error occurred. So in this case, you should always test the classes that depend on the class.

	
		// Java program to illustrate 
		// NoClassDefFoundError 
		class Products  
		{ 
		    void getProduct() 
		    { 
		        System.out.println("India Hires!"); 
		    } 
		} 
		  
		class ProductInfo { 
		    public static void main(String args[])  
		    { 
		        Products products = new products(); 
		        products.getProduct(); 
		    } 
		} 
	

Above program will be successfully compiled and generate two classes Products.class and ProductInfo.class. Now remove Products.class file and run ProductInfo.class. At Java runtime NoClassDefFoundError will be thrown.

ClassNotFoundException Vs NoClassDefFoundError

  1. As the name suggests, ClassNotFoundException is an exception, while NoClassDefFoundError is an error.
  2. ClassNotFoundException occurs when classpath is not modified with the correct JAR files while error occurs when the required class description is not present at runtime.

First and foremost-all spring beans are managed-they “live” inside a container, called the “application context.”

Second, every application has an entry point in that context. Web applications have a server, JSF uses a el-resolver, etc. Often, there is a position where the program context is bootstrapped and all beans are autowired. It can be a startup listener in web applications.

Autowiring occurs by placing an instance of one bean in the desired field in an instance of another bean. Both classes should be beans, i.e. they should be specified to live in the sense of the application.

What is “working” in the sense of the application? This means that the environment must instantiate the objects, not you. I.e.-You never create a new UserServiceImpl()-the container finds will injection point and sets an instance there.

In your controllers, you just have the following:

	
		@Controller // Defines that this class is a spring bean
		@RequestMapping("/users")
		public class SomeController {

		    // Tells the application context to inject an instance of UserService here
		    @Autowired
		    private UserService userService;

		    @RequestMapping("/login")
		    public void login(@RequestParam("username") String username,
		           @RequestParam("password") String password) {

		        // The UserServiceImpl is already injected and you can use it
		        userService.login(username, password);

		    }
		}
	
Key notes
  1. In your applicationContext.xml you can allow <context: component-scan> so that classes are scanned for annotations such as @Controller, @Service, etc.
  2. The entry point for the Spring-MVC code is the DispatcherServlet, but it is hidden from you, and thus the actual contact and bootstrapping of the application context takes place behind the scenes.
  3. UserServiceImpl can also be known as bean-either by using <bean id=”..” class=”..”> or by using the @Service annotation. Because it will be the only UserService provider, it will be inserted.
  4. Including the @Autowired tag, Spring can also use XML-configurable autowiring. In that case, all fields that have a name or form that matches an existing bean will automatically be injected with the bean. In fact, that was the initial concept of autowiring-to have fields injected without any configuration. Other annotations such as @Inject, @Resource may also be used.

Joshua Bloch says on Effective Java

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.

Let’s try and explain this with an example of what will happen if we override equals() without having and override hashCode() and try using a Map.

Say we have a class like this and that two MyClass objects are equal if their importantField is equal (with hashCode() and equals() generated by the eclipse)

	
		public class MyClass {

	    private final String importantField;
	    private final String anotherField;

	    public MyClass(final String equalField, final String anotherField) {
	        this.importantField = equalField;
	        this.anotherField = anotherField;
	    }

	    public String getEqualField() {
	        return importantField;
	    }

	    public String getAnotherField() {
	        return anotherField;
	    }

	    @Override
	    public int hashCode() {
	        final int prime = 31;
	        int result = 1;
	        result = prime * result
	                + ((importantField == null) ? 0 : importantField.hashCode());
	        return result;
	    }

	    @Override
	    public boolean equals(final Object obj) {
	        if (this == obj)
	            return true;
	        if (obj == null)
	            return false;
	        if (getClass() != obj.getClass())
	            return false;
	        final MyClass other = (MyClass) obj;
	        if (importantField == null) {
	            if (other.importantField != null)
	                return false;
	        } else if (!importantField.equals(other.importantField))
	            return false;
	        return true;
	    }

	}
	
Override only equals

If only equals are overridden, so when you call myMap.put(first, someValue) first hash to some bucket, and when you call myMap.put(second, someotherValue) it hash to some other bucket (as it has a specific hashCode). And, even if they’re similar, if they don’t have the same bin, the map can’t see it, so both of them remain on the map.

While it is not appropriate to override equals() if we override hashCode() let’s see what will happen in this particular case where we know that two MyClass objects are equal if their importantField is equal but we don’t override equals()

Override only hashCode

Imagine you have this

	
		MyClass first = new MyClass("a","first");
		MyClass second = new MyClass("a","second");				
	

When you override hashCode then then when you call myMap.put(first, someValue) it takes first, calculates the hashCode and stores it in a given bucket. Then when you call myMap.put(second, someotherValue) it will replace the first one with the second one as per the Map Documentation as they are equivalent (according to the business requirement).

But the problem is that equals was not redefined, because when the map is second and iterates through the container, searching if there is an object k, the second.equals(k) is true, it won’t find a second.equals(first) is false.

The singleton pattern is one of the simplest patterns of architecture. Sometimes we only need one instance of our class, such as a single DB connection shared by multiple objects, because creating a separate DB connection for each object can be costly. Similarly, there might be a single configuration manager or error manager in an application that manages all problems instead of having multiple managers.

Definition:

The singleton pattern is one of the simplest patterns of architecture. Sometimes we only need one instance of our class, such as a single DB connection shared by multiple objects, because creating a separate DB connection for each object can be costly. Similarly, there might be a single configuration manager or error manager in an application that manages all problems instead of having multiple managers.

Method 1: Classic Implementation
	
		// Classical Java implementation of singleton  
		// design pattern 
		class Singleton 
		{ 
		    private static Singleton obj; 
		  
		    // private constructor to force use of 
		    // getInstance() to create Singleton object 
		    private Singleton() {} 
		  
		    public static Singleton getInstance() 
		    { 
		        if (obj==null) 
		            obj = new Singleton(); 
		        return obj; 
		    } 
		} 					
	

The singleton pattern is one of the simplest patterns of architecture. Sometimes we only need one instance of our class, such as a single DB connection shared by multiple objects, because creating a separate DB connection for each object can be costly. Similarly, there might be a single configuration manager or error manager in an application that manages all problems instead of having multiple managers.

This execution sequence creates two objects for singleton. Therefore this classic implementation is not thread safe.

Method 2: make getInstance() synchronized
	
		// Thread Synchronized Java implementation of  
		// singleton design pattern 
		class Singleton 
		{ 
		    private static Singleton obj; 
		  
		    private Singleton() {} 
		  
		    // Only one thread can execute this at a time 
		    public static synchronized Singleton getInstance() 
		    { 
		        if (obj==null) 
		            obj = new Singleton(); 
		        return obj; 
		    } 
		} 					
	

Using synchronized here means that only one thread can run getInstance() at a time. The main downside of this approach is that using synchronized any time you construct a singleton object is costly and can reduce the output of your software. However, if the efficiency of getInstance() is not important to your application, this method provides a clean and easy solution.

Method 3: Eager Instantiation
	
		// Static initializer based Java implementation of 
		// singleton design pattern 
		class Singleton 
		{ 
		    private static Singleton obj = new Singleton(); 
		  
		    private Singleton() {} 
		  
		    public static Singleton getInstance() 
		    { 
		        return obj; 
		    } 
		} 					
	

Here we’ve built singleton instance in the static initializer. JVM executes a static initializer when the class is loaded and hence the thread is guaranteed to be secure. Use this approach only if your singleton class is light and is used in the execution of your program.

Method 4: Use “Double Checked Locking”

If you note carefully when an object is created, synchronization is no longer useful, since now obj will not be null and any sequence of operations will result in consistent results. And we’ll just get a lock on the getInstance() until the obj is null. This way, we ‘re just syncing the first way around, exactly what we want.

	
		// Double Checked Locking based Java implementation of 
		// singleton design pattern 
		class Singleton 
		{ 
		    private volatile static Singleton obj; 
		  
		    private Singleton() {} 
		  
		    public static Singleton getInstance() 
		    { 
		        if (obj == null) 
		        { 
		            // To make thread safe 
		            synchronized (Singleton.class) 
		            { 
		                // check again as multiple threads 
		                // can reach above step 
		                if (obj==null) 
		                    obj = new Singleton(); 
		            } 
		        } 
		        return obj; 
		    } 
		}  					
	

We have declared the obj volatile, which ensures that multiple threads give the obj variable correctly when it is initialized to the Singleton case. This system decreases the overhead of the synchronized process every time.

References

Singleton pattern

The key feature of multithreading is to run or execute several tasks simultaneously. Such tasks are described as threads in a Java program and have a separate execution path. Also, managing multi-threaded Java programs is simple since you can specify the order in which Java thread execution takes place. Multithreading also has some common disadvantages:

Following are some of the common advantages of multithreading:
  1. Enhanced performance by decreased development time
  2. Simplified and streamlined program coding
  3. Improvised GUI responsiveness
  4. Simultaneous and parallelized occurrence of tasks
  5. Better use of cache storage by utilization of resources
  6. Decreased cost of maintenance
  7. Better use of CPU resource
Following are some of the common disadvantages of multithreading:
  1. Complex debugging and testing processes
  2. Result is sometimes unpredictable
  3. Overhead switching of context
  4. Increased potential for deadlock occurrence
  5. Increased difficulty level in writing a program
  6. general: increased complexity
  7. synchronization of shared resources (objects, data)
  8. potential deadlocks
  9. “starvation”: some threads may not be served with a bad design
  10. constructing and synchronizing threads is CPU/memory intensive

Leave a Comment