Java Study Guide

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

JDK .

- Java Development Kit, this kits contains the libraries necessaries to develop an application in
java.

JRE .- Java Run-time Environment, this kit contains the libraries necessaries to run any application in
java.

JVM .- Java Virtual Machine, this machine is the environment that is able to execute the bytecode java;
that bytecode is created when any java file is complied and creates

Static .- The Keyword static is used for memory management mainly, it's a property that belongs to
the class and not to object(instance) .We can apply it with:
• Variables
• Methods
• Blocks
• Nested class

Final .- The keyword final is used to restrict the behavior of Variables, Methods and Classes.
• Variable its assigned value once and can't be changed.
• Methods that cannot be override
• Class cannot be extended.

Garbage Collector .-It's a feature of java to provide memory management with destroying
Automatically the unreferenced objects. For this behavior they said java is SIMPLE.
We have two ways to call the garbage collector:
• Instancing the Runtime class and calling the gc method.
Runtime r = Runtime.getRuntime();
r.gc();
• Calling the gc method in System class.
System.gc();

Annotation .- The Annotation in java is preceded by At Symbol (@). Is a tag that represents the
metadata and it provide additional information which can be used by java compiler and JVM. It can be
used in class, interface, methods or fields. Annotations became available in the language itself
beginning with version 1.5 of the JDK.
Annotations applied to Java code:
• @Override - Checks that the method is an override.
• @Deprecated - Marks the method as obsolete.
• @SuppressWarnings - Instructs the compiler to suppress the compile time warnings specified
in the annotation parameters.

Super .- The Keyword Super is used to access methods of the parent class.

This .- The keyword This is used to access methods of the current class.

Method .- Method is used to expose behavior of an object, Method must have return type, Method is
invoked explicitly, Method is not provided by compiler in any case, Method name can be or not the
same as class name.
Constructor .-Is used to initialize the state of an object, Constructor must not have return type,
constructor is invoked implicitly, The java compiler provides a default constructor if you don't have any
constructor and The Constructor name must be same as the class name.

Access modifiers.-Access level modifiers determine whether other classes can use a particular field or
invoke a particular method.

Access Levels

Modifier Class Package Subclass World


public Yes Yes Yes Yes
protected Yes Yes Yes No
default Yes Yes No No
private Yes No No No

Encapsulation .-Is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as a single unit.

Abstraction .-Is process of hiding the implementation details and showing only the functionality.

Differences between Abstract class, Interface and Class.


• Basically the interface are a list of methods without implementation and variables. When
implements the interface the methods should be implemented.

• The Abstract class can't be instanced, can be contains variables and methods with and without
implementation.

• The Class can contains variables and methods with implementation and can be instantiated.

When use Interface .-We are talking about establishing a contract about what the object can do.

When use Abstract class .-When we talk about abstract classes we are defining characteristics of an
object type; specifying what an object is. The classes that extends from that classes
Inheritance .- Is defined as the process where one class acquires the properties (methods and fields) of
another.

Types of Inheritance

Polymorphism.-Polymorphism is the ability of an object to take on many forms. When a parent class
reference is used to refer to a child class object.

Overloading .-Method Overloading is a feature that allows a class to have more than one method
having the same name, if their argument lists are different.
It is similar to constructor overloading in Java, that allows a class to have more than one constructor
having different argument lists.

Overriding .-Is ability to define a behavior that's specific to the subclass type, which means a subclass
can implement a parent class method based on its requirement.

What Types of exceptions does exist in java? .-There are mainly two types of exceptions: checked
and unchecked where error is considered as unchecked exception.

Exceptions .-An exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

Checked exceptions .-A checked exception is an exception that occurs at the compile time, these are
also called as compile time exceptions. The programmer should take care of (handle) these exceptions.

Unchecked exceptions .-Are not checked at compile time. It means if your program is throwing an
unchecked exception and even if you didn’t handle/declare that exception, the program won’t give a
compilation error.
Exception Hierarchy

How handle an exception in Java?


Using Try, Catch or Finally.

Try.-Java try block is used to enclose the code that might throw an exception. It must be used within
the method. Java try block must be followed by either catch or finally block.

Catch .-A catch block is where you handle the exceptions, this block must follow the try block. A
single try block can have several catch blocks associated with it. You can catch different exceptions in
different catch blocks.

Finally .-contains all the crucial statements that must be executed whether exception occurs or not.

Should we handle runtime exceptions? .-We can handle a runtime exception using a try-catch block,
but it is not mandatory.

Difference between throw, throws keywords:


