Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Spring MVC Framework Collection API Question - 2

This is the second set of questions that are generally asked for Collection Framework questions. These are a bit more advanced then the earlier set of questions.

Question 1: What is difference between ArrayList and LinkedList?
There are quiet a few difference between ArrayList and LinkedList:
  1. ArrayList uses a primitive array to store the values internally. However, LinkedList is made up of nodes where each nodes has three elements: value, pointer to next element and pointer to previous element.
  2. ArrayList implements the RandomAccess interface whereas LinkedList does not. RandomAccess is a marker interface which states that the implementation implements the fast algorithm to access the Nth element. So accessing Nth element is fast and takes constant-time for ArrayList whereas LinkedList has to scan the whole list to find the Nth element, hence making it slower for random access.
  3. Inserting and deleting an element at the start and end is faster in LinkedList as compared to ArrayList. While inserting an element in the LinkedList at the start and the beginning , we just need to create a node and assign the pointers whereas in ArrayList if you are inserting an element at the start, then first it will copy all the elements in a different list and then adds them after it, similarly while adding an element at the end means ArrayList will have to scan the whole list for inserting an element.
  4. LinkedList usually takes more memory than ArrayList as each node in the LinkedList will also store the next and previous pointers.
  5. ArrayList may also have issue if your list fills up quiet frequently as the ArrayList will create a new list with increased capacity and then copies all the elements whereas no such thing is required for LinkedList.
Question 2: Where will you use ArrayList and where will you use LinkedList?
If you have add elements at the start and end frequently or iterate over it for deleting elements then you should consider using LinkedList as it requires constant time for these operations and linear-time in ArrayList. If you have to access the positional elements then you should consider using ArrayList as it takes constant time for that and LinkedList take linear time for positional access.

Question 3: What is the difference between HashMap and HashTable?
The main difference is that HashTable is synchronised whereas HashMap is not. You need to provide external synchronisation if you want to synchronise the HashMap. Another difference is that HashTable does not allows null as keys or values whereas HashMap allow one null key and any number of null values.

Question 4: What is the difference between HashMap and TreeMap?
The basic difference is that in TreeMap objects are stored in an order decided either by the natural ordering of key or by the comparator that is defined at the the instantiation time of the TreeMap whereas HashMap does not guarantee any ordering. Since the elements are stored in an order, I think it is safe to say that the insertion of element in TreeMap will be slower as compared to HashMap whereas retrieval will be faster than HashMap.

Question 5: Explain how HashMap works or how the hashcode() and equals() method is used by the HashMap or how the get() method works in HashMap?
This question generally is the starting point for more complicated questions on HashMap. Basically what happens is when we call get(), put() method of HashMap. The HashMap uses the hashcode() method of the key to find the hashcode, then it uses its internal hashing mechanism to find the index of the correct "bucket" where the value might be stored. This bucket contains a list of Map.Entry objects in the form of a linked list. Once the bucket is identified, the map will traverse through the Map.Entry to find the exact key by using equals method, once found it will overwrite or return the value.

Question 6: How is HashSet implemented? or How will you implement the HashSet using HashMap?
Actually if you look closely on the HashMap methods there is already a set in the HashMap, they keySet. It has all the properties like no duplicates (HashMap does not allow duplicate keys). So, all you need to do is following, when you insert an object in HashSet, you insert the object as key in the HashMap and put the value as an EMPTY object. Same is the case when retrieving a value from HashSet, rather returning a value just return the key.

Question 7: Is Collection.synchronisedMap() is really thread-safe?
Question 8: What is the difference between ArrayList and Vector?
As per the Java API, the main difference between the ArrayList and Vector is that Vector is synchronised whereas ArrayList is not. The other difference is the way there size is incremented, Vector always doubles the size whereas ArrayList increases the size by half the initial capacity. So if there is a need for thread-safety is advisable to use Vector but since synchronisation takes a hit on the performance we may consider using the ArrayList and synchronise it using the Collections utility class.

Question 9: What are the mandatory  methods you should override while using TreeMap and why?

Java J2EE Spring Java The Complete Reference 7the Edition Download


The world's leading programming author offers comprehensive coverage of the new Java release

The definitive guide to Java has been fully expanded to cover every aspect of Java SE 6, the latest version of the worldAnd#39;s most popular Web programming language. This comprehensive resource contains everything you need to develop, compile, debug, and run Java applications and applets.

The Definitive Guide for Java Programmers

In this comprehensive resource, top-selling programming author Herbert Schildt shows you everything you need to develop, compile, debug, and run Java programs. This expert guide has been updated for Java Platform Standard Edition 6 (Java SE 6) and offers complete coverage of the Java language, its syntax, keywords, and fundamental programming principles.

You'll also find information on Java's key API libraries, learn to create applets and servlets, and use JavaBeans. Herb has even included expanded coverage of Swing--the toolkit that defines the look and feel of the modern Java GUI. Essential for every Java programmer, this lasting resource features the clear, crisp, uncompromising style that has made Herb the choice of millions of programmers worldwide.
Coverage includes:
  • Data types and operators
  • Control statements
  • Classes and objects
  • Constructors and methods
  • Interfaces and packages
  • Method overloading and overriding
  • Inheritance
  • Exception handling
  • Generics
  • Autoboxing
  • Enumerations
  • Annotations
  • The enhanced for loop
  • Varargs (variable-length arguments)
  • Multithreading
  • The I/O classes
  • Networking
  • The Collections Framework
  • Applets and servlets
  • AWT and layout managers
  • JavaBeans
  • Swing
  • The Concurrent API
  • Much, much more

About the Author
Herbert Schildt is a leading authority on Java, C, C++, and C#. His programming books have sold more than 3.5 million copies worldwide and have been translated into all major foreign languages. Herb is the author of numerous bestsellers, including The Art of Java, Java: A Beginner's Guide, Swing: A Beginner's Guide, and many others.




Spring Hibernate How to configure Java in MyEclipse 9.1

