Realtime Java Interview Question PDF
Realtime Java Interview Question PDF
-> It simplifies the software development and maintainance by providing some concepts:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Object:
=======
-> Instance of a class is known as an Object whereas instance is nothing but allocating sufficient amount
of memory
-> Any entity that has state and behavior is known as an object.
Class:
======
-> The process of binding data-members and associated methods in a single unit is called class.
Inheritance:
===========
-> When an object acquires all the properties and behaviors of parent class object.
i.e., known as inheritance. It provides code-reusability. It is used to achieve runtime polymorphism.
Polymorphism:
==============
-> When one task is performed by different ways. i.e., known as polymorphism.
-> The process of representing "one form in multiple forms" whereas One form represents
original method and it always resides in Base class. Multiple forms represent overriden
{ { {
} } }
-> In java, we use method overloading and method overriding to achieve polymorphism.
-> Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
===========
-> Highlighting set of services what we are offering and hiding implementation details is nothing but
Abstraction. Example: ATM.
-> For example: phone call, we don't know the internal processing.
Encapsulation:
=============
-> Binding (or wrapping) code and data together into a single unit is known as encapsulation.
-> For example: capsule, it is wrapped with different medicines.
-> A java class is the example of encapsulation. Java bean is the fully encapsulated class
Q.What is Interface:
===================
-> There can be only abstract methods in the java interface not method body.
===========
-> Highlighting set of services what we are offering and hiding implementation details is nothing but
Abstraction. Example: ATM.
-> For example: phone call, we don't know the internal processing.
Interface
=================
3. We can't declare Interface methods with the following modifiers: private, protected,
4. Every variable present inside Interface must be public, static, final whether we are declaring
or not.
5. We can't declare Interface variables with the following modifiers private, protected, transient
and volatile.
6. For Interface variables compulsory we should perform initialization at the time of declaration,
=====================================================================================
=====
Abstract Class
=============
2. Every method present inside Abstract Class need not be public & abstract, we can
4. Every variable present inside Abstract Class need not be public static and final.
6. For Abstract Class variables which is not required to perform initialization at the time of declaration.
================================================================================
HashMap
Hashtable
2. At a time multiple threads are allowed to operate on HashMap object simultaneously and hence it is
not a Threadsafe.
2. At a time only one thread is allowed to operate onHashtable object and hence it is Threadsafe.
4. Null is not allowed for both keys and values. Otherwisewe will get NullPointerException.
============================================================================
HashMap LinkedHashMap
=====================================================================================
HashMap
LinkedHashMap
IdentityHashMap
==================
-> It is exactly same as HashMap except the following difference.
-> In case of HashMap, JVM will use .equals(-) method to identify duplicate keys, which is meant for
content comparison.
-> But in case of IdentityHashMap, JVM will use == operator to identify duplicate keys which is meant for
reference comparison.
WeakHashMap
==================
-> In case of HashMap, if an object associated with HashMap then it is not eligible for garbage collection,
eventhough it doesn't contain any external references. i.e., HashMap dominates Garbage Collector.
-> But in case of WeakHashMap, if an object doesn't contain any references then it is always eligible for
Garbage Collector eventhough it is associated with WeakHashMap. ie., Garbage Collector dominates
WeakHashMap.
***********
-> Map.Entry interface - This interface gives a map entry (key-value pair).
-> hashCode() -HashMap provides put(key, value) for storing and get(key) method
for retrieving Values from HashMap. When put() method is used to store (Key, Value) pair,
When get() method is used to retrieve value, again key object is used to calculate a hash
which is used then to find a bucket where that particular key is stored.
Map knows how to handle hashing collision (hashing collision means more than
one key having the same hash value, thus assigned to the same bucket.
Where hashCode method helps in finding the bucket where that key is stored,
equals method helps in finding the right key as there may be more than one key-value pair
** Bucket term used here is actually an index of array, that array is called table in HashMap
So it is implementaion of HashMap
************
In Array we don't have the capability of dynamically increasing the size of the array
but in ArrayList we can, We know that ArrayList has initial capacity of the element
second things we need an Array of Objects to store the element of the ArrayList.
->Now declare an empty CustomArrayList which will return while creating empty CustomArrayList
->Now we need to define an Array of an Object to store the elements view sourceprint?
Q. Synchronized keyword
=====================================================================================
====================================
Ans--> Synchronized modifier is applicable only for methods and blocks but not for classes and variables.
-> If multiple threads are operating simultaneously on same java object then there may be a chance of
data inconsistency problem.
-> If a method or block declared as synchronized then at a time only one thread is allowed to operate
method or block on the given object.
-> The main advantage of synchronized keyword is we can overcome data inconsistency problems.
-> But the main disadvantage is it increases waiting time of threads and creates performance problems.
-> Hence if there is no specific requirement then it is never recommanded to use synchronized keyword.
-> Synchronized method should compulsory contain implementation whereas abstract method should
not contain implementation.
Q.4. Diff_Serialization&Externalization.
Ans-*****************************************
The process of converting data from network representation to sysytem representation is called un
marshalling.
****************************************
Serialization:
================
or
-> But strictly speaking, it is a process of converting an object from java supported form to either file
supprted form
Here everything takes care by JVM and Programmer doesn't have any control.
In Serialization, total object will be serialized always & it is not possible to serialize part of the object.
-----------------------------
----
-----
oos.writeobject(emp);
Desirialization:
==================
The process of regenerating the object on the basis of data is called the deserialization.
-------------------------------
ex:
Externalization:
=================
Here everything takes care by Programmer and JVM doesn't have any control.
In Externalization, based on our requirement we can save either total object or part of the object.
Externalization is best choice if we want to save part of the object to the file.
Marker Interface:
==================
-> Marker interface in Java is interfaces with no field or methods or in simple word empty interface in
java is called marker interface.
-> So if JVM sees a class is Serializable it done some special operation on it,
similar way if JVM sees one class is implement Clonnable it performs some operation to support
cloning.
Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a
command to Compiler or JVM.
-> After introduction of Annotation on Java5, Annotation is better choice than marker interface and
JUnit is a perfect example of using Annotation.
-> In summary marker interface in Java is used to indicate something to compiler, JVM or any other tool
but Annotation is better way of doing same thing.
Q. equals&==operator.
=====================================================================================
= = equals
.equlas
Note:**.equals method present in object class also meant for reference comparision only based on our
requirement we can override fro content comparision.
** In string class all wrapper class and all collection classes .equals() is overridden for content
comparision.
====================================
Ans-> The Java class that allows us to create only one object per JVM is called singleton java class.
-> Situations to take singleton java class:
c. If class is having huge amount of state and performing write operations on that state in
synchronized manner (1 Thread at a time).
=======================
private constructor,
static variables,
static methods
Example:
private Test()
if(t==null)
t=new Test();
return t;
}
public Object clone()
return this;
Now ,
Test t1=Test.getInstance();
Test t2=Test.getInstance();
Test t3=Test.getInstance();
Test t100=Test.getInstance();
Like this, Only one object is created here with multiple references.
=====================================================================================
===
-> If Constructor is not private then outside person can create object directly by calling constructor.
In that case they can create multiple objects and also we will miss singleton behavior.
-> If 't' is not private then after creation of first object outside person can reassign 't' with null. In
that case a second new object will be created, whenever we call getInstance() method again.
Test t1=Test.getInstance();
Test.t=null;
Test t2=Test.getInstance();
-> If we are not overriding clone() method & Test class implements Cloneable then Object class
clone() method will be executed which provides always a separate new object.
Test t1=Test.getInstance();
Test t2=(Test)t1.clone();
=====================================================================================
===
==========================
Instead of creating multiple objects we can run entire show with only one object but with multiple
references.
Hence the main advantage of singleton class is performance will be improved and we know object
creation is most precious.
Ans--> There is string pool in java which is used for managing the memory efficiently and save the
money invested in the memory.
String Literal
String Object.
Example:
**
When we use String s="Abc" then string object will be created in the string constant pool SCP area. it is
one of memory in method area.
when String literal is created in java, JVM checks the string pool if the string content is already present
then again memory is not allocated.
But this is not true of u create a string using Option 2. Then the String object is created on heap and
each time you create a string object,
make all members final, set them explicitly, in a static block, or in the constructor
Be extremely careful to limit access to mutable members(remember the field may be final but the object
can still be mutable.
ie private final Date imStillMutable). You should make defensive copies in these cases.
Q.8. Diff_yield,join&sleep.
Ans-
sleep()
========
-> If a thread doesn't want to perform any operation for a particular amount of time that is just
-> sleep(n) says "I'm done with my timeslice, and please don't give me another one for at least n
milliseconds."
The OS doesn't even try to schedule the sleeping thread until requested time has passed.
join()
========
-> If a thread wants to wait until completing other threads then we should go for join() method.
-> It is final method but not static method and native method.
=========
-> It causes to pause current executing thread to give the chance for remaining waiting threads of same
priority.
-> yield() says “I’m done with my timeslice, but I still have work to do.” The OS is free to immediately
give the
thread another timeslice, or to give some other thread or process the CPU the yielding thread just
gave up.
-> It is static method and native method but not final method.
wait()
===========================================
-> A wait can be "woken up" by another thread calling notify on the monitor which is being waited on
-> While sleeping a Thread does not release the locks it holds, while waiting releases the lock on the
-> sleep(n) says "I'm done with my timeslice, and please don't give me another one for at least n
milliseconds."
The OS doesn't even try to schedule the sleeping thread until requested time has passed.
.wait() says "I'm done my timeslice. Don't give me another timeslice until someone calls notify()."
-> we can normally use sleep() for time-synchronization and wait() for multi-thread-synchronization.
=============================================================
Ans--> Whenever we inherit the base class features into derived class there is a possibility
-> In order to differentiate between Base class features and Derived class features, for
-> In other words, super is a keyword which is used for differentiate between Base class
***
-> super keyword is playing an important role in three places. They are:
1. At variable level
2. At method level
3. At constructor level
==============================================================
-> Checked Exception: The Exceptions which are checked by compiler for smooth execution of the
program at runtime are called Checked Exception.
-> Compiler will check whether we are handling checked exceptin or not. If we are not handling then we
will get compile time error.
-> Unchecked Exception: The Exceptions which are not checked by compiler whether the programmer
handling or not are called Unchecked Exception.
RuntimeException and its child classes, Error and its child classes are unchecked except these the
remaining are checked exception.
-> Checked Exception is required to be handled by compile time while Unchecked Exception doesn't.
-> Checked Exception is direct sub-Class of Exception while Unchecked Exception are of
RuntimeException and Error.
Q.How can you create our own Exception?
===========================================================================
-> If you are creating our own Exception that is known as custom exception or user-defined exception.
-> Java custom exceptions are used to customize the exception according to user need.
-> By the help of custom exception, we can have our own exception and message.
TooYoungException(String s)
super(s);
class CustomExceptionTest
int age=17;
if(age<18)
throw new TooYoungException("You are too Young..Just wait for "+(18-age)+" years");
else
==========================================================================
-> length is a final variable, applicable only for arrays.
Ans-
-> It occurs when an application tries to load a class at run time which is not updated in the classpath.
where as It occurs when java runtime system doesn’t find a class definition,which is present at compile
time, but missing at run time.
-> It is thrown by the application itself. It is thrown by the methods like Class.forName(),
-> It occurs when classpath is not updated with required JAR files.
** ClassNotFoundException *
Ex.
try
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch (ClassNotFoundException e)
{
e.printStackTrace();
Ex....
class A
// some code
public class B
A a = new A();
=================================
-> Immutable class is a class which once created, it’s contents can not be changed.
-> Immutable objects are the objects whose state can not be changed once constructed.
=====================================
-> Because java uses the concept of string literal. Suppose there are 5 reference variables,all referes to
one object "sachin".
If one reference variable changes the value of the object, it will be affected to all the reference
variables.
-> In case of String object, just because of SCP a single object is referred by multiple references.
by using one reference if we are allowed to change the content then remaining refereces will be
impacted.
....
-> But in case of StringBuffer for every requirment a separate object will be created.
by using one reference if we are allowed to change the content then remaining refereces won't be
impacted.
=============================================
If the instance fields include references to mutable objects, don't allow those objects to be changed:
create copies of your internal mutable objects when necessary to avoid returning the originals in your
methods.
-> Ex..
this.name = name;
this.age = age;
return age;
return name;
Ans-
** String **
Every immutable object in Java is thread safe ,that implies String is also thread safe .
-> StringBuffer is mutable means one can change the value of the object .
** StringBuilder **
The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread
safe.
Q.Reflection API:
=================================
-> Reflection API is used for reading a class at execution time, loading its byte code
and creating its object and further calling its datamembers and member methods.
-> Reflection API contains all information about our class that is what types of modifiers,
Why String class is made Immutable or Final in JavaThough true reasons of why String class was made
final is best known to Java designers,
and apart from that hint on security by James Gosling, I think following reasons also suggest Why
String is Final or Immutable in Java.
1) String Pool
Java designer knows that String is going to be most used data type in all kind of Java applications and
that's
why they wanted to optimize from start. One of key step on that direction was idea of storing String
literals in String pool.
Goal was to reduce temporary String object by sharing them and in order to share, they must have to be
from Immutable class.
You can not share a mutable object with two parties which are unknown to each other.
Let's take an hypothetical example, where two reference variable is pointing to same String object:
String s1 = "Java";
String s2 = "Java";
Now if s1 changes the object from "Java" to "C++", reference variable also got value s2="C++", which it
doesn't even know about it.
By making String immutable, this sharing of String literal was possible. In short,
key idea of String pool can not be implemented without making String final or Immutable in Java.
2) Security
Java has clear goal in terms of providing a secure environment at every level of service and String is
critical in those whole security stuff.
String has been widely used as parameter for many Java classes, e.g. for opening network connection,
you can pass host and port as String, for reading files in Java you can pass path of files and directory as
String and for opening database connection,
you can pass database URL as String. If String was not immutable, a user might have granted to access a
particular file in system,
but after authentication he can change the PATH to something else, this could cause serious security
issues.
Similarly, while connecting to database or any other machine in network, mutating String value can pose
security threats.
Mutable strings could also cause security problem in Reflection as well, as the parameters are strings.
Another reason for making String final or Immutable was driven by the fact that it was heavily used in
class loading mechanism.
As String been not Immutable, an attacker can take advantage of this fact and a request to load standard
Java classes
e.g. java.io.Reader can be changed to malicious class com.unknown.DataStolenReader. By keeping String
final and immutable,
4) Multithreading Benefits
Since Concurrency and Multi-threading was Java's key offering, it made lot of sense to think about
thread-safety of String objects.
Since it was expected that String will be used widely, making it Immutable means no external
synchronization,
means much cleaner code involving sharing of String between multiple threads.
This single feature, makes already complicate, confusing and error prone concurrency coding much
easier.
Because String is immutable and we just share it between threads, it result in more readable code.
Now when you make a class Immutable, you know in advance that, this class is not going to change once
created.
This guarantee open path for many performance optimization e.g. caching. String itself know that, I am
not going to change,
so String cache its hashcode. It even calculate hashcode lazily and once created, just cache it. In simple
world,
when you first call hashCode() method of any String object, it calculate hash code and all subsequent
call to hashCode() returns already calculated,
cached value. This results in good performance gain, given String is heavily used in hash based Maps e.g.
Hashtable and HashMap. Caching of hashcode was not possible without making it immutable and final,
as it depends upon content of String itself.
Throw
Throws
Method Overloading
Method Overriding
1) Method Overloading occurs with in the same Method Overriding occurs between
Since method overriding occurs between superclass and subclass inheritance is involved.
is not involved.
overloading
method overloading
another
Pros and Cons of String being Immutable or Final in Java
---------------------------------------------------------------
Apart from above benefits, there is one more advantage that you can count due to String being final in
Java.
It's one of the most popular object to be used as key in hash based collections e.g. HashMap and
Hashtable.
Though immutability is not an absolute requirement for HashMap keys, its much more safe to use
Immutable object as key than mutable ones,
because if state of mutable object is changed during its stay inside HashMap, it would be impossible to
retrieve it back,
given it's equals() and hashCode() method depends upon the changed attribute. If a class is Immutable,
there is no risk of changing its state,
when it is stored inside hash based collections. Another significant benefits, which I have already
highlighted is its thread-safety.
Since String is immutable, you can safely share it between threads without worrying about external
synchronization.
Despite all these advantages, Immutability also has some disadvantages, e.g. it doesn't come without
cost.
Since String is immutable, it generates lots of temporary use and throw object, which creates pressure
for Garbage collector.
Java designer has already thought about it and storing String literals in pool is their solution to reduce
String garbage.
It does help, but you have to be careful to create String without using constructor e.g. new String() will
not pick object from String pool.
Also on average Java application generates too much garbage. Also storing Strings in pool has a hidden
risk associated with it.
String pool is located in PermGen Space of Java Heap, which is very limited as compared to Java Heap.
Having too many String literals will quickly fill this space, resulting in java.lang.OutOfMemoryError:
PermGen Space. Thankfully,
Java language programmers has realized this problem and from Java 7 onwards, they have moved String
pool to normal heap space,
which is much much larger than PermGen space. There is another disadvantage of making String final, as
it limits its extensibility.
Now, you just can not extend String to provide more functionality, though more general cases its hardly
needed,
still its limitation for those who wants to extend java.lang.String class.
Class----> if will declae the class as final then we cannot extend that class.or say we cant create child
class for that.
Variable--->That will be constant and we canot perform re-assignment for that variable.
ArrayList
LinkedList
preferable
LinkedList is preferable
complicated
not required
ArrayList
heterogeneous object
class
l1Key.add("Basant");
l1Key.add("Babul");
l1Value.add(50.000);
l1Value.add(40.000);
Example:
List<Map<String, Integer>> listMap = new ArrayList<>(); Map<String, Integer> map = new HashMap<>();
map.put("A", 34);
return listMap;
}
=====================================================================================
=================
Q.RequestDispatcherVsSendRedirect.
====================================
-> When we use forward method, request is transfer to other resource within the same server for
further processing.
-> In case of forward, web container handle all process internally and client or browser is not involved.
-> When forward is called on requestdispatcher object we pass request and response objects so our old
request object
-> Visually we are not able to see the forwarded address, it is transparent.
-> When we redirect using forward and we want to use same data in new resource we can use
request.setAttribute () as we have request object available.
SendRedirect
====================================
-> In case of sendRedirect, request is transfer to another resource to different domain or different server
for further processing.
-> When you use sendRedirect, container transfers the request to client or browser so URL given inside
the sendRedirect method
-> In case of sendRedirect call, old request and response objects are lost because it’s treated as new
request by the browser.
-> In address bar, we are able to see the new redirected address. It’s not transparent.
-> sendRedirect is slower because one extra round trip is required, because completely new request is
created and old request object is lost.
-> But in sendRedirect, if we want to use we have to store the data in session or pass along with the URL.
-> Its depends upon the scenario that which method is more useful.
-> If you want control is transfer to new server or context and it is treated as completely new task then
we go for Send Redirect.
Generally, forward should be used if the operation can be safely repeated upon a browser reload of
the web page will not affect the result.
=====================================================================================
-> The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.
-> The ServletContext parameters are specified for an entire application outside of any particular servlet
-> Object of ServletConfig will be created during initialization process of the servlet.
-> Object of ServletContext will be created at the time of web application deployment.
-> ServletConfig object will be destroyed once the servlet execution is completed.
-> ServletContext object will be destroyed once the application is removed from the server.
Q.WebServer&AppServer.
=====================================================================================
-> I have web application and I have to run web application , Web Server is required.
-> Web Server can provide support for Servlet, JSP, Html, etc...
-> I have enterprise application and i have to run enterprise application, Application Server is required.
-> Application Server provides environment to run both web application and enterprise application.
-> Application Server is superior server. Every Application Server contain inbuilt Web server to provide
-> Any technology, we can use to develop enterprise application then we can go for Application Server.
Ans-End-to-end testing validates all the processes in the workflow to check if everything is working as
expected. It also ensures that the system works in a unified manner, thereby satisfying the business
requirement.
I have seen many devs fumble over this question. After all, they're getting asked this question when
interviewing for a microservices architect role, so acknowledging its cons can be a little tricky. Here are
some good answers:
They require heavy investment – Microservices demand a great deal of collaboration. Since your teams
are working independently, they should be able to synchronize well at all times.
They need heavy architecture set up – The system is distributed, the architecture is heavily involved.
They need excessive planning for handling operations overhead – You need to be ready for operations
overhead if you are planning to use a microservices architecture.
They have autonomous staff selection – Skilled professionals are needed who can support microservices
that are distributed heterogeneously
Find out the services which are impacted whenever changes in a component occur.
This is a very common microservices interview question which you should be ready for! There are plenty
of pros that are offered by a microservices architecture. Here are a few of them:
Eureka configuration involves two steps – client configuration and server configuration.
Client configuration can be done easily by using the property files. In the clas spath, Eureka searches for
a eureka-client.properties file. It also searches for overrides caused by the environment in property files
which are
environment specific.
For server configuration, you have to configure the client first. Once that is done, the server fires up a
client which is used to find other servers. The Eureka server, by default, uses the Client configuration to
find the peer server.
It is one of the most important features, which helps you to access the current state of an application
that is running in a production environment. There are multiple metrics which can be used to check the
current state. They also provide endpoints for RESTful web services which can be simply used to check
the different metrics.
Spring Cloud, in microservices, is a system that provides integration with external systems. It is a short-
lived framework that builds an application, fast. Being associated with the finite amount of data
processing, it plays a very important role in microservice architectures.
For typical use cases, Spring Cloud provides the out of the box experiences and a sets of extensive
features mentioned below:
Routing.
Spring boot is a major topic under the umbrella of microservices interview questions.
With the new functionalities that have been added, Spring keeps getting more complex. Whenever you
are starting a new project, it is mandatory to add a new build path or Maven dependencies. In short, you
will need to do everything from scratch. Spring Boot is the solution that will help you to avoid all the
code configurations.
For example, in Spring MVC applications, you have to specify the suffix and prefix. This can be done by
entering the properties mentioned below in the application.properties file.
Minimal configuration is needed for implementation. All you need to do is add thespring-boot-starter-
securitystarter in the pom.xml file. You will also need to create a Spring config class that will override
the required method while extending the WebSecurityConfigurerAdapter to achieve security in the
application. Here is some example code:
package com.gkatzioura.security.securityendpoints.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@Override
Spring Boot contains Jetty, Tomcat, and Undertow servers, all of which are embedded.
Jetty – Used in a wide number of projects, Eclipse Jetty can be embedded in framework, application
servers, tools, and clusters.
Tomcat – Apache Tomcat is an open source JavaServer Pages implementation which works well with
embedded systems.
Undertow – A flexible and prominent web server that uses small single handlers to develop a web
server.
PACT is an open source tool. It helps in testing the interactions between consumers and service
providers. However, it is not included in the contract, increasing the reliability of the application. The
consumer service developer starts by writing a test which defines a mode of interaction with the service
provider. The test includes the provider’s state, the request body, and the response that is expected.
Based on this, PACT creates a stub against which the test is executed. The output is stored in a JSON file.
Note
In an enterprise application avoid adding it in application’s WEB-INF/lib. Mostly this connector will be
configured at server level so that same version will be shared among multiple applications. It helps in
upgrading jar at server without touching the application.
<dependencies>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2</version>
</dependency>
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ucp</artifactId>
<version>12.1.0.2</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>maven.oracle.com</id>
<name>oracle-maven-repo</name>
<url>https://maven.oracle.com</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>maven.oracle.com</id>
<name>oracle-maven-repo</name>
<url>https://maven.oracle.com</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</releases>
</pluginRepository>
</pluginRepositories>
b. or if you are using direct tomcat without eclipse then change /tomcat_install_dir/context.xml
username="javausecasedbuser" password="javausecasedbpassword"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:xe"/>
username="javausecasedbuser" password="javausecasedbpassword"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@DB_SERVER:1521:xe"/>
Note
maxTotal – Maximum number of database connections in pool. Make sure you configure your
max_connections large enough to handle all of your db connections. Set to -1 for no limit.
Connecting to shared DB in DEV environment in an organization do not use more than 1 or 2 total
connections.
maxIdle: Maximum number of idle database connections to retain in pool. Set to -1 for no limit. See also
the DBCP documentation on this nd the minEvictableIdleTimeMillis configuration parameter.
Connecting to shared DB in DEV environment in an organization do not use more than 1 or 2 idle
connections.
maxWaitMillis: Maximum time to wait for a database connection to become available in ms, in this
example 10 seconds. An Exception is thrown if this timeout is exceeded. Set to -1 to wait indefinitely.
Tomcat 7 and below uses org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory which uses maxActive,
maxWait
username="javausecasedbuser" password="javausecasedbpassword"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:xe"/>
Note
maxActive – (int) The maximum number of active connections that can be allocated from this pool at the
same time. The default value is 100
Connecting to shared DB in DEV environment in an organization do not use more than 1 or 2 active
connections.
maxIdle – (int) The maximum number of connections that should be kept in the pool at all times. Default
value is maxActive:100 Idle connections are checked periodically (if enabled) and connections that been
idle for longer than minEvictableIdleTimeMillis will be released. (also see testWhileIdle)
Connecting to shared DB in DEV environment in an organization do not use more than 1 or 2 idle
connections.
initialSize – (int)The initial number of connections that are created when the pool is started. Default
value is 10
Connecting to shared DB in DEV environment in an organization do not use more than 1 or 2 initial
connections.
3. Change web.xml, This is optional step. Rather if you are going to deploy it to Websphere in Production
environment do not add this entry.
<resource-ref>
<res-ref-name>jdbc/javausecasedb</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
4. You can even create Oracle DB datasource through spring DBCP configuration. This is useful for
testing application without any server.
destroy-method="close">
</bean>
destroy-method="close">
</bean>
bds.setDriverClassName("oracle.jdbc.driver.OracleDriver");
bds.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
bds.setUsername("javausecasedbuser");
bds.setPassword("javausecasedbpassword");
bds.setInitialSize(5);
import javax.naming.Context;
import javax.naming.InitialContext;
..
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/javausecasedb");
Notice java:comp/env
The InitialContext is configured as a web application is initially deployed, and is made available to web
application components (for read-only access). All configured entries and resources are placed in the
java:comp/env portion of the JNDI namespace.
package com.javausecase;
import java.io.IOException;
import java.sql.Connection;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
@WebServlet("/Servlet2")
@Resource(name = "jdbc/javausecasedb")
public Servlet2() {
super();
System.out.println("Servlet2()");
try {
// check datasource
System.out.println("ds=" + ds);
conn = ds.getConnection();
System.out.println("ds.getConnection()=" + conn);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
doGet(request, response);
I want to ask
How to Make a program that takes one number from user for Ex (a) and
-print " this number is little " when (a) is little than or equal 10
Up to java 7 , interface can only contain abstract methods i.e. we can only declare the method but can't
define the method. So the class that implements the interface must have to override every method of
that interface in the class .
Ex:
package com.sudhir.java8;
void post();
void comment();
package com.sudhir.java8;
package com.sudhir.java8;
Problem: Now the problem will be if SocialNetworkingApi will declare the new method shareStatus() ,
then FaceBookApi and WhatsappApi must have to override shareStatus() method because abstarct
method must have to be overriden in subclass otherwise it will throw error , which may result in
business loss because their customer will suffer.
So Java 8 introduced new keyword (default) which allows a method, present in an interface, can have
logic . Now subclass is not forced to define those methods inside the class. If they want any custom logic
they can define otherwise they will call the default method .So no business will suffer.
Java8 code:
package com.sudhir.java8;
void post();
void comment();
};
}
package com.sudhir.java8;
facebook.post();
facebook.comment();
package com.sudhir.java8;
public class WhatsappApi implements SocialNetworkingApi{
whatsapp.post();
whatsapp.comment();
whatsapp.shareStatus();
Conculsion: Interface can contain subclass child object also with method defintion.