There are many differences between throw and throws keywords
• Throw: is used within method to explicitly throw an exception, Checked exception cannot be
propagated using throw only, Throw is followed by an instance, You cannot throw multiple
exceptions. We can throw either checked or unchecked exception in java by throw keyword.
The throw keyword is mainly used to throw custom exception.
• Throws: is used with the method signature to delegate an exception, is used to declare an
exception handling requirement, Checked exception can be propagated with throws, Throws is
followed by class, You can declare multiple exceptions handling requirements.
• Throwable .-The Throwable class is the super class of all errors and exceptions

String .-The java.lang.String class provides a lot of methods to work on string.

Immutable .-An object is considered immutable if its state cannot change after it is constructed.
What is the definition of Immutable String? .-String objects are immutable Immutable simply
means unmodifiable or unchangeable. Once string object is created its data or state can't be changed but
you can create a new string object is base on the previous one was created.

What are the differences between StringBuffer and StringBuilder? .-StringBuffer is synchronized
(thread safe) while StringBuilder is not synchronized.

What are the differences between ==, equals and hashcode? .-


• The == operator. compares references of memory not values.
• The hascode method. returns a hash code value (an integer number) and It's related to how
the equals method works. (if two keys by calling equals() method are same).
• The equals method. compares the original content of the string to the specified object.

String Pool .-String literal objects are stored in a special memory area known as string constant pool.
To make Java more memory efficient.

Auto Boxing .-is used to convert primitive data types to their wrapper class objects. Wrapper class
provide a wide range of function to be performed on the primitive types. The most common example
is :
int a = 56;
Integer i = a; // Auto Boxing

Unboxing is opposite of Auto Boxing where we convert the wrapper class object back to its primitive
type. This is done automatically by JVM so that we can use a the wrapper classes for certain operation
and then convert them back to primitive types as primitives result int faster processing. For Example :
Integer s = 45;
int a = s; // Auto Unboxing

Differences between comparator and comparable .-Comparable Obligate to implement the Method
compareTo (Object o), Comparator interface obligate to implement method compare (Object o1, Object
o2).

Comparable .-When your class implements Comparable, the compareTo method of the class is
defining the "natural" ordering of that object. That method is contractually obligated (though not
demanded) to be in line with other methods on that object, such as a 0 should always be returned for
objects when the .equals() comparisons return true.

Comparator .-A Comparator is its own definition of how to compare two objects, and can be used to
compare objects in a way that might not align with the natural ordering.

Collection Framework .-Java provided ad hoc classes such as Dictionary, Vector,


Stack, and Properties to store and manipulate groups of objects.

Collection interface .-Is one of the root interfaces of the Java collection classes. Though you do not
instantiate a Collection directly.
List interface .-Is the sub interface of Collection. It contains methods to insert and delete elements in
index basis.

You can choose between the following List implementations in the Java Collections API:
• java.util.ArrayList .- Resizable-array implementation of the List interface. Implements all
optional list operations, and permits all elements, including null. In addition to implementing
the List interface, this class provides methods to manipulate the size of the array that is used
internally to store the list.
• java.util.LinkedList .-Doubly-linked list implementation of the List and Deque interfaces.
Implements all optional list operations, and permits all elements (including null).
• java.util.Vector .-The Vector class implements a growable array of objects. Like an array, it
contains components that can be accessed using an integer index.
• java.util.Stack .-The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends
class Vector with five operations that allow a vector to be treated as a stack.

Set interface .-A collection that contains no duplicate elements. The Set interface places additional
stipulations, beyond those inherited from the Collection interface, on the contracts of all constructors
and on the contracts of the add, equals and hashCode methods.

• java.util.EnumSet .-Java EnumSet class is the specialized Set implementation for use with
enum types. It inherits AbstractSet class and implements the Set interface.
• java.util.HashSet .-Java HashSet class is used to create a collection that uses a hash table for
storage. It inherits the AbstractSet class and implements Set interface.
• java.util.LinkedHashSet .-Java LinkedHashSet class is a Hash table and Linked list
implementation of the set interface. It inherits HashSet class and implements Set interface.
• java.util.TreeSet .-TreeSet class implements the Set interface that uses a tree for storage. It
inherits AbstractSet class and implements NavigableSet interface. The objects of TreeSet class
are stored in ascending order.
Map Interface .-A Map is an object that maps keys to values. A map cannot contain duplicate keys:
Each key can map to at most one value. The Map interface includes methods for basic operations (such
as put, get, remove, containsKey, containsValue, size, and empty).

• java.util.HashMap .-Hash table based implementation of the Map interface. This