To run java using MyEclipse 9.1 we should configure this. MyEclipse having more features to develop projects and this will be very useful for developers. This is the next generation of the MyEclipse Enterprise Workbench IDE for enterprise Java and web developers. Basically it supports Java EE 6.0 features such as:
  • Servlet 3.0
  • JSF 2.0
  • JPA 2.0
  • EJB 3.1
  • JAX-RS 1.1
MyEclipse having some Struts 2 Enhancements
  • Improved connection routing
  • Better undo/redo suport
  • Struts 2 specific validation for Struts 2 configuration files
Install MyEclipse in you System.
Step1: Go to MyEclipse Window menu then Select preferences option.
Step2:  Select Java Option from preferences window. Select Compiler, at right side you can seed the Compiler Compliance level drop down list box.

       here select the JDK version you are going to select. Here i am selecting JDK 1.5 version to run Tomcat 1.6 in my workspace.Then click Apply button then OK.
Step3: After adding the compiler version you should add the JRE location.
Here Select Standard VM(virtual machine) in Add JRE window then click Next button.
Step4: Click on Add button at the right side. then add the Java Home folder
C:\Program Files\Java\jdk1.5.0_22 . This should be select.Add the Java folder then click finish.


Click Ok button. your MyEclipse is ready to run java.
Now you are able to run java in your MyEclipse.

J2EE Spring Hibernate Download HeadFirstServlets Chapter - 3 Mini MVC Tutorial



Download the HeadFirstJava - Chapter-3 ..Mini MVC Tutorials..

The Continuous Download of the Chapter - 2.

J2EE Spring Hibernate Java Packages and interface

Java Packages and interface

1) What are packages ? What is use of packages ?

Ans :The package statement defines a name space in which classes are stored.If you omit the package, the classes are put into the default package.
Signature... package pkg;
Use: * It specifies to which package the classes defined in a file belongs to. * Package is both naming and a visibility control mechanism.

2) What is difference between importing "java.applet.Applet" and "java.applet.*;" ?

Ans :"java.applet.Applet" will import only the class Applet from the package java.applet
Where as "java.applet.*" will import all the classes from java.applet package.

3) What do you understand by package access specifier?

Ans : public: Anything declared as public can be accessed from anywhere
private: Anything declared in the private can’t be seen outside of its class.
default: It is visible to subclasses as well as to other classes in the same package.

4) What is interface? What is use of interface?

Ans : It is similar to class which may contain method’s signature only but not bodies.
Methods declared in interface are abstract methods. We can implement many interfaces on a class which support the multiple inheritance.

5) Is it is necessary to implement all methods in
an interface?

Ans : Yes. All the methods have to be implemented.

6) Which is the default access modifier for an interface method?

Ans : public.

7) Can we define a variable in an interface ?and what type it should be ?

Ans : Yes we can define a variable in an interface. They are implicitly final and static.

8) What is difference between interface and an abstract class?

Ans : All the methods declared inside an Interface are abstract. Where as abstract class must have at least one abstract method and others may be concrete or abstract.
In Interface we need not use the keyword abstract for the methods.

9) By default, all program import the java.lang package.

True/False

Ans : True

10) Java compiler stores the .class files in the path specified in CLASSPATH
environmental variable.

True/False

Ans : False


11) User-defined package can also be imported just like the standard packages.

True/False

Ans : True

12) When a program does not want to handle exception, the ______class is used.

Ans : Throws

13) The main subclass of the Exception class is _______ class.

Ans : RuntimeException

14) Only subclasses of ______class may be caught or thrown.

Ans : Throwable

15) Any user-defined exception class is a subclass of the _____ class.
Ans : Exception

16) The catch clause of the user-defined exception class should ______ its
Base class catch clause.

Ans : Exception

17) A _______ is used to separate the hierarchy of the class while declaring an
Import statement.

Ans : Package

18) All standard classes of Java are included within a package called _____.
Ans : java.lang

19) All the classes in a package can be simultaneously imported using ____.

Ans : *

20) Can you define a variable inside an Interface. If no, why? If yes, how?

Ans.: YES. final and static

21) How many concrete classes can you have inside an interface?

Ans.: None

22) Can you extend an interface?

Ans.: Yes

23) Is it necessary to implement all the methods of an interface while implementing the interface?

Ans.: No

24) If you do not implement all the methods of an interface while implementing , what specifier should you use for the class ?

Ans.: abstract

25) How do you achieve multiple inheritance in Java?

Ans: Using interfaces.

26) How to declare an interface example?

Ans : access class classname implements interface.

27) Can you achieve multiple interface through interface?

a)True
b) false

Ans : a.

28) Can variables be declared in an interface ? If so, what are the modifiers?

Ans : Yes. final and static are the modifiers can be declared in an interface.

29) What are the possible access modifiers when implementing interface methods?

Ans : public.

30) Can anonymous classes be implemented an interface?

Ans : Yes.

31) Interfaces can’t be e
xtended.

a)True

b)False
Ans : b.

32) Name interfaces without a method?

Ans : Serializable, Cloneble & Remote.

33) Is it possible to use few methods of an interface in a class ? If so, how?

Ans : Yes. Declare the class as abstract.

Java J2EE Spring Download Java 2 Core Language Little Black Book

The focus of this book is on the core Java language as implemented by the new version of Java, version 1.4. The book features a logical, sequential approach with concise overviews, then step-by-step immediate solutions created by a master Java programmer. This book is also packed with over 150 code listings which can be used as is or quickly modified.


  • Paperback: 440 pages
  • Publisher: Paraglyph Press; 1 edition (August 2002)
  • Language: English





About the Author:


Alain Trottier observes the .com warfare of Southern California as a technology management consultant (Strategic Business Resources) and an adjunct professor at Vanguard University. He has been in the tech sector for two decades. On the electronics side, he has worked with RF gear, nuclear power plants, and electromechanical devices. On the IT side, he has held roles as a technologist, a developer support specialist, a programmer, an architect, and a manager. Alain got a kick out of being in the U.S. Submarine Navy (nuclear power division), and he was impressed with his bosses at Chevron's world-class research center. He was astonished by the .com bubble while at Adforce and then Winfire, where he experienced a meteoric IPO and then a subsequent flameout. He has been through a get-it-right-at-all-cost experience in a Fortune 30 company, and he also has witnessed the other extreme, in which one bets it all on a get-it-out-there-at-no-cost venture.