implementation provides all of the optional map operations, and permits null values and
the null key. This class makes no guarantees as to the order of the map.
• java.util.Hashtable .-This class implements a hash table, which maps keys to values. Any non-
null object can be used as a key or as a value.
• java.util.LinkedHashMap .-Hash table and linked list implementation of the Map interface,
with predictable iteration order. This implementation differs from HashMap in that it maintains
a doubly-linked list running through all of its entries. This linked list defines the iteration
ordering
• java.util.TreeMap .- implements Map interface similar to HashMap class. The main difference
between them is that HashMap is an unordered collection while TreeMap is sorted in the
ascending order of its keys. TreeMap is unsynchronized collection class which means it is not
suitable for thread-safe operations until unless synchronized explicitly.
Generics class. A class or even Interface that can refer to any type as parameter.
• The type parameter section, delimited by angle brackets (<>), follows the class name
• This pair of angle brackets, <>, is informally called the diamond.
• The type parameters naming conventions are important to learn generics thoroughly. The
commonly type parameters are as follows:
◦ E - Element (used extensively by the Java Collections Framework)
◦ K – Key
◦ N – Number
◦ T – Type
◦ V – Value

Advantage of Generic collections .-If we use generic class, we don't need typecasting. It is type safe
and checked at compile time.

Difference between ArrayList and Vector


• ArrayList. is not synchronized, is not a legacy class, increases its size by 50% of the array size.
• Vector. is synchronized, is a legacy class, increases its size by doubling (100%) the array size.

Difference between Hashmap and HastTable


• Hashmap. is not synchronized, can contain one null key and multiple null values.
• HastTable. is synchronized, cannot contain any null key or null value.

Difference between Iterator and ListIterator


• Iterator traverses the elements in forward direction only whereas.
• ListIterator traverses the elements in forward and backward direction.

Difference between Array and ArrayList


• Array is a fixed length data structure whereas
• ArrayList is a variable length Collection class.

Difference between ArrayList and LinkedList


• ArrayList. uses a dynamic array, is not efficient for manipulation because a lot of shifting is
required, is better to store and fetch data.
• LinkedList. uses doubly linked list, is efficient for manipulation, is better to manipulate data.

Serialization. is a mechanism of writing the state of an object into a byte stream.

Serializable interface. is a marker interface (has no data member and method). It is used to
"mark" java classes so that objects of these classes may get certain capability. The Cloneable and
Remote are also marker interfaces.

Transient Keyword. If you don't want to serialize any data member of a class, you must use it.
Synchronization .-Is the capability to control the access of multiple threads to any shared resource

How Synchronization works?


Synchronization is built around an internal entity known as the lock or monitor.
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.

What type of synchronization does exist?


• Mutual Exclusive
◦ Synchronized method.
◦ Synchronized block.
◦ Static synchronization.
• Cooperation (Inter-thread communication in java)

Thread .-Thread is a block of code which can execute concurrently with other threads in the JVM.

Runnable Interface .-The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. The class must define a method of no arguments called run.

Life cycle of a Thread (Thread States) .-According to sun, there is only 5 states in thread life cycle in
java new, runnable, running, wait(Blocked or Waiting) and terminated. There is no running state.

• New .-The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.Runnable.The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to be the running thread.
• Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
• Running .-The thread is in running state if the thread scheduler has selected it.
• Non-Runnable (Blocked / Waiting) .-This is the state when the thread is still alive, but is
currently not eligible to run.
• Terminated (Dead) .-A thread is in terminated or dead state when its run() method exits.
Ways to implement a thread
There are two ways to create a thread:
• Extending Thread class.
• Implementing Runnable interface.

Where use runnable


• Implementing Runnable, many threads can share the same runnable instance it becomes a
big performance overhead.
• You can save a space for your class to extend any other class in future or now. If we are not
making any modification on Thread then use Runnable interface instead.

Where use Thread .-Just in case if we need add new functionality, modifying or improving behaviors.

Difference between wait() and sleep() method?


• The wait(). is defined in Object class, it releases the lock.
• The sleep(). is defined in Thread class, it doesn't releases the lock.

Volatile Keyword .-Guarantees the visibility for other threads of writes to one variable.

Multithreading .-Is a process of executing multiple threads simultaneously. Its main advantage is:
• Threads share the same address space.
• Thread is lightweight.
• Cost of communication between process is low.

Reflection .-It is a process of examining or modifying the run time behavior of a class.

How to use Reflection .-Imagine that you have any object with whatever name, you can use dot to
access to getClass Method and then getMethod to create a reference to that element. Once you
created this reference you can call the method invoke whenever you want. All theses steps within try
and catch block.

What is the most common way to use it .-One very common use case in Java is the usage with
Junit @Test annotation. Because you should look through your classes for methods tagged and will
then call them when running the unit test.

Note: The Reflection API is mainly used in:


• IDE (Integrated Development Environment) e.g. Eclipse, My Eclipse, Net Beans etc.
• Debugger
• Test Tools etc.
Object class java .-Is the root of the class hierarchy. Every class has Object as a superclass.
Method Summary:

• Clone() .-Creates and returns a copy of this object.


• equals(Object obj) .-Indicates whether some other object is "equal to" this one.
• finalize() .-Called by the garbage collector on an object when garbage collection determines
that there are no more references to the object.
• getClass() .-Returns the runtime class of this Object.
• hashCode() .-Returns a hash code value for the object.
• notify() .-Wakes up a single thread that is waiting on this object's monitor.
• notifyAll() .-Wakes up all threads that are waiting on this object's monitor.
• ToString() .-Returns a string representation of the object.
• wait() .-Causes the current thread to wait until another thread invokes the notify() method or
the notifyAll() method for this object.
• wait(long timeout) .-Causes the current thread to wait until either another thread invokes
the notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
• wait(long timeout, int nanos) .-Causes the current thread to wait until another thread invokes
the notify() method or the notifyAll() method for this object, or some other thread interrupts the
current thread, or a certain amount of real time has elapsed.

JDBC.- Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc
drivers to connect with the database.

JDBC Driver .-For communicating with the database.

There are 4 types of JDBC drivers:


• JDBC-ODBC bridge driver
• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• 4.Thin driver (fully java driver)

DriverManager .-For managing a list of database drivers.

Connection .-For interfacing with all the methods for connecting a database.

Statement .-For encapsulating an SQL statement for passing to the database which had been parsed,
compiled, planned and executed.

PreparedStatement .-Interface is a subinterface of Statement. It is used to execute parameterized


query.

ResultSet .-for representing a set of rows retrieved for the query execution.
Why use return type “executeQuery” .-(When we want to execute SQL statements which
retrieve some data from the database, for example a select statement). This method returns
a ResultSet object with the results of the query.

Why use return type “executeUpdate” .-(When we want to update or modify the database is
some way using create, alter, insert, update or delete statements). Returns an int value
which represents the number of rows affected by the query.

JSP .-stands for JavaServer Pages. JSP is java server side technology to create dynamic web pages.

Servlet .-Is a Java program that extends the capabilities of a server. Although servlets can respond to
any types of requests, they most commonly implement applications hosted on Web servers.

Servlet Lifecycle

JSP Initialization .-When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override the jspInit() method.

JSP Execution (Ready) .-the JSP engine invokes the _jspService() method in the JSP. The
_jspService() takes an HttpServletRequest and an HttpServletResponse.

JSP Cleanup .-The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Override jspDestroy when you need to perform any cleanup.
MVC in JSP .-MVC stands for Model View and Controller. It is a design pattern that separates the
business logic, presentation logic and data.

• Controller acts as an interface between View and Model. Controller intercepts all the incoming
requests.

• Model represents the state of the application i.e. data. It can also have business logic.

• View represents the presentation i.e. UI(User Interface).

JSP - Implicit Objects .- in JSP we have 9 implicit objects.


• Request .-This is the HttpServletRequest object associated with the request.
• Response .-This is the HttpServletResponse object associated with the response to the client.
• Out .-This is the PrintWriter object used to send output to the client.
• Session .-This is the HttpSession object associated with the request.
• Application .-This is the ServletContext object associated with the application context.
• Config .-This is the ServletConfig object associated with the page.
• PageContext .-This encapsulates use of server-specific features like higher
performance JspWriters.
• Page .-This is simply a synonym for this, and is used to call the methods defined by the
translated Servlet class.
• Exception .-The Exception object allows the exception data to be accessed by designated JSP.
Spring .- The Spring Framework provides a comprehensive programming and configuration model, is
a lightweight, loosely coupled and integrated framework for developing enterprise applications.

Modules of spring framework:


• Test
• Spring Core Container
• AOP, Aspects and Instrumentation
• Data Access/Integration (ORM)
• Web
• Security
• Spring MVC

IoC .- The IoC container is responsible to instantiate, configure and assemble the objects. The main
tasks performed by IoC container are:
• To instantiate the application class
• To configure the object
• To assemble the dependencies between the objects
There are two types of IoC containers. They are:

• BeanFactory .-The XmlBeanFactory is the implementation class for the BeanFactory


interface. (applicationContext.xml).
• ApplicationContext .-The ClassPathXmlApplicationContext class is the
implementation class of ApplicationContext interface.

DI .-Dependency Injection. It's a form of IoC, where implementations are passed into an object
through constructors/setters/service lockups, and make our application loosely coupled.