Alain enjoys a difficult technological challenge and likes the people even better. He believes that his degrees in religion (Bachelor of Arts, Master of Arts with a specialization in the linguistics of ancient religious texts) is a terrific way to broaden one's abilities. He has certifications from both Microsoft and Sun, so his bias is simply what works best for a given situation. If you have a question, comment, or even a challenge, the author would be delighted to hear from you. Please contact him (think Chief Technology Ambassador) from the book's Web site, at http: //www.inforobo.com/scwcd/examcram.


Steve Heckler is a freelance programmer and IT trainer specializing in .NET, Java, ColdFusion, Flash ActionScript, and XML. Based inAtlanta, Georgia, he works with clients nationwide. In addition, he is the author of the Sun Certification Instructor Resource Kit (310-025, 310-027): Java 2 Programmer and Developer Exams and Sun Certification Instructor Resource Kit (310-080): Java 2 Web Component Developer Exam. He is currently writing an ASP.NET-related book for Addison-Wesley.


Before being self-employed, Steve served nearly seven years as vice president and president of a leading East Coast IT training firm. He holds bachelors and masters degrees from Stanford University.




Spring MVC Framework Test Driven Development - using Eclipse

TDD is getting very important these days due to some of its benefits that most of the bugs are found at the development stage. Unit tests are already in place which gives you a better code coverage, more confident code and more importantly you always know that the addition of behaviour has not broken your previous code. Apart from that there are other benefits like you may end up getting a better design than you originally thought. It will also help in using a lot of patterns in your code, which may not be visible at the start.

I was going through some videos here, that explains how to use TDD in Java Development in Eclipse. The instructor has actually broken it down nicely and try to convince you of all the above points.

I liked some of his principle or things to remember, which are:
  • We are only doing one activity at a time
  • We can be doing any one activity of the four
    • Writing Test
    • Writing Production Code
    • Refactoring / updating / Cleaning Test code
    • Refactoring / updating / cleaning production code
  • We are only going to write production code when we have a failing test
  • When we add a test, earlier written test should not fail

J2EE Spring Hibernate Chapter 15: Stack and Heap