Different types of IoC (dependency injection)


• Constructor-based dependency injection− Constructor-based DI is accomplished when the
container invokes a class constructor with a number of arguments, each representing a
dependency on other class.
• Setter-based dependency injection− Setter-based DI is accomplished by the container calling
setter methods on your beans after invoking a no-argument constructor or no-argument static
factory method to instantiate your bean.

AOP .- Is a way for adding behavior to existing code without modifying that code.

MVC .-Is a design pattern which provides a solution to layer an application by separating Business
(Model), Presentation (View) and Control Flow (Controller).

• The Model .-Contains the business logic.


• The View .-Component contains the presentation part of the application.
• The Controller .-Is responsible for the redirection and the interaction between View component
and Model.
MVC diagram.

web.xml .- Is a configuration file to describe how a web application should be deployed.

DispatcherServlet .-The Spring Web MVC framework is designed around a DispatcherServlet that
handles all the HTTP requests and responses. it loads the spring bean configuration file and initialize all
the beans that are configured
• It's the front controller class that initializes the context based on the spring beans configurations.
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

• If annotations are enabled, it also scans the packages and configure any bean annotated with
@Component, @Controller, @Repository or @Service annotations.
ContextListener .-It is the listener to start up and shut down Spring’s root WebApplicationContext
when we have multiple ApplicationContext we can use it to define shared beans that can be used across
different spring contexts.

ContextLoaderListener .-Is the listener class used to load root context and define spring bean
configurations that will be visible to all other contexts. It’s configured in web.xml. Belongs to the
package org.springframework.web.context.ContextLoaderListener starts and stops
WebApplicationContext. ContextLoaderListener is registered in web.xml

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>

if you want to load other Spring context XML files as well while loading the app and you can specify.

ApplicationContext .-Is the central interface within a Spring application for providing configuration
information to the application and provides:
• Bean factory methods for accessing application components.
• The ability to load file resources in a generic fashion.
• The ability to publish events to registered listeners.
• The ability to resolve messages to support internationalization.
• Inheritance from a parent context.

Bean (In Spring Framework) .-Any normal java class that is initialized by Spring IoC container Theses
objects form the backbone of your application and that are managed by the Spring IoC container.

Bean Scope (In Spring Framework) .-It a behavior that you can specify to any bean when you defined
it. Spring Framework supports the following five scopes, three of which are available only if
you use a web-aware ApplicationContext.

• Singleton. This scopes the bean definition to a single instance per Spring IoC container
(default).
• Prototype. This scopes a single bean definition to have any number of object instances.
• Request. This scopes a bean definition to an HTTP request. Only valid in the context of a web-
aware Spring ApplicationContext.
• Session. This scopes a bean definition to an HTTP session. Only valid in the context of a web-
aware Spring ApplicationContext.
• Global-session. This scopes a bean definition to a global HTTP session. Only valid in the
context of a web-aware Spring ApplicationContext.
Difference between BeanFactory and ApplicationContext .-BeanFactory and ApplicationContext
both are Java interfaces and ApplicationContext extends BeanFactory. BeanFactory provides basic
IOC and DI features while ApplicationContext provides advanced features.

@Autowiring .-Autowiring feature of spring framework enables you to inject the object dependency
implicitly. It internally uses setter or constructor injection.
Autowiring can't be used to inject primitive and string values. It works with reference only.

@Qualifier .-Allows you to associate a given name with a specific bean type. is to fix that the bean
with a given name will only qualify for dependency injection in Autowiring.

@Bean .-Is used to explicitly declare a single bean, rather than letting Spring do it automatically as
above

@Component (and @Service and @Repository) are used to auto-detect and auto-configure beans
using classpath scanning.

@Component annotation is a stereotype and is used at class level that makes the class a component.
These classes are eligible for auto-detection through classpath scanning.

@ComponentScan annotation is used to auto detect the component and in spring application context
XML.

@Service annotation .-Is a stereotype and is used at class level that makes the class a service for
service layer.

@Repository annotation .-Is a stereotype and is used at class level that makes the class a repository
for persistence layer.

@Controller annotation .-Is a stereotype and is used at class level that makes the class a controller for
presentation layer (spring-mvc).

@PostConstruct and @PreDestroy .-The support for these annotations offers yet another alternative
to those described in initialization callbacks and destruction callbacks.

public class CachingMovieLister {

@PostConstruct
public void populateMovieCache() {
// populates the movie cache upon initialization...
}

@PreDestroy
public void clearMovieCache() {
// clears the movie cache upon destruction...
}
}
Web Service .-A web service is a kind of software that is accessible on the Internet. It makes use of the
XML messaging system and offers an easy to understand, interface for the end users.

Advantages of Web Services :


• Interoperability: Web services are accessible over network and runs on HTTP/SOAP protocol
and uses XML/JSON to transport data, hence it can be developed in any programming
language. Web service can be written in java programming and client can be PHP and vice
versa.
• Reusability: One web service can be used by many client applications at the same time.
• Loose Coupling: Web services client code is totally independent with server code, so we have
achieved loose coupling in our application.
• Easy to deploy and integrate, just like web applications.
• Multiple service versions can be running at same time.

Types of Web Services .-There are two types of web services:

• SOAP Web Services: Runs on SOAP protocol and uses XML technology for sending data.

• Restful Web Services: It’s an architectural style and runs on HTTP/HTTPS protocol almost all
the time. REST is a stateless client-server architecture where web services are resources and can
be identified by their URIs. Client applications can use HTTP GET/POST methods to invoke
Restful web services.

SOAP .-SOAP stands for Simple Object Access Protocol. SOAP is an XML based industry standard
protocol for designing and developing web services. Since it’s XML based, it’s platform and language
independent.

Advantages SOAP Web Services .-SOAP web services have all the advantages that web services has,
some of the additional advantages are:
• WSDL document provides contract and technical details of the web services for client
applications without exposing the underlying implementation technologies.
• SOAP uses XML data for payload as well as contract, so it can be easily read by any
technology.
• SOAP protocol is universally accepted, so it’s an industry standard approach with many easily
available open source implementations.

Disadvantages of SOAP Web Services .-Some of the disadvantages of SOAP protocol are:
• Only XML can be used, JSON and other lightweight formats are not supported.
• SOAP is based on the contract, so there is a tight coupling between client and server
applications.
• SOAP is slow because payload is large for a simple string message, since it uses XML format.
• Anytime there is change in the server side contract, client stub classes need to be generated
again.
• Can’t be tested easily in browser
REST stand for .-REST stand for REpresentational State Transfer, term by Roy Fielding. REST is an
architectural style that describes best practices to expose web services over HTTP with Emphasizes
scalability.

What is RESTful web services.-Web services written by apply REST Architectural concept are
called RESTful web services which focus on System resources and how state of Resource should be
transferred over http protocol to a different clients written in different languages. In RESTful web
services http methods like GET, PUT, POST and DELETE can can be used to perform CRUD
operations.

Differences between RESTful web services and SOAP web services:


• REST is more simple and easy to use than SOAP.
• REST uses HTTP protocol for producing or consuming web services while SOAP uses XML.
• REST is lightweight as compared to SOAP and preferred choice in mobile devices and PDA’s.
• REST supports different format like text, JSON and XML while SOAP only support XML.
• REST web services call can be cached to improve performance.

REST Web Services .-REST is the acronym for Representational State Transfer. REST is an
architectural style for developing applications that can be accessed over the network. REST
architectural style was brought in light by Roy Fielding in his doctoral thesis in 2000.

Advantages of REST web services .-Some of the advantages of REST web services are:
• Learning curve is easy since it works on HTTP protocol
• Supports multiple technologies for data transfer such as text, xml, json, image etc.
• No contract defined between server and client, so loosely coupled implementation.
• REST is a lightweight protocol
• REST methods can be tested easily over browser.

Disadvantages of REST web services .-Some of the disadvantages of REST are:


• Since there is no contract defined between service and client, it has to be communicated through
other means such as documentation or emails.
• Since it works on HTTP, there can’t be asynchronous calls.
• Sessions can’t be maintained.

Different HTTP Methods supported in Restful Web Services .-Restful web services supported
HTTP methods are – GET, POST, PUT, DELETE and HEAD.

Resource.- The key abstraction of information in REST is a resource. Any information that can be
named can be a resource like Student, Employee etc. REST is resource based API. Expose resources
through URIs like http://localhost:8080/api/employees/1111 .

REST operations .-Safe REST operations are HTTP methods that do not modify resources. For
example, using GET or HEAD on a resource URL, should NEVER change the resource.

Idempotent operations .-Idempotent operations are those HTTP methods that can be called
repetitively many times without different outcomes. It would not matter if the method is called only
once, or many times over.
Idempotency important .-Idempotency is important in building a fault-tolerant API. Suppose a client
wants to update a resource through POST. Since POST is not a idempotent method, calling it multiple
times can result in wrong updates.

SOAP .-Is XML based protocol. It is platform independent and language independent. By using SOAP,
you will be able to interact with other programming language applications.