You might be wondering, is Stack and Heap such a large topic that I have dedicated one full chapter to it? Actually it isnt such a big topic but it is extremely important to understand them fully and clearly in order to grasp the forthcoming topics clearly. And combining this with any other topic would make it a bit confusing or rather off-place. So it is given a separate topic status. (We will

J2EE Spring Hibernate 2. Introduction to FrameWork

In MVC architecture based webapplication we use JSPs in view Laer servlet in controller Layer. JavaBean, EJB, Spring with Hibernate technologies in model layer.
Q. What happens if interchange technologies of these layers.?
A. We can change rolls of these technologies , but it is not recommended to do.

Reasons: If servlet is taken as view layer component
  • preesntation Logic of the webapplication changes at regulat intervals.
  • If source code of servlet is modified we need to recompile the servlet and we need to reload the webapplication.
  • If Source code of JSP is modified these is no need of recompiling JSP and reloading the webapplication.
  • Since presentation logic of webapplication changes regularly it is recommended to take JSP s as View components.
If JSP is taken as Controller
  • Integration Logic of controller is always java code.
  • Keeping Java Code in JSP is not industry standard.
  • It is always recommended to develop JSP as java codeless JSP.
  • If JSP is taken as controller it will be forced to have java code,representing integration logic which is not a recommended operation.So always prefer taking servlet as controller.
Note.:Only webComponents(Servlets, JSPs) can acts as controller Because they only can take Http request given by browser. So we can't see JavaBean, EJB, Hibernate and spring applications as controller because they can't take Http request.
These application can't act as view Layer application because they are not capable of generating web-pages.
  • If Seperates or another Servlet/JSP is taken as model layer components.
  • Business Logic placed in Servlet/JSP gives following limitations.
  • Allow only HttpClients(browsers) to access the business logic.
  • Business Logic becomes specific to one webapplication(businessLogic is not reusable).
  • Middleware services must be implemented manually.
  • To overcome these problems use EJB, Spring with hibernate to develop business logic of model layer,and take the advantage of reuability of business logic built in middle ware services under capability of allowing all types of java applications as clients(Both Http & Http Clients).
Note: Browsers are called HttpClients. Java application, awt, spring applications are called non HttpClients.

Framework is a special software that is capable of developing applications based on certain architectuere havingg ability to generate common logics of applications devolopment dynamically.
Due to framework software program need not to develop of all the logic of application. He just need to concentrate only on the logics that are specific to our applications.
Strut is a web based frame work software to develop MVC architecture based webapplication having capability of generating integration logic of controller Servlet dynamic calls.
In Struct based webbased application controller servlet is built in servlet and its integration logic will be generated dynamically By struct framework software . So programmer needs to develop only presentation , business logics.
  • Struts framework Software is designed by using servlet JSP technologies has underlaying technologies.
  • In strut based web application, MVC priciple will not be violated , because it experts source code files to programmer according to MVC principles.
  • By using struts frame work software complex operation of web application can be done easily with the support of built in wizards and (Phonics).
  • If web application developed manually with out using framework softwares are based on MVC architecture programmer needs to develop all the applications manually.
  • Compare to mannual implementation of MVC architecture(with out framework software) to develop web applications the framework software based web applications can be developed fastly.
Struts ----> Apache
JSF ----> Sun MicroSystems
Cocoon ----> Adobe
Webwork ----> OpenSymphony
Spring MVC----> Interface21.
TapStray ----> OpenCommunity
ASP.net ----> MicroSoft

Note : All java based webframe work softwares are given based on servlet JSP technologies.

J2EE Spring Hibernate 1.5. Disadvantages of MVC :

For parallel development more programmers with knowledge on multiple technologies is required.
Note: in the development of MVC architecture based web application not only we need to use multiple technologies , but we also need to use(follow) set of rules in the devolopment of web application.
  • Multiple layers are given in web-application development.Each layer is given for specific logics. Just keep only these logics and don't place any extra logics.
  • Every operation /execution that takes place in MVC architecture webapplication must be executed under the control of controller Servlet.
  • We can see multiple business components in model layer. Multiple view components in view layer, But these should be only one servlet acting as controller.
  • Clean separation of logic is required in multiple layers of application development.
  • View components should not interact with model components directly and viceversa. This communication must be executed or happened through the controller servlet.
  • Two types of web application must not interact each other directly. This communication should happens through controller servlet.
  • Design pattern are the set of rules which come as best solution for real time problems of application development.
  • Senior developers design these design pattern based on experience and junior devolopers use these design patterns in projects development.
  • To develop Java, J2EE application as best application without having sideaffects of java, J2EE technologies. It is recommended to develop application by applying design patterns.
  • If design patterns becomes popular & minimum standards to devolop applications,base to design new softwares then design patterns acts as architectures.
  • MVC is gives as design patterns initially. After its popularity it has become MVC architecture.
  • Struts, JSF and etc frame work softwares are designed based on MVC design pattern/architecture.

J2EE Spring Hibernate 1.4. Advantages of MVC Architecture

Since there are multiple layers representing multiple logics there will be clean separation of roles or logics.
  • Modification of one logic does not effect other logics.
  • Easy to maintain and enhance the project.
  • Parallel development is possible due to this productivity is very good.
  • Project Leader divides a team into two parts.
  • 1. Web Authors
  • 2. J2EE Developers.
1.Web Authors : These programmers use JSP in developers presentation logic of the application.
2.J2EE Developers: These programmers use J2EE technologies like servlets EJB and e.t.c, to develop integration logic and business logic, persistence logic of the application.
While working with EJB , Spring and Hibernate technologies in model layer we can take the advantage of built in middle ware services due to this programmer will not be over burdened.

J2EE Spring Hibernate 1.3. MVC Architecture.

In MVC architecture based web-application devolopment multiple layers will be involved like
  • View layer,
  • Model layer,
  • Controller layer.

M(Model) Contains
  • Business Logic
  • Persistence Logic
  • Java Bean/EJB
  • Spring with Hibernate simply named as (Accounts Officer)
V(View) Contains
  • Presentation Logic
  • JSPs /Free marker simply named as (Beauticians)
C(Controller) Contains
  • Integration Logic
  • Servlet simply named as (Traffic Police).
Java application use JDBC or ORM (Object Relational Mapping)technologies like Hibernate to interact with database softwares.
  • Java applications use JCA(Java Connector Architecture) to interact with ERP (Enterprise Resource Plan) & CRM (Customer Resource Management).
  • Java Application use JNI ( Java Native Interface) to communicate with legacy system.
  • Integration Logic is the connectivity logic b/w model layer components.
  • Integration Logic controls and monitors all the operations that are taking place in MVC architecture based web-application.
  • Integration Logic is responsible to trap and take the request to send request to Model Layer, to get business logic execution request from model layer to pass request to view layer components
with respect to the above diagram:
  1. 1.Browser gives request to web application.
  2. 2.The controller Servlet traps and taken the request.
  3. 3.Controller servlet uses integration logic and passes the request to appropriate model layer to business component.
  4. 4.& 5. Model Layer business logic executes if necessary business components interacts with one of the back-end softwares for using persistence Logic.
  5. 6.The business Logic execution logic comes to controller servlet.
  6. 7. Controller servlet passes the new request to view always components JSP.
  7. 8. Presentation Logic of JSP formats the result and sends formatted result to browser as response.
Calling Model 1 as MVC 1, Model 2 as MVC 2 is always an appropriate terminalogy.

J2EE Spring Hibernate 1.2. Limitations Of Model 1 Architecture

Since multiple logic's are mixed up in every web resources of web application there are no clean separation of logic's/rolls.
  • Modification done in one logic disturbs other logic of the web application parallel development is not possible due to this productivity is very poor.
  • Maintenance and enhancement of the project is always complex.
  • Programmer will be overburdens because he has to implement middle-ware services along with main logic's.
Advantages : Knowledge servlets of JSP is enough to develop the web-application.
  • Model 1 architecture is not a industry standard to develop the web-application.
  • To overcome the problem of Model 2 architecture use MVC architecture Model 3 architecture to develop the web-application.

J2EE Spring Hibernate Chapter 14: Coupling and Cohesion

You would have heard or learnt a lot about coupling and cohesion when you learnt object oriented concepts or while learning other programming languages like c++. Let me tell you up front that, this chapter is going to be from the SCJP exam perspective and is going to cover concepts related to these two topics only from the exam point of you and not the overall dig deep into the topics. Frankly

J2EE Spring Hibernate Chapter 13: Statics

Static is one of the most important and powerful keywords in the java programming language. It can alter the behavior of variables and methods. The purpose of this chapter is to take a detailed look at this feature.

Static Variables and Methods

The static modifier has such a profound impact on the behavior of a method or variable that we’re treating it as a concept entirely separate from the

J2EE Spring Hibernate Chapter 12: Constructors and Instantiation

Objects are constructed. You can’t make a new object without invoking a constructor. In fact, you can’t make a new object without invoking not just the constructor of the object’s actual class type, but also the constructor of each of its superclasses including the Object class itself! Constructors are the code that runs whenever you use the keyword new. To be a bit more accurate, there can also

J2EE Spring Hibernate Chapter 11: Legal Return Types

In the previous chapters we have seen many methods and classes. Every method in java has a return type which specifies the kind of data that would be returned by the current method. It is mandatory for all java methods to return something and if it is not going to return anything, we have to mark the method with a “void” return type to let the JVM know that it must not expect anything from the

Spring MVC Framework Basic Java Questions - 2

This is the second part of Basic Questions asked on Core Java. Please leave a comment if you think there is something wrong with an answer as it will help me greatly.
Question 1: What is data encapsulation in Java?
Data Encapsulation is the process of hiding the internal information from the external world. The information can only be manipulated using a set of operations exposed by the objects known as methods. This is also called as data hiding.

Question 2: What is the difference between Abstract Class and Interface?
Interface is a pure abstract class, means all the methods in interface are abstract whereas in Abstract class we can have non-abstract methods. All the methods in an interface are public by default, whereas Abstract class can have methods with other access modifier. All the method in an interface have only definition and no declaration, whereas an Abstract class can have method with the default implementation. All the member variables in the interface are final, whereas Abstract class can have non-final variables. An interface needs to be implemented using implements whereas an Abstract class needs to be extended using extends. A Java class can implement multiple interfaces but can only extend one Abstract class.

Question 3: Can I have an Abstract Class without any abstract method and vice-versa?
You can have an abstract class without any abstract method, if you don't declare a class as Abstract that have abstract methods, the class will give compilation error.

Question 4: What is the difference between Exception and Error?
Basically a user can recover from an exception at runtime but not from an Error. For example, a user program may recover from an FileNotFoundException, however, it wont be able to recover from an OutOfMemoryError. In other words, Exceptions are programmer generated and should be handled at the application level, whereas Errors are system generated and should be handled at the system level, if possible.

Errors are also a sub class of the Throwable, however we should try to avoid catching errors. If you have a catch Throwable, the block will also catch the Error, which is not a good practice.

Question 5: What is the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when the class is loaded using one of the following methods:
  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader .
  • The loadClass method in class ClassLoader.
Whereas, NoClassDefFoundError is encountered, when the JVM is trying to load the class as part of a normal method call or as part of creating a new instance using the new expression.

Question 6: Under what condition does finally block will not execute?
Finally block is a block in Java program, which gets executed most of the times. There are only few conditions under which the finally clock will not get executed.
1. If the Application executing the try or catch block exits by calling System.exit or by shutting down JVM.
2. If a thread executing the try or catch block is killed or interrupted, the finally block will not execute.

Question 7: Can you have a finally block without catch?
Yes, you can have finally block with the try statement, without a catch statement.

Spring MVC Framework Spring Interview Questions - 1

Spring is one of the most widely used framework in the Java/J2EE application. Almost all the job postings / consultancy requirements list Spring as one of the key skills. So it is no surprise that most of the interviews contains a wide list of Spring related questions. Here we will try to list some of the basic questions asked on the Spring Framework.
Question 1: What is Spring Framework?
Spring is an open source lightweight inversion of control application framework that supports the various aspects of application development.

Question 2: What are its features?
Spring has the following features:
  • Lightweight
  • Inversion of Control - A component lists its dependencies rather than looking for dependent objects.
  • Container - Contains and manages the lifecycle of various application components.
  • Aspect Oriented - Cross cutting concerns are handled separately through AOP module.
  • Transaction Management - Spring container provides an abstract layer of components to handle the transaction management thus allowing the developers to concentrate more on the business logic and allowing them to demarcate the transactions without worrying about the low-level issues, by providing plugable transaction managers. The spring transaction management can be run in a container less environment as well.  
  • JDBC Handling - Spring can be easily integrated with the Hibernate, JDO and iBATIS.
  • MVC Framework - Spring comes with a MVC framework as well which can use various presentation technologies like JSP, JSF, Velocity and Tiles etc. However, if you wish you to use some other MVC framework spring can be easily integrated with them as well.
Question 3: What is Inversion of Control / IoC?
Inversion of Control or IoC is a phenomenon used by frameworks to invert the control. Basically, in traditional programming the user / developer control the calling of a procedure, however when using IoC the framework controls the calling mechanism. Hence, saying simply that the framework calls us, we don't call it. Although the above statement state the calling of procedure, this can be used for any development term like instantiation etc. A better and elaborated discussion can be found here by Martin Fowler. Servlets, EJB, template method pattern can be stated as examples of Inversion of Control, in general they are Inverting the control. (Hint: Don't call us, we will call you.)

Question 4: How is Inversion of Control different from Dependency Injection?
Inversion of Control is a principle that is being followed in many frameworks, however dependency injection in one such patter that is built on top of IoC. IoC is generally followed in all framework as they are trying to invert some sort of control, however every framework may not provide you with dependency injection. In dependency injection it is the dependency creation control that is being inverted. In DI, rather than object creating the dependencies the framework will invert the control and inject dependencies. More on this can be found here.

Question 5: What pattern does Spring uses to create beans?
Generally there are lot of design patterns used in Spring to create beans. For Example,
  • Proxy interface, in case of AOP
  • Singleton, beans created in spring are singleton by default
  • Template method, in case of JdbcTemplate, JmsTemplate etc.
  • Abstract Factory pattern, is use to register and then instantiate various beans defined in the Configuration file.
Question 6: What are the ways to inject beans in Spring and which one should be used where?
In Spring beans can be inject by the setter method or by constructor. In Setter Injection, the bean is created using the default constructor or no-arg constructor and then the setter methods are called in to inject various beans. In Constructor Injection, the bean is created using the Constructed with a number of arguments and then these arguments can be inject while instantiation. Now the question arises which one should be used. IMHO I think we should use a combination of both. You should have a constructor with the "Required" arguments or collaborators and should have setter injection for dependencies which are optional. In this way, you are also making sure that you have all the required dependencies during its instantiation and optional properties can be set using setter injection. You can refer to the following blog at springsource to learn more about the above reason.

Question 7: What is JdbcTemplate in Spring DAO?
JDBCTemplate is the central class in the Spring DAO module, it has the template methods to open and close various resources, hence decreasing the programming errors. This class provides the basic workflow for a JDBC like opening the connection, preparing the statement , executing and then closing the connection thus leaving the application code to only provide the SQL and retrieve the results. It has methods for executing SQL queries, update statements and procedure calls. It also provides the methods for iterating over a result set. This class also catches SQL Exceptions and generates more informative exceptions defined in the Spring Exception hierarchy.