WSDL .-WSDL stands for Web Service Description Language. It is an XML file that describes the
technical details of how to implement a web service, more specifically the URI,port, method names,
arguments, and data types. Since WSDL is XML, it is both human-readable and machine-consumable.

Different components of WSDL .-Some of the different tags in WSDL xml are:
• xsd:import namespace and schemaLocation: provides WSDL URL and unique namespace for
web service.
• message: for method arguments
• part: for method argument name and type
• portType: service name, there can be multiple services in a wsdl document.
• operation: contains method name
• soap:address for endpoint URL.

Different ways to test web services:


• SOAP web services can be tested programmatically by generating client stubs from WSDL or
through software such as Soap UI.
• REST web services can be tested easily with program, curl commands and through browser
extensions. Resources supporting GET method can be tested with browser itself, without any
program.

Can we maintain user session in web services .-Web services are stateless so we can’t maintain user
sessions in web services.

Difference between SOA and Web Services .-Service Oriented Architecture (SOA) is an architectural
pattern where applications are designed in terms of services that can be accessed through
communication protocol over network. SOA is a design pattern and doesn’t go into implementation.

Use of Accept and Content-Type Headers in HTTP Request .-These are important headers in
Restful web services. Accept headers tells web service what kind of response client is accepting, so if a
web service is capable of sending response in XML and JSON format and client sends Accept header as
“application/xml” then XML response will be sent. For Accept header “application/json”, server will
send the JSON response.
Content-Type header is used to tell server what is the format of data being sent in the request. If
Content-Type header is “application/xml” then server will try to parse it as XML data. This header is
useful in HTTP Post and Put requests.
UDDI .-UDDI is acronym for Universal Description, Discovery and Integration. UDDI is a directory of
web services where client applications can lookup for web services. Web Services can register to the
UDDI server and make them available to client applications.

• UDDI stands for Universal Description, Discovery, and Integration.


• UDDI is a specification for a distributed registry of web services.
• UDDI is a platform-independent, open framework.
• UDDI can communicate via SOAP, CORBA, Java RMI Protocol.
• UDDI uses Web Service Definition Language(WSDL) to describe interfaces to web services.
• UDDI is seen with SOAP and WSDL as one of the three foundation standards of web services.
• UDDI is an open industry initiative, enabling businesses to discover each other and define how
they interact over the Internet.

Difference between Top Down and Bottom Up approach in SOAP Web Services .-In Top Down
approach first WSDL document is created to establish the contract between web service and client and
then code is written, it’s also termed as contract first approach.

How would you choose between SOAP and REST web services .-Web Services work on client-
server model and when it comes to choose between SOAP and REST, it all depends on project
requirements. Let’s look at some of the conditions affecting our choice:
• Do you know your web service clients beforehand? If Yes, then you can define a contract before
implementation and SOAP seems better choice. But if you don’t then REST seems better choice
because you can provide sample request/response and test cases easily for client applications to
use later on.
• How much time you have? For quick implementation REST is the best choice. You can create
web service easily, test it through browser/curl and get ready for your clients.
• What kind of data format are supported? If only XML then you can go with SOAP but if you
think about supporting JSON also in future then go with REST.

JAX-WS API .-JAX-WS stands for Java API for XML Web Services. JAX-WS is XML based Java
API to build web services server and client application. It’s part of standard Java API, so we don’t need
to include anything else which working with it. Refer to JAX-WS Tutorial for a complete example.

Name some frameworks in Java to implement SOAP web services .-We can create SOAP web
services using JAX-WS API, however some of the other frameworks that can be used are Apache Axis
and Apache CXF. Note that they are not implementations of JAX-WS API, they are totally different
framework that work on Servlet model to expose your business logic classes as SOAP web services.
Read more at Java SOAP Web Service Eclipse example.

Name important annotations used in JAX-WS API .-Some of the important annotations used in
JAX-WS API are:
• @WebService
• @SOAPBinding
• @WebMethod
What is use of javax.xml.ws.Endpoint class .-Endpoint class provides useful methods to create
endpoint and publish existing implementation as web service. This comes handy in testing web services
before making further changes to deploy it on actual server.
-RS
Difference between RPC Style and Document Style SOAP web Services .-RPC style generate
WSDL document based on the method name and it’s parameters. No type definitions are present in
WSDL document.
Document style contains type and can be validated against predefined schema. Let’s look at these with
a simple program. Below is a simple test program where I am using Endpoint to publish my simple
SOAP web service.

How to get WSDL file of a SOAP web service? .-WSDL document can be accessed by appending ?
wsdl to the SOAP endoint URL. In above example, we can access it at http://localhost:8888/testWS?
wsdl location.