Spring MVC Framework Basic Java Questions - 1

This page contains the list of question that are generally asked in the Java General Questions. They can also be termed as questions asked on Basic Java Language.
Question 1: What is the difference between java.util.Date and java.sql.Date?
The main difference is that java.util.Date represents "date and time" stored upto a milisecond. However, java.sql.Date only stores data value which is required for the SQL DATE type. java.sql.Date has a java.sql.Time counterpart which stores only time.

Question 2: What is the difference between String, StringBuffer and String Builder?
  • String is immutable whereas StringBuffer/StringBuilder are not. It means it gives faster performance while update operations. 
  • StringBuffer is synchronised whereas StringBuilder is not.
  • Use String if you need immutability, use StringBuffer is you need mutability and thread-safety, use StringBuilder if you need mutability but not thread safety. 

Question 3: What are various visibility modifiers in Java and what is the difference between them?
There are four access modifiers : public, private, protected and default. There accessibility is as defined below:

public - Any class can access it directly.
protected - It is available to class, subclasses and package.
default or no-modifier: It has the package accessibility but is not available to subclasses.
private: This is only visible with the class itself.

Question 4: What is difference between .equals and "=="?
"==" checks whether the two references refer to the same instance whereas .equals check if the two different instances are equal.

Question 5: What is the relationship between .equals and hashcode()? or Why is it a good practise to either override both .equals() and hashcode() or none at all?
The relationship can be explained in simple way as, if two objects returns true for .equals() then their .hashcode() method must return the same value. However, if .hashcode() value returns same value .equals() may not return true, provided .hashcode() and .equals() uses the same fields for evaluation.

You should always override both these methods together because they should use the same fields to evaluate hashcode() and compare the two objects in .equals().

Question 6: Why is clone method "protected" in the Object class?
Default method in the Object class does not provide any implementation, so it does not make sense to make it public. Also, the object which needs to be cloned needs to implement Cloneable interface. Any object that wishes to be available for cloning can override this method and make it public.

Question 7: Is Generics a compile-time feature or runtime feature?
Generics are a compile-time feature, they help us to find some of the bugs at compile-time itself. Generics helps in ensuring the strong type checking. This information is not kept along with the compiled version of class.

Question 8: What is the use of serialVersionUId in Serializable class?
serialVersionUId is used in the serialization and de-serialization process. While serialization and de-serialization the serialVersionUId needs to be same. In case, the serialVersionUId is changed in a class the JVM will throw an "InvalidClassException". You should only change the serialVersionUId only,  when your serialization class is updated by some incompatible Java types changes to a serializable class. Please refer this for further explanation on serialVersionUId.

Question 9: What is the difference between Serializable and Externalizable?
When a class implement the serializable interface, the JVM will serialize and de-serialize the class variables by itself, however, if you want to change the way serialization is done you need to implement the Externalizable interface. When you implement the Serializable interface you dont need to implement any method the JVM will use reflection to serialize your class. However, if you implement Externalizable interface, you need to implement two methods readExternal() and writeExternal(). If you have implemented Serializable you can still control the serialization by writing two methods in your class namely, readObject() and writeObject().

Question 10: How can you control which fields should be serialized?
There are three exceptions to the Serialization process. They are:
1) Static fields are not serialized.
2) transient fields are not serialized.
3) Base class variables are only serialized if the Base class itself implement Serializable.

Labels

.equals = operator abstract class abstract method abstract window toolkit Access Modifiers accessing java beans accessing javabeans action events actionperformed active addition Advanced Advanced Overloading AdvJavaBooks Agile development ajax alive AMQP and Android anonymous class anonymous inner class Ant ant tutorials anti patterns antipatterns Apache Camel api for jsp api for servlet api for servlets api jsp application context application scope application session Apps Architecture are you eligible for the ocmjd certificaiton are you eligible for the scjd certification arithmetic operator arpanet array construction array declaration array initialization array list array to list conversion arraylist arraylist of strings arraylist of types arraylist questions arraylists Arrays arrays in java ask for help assert assert in java assertions assertions in java assignment assignment operator Atlassian attribute visibility authentication authorization autoboxing autounboxing awt AWT Event Handling awt interview questions AWT Layouts awt questions awt questions and answers backed collection backed collections Basic Basics of event handling bean attributes bean properties bean scope Beginner best practices BigData blocked books boxing buffer size bufferedreader bufferedwriter business delegate business delegate pattern calendar case statement casting in java casting interview questions chapter review choosing a java locking mechanism choosing a locking mechanism choosing a thread locking mechanism class inside a method class questions class with no name class without a name classes interview questions Clipboard closing jsp tags code snap coding cohesion collection generics collection interview questions collection methods collection of types collection questions collection searching collection types Collections Collections Framework collections interview questions collections sorting colors in java swings colors in swing command line arguments communication between threads comparable comparator comparison operators compiling java classes computers concurrency example and tutorial config Configuration ConnectionPooling constructor creation constructor interview questions constructor overloading constructors in java containers contents of deployment descriptor contents of web.xml context context scope converting array to list converting list to array core java core java interview core java interview question core java interview questions core java questions core java; core java; object oriented programming CoreJava CoreJavaBooks CORS coupling create threads creating 2 dimensional shapes creating 2D shapes creating a frame creating a jframe creating a thread creating an arraylist creating an inner class creating an interface creating java beans creating java threads creating javabeans creating threads creating threads in java CSS cURL currency current thread determination custom tag library custom taglib custom taglibs custom tags CVS dao dao design pattern dao factory pattern dao pattern data access object data access object pattern data structure and algorithm database date and time tutorial date format dateformat dates deadlock deadlocks debugging Declarations decorator pattern decrement default deleting sessions deploy web app deployment deployment descriptor deployment descriptor contents deployment of web application deserialization deserialize design pattern design pattern interview questions design patterns Designpatterns destory method destroy destroying sessions determining current thread determining the current thread Developer Differences different types of collections display stuff in a frame displaying images displaying images in java swings displaying images in swings displaying text in a component division do while loop doget dohead dopost doput DOS Downloads drawing a line drawing an ellipse drawing circles drawing ellipses drawing lines Drools tutorial eBooks Eclipse Eclipse Tutorial Encapsulation encapsulation in java enhanced for loop entity facade pattern enumerations enumerations in java enums equal to equals equals comparison error and exception error codes error handling in servlets error page event handling in swings event listeners exam prep tips example servlet Examples exception exception handling exception handling in servlets exception handling interview questions exception handling questions Exceptions exceptions in java exceptions in web applications explicit locking explicit locking of objects file file navigation filereader filewriter final class final method FireBug first servlet FIX protocol FIX Protocol interview questions FIX protocol tutorial font fonts for each loop for loop form parameters form values formatting forwarding requests frame frame creation frame positioning frame swings front controller front controller design pattern front controller pattern fundamental.Java FXML Games garbage collection garbage collection interview questions garbage collection questions garbage collector gc gc questions general generic Generics generics collections Geo get get set methods getattribute getting bean property getting form values getting form values in servlet getting scwcd certified getting servlet initialization parameters getting sun certified Google Graphics2D gregorian calendar handling strings in java hash hash map hash table hashcode hashmap hashset hashtable head head request HeadFirst heap heaps hibernate hibernate interview questions hibernate interview questions and answers hibernate questions hibernate questions and answers Hibernate Tutorial HibernateBooks homework How To HTML HTML and JavaScript html form http request http request handling http request header http request methods http request servlet http request type http session httprequest httprequest methods httpservlet httpservlet interview questions httpservlet interview questions with answers httpsession httpsession interview questions httpsession questions HttpSessionActivationListener HttpSessionAttributeListener HttpSessionBindingListener if if else if else block if else statement Image IO implementing an interface Implicit objects increment info inheritance inheritance in java init init method Initialization Blocks inner class inner class inside a method inner classes innerclass installation instanceof instanceof operator IntelliJ interaction between threads interface interface interview interface questions interfaces interfaces in java interfaces interview questions internet history interrupting a thread interrupting threads Interview interview questions interview questions on design patterns interview questions on exception handling interview questions on java collections interview questions on serialization introduction to java threads introduction to jsps introduction to threading introduction to threads invalidating session Investment Banking IO Package iscurrentthread iterator J2EE j2ee api j2ee design pattern j2ee design pattern interview questions j2ee design patterns j2ee hibernate interview questions j2ee history j2ee interview j2ee interview questions j2ee mvc j2ee mvc pattern j2ee programmer j2ee questions j2ee servlet api j2ee session j2ee struts interview questions java java 5 tutorial Java 8 java arrays java assertions java assignments java awt questions java bean java bean scope java beans java beginners tutorial Java career java certification Java Class java collection interview questions and answers java collection tutorial java collections java collections interview questions java constructors java currency Java CV java data base connectivity java database connectivity java database connectivity interview questions and answers java dates java design pattern java design patterns java developer certification Java EE java encapsulation java enums java event listeners java exceptions java formatting java garbage collection java garbage collector java gc java heap Java I/O java inheritance java input output Java Interface Java Interview Java Interview Answers Java Interview Questions Java Introduction java io java IO tutorial java iterator java jdbc Java JSON tutorial Java Key Areas java lists java literals java locks nested Java Media Framework java methods java multithreading Java multithreading Tutorials java nested locks java networking tutorial java numbers Java Objects java operators java overloading java parsing Java Programming Tutorials java race conditions java regex java regular expressions Java resume java scjp java searching java serialization java server pages java server pages api java server pages questions java spring interview questions. j2ee spring interview questions java stack java strings java swing java swing event listeners java swing frame java swing images java swings java swings images java thread explicit locking java thread lock scope java thread locking java thread locking mechanism java thread locking objects java threads java threads race condition java tips java tokenizing Java Tools Java Tutorial java ui questions Java Utilities java variables java wrappers Java xml tutorial java.lang java8 javabean javabean accessing javabean scope JavaBeans javac JavaEE JavaFX JavaFX 3D JavaFX 8 JavaOne JavaScript JavaTips JDBC jdbc driver jdbc example jdbc interview questions jdbc interview questions and answers jdbc interview questions with answers jdbc sample code JDBC Tutorial jdbc type 1 driver jdbc type 2 driver jdbc type 3 driver jdbc type 4 driver Jdeveloper JDK JDK8 JEE Tutorial jframe jframe creation jframe position jframe positioning JIRA JMeter JMS JMX join() joining threads JPA JQuery JS JSF JSF Tutorial JSONP JSP jsp and java beans jsp and servlets jsp and xml jsp api jsp code jsp compilation jsp conversion jsp directives jsp error page jsp error page directive jsp implicit objects jsp interview jsp interview questions jsp introduction jsp intvw questions jsp life jsp life cycle jsp life-cycle jsp lifecycle jsp page directive jsp questions jsp sample jsp scripting jsp scriptlets jsp servlets jsp summary jsp synopsis jsp tag libraries jsp tag library jsp taglib jsp tags jsp technology jsp to servlet jsp to servlet conversion jsp translation jsp usage jsp usebean jsp xml tags jsp xml tags usage jsp-servlet jsp:getProperty jsp:setProperty jsp:usebean jsps JSTL JUnit testing keyword synchronized keyword volatile Keywords Lambda Expressions Learning libraries life cycle life cycle of a jsp life cycle of a servlet life cycle of a thread life cycle of jsp life cycle of threads lifecycle of a thread linked list linkedhashmap linkedhashset linkedlist linux List listeners lists Literals locale lock manager pattern lock scope locking objects using threads log Logging logging errors logical and logical operators logical or loops loosely coupled making an arraylist making threads sleep making threads sleep for time MapReduce maps maps usage Maven Maven Tutorial max priority member access method arguments method local inner class method overloading method overriding method return types methods creating classes min priority Miscellaneous mobile mock exam model view controller model view controller design pattern model view controller pattern Multi Threading Multi-threading multiple threads multiplication multithreading multithreading in java multithreading interview questions multithreading questions mvc mvc design pattern mvc pattern MyEclipse mysql nested java lock nested java locks nested java thread locks nested locks nested thread locks NetBeans Networking new news nio NonAccess Modifiers norm priority normal inner class Normalization not equal to Notepad notify notifyall number format numberformat numbers object comparison object notify object orientation object oriented object oriented programming Object Oriented Programming in java objects interview questions ocmjd certification ocmjd certification eligibility OO OO Java oops OpenCSV OpenCV opening jsp tags OpenJDK OpenJFX Operators or Oracle Oracle ADF Mobile Oracle Certified Exams oracle certified master java developer oracle database ORM other topics out overloading overloading constructors overloading in java overriding page page directive page scope parsing passing variables passing variables to methods performance Platform Playing with Numbers points to remember polymorphism positioning a frame post practice exam Primitive Casting primitive variables printwriter priority queue priority queues priorityqueue priorityqueues private processing form values Products programming Projects protected public put questions questions on garbage collection questions on java strings queue quick recap quick review race conditions read objects from stream reading http request header RealTime_Tips redirecting to another servlet redirection reference reference variable casting reference variables Refreshing Java regex Regular Expressions regular inner class relational operators reminder request request dispatcher request forwarding request header request object. httpservletrequest request scope requestdispatcher response RESTClient RESTful retrieving values from session return error codes return types returning values runnable runnable interface running running java programs RUP sample jsp sample questions sample questions scwcd sample servlet scanner Scene Builder scjd certification scjd certification eligibility requirements scjp SCJP Certification scjp exam scjp exam questions scjp exam sample questions scjp questions scjp test scjp test questions scope scope of java locks scope of java thread locks scope of locks scripting in jsp scriptlet tags scriptlets scriptlets in jsp pages scwcd scwcd certification scwcd certification practice exam scwcd exam scwcd exam questions scwcd jsp summary scwcd mock exam scwcd mock exam answers scwcd practice exam scwcd practice test scwcd questions scwcd test SDLC searching searching arrays searching collections searching in java searching treemap searching treesets security self assement self assement scwcd self assessment scjp self test self test scjp self test scwcd send error method senderror method sending error code to browser serialization serialization in java serialization interview questions Serialization on Swing serialization questions service service method servlet servlet and forms servlet and jsp servlet api servlet attributes servlet code servlet container servlet context servlet error handling servlet exception handling servlet handling http request servlet initialization servlet initialization parameters servlet interview servlet interview questions servlet interview questions with answers servlet intvw questions servlet life cycle servlet lifecycle servlet questions servlet questions with answers servlet request servlet request dispatcher servlet request type servlet skeleton servletcontext servletcontextevent servletrequest Servlets servlets and jsps servlets api servlets details servlets request handling session session clean up session event listeners session facade pattern session interview questions session invalidation session listeners session management session questions session scope session timeout session tracking through url rewriting set collections set status method setattribute sets setstatus method setting bean property setting request type short circuit operators Singleton sleep sleeping threads soapUI Software Installation sorting sorting arraylist sorting arrays sorting collections special collections special inner classes split spring spring and hibernate interview questions spring batch Spring Core Spring Framework Spring Integration spring interview questions Spring JDBC Spring MVC Spring security Spring tutorial SQL SQL and database tutorial examples SQL Tutorial SSL stack stacks stacks and heaps static static class static declaration static imports static inner static inner class static method Static variable stopped stopping a thread stopping thread stopping threads Stored Procedure storing values in session Streams strictfp StrictMath string string buffer string builder string class string formatting String Handling string interview questions string manupulation string questions string tokenizer stringbuffer stringbuffer questions stringbuilder Strings strings in java struts Struts 1 Struts 1.2 Struts 2 struts framework interview questions struts interview questions struts interview questions with answers struts mvc interview questions struts questions Struts2 StrutsBooks submitting request subtraction Sun Certification sun certified java developer Sun Certified Java Programmer swing swing action performed swing and colors Swing Components swing event handling swing event listeners swing events Swing Hacks swing images Swing Look And Feels swings swings frame switch block switch case block switch case statement Sybase Sybase and SQL Server synchronization synchronized code synchronized keyword synchronized method System Properties tag lib tag library tag-lib taglibs tags TDD Technical Blogging ternary operator Test Driven Development test scjp Testing the context the session the volatile keyword thread thread class thread deadlocks thread interaction thread interruption thread life cycle thread lifecycle thread lock scope thread locks thread notify thread priorities thread race conditions race conditions in threads thread sleep thread states thread stoppage thread stopping thread synchronization thread syncing thread yield Threads threads in java threads interview questions threads life cycle threads questions tibco tightly coupled tips tips and tricks tips.FXML tokenizing Tomcat Tools toString transitions treemap treeset tricks Tricks Bag try catch try catch finally. finally block Tutorial type casting in java ui programming with java swings UML unboxing unit testing unix url rewriting use bean usebean using a arraylist using collections using colors using colours using command line arguments using different fonts using expressions using font using fonts using fonts in swings using hashmap using http session using httpsession using iterator using java beans in jsp using javabean in jsp using javabeans in jsp using javac using lists using maps using request dispatcher using scriptlets using session persistense using sets using special fonts using system properties using the jsp use bean using treeset using use bean Using Variables using volatile Using Wrappers using xml in jsp Util pack value object value object design pattern value object pattern var-args varargs Variable Arguments Variables vector vector questions vectors visibility vo pattern volatile volatile keyword volatile variables wait method waiting web app exception handling web app interview web application deployment web application exceptions web application scope web application security web component developer web component developer certification web context web context interfaces web context listeners web interview questions web security web server web servers Web services web.xml web.xml deployment webapp log weblogic website hacking website security what are threads what is a java thread what is a thread what is thread while loop windows windows 8 wrapper classes wrappers write objects to stream WSAD xml xml and jsp xml tags xslt yield()