What is sun-jaxws.xml file? .-This file is used to provide endpoints details when JAX-WS web
services are deployed in servlet container such as Tomcat. This file is present in WEB-INF directory
and contains endpoint name, implementation class and URL pattern.

What is JAX-RS API? .-Java API for RESTful Web Services (JAX-RS) is the Java API for creating
REST web services. JAX-RS uses annotations to simplify the development and deployment of web
services. JAX-RS is part of JDK, so you don’t need to include anything to use it’s annotations.

Name some implementations of JAX-RS API


There are two major implementations of JAX-RS API.
• Jersey: Jersey is the reference implementation provided by Sun. For using Jersey as our JAX-
RS implementation, all we need to configure its servlet in web.xml and add required
dependencies. Note that JAX-RS API is part of JDK not Jersey, so we have to add its
dependency jars in our application.
• RESTEasy: RESTEasy is the JBoss project that provides JAX-RS implementation.

What is wsimport utility .-We can use wsimport utility to generate the client stubs. This utility comes
with standard installation of JDK. Below image shows an example execution of this utility for one of
JAX-WS project.

Name important annotations used in JAX-RS API?


Some of the important JAX-RS annotations are:
• @Path: used to specify the relative path of class and methods. We can get the URI of a
webservice by scanning the Path annotation value.
• @GET, @PUT, @POST, @DELETE and @HEAD: used to specify the HTTP request type
for a method.
• @Produces, @Consumes: used to specify the request and response types.
• @PathParam: used to bind the method parameter to path value by parsing it.
What is the use of @XmlRootElement annotation .-XmlRootElement annotation is used by JAXB to
transform java object to XML and vice versa. So we have to annotate model classes with this
annotation.
What is SQL .- Structured Query Language(SQL) is a language designed specifically for
communicating with databases.

Different type of SQL's statements:


• DDL – Data Definition Language .-DDL is used to define the structure that holds the data. For
example, Create, Alter, Drop and Truncate table.
• DML – Data Manipulation Language .-DML is used for manipulation of the data itself.
Typical operations are Insert, Delete, Update and retrieving the data from the table.
• DCL – Data Control Language .-DCL is used to control the visibility of data like granting
database access and set privileges to create tables, etc. Example - Grant, Revoke access
permission to the user to access data in the database.
Table in a database .-A table is a collection of records of a specific type.

Define Normalization .-It's an Organized data to avoid inconsistent dependency and redundancy
within a database.

Primary key .-It is a column whose values uniquely identify every row in a table.

Foreign Key .-It's a column value whose references another table's primary key value.

Unique Key .-It's a column like primary key only allows uniques values with the difference being the
existence of null.

Why do we use Foreign keys .- In Order to link two tables, maintain data integrity and faster queries.
Enlist the various relationships of database .-The various relationships of database are:
• One-to-one: Single table having drawn relationship with another table having similar kind of
columns.
• One-to-many: Two tables having primary and foreign key relation.
• Many-to-many: Junction table having many tables related to many tables.

Different type of joins


• (Inner) Join .-return rows when there is at least one match in both table. it is used to combine
data from two or more tables, based on a common field between them.
• Right (Outer) Join .-Return all rows from the right table, even if there are no matches in the
left table.
• Left (Outer) Join .-Return all rows from the left table, even if there are no matches in the right
table.
• Full (Outer) Join .-Return rows when there is a match in one of the tables.
• Cross Join. return all records where each row from the first table is combined with each row
from the second table.

View .-The views are virtual tables, views simply contain PRE-COMPILE queries that dynamically
retrieve data when used.

Stored procedure .-It is just a function which contains a collection of SQL Queries.

Trigger .-Those are sets of commands that get executed when an event(Before Insert, After Insert, On
Update, On delete of a row) occurs on a table, views.
Difference between having and where clause .-one of which is meant to be used with aggregates and
one of which is not and They have different semantics.
• Where. It's a clause selects before grouping, this clause cannot contain aggregate functions.
• Having. it is used to specify a condition for a group or an aggregate function used in select
statement and it's a clause that selects rows after grouping.
Difference between group by and distinct .-One of which is meant to be used with aggregates and
one of which is not and They have different semantics, even if they happen to have equivalent results
on your particular data.

• DISTINCT. It refers to distinct records as a whole, not distinct fields in the record.
Note: Don't be mislead into thinking SELECT DISTINCT(A), B does something different. This
isequivalent to SELECT DISTINCT A, B.
• GROUP BY. It refers to distinct fields in the record and lets you use aggregate functions,
Note: functioning the same as a distinct when no aggregate function is present
• ORDER BY .-clause is used to sort the data in ascending or descending order,based on one or
more columns.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy