AnswerList Interview
AnswerList Interview
1 proj exp
2 db - connectivity flow
3 db link
4 database cursor
5 spring boot
6 core java
7 java 8 [stream , default method, optional ]
7 microservice deploye
Q : Diff bw HttpClient vs RestTemplate ?
Q : how to communicate 2 service ?
1 Mutual exclusion
2 Synchronize the process [see Syncronized_Account example]
------
transactions can be described with the following four key properties described as
ACID -
Same as with @PostConstruct, the methods annotated with @PreDestroy can have any
access level, but can�t be static.
or
it gets called when bean instance is getting removed from the context.
Note-if your spring bean scope is �prototype� then it�s not completely managed by
the spring container and
PreDestroy method won�t get called.
----------------------------
Q - Component life cycle ?
ans:
public void init() [initialization code, loading configuration file , Connection
code , webservice]
public void destroy()
-----------------------------
Note 1:
-------
>a class can extends only a class at a time,
but
>a interface can extends any no. of interface simultansouly
and
>a class can implement any no. of interface at a time.
mean a class can extends only one class at a time but can implement any no of
interface at a time.
Ex : class A extends B // not more than one .
{
}
class A implements B,C,D // can implement more than one.
{
}
OR
diff
Java Extends vs Implements: In short, extends is for extending a class and
implements are for implementing an interface.
first write extends then implements or
implements must always be written after extends in class declaration .
it allow more clarity , and simplicity, reduce redudancy and keep data confidencial
** OOPS PRINCIPLE:
------------------
1 ENCAPSULAITON:
2 INHERITANCE
3 POLYMORPHYSIM
4 ABSTRACTION
2 INHERITANCE:
--------------
> its a process of reusing one object properties to another object.
3 POLYMORPHYSIM:
----------------
>defining multiple methods with same name with diff impl
4 ABSTRACTION:-
---------------
> Process of defining a class by necessary details to call operation by hiding its
impl details.
Note: java does not support multiple inheritance, but it provides alternative to
support it with interfaces.
*TYPE OF INHERITANCE:
======================
1 single level : if only two classes or interface participating
2 multi level : if more than two class are particapating relation vertically.
3 hierarchical : if we drive multiple subclasses from one super class or
more than one class extends one super class.
4 hybrid : (mixing all type inheritances) or combining other type inheritances
Note: we can stop multi level inheritance by declaring our sub class as final.
Note : => we can call class method by using interface ref var also. and that method
is executed from subclass of that interface.
and also we can call object class method by using interface ref var.
CASE : if two interface has method with same protype then subclass should impl only
one method.
CASE : if two interface has method with same name but diff param then subclass
should impl both methods.
because they are overloading method.
CASE : if two interface has 2 method with same signature but diff return type then
inheritance not possible.
CASE : if two interface has method with diff return type like object and String
type then subclass should impl String type(covariant type) method allowed.
CASE : after declaring a method static, we can not override static method as non
static and non static as static.
Note:- we can access interface var from subclass by using var name directally
because var are static final in interface.
Note: if two interface var has same name then we diff it using interface name with
var name.
**POLYMORPHISM :
----------------
it can be develop by using
1 method overriding [it occures in parent and child class]
2 method overloading. [it occures in same class]
Note:- only non static overriden methods comes under runtime polymorphsim
and
private non static methods and default non static methods comes under
compiler time polymorephism.
Note: => To develop runtime polymorphism, we must call method by using super class
ref var , then only we can store all subcalss objects.
class Mobile
{
void insertSim(Sim s)
{
s.dialCall();
s.sendSms();
}
}
class OOPSConceptMobileUser
{
public static void main(String[] args)
{
Mobile nokia = new Mobile();
nokia.insertSim(new Docomo());
}
}
or
class Adder{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
or
class Adder{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
class CompileTimePolymorphismDemo
{
public static void main (String args [])
{
ClassMain obj = new ClassMain();
double result;
obj.disp(40);
obj.disp(50, 30);
result = obj.disp(5.1);
System.out.println("Answer is:" + result);
}
}
2 RUNTIME POLYMORPHISM
EX 1:
interface vehicle
{
public void engine();
public void breaks();
}
class ClassesType
{
public static void main(String[] args)
{
Driver d=new Driver();
d.assignVehicle(new volvo());
op:
volvo engine capacity 180 kmph
bus has 2 breaks
Redbus engine capacity 40 kmph
bus has 2 breaks
EX2:
class Bank
{
float getRateOfInterest()
{
return 0;
}
}
OR
abstraction, encapsulation, inheritance, and polymorphism.
1 Abstraction:
Abstraction is the concept of hiding the internal details and describing things in
simple terms.
ways to achieve abstraction in object oriented programming, such as encapsulation
and inheritance.
2 Encapsulation :
Encapsulation is used for access restriction to a class members and methods.
3 Polymorphism :
Polymorphism is the concept where an object behaves differently in different
situations. There are two types of polymorphism � compile time polymorphism and
runtime polymorphism.
Compile time polymorphism is achieved by method overloading.
STATIC MODIFIER:
----------------
>applicable for var , method, block, inner-class, but not allowed for top class
>we can access static members directally from both area's static and instance
but we can not directally access instance(non-static) member from static area,
require class obj ref.
>instance and static var with same name not allowed but local and static var may be
with same name
>inheritance concept is applicable for static methods including main() but while
executing child
class mm then parent class mm will be executed.
it seems overriding concept for static members but its not overriding its method
hiding.
> if we r not using any instance var inside a method then we should declare static
but if we r using any instance var inside a method then declare that method as
instance method.
2 Aggrigation : in this relation object are loose couply, both class can exist
indepedentally, both have seperate life cycle.
ex: Team <->Cricket player
3 Composition : in this relation object are tight couply, both class can not exist
indepedentally, both not have seperate life cycle
ex: Car <-> Engine
------------------------------------------
or
Association is a relationship between two separate classes and the association can
be of any type say one to one, one to many etc.
It joins two entirely separate entities.
Example: Room has a table, but the table can exist without the room.
or
Aggregation is a special form of association which is a unidirectional one way
relationship between classes (or entities), for e.g. Wallet and Money classes.
Wallet has Money but money doesn�t need to have Wallet necessarily so its a one
directional relationship. In this relationship both the entries can survive if
other one ends. In our example if Wallet class is not present, it does not mean
that the Money class cannot exist.
Explanation: In the above program the Subject class is dependents on Topic class.
In the above program Subject class is tightly coupled with Topic class it means if
any change in the Topic class requires Subject class to change. For example, if
Topic class understand() method change to gotit() method then you have to change
the startReading() method will call gotit() method instead of calling understand()
method.
or
In the above code the Journey class is dependents on Car class to provide
service to the end user(main class to call this Journey class).
In the above case Journey class is tightly coupled with Car class it means
if any change in the Car class requires Journey class to change. For example if Car
class travel() method change to journey() method then you have to change the
startJourney() method will call journey() method instead of calling travel()
method.
or
class Traveler
{
Car c=new Car();
void startJourney()
{
c.move();
}
}
class Car
{
void move()
{
// logic...
}
}
Loose Coupling:- In simple words, loose coupling means they are mostly independent.
----------------
only a few parts of the application should be affected when requirements change.
It's highly changeable. One module doesn't break other modules in unpredictable
ways.
In the below example, Journey and Car objects are loosely coupled. It means Vehicle
is an interface and we can inject any of the implemented classes at run time and we
can provide service to the end user.
The examples of Loose coupling are Interface, JMS, Spring IOC(Dependency Injection,
it can reduce the tight coupling).
ex:
Below code is an example of loose coupling,
or
best ex:
class Traveler
{
Vehicle v;
public void setV(Vehicle v)
{
this.v = v;
}
void startJourney()
{
v.move();
}
}
//=========================Interface====================================
Interface Vehicle
{
void move();
}
and
String s="hello";
s=s+"india";
System.out.println(s); // helloindia
or
String s="hello";
String s2=s+"india";
System.out.println(s2);// helloindia
and
String s1="java1";
String s2=new String("java2");
s1.concat("java-1 is added");
s2.concat("java-2 is added");
System.out.println(s1); //java1
System.out.println(s2); //java2
and
String s1="java1";
s1="hello";
System.out.println(s1); //hello
and
String s="hello";
s.concat("BL");
System.out.println(s); // hello
and
String s=new String("java");
s.concat("jee");
System.out.println(s);// java
and
String s=new String("java");
String s2=s.concat("jee");
System.out.println(s2); //javajee
--------------------------------
String s=�java�;
s=s+�j2ee�;
System.out.println(s); //javaj2ee here the reference changes.
and
String s=new String("java");
String s2=s.concat("jee");
s2=s2.concat("spring");
System.out.println(s2);//javajeespring
------------------------------
Q-
String s1 = new String(�JAVA�);
System.out.println(s1); //Output : JAVA
s1.concat(�J2EE�);
System.out.println(s1); //Output : JAVA
s1 = s1 + �J2EE�;
System.out.println(s1); //Output : JAVAJ2EE
s1.concat(�wwee�);
System.out.println(s1); // Output : JAVA
System.out.println(s1.concat(�wwee�)); // Output : JAVAwwee
Q
String s1 = �JAVA�, s2 = �JAVA�;
System.out.println(s1==s2); //true
Q
String s1 = �Hello�;
s1 = �helloWorld�;
S.o.p(s1); // o/p- helloworld.
Q
String s1 = "Hel" + "lo";
String s2 = "Hello";
System.out.println(s1 == s2);
The code above will return true
Q what is syncronized ?
-----------------------
ans:-
Java Synchronization is to allow only one thread to access the shared resource and
to control the access of multiple threads to any shared resource.
--
Synchronized blocks in Java are marked with the synchronized keyword. A
synchronized block in Java is synchronized on some object
Concurrent access of shared objects in Java introduces to kind of errors: thread
interference and memory consistency errors and to avoid these errors you need to
properly synchronize
ex:
public class Counter{
long count = 0;
or
4. Java Thread acquires an object level lock when it enters into an instance
synchronized java method and
acquires a class level lock when it enters into static synchronized
java method.
10. Java synchronized block is better than java synchronized method in Java because
by using synchronized block you can only lock critical section of code and avoid
locking the whole method which can possibly degrade performance. A good example of
java synchronization around this concept is getting Instance() method Singleton
class.
or
synchronized method by using annonymous class
In this program, we have created the two threads by annonymous class, so less
coding is required.
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
t1.start();
t2.start();
}
}
Output: 5
10
15
20
25
100
200
300
400
500
long count = 0;
threadA.start();
threadB.start();
}
}
or
Need of Synchronization:
ex:1st thread fetches the value of i. (Currently value i is 0) and increases it by
one, so value of variable i becomes 1.
Now 2nd thread accesses the value of i that would be 0 as 1st thread did not store
it back to its location.
And 2nd thread also increment it and store it back to its location. And 1st also
store it.
Finally value of variable i is 1. But it should be 2 by the effect of both threads.
That�s why we need to synchronize the access to shared variable i.
Train(Line line)
{
this.line = line;
}
@Override
public void run()
{
line.getLine();
}
}
class GFG
{
public static void main(String[] args)
{
Line obj = new Line();
0
1
2
0
1
2
BLOCK:
Block Synchronization
If we only need to execute some subsequent lines of code not all lines
(instructions) of code within a method, then we should synchronize only block of
the code within which required instructions are exists.
For example, lets suppose there is a method that contains 100 lines of code but
there are only 10 lines (one after one) of code which contain critical section of
code i.e. these lines can modify (change) the Object�s state. So we only need to
synchronize these 10 lines of code method to avoid any modification in state of the
Object and to ensure that other threads can execute rest of the lines within the
same method without any interruption.
import java.io.*;
import java.util.*;
class GFG
{
public static void main (String[] args)
{
Geek gk = new Geek();
List<String> list = new ArrayList<String>();
gk.geekName("mohit", list);
System.out.println(gk.name);
}
}
Run on IDE
Output :
1
Important points:
When a thread enters into synchronized method or block, it acquires lock and once
it completes its task and exits from the synchronized method, it releases the lock.
When thread enters into synchronized instance method or block, it acquires Object
level lock and when it enters into synchronized static method or block it acquires
class level lock.
Java synchronization will throw null pointer exception if Object used in
synchronized block is null. For example, If in synchronized(instance) , instance is
null then it will throw null pointer exception.
In Java, wait(), notify() and notifyAll() are the important methods that are used
in synchronization.
or
or
Synchronized block can be used to perform synchronization on any specific resource
of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only
5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same
as the synchronized method.
class TestThread {
public static void main (String arg[]) {
or
or
class MultiThread {
public static void main(String args[]) {
new MyThread("One");
new MyThread("Two");
new NewThread("Three");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
* 2nd version : this definitely thread-safe and only * creates one instance of
Singleton on concurrent environment * but unnecessarily expensive due to cost of
synchronization * at every call. */
or
/* * 3rd version : An implementation of double checked locking of Singleton. *
Intention is to minimize cost of synchronization and improve performance, * by only
locking critical section of code, the code which creates instance of Singleton
class. * By the way this is still broken, if we don't make _instance volatile, as
another thread can * see a half initialized instance of Singleton. */
synchronized (Singleton.class)
{
if (instance == null) // Double checked
{
}
}
}
return instance;
}
extra reading
AUTOMATIC TYPE PROMOTION IN EXPRESSION:
-----------------------------------------
> both operand should be compatible type else we get error
ex boolean b
int i
int res=b+i ; // errore
>in arthimatic operation , result always comes in highest data type
int=byte+byte
case2:
>if you hold char in a char data and print
char ch='a';
System.out.println("Result : "+ch); //97
>char ch=98; sop(ch); //b
---------------------------------------------------------
** Expressions in :- System.out.Println();
---------------------------------------------
> System.out.println(10); /10
> System.out.println('a'); /a
> System.out.println("a"); /a
> System.out.println(10.0); /10.0
> System.out.println(30L); /30
> System.out.println(10.12l); /error
> System.out.println(50+30); /80
>int a=20,b=15;
System.out.println(a+b); /35
>int a=20,b=15;
System.out.println("a+b"+a+b); / ab2015
>int a=20,b=15;
System.out.println("a+b"+(a+b)); / ab35
>int a=20,b=15;
System.out.println("a+b"+a-b); /error
>int a=20,b=15;
System.out.println("a-b"+(a-b)); /a-b5
>int a=20,b=15;
System.out.println("a*b"+a*b); /a*b300
>int a=20,b=15;
System.out.println("a*b"+(a*b)); /a*b300
>System.out.println(10+""+20); //1020
>System.out.println(10+20+""); /30
>System.out.println(10/5*5*5); /50
>System.out.println(10.0/0) //infinity
>System.out.println(-10.0/0);/-infinity
int a=20;
String s="a"+a; //a20
Imp Note:
---------
1- we can not divide integer number by zero, if then get errore-
java.lang.ArthimaticException
ex:10/0 - java.lang.ArthimaticException.
but
we can devide float by zero - it output is-> INFINITY
ex:10.0/0 - infinity
The object cloning is the exact copy of an object. and clone() method of Object
class is used to clone an object.
Security:
String is immutable is that it is used by the class loading mechanism
parameters are represented as String in network connections, database connection
urls, usernames/passwords etc. If it were mutable, these parameters could be easily
changed
Caching :
being immutable String in Java caches its hashcode, and do not calculate every time
we call hashcode method of String, which makes it very fast as hashmap key to be
used in hashmap in Java
String is immutable, its hashcode is cached at the time of creation and it doesn�t
need to be calculated again.
Thread Safety:
it is safe for multithreading and a single String instance can be shared across
different threads. This avoid the usage of synchronization for thread safety,
Strings are implicitly thread safe.
thread-safe in Java, means you don't need to synchronize String operation
externally.
to avoid any synchronization issues in Java,
Synchronization and concurrency: making String immutable automatically makes them
thread safe thereby solving the synchronization issues.
or
Security:
parameters are typically represented as String in network connections, database
connection urls, usernames/passwords etc. If it were mutable, these parameters
could be easily changed.
Main reason is about security
Many passwords, db connection infos and important parameters are sending using
"String".
or
String Constant Pool ... If string is mutable, changing the string with one
reference will lead to the wrong value for the other references.
Security:
String is widely used as parameter for many java classes, e.g. network connection,
opening files, etc. Were String not immutable, a connection or file would be
changed and lead to serious security threat. ...
ex:
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
printing s1 and s2 prints the hashcode values of the objects but I want to print
the values of these objects. Since java compiler internally calls toString()
method, overriding this method will return the specified values. Let's understand
it with the example given below:
how to override:-
public String toString()
{
//overriding the toString() method
return rollno+" "+name+" "+city;
}
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
or
or
Serializable interface :
Serializable interface is present in java.io package. It is used to make an object
eligible for saving its state into a file. This is called Serialization.
This interface is used to mark serialization and deserialization of an object.
Serialization is a process in which an object state is read from memory and written
into a file or a database. Deserialization is a process in which an object state is
read from a file or a database and written back into memory. Any class which wants
it�s object to be eligible for serialization and deserialization must implement
Serializable interface.
Classes that do not implement this interface will not have any of their state
serialized or deserialized.
All subtypes of a serializable class are themselves serializable.
1) java.lang.Cloneable Interface :
This interface is used to mark the cloning operation. An object of a class which
implements Cloneable interface is eligible for field-by-field copying of an object.
Invoking Object�s clone method on an instance of the class that does not implement
the Cloneable interface results in an exception CloneNotSupportedException being
thrown.
2) java.io.Serializable Interface :
ex:-
interface Cash
{
interface Checque
{
PaymentTwo.paymentByChecque();
}
}
SHALLOW CLONING:
----------------
> the process of creating depedent copy of an object is called shallow cloning.
if main object contains any primitive vars then exactaly duplicate copies will be
created in cloned object.
if main object contains any reference var then same object will not be created
just ref var will be created by pointing to old contained object.
> by using main ref if we perform any changes to contained object then changes will
be reflected automatically to cloned object.
> by default object class clone() meant for shallow cloning.
Note:- shallow cloning is the best choice , if object contains only primitive
values.
in shallow cloning by using main object ref , if we perform any changes to
contained object then changes reflected automaticaly to cloned copy.
** DEEP CLONING:
-----------------
The process of creating exactaly indepedent duplicate object, is called deep
cloning.
> in deep cloning, if main object contain any ref var then correspondence object
copy also will be created in cloned object.
> Object class clone() mehtod mean for shallow cloning , if we want deep cloning
then prog is responsible to impl by overriding clone() method.
Note:- in deep cloning by using main object ref if we perform any changes to
contained object those changes will not be reflected to cloned object.
if object contains reference vars then deep cloning is the best choice.
What is Shallow Copy:-
Shallow copy is a bit-wise copy of an object. A new object is created that has an
exact copy of the values in the original object.
If any of the fields of the object are references to other objects, just the
reference addresses are copied i.e., only the memory address is copied.
The shallow copy of an object will have exact copy of all the fields of original
object.
If original object has any references to other objects as fields, then only
references of those objects are copied into clone object, copy of those objects are
not created.
That means any changes made to those objects through clone object will be reflected
in original object or vice-versa.
Shallow copy is not 100% disjoint from original object. Shallow copy is not 100%
independent of original object.
Shallow copy:Generally clone method of an object, creates a new instance of the
same class and copies all the fields to the new instance and returns it. This is
called shallow copy. Object class provides a clone method and provides support for
the shallow copy. It returns �Object� as type and you need to explicitly cast back
to your original object. Since the Object class has the clone method, you cannot
use it in all your classes. The class which you want to be cloned should implement
clone method and overwrite it. It should provide its own meaning for copy or to the
least it should invoke the super.clone(). Also you have to implement Cloneable
marker interface or else you will get CloneNotSupportedException. When you invoke
the super.clone() then you are dependent on the Object class�s implementation and
what you get is a shallow copy.
Deep copy:-
When you need a deep copy then you need to implement it yourself. When the copied
object contains some other object its references are copied recursively in deep
copy.
A deep copy copies all fields, and makes copies of dynamically allocated memory
pointed to by the fields. A deep copy occurs when an object is copied along with
the objects to which it refers.
Deep copy of an object will have exact copy of all the fields of original object
just like shallow copy. But in additional, if original object has any references to
other objects as fields, then copy of those objects are also created by calling
clone() method on them. That means clone object and original object will be 100%
disjoint. They will be 100% independent of each other. Any changes made to clone
object will not be reflected in original object or vice-versa.
To create a deep copy of an object, you have to override the clone() method.
deep copy is a fully independent copy of an object. If we copied our Person object,
we would copy the entire object structure.
Serializable Objects:
To serialize an object means to convert its state to a byte stream so that the byte
stream can be reverted back into a copy of the object.
Serialization:- in java is a mechanism of writing the state of an object [java
support form] into a byte stream [network supported form].
Deserialization:- the process of reading state of a object from a file is called
De-Serialization.
It is mainly used to travel object's state on the network (known as marshaling).
A Java object is serializable if its class or any of its superclasses implements
either the java.io.Serializable interface
Product p2 =(Product)ois.readObject();
Q While serializing you want some of the members not to serialize? How do you
achieve it?
-----------------------------------------------------------------------------------
------
transient keyword.
Note:- once we create a string object, we can not perform any chages in existing
object.
if we try to change then a new object is created, this behaviour is called
Immutable of string object.
CASE 2:
-------
ex:1
String s1 = new String("bhaskar");
String s2 = new String("bhaskar");
Note:- after using New keyword , every time creating new object so-
sop(s1==s2); // false-> both are pointing diff obj
sop(s1.equals(s2)); // true-> contents are same
CASE 3:
-------
Ex: String s = new String("bhaskar");
IMP_NOTE:=> in this case, two object will be created , one is on heap and other one
is SCP- string constant pool and s is always pointing to heap object.
**IMP- POINTS:
--------------
1: Object creation in SCP is always optional, first jvm will check is any object
already created with req content or not in SCP.
if is already availble then it will reuse existing instead of creating new.
if it is not there then only new object will created.
so there is no chance of existing two objects with same content on scp or
duplicate obj are not allowed in SCP.
2 Garbage collector can not access SCP area , even though object do not have any
ref[not usable long time] still that obj is not
eligible for GC if it is present in SCP.
All scp objects will be destroyed at the time of jvm shutdown automatically.
String s3="bhaskar";
String s4="bhaskar";
ans: total 3 object will created, 2 object with each new kw , 1 in scp with bhaskar
content
[other object content is same so point to same scp]
Explanatin:=>
s1-> create two obj , one in heap , and one in scp for futur.
s2-> create one obj in heap, and in scp its point to old content, not create new
object.
s3-> not create any object , only point to old content already availble in scp
Imp-note:=> whever we are using new operator compulsory a new object will be
created on heap. and there may be chance of existing two object with same content
on heap, but there is no chance of existing two objects with same content on scp.
or duplicate object possible in heap but not in scp.
2 we can create one copy and we can reuse same obj for every req. this improve
performance and mem utilization,
we can achive this by using scp.
3 Disadavntage in scp, several refs pointing to same obj , so by using one ref if
we perform any change the remaining refs will be effected. to overcome this
problum sun implemented immutability concept for string objects.
4 once we creats a string obj , we can not perform any changes in existing obj if
we try to perform any changes with changes a new string obj will be created so
immutaiblility is the main disadvantage of SCP.
----------------------------------------------------------------------------------
diff bw
String s = new String("Durga");
and
String s="Durga"; ?
ans: in case of - String s = new String("Durga"); two obj created , one in scp and
one in heap.
in case of - String s="Durga"; only one obj is created in scp.
SCP :
ans: string constant pool is specially designed memory area for string object to
reuse .
advantage of SCP ?
ans: memory utilizataion , and performance improved.
disadvantage of SCP ?
ans: immutaibility
why string objects are req immutaible whereas stringbuffer obj are imutaible?
ans:
in case of string as several refs pointing to same object, and by using one ref if
we allowed perform changes then the remaining ref will be effect. so to prevent ,
once we created a string obj we can not perform changes in existing object that is
immutaibility.
Note:- if the corresponding obj is not there in scp then intern() method itself
will create that obj and return it.
programme-
public class Immutable
{
private final int a;
public Immutable(int a)
{
this.a=a;
}
CreateImmutable(int i)
{
this.i=i;
}
else
return (new CreateImmutable(i));
}
SOP(c1==c2); // false
}
}
**or
To create immutable class in java, you have to do following steps.
or
ClassNotFoundException:
-----------------------
if dynamically provided class name is not availble at runtime then we get runtime
exception - ClassNotFoundException
ex: Object o = Class.forName("Test").newInstance();
then at runtime if this Test class file not availble so we get
ClassNotFoundException error.
ans:-
In Java the Singleton pattern will ensure that there is only one instance of a
class is created in the Java Virtual Machine. It is used to provide global point of
access to the object. In terms of practical use Singleton patterns are used in
logging, caches, thread pools, configuration settings, device driver objects.
Singleton Class:
Static member : This contains the instance of the singleton class.
Private constructor : This will prevent anybody else to instantiate the Singleton
class.
Static public method : This provides the global point of access to the Singleton
object and returns the instance to the client calling class.
or
Some basics rules required to implement a singleton class
}
/**
* Create a static method to get instance.
*/
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
//or
Output
demoMethod for singleton
Example 2
Following implementation shows a classic Singleton design pattern -
SingleObject.java
SingletonPatternDemo.java
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
or
or
ex:
BufferedReader br = null;
FileReader fr = null;
try {
Q finalize method ?
-------------------
finalize is a method, always invoked by Garbage collector just befor destroying an
object to perform cleanup activities.
The java.lang.Object.finalize() is called by the garbage collector on an object
when garbage collection determines that there are no more references to the object.
** Exception Hierarchy:
-----------------------
Objcet
|
Throwable
Objcet
|
Throwable
|
-----------------------------------------------------------------------------------
-----------------------------
|
|
Exception
Error
|_____________________
_________________________________|____________
| |
| |
--------------------------------------------------------
VMError LinkageError AssertationError
| | | _______|___________
| RuntimeException
IOException SQLException ServletException
| |
| | OutOfMemoryError
StackOverflowError
| |_________
| |--EOFException
|--ArthimeticException |
| |--FileNotFoundException
|--NullPointerException |
| |--InterrptedIOException
|--IndexOutBoundException
| |
| |-ArrayIndexOutOfBoundException
| |-StringIndexOutOfBoundException
|
|--IllegalArgumentException
| |
| |--NumberFormatException
|
|--ClassCastException
|
|--IllegalStateException
Unchecked: �Error� and its subclasses,�RunTimeException� and its subclasses
Checked:- except -Error� and its subclasses,�RunTimeException� and its subclasses ,
remaining all are checked.
or
*** CHECKED Vs UNCHECKED EXCEPTION:
-----------------------------------
UNCHECKED EXCEPTION:-
classes that extend RuntimeException are known as unchecked exceptions
e.g.
ArithmeticException,
NullPointerException,
ArrayIndexOutOfBoundsException
IllegalArgumentException
IllegalStateException
Note:- Unchecked exceptions are not checked at compile-time rather they are
checked at runtime.
Note:-Runtime and its childs+ Errors and its child are un checked and
remaining all are checked Exceptions
Q multithreading ?
-------------------
executing several tasks simultaneously where each task is seprate indepedent part
of same program.
and each part is called a "Thread".
Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
But we use multithreading than multiprocessing because threads share a common
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
ex: its best sutaible for programatic level.
and its easy in java, becouse java provide in built support for multithreading
through a API [Thread, Runnable, ThreadGroup,ThreadLocal, etc.]
Advantages Multithreading-
1) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
2) You can perform many operations together so it saves time.
3) Threads are independent so it doesn't affect other threads if exception occur in
a single thread.
What is Thread in java
A thread is a lightweight sub process, a smallest unit of processing. It is a
separate path of execution.
Threads are independent, if there occurs exception in one thread, it doesn't affect
other threads. It shares a common memory area.
Note: the most powerfull search algorithm is hashing which will work based on
hashCode().
Note: overriding hashCode() mehtod is said proper if , for every object we have to
generate a [diff] unique number as hashCode.
Diff
----
toString(): use to print object ref or in meaningfull string representation of
object.
hashCode(): use to saving objects into HashSet or Hashtable or HashMap.
Note:
-----
== for ref comparision
wheres
.equals() for content comparision
Note: - if two refs pointing to the same object then it return true.
Note:- if passing same value while creating object then its not same object,
becouse its creating through new kw so its diff object.
if we assigning one obj ref to other ref then its point to same object.
Note:- based on our prog req we can override .equal() mehtod for content
comparision.
Note:- if two refs pointing to same object then ..equals() retrun true directally
without performing any content comparision.
Imp-Note:
---------
> in String class, .equals() is overriden for content comparision so if content is
same .equals() returns true, even though object is different.
> in StringBuffer class .equals() is not overriden for content comparision so
object class .equals() will be executed which meant for ref comparision, so if
objects are diff then .equals() return false even though content is same.
> in String class, Wrapper class and all Collection classes .equals() method is
overriden for content comparision.
2 we can not override == operator for content comparision in ref obj. 2 we can
override .equals() method for content comparision.
4 for any obj ref r, r--null is always false. 4 for any obj ref
r, r.equals(null) is also always false.
-----------------------------------------------------------------------------------
------------------------------------------------
Note:
-----
== for ref comparision
wheres
.equals() for content comparision
@Override
public boolean equals(Object o) {
if (o == this)
return true;
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + age;
result = 31 * result + passport.hashCode();
return result;
}
or
@Override
public boolean equals(Object o) {
@Override
public int hashCode() {
return Objects.hash(name, age, passport);
}
INTERFACE ABSTRACT-CLASS
-----------------------------------------------------------------------------------
-------------------
0.contains only abstract methods 0. can contains both
abstract and concreate methods.
**IMPORTANT NOTE:
1. we can not create object for abstract class but abstract class can contain
constructor.
Q what is need?
ans - to perform initialization of child object at the time of child object
creation.
Note: Either directally or indirectally we cant create obj for abstract class.
> whenever we r creating child class object parent constructor will be executed,
but parent obj will not be
created.
> interface contains only abstract methods but abstract class can contain both
abstract and concreate methods.
Q-> if interface contains only abstract methods but abstract class also contain
fully abstract methods
then what is difference?
or
is it possible interface replace by abstract class.
ans: yes we can replace but two problums are there
1 abstract class can extends only one class where as interface can more than one
interfaces
2 object creation is costally for abstract classes.
1 INTERFACE:
------------
>a interface is fully unimplemeted class used for declaring a set of operation of
object.
it contain only final static var and public abstract methods.
2 ABSTRACT CLASS:
-----------------
>a class that is declared as abstract .
it is a partially implimented class used for developing some of the operations of
an object which are common for
all next level subclasses.
> abstract class contains both abstract method and concrete methods including
variables blocks, constructor.
You expect that unrelated classes would implement your interface. For example,many
unrelated objects can implement Serializable interface.
You want to specify the behaviour of a particular data type, but not concerned
about who implements its behaviour.
You want to take advantage of multiple inheritance of type.
Q what is method overridding? with use case? why we prefer Polymorphism over
inheritance?
-----------------------------------------------------------------------------------
-------
**POLYMORPHISM :-
-----------------
>a method with same name with diff forms is concept of polymorphism.
*POLYMORPHISM : consist of-
----------------------------
1-Compiletime or static or earlybinding : [overloading (same method name but diff
args)+ method hiding]
2-Runtime/dynamic/latebinding : [overriding] (same method name and same
args)
OOPS : PILLARS-
---------------
1- inheritance is talks to reusability.
2- polymorphism talks to flexibility.
3- encapsulation talks to security.
ans:
CO-VARIANT:
ALLOWED PARENT => OBJECT NUMBER
| | |
CHILD => STRING INTEGER
Note:- Co-variant return type concept is applicable only for object type not for
primitive.
Note:- private methods are not visible in child classes hence overriding concept is
not applicable for private method.
base on our requirment we can declare same parent private method in child it
is allowed , but it is not overriding.
Note:- parent class final method can not be override in child class.
Note:- parent class final method we can override as final in child class. we can
also override native methods in child.
Note:- we can override a non abstract method as abstract.
Note:- syncronized, strictfp will not has any restriction on overriding.
Note:- not allowed: final -->non final but non-final -> final is allowed.
native <====> non native, abstract <====> non abstract,
syncronized <====> non syncronized,
strictfp <====> non strictfp.
*OVERRIDING RULE:- while overriding if the child class method throws any checked
exception compulsory the parent class method should throw same checked exception.
else we get C.E
but
There is no restrictions on un-checked exceptions.
Note:- if we overriding static to static then its not overriding , its mehtod
hiding.
**METHOD HIDING:-re defining same parent class static method in child class.
-----------------
overriding hiding
-----------------------------------------------------------------------------------
------------------------------------
1.both non static 1.both static
2.take care by jvm 2. take care by compiler
3.runtime/dynamic/latebinding
3.compiletime/static/early binding.
-----------------------------------------------------------------------------------
------------------------------------
Note:- overriding concept is not applicable for variables.
OVERLOADING OVERRIDING
-----------------------------------------------------------------------------------
----------------------------------
1. method name must be same 1. Must be same
2. argument type diff 2. must be same.
3. method signature must be diff 3. must be same.
4. return type no restriction 4. same or co-variant.
5. private, static, final can not be overloaded. 5. also can not be
overriden.
6. no restriction on Access Modifiers 6. weak / reducing is not
allowed.
7. no restriction on throws clause 7. parent method should
throw same checked exception as child,
not restiction for un-
checked.
8.also called compiletime/static/early binding 8.also called
runtime/dynamic/late binding.
-----------------------------------------------------------------------------------
-------------------------
imp note:
1 : in overloading , we have check only method name same, and args diff , remaining
things like return type extra not req.
but
2 : in overriding , we check everything like mehtod names, args, return type,
throws , modifiers.
try {
ex 2:
------
Note:- Generally we can use throw kw for customized exceptions but not for
predefined exceptions.
CASE 2: after throw stmt , we can not take any stmt directally , then we get CE -
unreachable stmt.
ex: throw new ArthimeticException("\ by zero");
sop("hello");
CASE 3: we can use throw kw only for Throwable type , otherwise we get CE-
incompatible type.
ex:
2 : throws kw required only for checked exception, and usage for unchecked is no
use.
3 : throws kw req only to continue compiler, but it not handle exception,and throws
does not prevent abnormal termination of program.
4 to handle exception we use try catch. so
IMP_NOTE: => In our prog, if there is any chance of raising checked exception
then compulsory we should handle either try catch or by throws kw else
code will not compile.
or
Class Test
{
PSVM() throws InterruptedException
{
Thread.sleep(5000);
}
}
ex:2
-----
or
throws clause is used to declare an exception and throw keyword is used to throw an
exception explicitly.
If we see syntax wise then throw is followed by an instance variable and throws is
followed by exception class names.
The keyword throw is used inside method body to invoke an exception and throws
clause is used in method declaration (signature).
or
Difference between throw and throws in Java
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
------------------------------------
MethodOverriding in Java
---------------------------
If the superclass method does not declare an exception
If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but it can declare unchecked exception.
If the superclass method declares an exception
If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent
exception.
sleep():
It is a static method on Thread class. It makes the current thread into the
"Not Runnable" state for specified amount of time. During this time, the
thread
keeps the lock (monitors) it has acquired.
wait():
It is a method on Object class. It makes the current thread into the "Not
Runnable"
state. Wait is called on a object, not a thread. Before calling wait()
method, the
object should be synchronized, means the object should be inside synchronized
block.
The call to wait() releases the acquired lock.
or
wait()
wait() Method.
1) The thread which calls wait() method releases the lock it holds.
2) The thread regains the lock after other threads call either notify() or
notifyAll() methods on the same lock.
1) The thread which calls sleep() method doesn�t release the lock it holds.
4) Sleeping threads can not be woken up by other threads. If done so, thread will
throw InterruptedException.
STATIC MODIFIER:
----------------
>applicable for var , method, block, inner-class, but not allowed for top class
>we can access static members directally from both area's static and instance
but we can not directally access instance(non-static) member from static area,
require class obj ref.
>inheritance concept is applicable for static methods including main() but while
executing child
class mm then parent class mm will be executed.
it seems overriding concept for static members but its not overriding its method
hiding.
> if we r not using any instance var inside a method then we should declare static
but if we r using any instance var inside a method then declare that method as
instance method.
Final method:
-------------
>if child method not allowed to override then declare final method in parent class.
>whatever parent has by default availble to child through inheritance.
but if child is not satisfy with parent impl then child is allowed to override tht
method on
its requirement.
but
if parent class method declared final then child is not allowed to override that
method.
or means we cant override final method and final class methods also.
Final Class:
------------
>if a class declared final then we cant create child class
or
>we cant extends final class or inharitance is not applicable to final class.
Note:- every method inside final class is final method , whether we r declaring or
not.
but
every variable present inside final class need not be final.
Abstact modifier:
-----------------
> applicable only for method and classes not for variable.
Abstact method:
---------------
>if we dont know implitation then we can declare method with abstract modifier
>abstact method has only declaration but not implementation.
>abstact method declaration should end with semicolon ;
>its not allowed body.
Note:-advantage is we can provide guidline to child for impl.
ex;
public abstact void showData();
>child class is responsible to provide impl for parent class abstact method.
ex:
abstact class vechile
{
public abstact int getnowheels();
}
class bus extends vechile
{
public int getnowheels()
{
return 7;
}
}
Abstract Class:
---------------
>if we dont want to create object, or dont allow to create object of class then
declare with abstract modifier
>for abstract class instantiation is not possible.
ex: HttpServlet, Adapter class that is absract class but doesnot contains any
absract method.
Abstract Vs Final:
------------------
1>for abstract class we can create child class to provide impl but final class
we can not create child class.
collections.
------------
Q tell me interfaces in collection framwork ?
key interfaces in collection :-
ans:-
1 Collection (I)
2 List(I)
3 Set(I)
4 Map(I)
5 SortedSet(I)
6 SortedMap(I)
7 NaviabeSet(I)
8 NavigableMap(I)
9 Queue(I)
Q collection herairchy ?
---------------------------
Set(i) :
-------------
Map(i) : diag
==========
Map(i) [1.2]
|
-----------------------------------------------------------------------------------
----Dictionary(AC) [1.0]
| | | |
|
HashMap(i) WeakHashMap(i) IdentityHashMap(i) SortedMap(i)[1.2]
Hashtable [1.0]
[1.2] [1.2] [1.4] |
|
NavigableMap(i) [1.6]
Properties [1.0]
|
TreeMap(i) [1.6]
CASE 1: Type-Safety
-------------------
> array are always type safe.
> ex : if our prog req is to hold string type of objects its recommended to use
string array.
in case of string array , we can hold only string type of objects, if by
mistak we try to add any other then get CE.
Note:-
> array are type safe.
but
> collections are not type-safe.[means we can not say which type elements present
inside colleciton]
ex: if req to hold string type of objects then its never recomended to for for
arraylist.
by mistake if we try to add any other type then we will not get any CE but prog
may fail at Runtime.
CASE 2: Type-Casting:
---------------------
> in case of array at the time of retrivel , its not req to perform any type
casting.
ex: String sname=str[0];
but
> in case of collection, at the time of rerival compulsory req type casting else we
get CE.
ex: String s=(String) al.get(0);
Integer i = (Integer) al.get(1);
Note:we can store only defined type objects. like above string only.
Imp-Note: after defining a generic type object , while retriving object type
casting not required.
this is done through generic syntax.
**CONCLUSION 1:
===============
Note:- Polymorphism concept is applicable only for base type not for param type.
[holding child ref in parent]
ex: ArrayList<String> // here Arraylist is base type and String is param type.
**Note:-
Comparable mean -> for default natural sorting
Comparator mean -> for Customized sorting order
**Note:-
Q- what is Comparable ?
-----------------------
ans-it is interface present in java.lang package , used to Natural default sorting
order, it contain only one mehtod- compareTo().
ex it return 3 value
+ for above element
0 for same element
- for back element
if null -then null pointer excption.
Q- what is Comparator ?
-----------------------
-> it is interface present in java.util package.
1 in java.lang in java.util
2 for Defualt Natural Soring order for Customized Sorting
Order
3 one mehtod- compareTo() two method:- compare() ,
equals()
programme for Comparator:-[insert into string object treeset and order is reverse
of alphabatical]
----------------------------
ex:
import java.util.*;
class TreeSetDemo
{
Public static void Main(st[args])
{
TreeSet t = new TreeSet(new MyComparator());
t.add("Roja");
t.add("Sobha");
t.add("Ansual");
sop(t);
}
}
return s2.compareTo(s1);
}
}
code:
import java.util.*;
class IteratorDemo
{
Public static void Main(str[args])
{
ArrayList L = new ArrayList();
for(int i=0; i<=10 ; i++)
{
L.add(i);
}
sop(L);
while(itr.hasNext())
{
Integer i=(Integer)itr.next();
Sop(i)
}
}
}
Q Diff bw
---------
Enumerator Iterator ListIterator
List(i) [1.2v]:
===================
1- its child interface of collection interface.
2- duplicate are allowed
3- insertation order is preserved.
Note:- in 1.2v vector and stack classes are impl to impl List interface.
---------------------------
3 : Set(i) :
-------------
3 : Set(i) :
------------
>- child interface of collecion,
>- duplicate not allowed
>- insertion order not preserved(save in diff order)
4 : SortedSet(i):
-----------------
>- its child of Set interface
>- without duplicate but according to some sorting order.
5 : NavigableSet(i):
--------------------
>- child interface of SortedSet.
>- it Define several method for Navigation purpose.
-------------------------------------
7 : Map(i) :
-----------
>Note:-its not child of any collection interface.
>used to represent a group of object as Key-value pairs
>duplicate key not allowed but value can be duplicate.
8 : SortedMap(i) :
------------------
> its child of Map interface
> used to represent group of objects as Key-value with some sorting order.
> sorting based on key but not based on value.
9 : NavigableMap(i) :
---------------------
its child of SortedMap
>it define several method for navigation purpose.
List Q:
Collection(i) [1.2]
|
List(i) [1.2]
|
-------------------------------------------------------
| | |
ArrayList(c) [1.2] LinkedList(c) [1.2] Vector(c)[1.2]
|
Stack(c)[1.2]
ARRAYLIST(I):
----------------------
**IMP-NOTE:-ARRAYLIST best sutaible for retrival operations but
worst case if our operation is insertation or deletation in middile.(it
req several shift operation).
>underlying data structure for arraylist is "resizable array or growable array".
>duplicate allowed.
>insertion order is preserved.
>Heterogenous obj are allowed.
>null allowed.
*Note:- Except TreeSet and TreeMap everwhere heterogenuous object are allowed.
LinkedList:
---------------------
Note:-Best choice for our operation is - insertation or deletation in midile. but
worst choice for :- retrival.
>underlying data structur is "Double LinkedList"
>insertation order is preserved
>duplicate allowed
>hetero..obj is allowed.
>null is possible.
Note:- impl Serializable and Clonable interface but not RandomAccess interface.
LinkedList:
---------------------
Note:-Best choice for our operation is - insertation or deletation in midile. but
worst choice for :- retrival.
>underlying data structur is "Double LinkedList"
>insertation order is preserved
>duplicate allowed
>hetero..obj is allowed.
>null is possible.
Note:- impl Serializable and Clonable interface but not RandomAccess interface.
Set Q:-
Set(i) :
------------
>- child interface of collecion,
>- duplicate not allowed
>- insertion order not preserved(save in diff order)
LinkedHashSet: [imp]
=======================
> its child class of hashset
> underlying data structur is combination of LinkedList and Hashtable.
> insertation order is preserved
> Duplicate are not allowed . if we are trying then no CE, RE, only get False
Return.
> Null insertation is allowed.
> Heterogenous objects are allowed.
Note:=> HashSet impl Serializable and Clonable interface but not RandomAccess.
> Best for search operation.
> it is exactally same as HashSet except following diff.
TreeSet:
------------------
> underlying Data Structure is balanced Tree.
> insertation order is not preserved and it is based on some Sorting order.
> Heterogenous objects are not allowed, if we are trying then we will get RE-
ClassCastException.
> null Insertion is allow (Only Once)
IMP NOTE:-> impl Serializable and Clonable interfaces but not RandomAccess
interface.
** DIFF BW:
-----------
-----------------------------------------------------------------------------------
--------------------------------------------
Map Q:
-----------------------------------------------------------------------------------
----Dictionary(AC) [1.0]
| | | |
|
HashMap(i) WeakHashMap(i) IdentityHashMap(i) SortedMap(i)[1.2]
Hashtable [1.0]
[1.2] [1.2] [1.4] |
|
NavigableMap(i) [1.6]
Properties [1.0]
|
TreeMap(i) [1.6]
MAP(I):
===========
> map is not child of collection.
> if we want to represent a group of objects as a key-vlaue pairs then go for Map.
> Both key and values are objects only.
> Imp:->Duplicate Key not allwed but values can be duplicated.
HashMap:
-----------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)
LinkedHashMap:
-----------------
> its child class of HashMap.
> Note:- insertion order is preserved.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)
> its exactally same as HashpMap except following differences
**IdentityHashMap:
------------------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)
>exactally same as HashMap except following diff.
1 in HashMap jvm will use .equals() to identify duplicate keys, which mean for
content comparision.
but
in IdentityHashMap jvm will use == operator to identify duplicate keys, which is
mean for reference comparision.
WeakHashMap :
---------------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times).
Note 1: in case of HashMap, Dominates Garbage Collector, that mean if Object does
not have any ref still it is not Eligible for
garbage collector it is associated with HashMap.
Note 2: but in case of WeakHashMap if an Object does not contain any ref then it is
always Eligible for GC even though it is associated with
WeakHashMap.
that mean Garbage collector Dominate WeakHashMap.
** SortedMap :
--------------
>its child interface of Map.
>it represent according some sorting order of keys.
METHODS:
--------
>SortedMap defines the following methods.
1 Object firstKey()
2 Object lastKey()
3 SortedMapheadMap(Object key)
4 SortedMaptailMap(Object key)
5 SortedMapsubMap(Object key1, Object key2)
6 Comparator comparator()
** TreeMap:
-----------
>underlying data structur is : Red Black Tree.
>duplicate keys are not allowed but values can be duplicate.
>insertion order is not presrved,
> its based on some sorting order of keys.
Note 1:- if we denpend on Default Natural Sorting Order then keys should be :
Homogenous and Comparable.
else we get RE-Class cast exception
Note 2:- if we define our own sorting by Comparator then Keys can be Heterogenous
and Non-Comparable.
but
There is no restriction on values, they can be Heterogenous and Non
Comparable.
**Hashtable :
--------------
>underlying data structur for Hashtable is Hashtable only.
>Duplicate keys are not allowed. but values can be duplicate.
>insertion order is not preserved and its based on Hashcode of the keys.
>Heterogenous objects are allowed for both keys and values.
>null insertion is not posible for both key and values. we get :-NPE.
Properties:
==============
>it is child class of Hashtable.
use Properties Object to hold Properties which are comming from Properties File.
>if anything which changes frequently (like DB username, password, urls etc) never
Recommended to Hard Code in prog.
bcoz for every changes in source file we have to Recompile, Rebuild and
Redeploying apps and some times server restart also req.
HashMap:
-----------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)
TreeMap:
-----------
>underlying data structur is : Red Black Tree.
>duplicate keys are not allowed but values can be duplicate.
>insertion order is not presrved,
> its based on some sorting order of keys.
Note 1:- if we denpend on Default Natural Sorting Order then keys should be :
Homogenous and Comparable.
else we get RE-Class cast exception
Note 2:- if we define our own sorting by Comparator then Keys can be Heterogenous
and Non-Comparable.
but
There is no restriction on values, they can be Heterogenous and Non
Comparable.
**Hashtable :
--------------
>underlying data structur for Hashtable is Hashtable only.
>Duplicate keys are not allowed. but values can be duplicate.
>insertion order is not preserved and its based on Hashcode of the keys.
>Heterogenous objects are allowed for both keys and values.
>null insertion is not posible for both key and values. we get :-NPE.
or
diff bw HashMap, LinkedHashMap , TreeMap ?
-----------------------------------------------
HashMap LinkedHashMap
TreeMap
import java.util.*;
class HashMapDemo
{
Public static Void main(st[args])
{
HashMap m = new HashMap();
m.put("Chiru" , 300);
m.put("Bala" , 500);
m.put("Ashish" , 400);
sop(m); //
Collection c=m.values();
sop(c);
Set s1=m.entrySet();
or if(m1.getKey().equals("Naag"))
{
m1.setValue(1000);
}
}
sop(m);
}
}
TreeSet:
------------------
> underlying Data Structure is balanced Tree.
> insertation order is not preserved and it is based on some Sorting order.
> Heterogenous objects are not allowed, if we are trying then we will get RE-
ClassCastException.
> null Insertion is allow (Only Once)
IMP NOTE:-> impl Serializable and Clonable interfaces but not RandomAccess
interface.
TreeMap:
-----------
>underlying data structur is : Red Black Tree.
>duplicate keys are not allowed but values can be duplicate.
>insertion order is not presrved,
> its based on some sorting order of keys.
Note 1:- if we denpend on Default Natural Sorting Order then keys should be :
Homogenous and Comparable.
else we get RE-Class cast exception
Note 2:- if we define our own sorting by Comparator then Keys can be Heterogenous
and Non-Comparable.
but
There is no restriction on values, they can be Heterogenous and Non
Comparable.
Q If I want to make user defined class as a key within HashMap then which methods
do I need to override?
equals() and hashCode().
-----------------------------------------------------------------------------------
----------------
HashMap:
-----------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)
WeakHashMap :
---------------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times).
Note 1: in case of HashMap, Dominates Garbage Collector, that mean if Object does
not have any ref still it is not Eligible for
garbage collector it is associated with HashMap.
Note 2: but in case of WeakHashMap if an Object does not contain any ref then it is
always Eligible for GC even though it is associated with
WeakHashMap.
that mean Garbage collector Dominate WeakHashMap.
Concurrent collections :
---------------------------
1 Concurrent collections are thread safe
2 performance is more because of diff Locking Mechanism.
3 while one thread interacting collection the other thread allowed to modify
collection in safe manner.
ConcurrentHashMap(C):
=====================
> underlying data structur is Hashtable
>ConcurrentHashMap allows Concurrent Read and Thread safe update operations.
to perform Read operation thread will not require any Lock. but
to perform update operation thread requires Lock but it is lock of a perticular
part of Map.
Note:- instead of whole Map concurrent update achived by internally dividing Map
into smaller Portion which is defined by
Concurrency Level.
Note:- while one thread iterating , the other thread can perform update operation
and ConcurrentHashMap never threw ConcurrentModificationException
HashMap ConcurrentHashMap
-----------------------------------------------------------------------------------
---------------------------------------
1 not thread safe 1 thread safe
2 performance is high, not req to thread wait 2 performance is low, req
to thread wait.
3 while one thread iterating , other thread not allowed to modity.
3 while one thread iterating , other
thread allowed to modity.
5 null is allowed for both keys and values 5 null is not allowed for
both keys and values-get=>NPE
-----------------------------------------------------------------------------------
--------------------------------------
HashMap:
-----------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)
** HashMap:
-----------
> Underlying data structure is Hashtable.
> Duplicate key not allowed but values can be duplicated.
> heterogenous objects are allowed for both keys and values.
> insertion order is not preserved and its based on hashCode of keys.
> Note:- null (once) is allowed for key and allowed for values (any numbers of
times)
weakhashmap :
-------------
>Exactally same as HashMap Except following Diff-
Note 1: in case of HashMap, Dominates Garbage Collector, that mean if Object does
not have any ref still it is not Eligible for
garbage collector it is associated with HashMap.
Note 2: but in case of WeakHashMap if an Object does not contain any ref then it is
always Eligible for GC even though it is associated with
WeakHashMap.
that mean Garbage collector Dominate WeakHashMap.
Q where we are using security in our project and what kind of security is it?
------------------------------------------------------------------------------
ans:
we use filter security for User Login and
CODEC(Base64) security for Customer Operations using EDI.
filter security:-
what is Filters-> o A Filter is an interface. It provides request & response
filtering before processing.
o It works based on Servlet URL matching.
o Filter should be configured in web.xml, using Servlet URL pattern. It can /*
also to specify all request filtering.
o Filter also contains life-cycle methods
1. init()
2. doFilter()
3. destroy()
o init() and destroy() are executed only one time.
o Filter supports init parameters from web.xml
or
The main difference between HashMap and TreeMap actually reflect the main
difference between a Hash and a Binary Tree , that is, when iterating, TreeMap
guarantee can the key order which is determined by either element's compareTo()
method or a comparator set in the TreeMap's constructor.
or
HashMap is implemented as a hash table, and there is no ordering on keys or values.
or
HashMap on the other hand, makes no such guarantee. Therefore, when iterating over
the keys of a HashMap, you can't be sure what order they will be in.
TreeMap is an example of a SortedMap, which means that the order of the keys can be
sorted, and when iterating over the keys, you can expect that they will be in
order.
HashMap will be more efficient in general, so use it whenever you don't care about
the order of the keys.
or
HashMap only works with objects with a suitable hashCode() implementation. TreeMap
only works with Comparable objects,
or
HashMap allows null key and null values (Only one null key is allowed). If TreeMap
uses natural ordering or its comparator, does not allow null keys, an exception
will be thrown.
or
HashMap is used for fast lookup, whereas TreeMap is used for sorted iterations over
the map.
The HashMap is a general purpose Map (hash table data structure), which should be
used whenever you need a hashing-based data structure for storing your mappings
(key-value pairs).
or
TreeMap is a Red-Black tree based NavigableMap implementation provides you sorting,
on top of hashing offered by Map interface.
or
HashMap: Lookup-array structure, based on hashCode(), equals() implementations,
O(1) runtime complexity for inserting and searching, unsorted
TreeMap: Tree structure, based on compareTo() implementation, O(log(N)) runtime
complexity for inserting and searching, sorted
or
HashMap -- implement basic map interface
implemented by an array of buckets, each bucket is a LinkedList of entries
running time of basic operations: put(), average O(1), worst case O(n), happens
when the table is resized; get(), remove(), average O(1)
not synchronized, to synchronize it: Map m = Collections.synchronizedMap(new
HashMap(...));
Iteration order of the map is unpredictable.
TreeMap -- implement navigable map interface
implemented by a red-black tree
running time of basic operations: put(), get(), remove(), worst case O(lgn)
not synchronized, to synchronize it: SortedMap m =
Collections.synchronizedSortedMap(new TreeMap(...));
provide ordered iteration. higherKey(), lowerKey() can be used to get the successor
and predecessor of a given key.
or
When to Prefer TreeMap over HashMap :-
1. Sorted elements are required instead of unordered elements. The sorted list
return by TreeMap is always in ascending order.
2. TreeMap uses Red-Black algorithm underneath to sort out the elements . When one
need to perform read/write operations frequently , then TreeMap is a good choice.
wait() sleep()
The thread which calls wait() method releases the lock it holds. The thread which
calls sleep() method doesn�t release the lock it holds.
The thread regains the lock after other threads call either notify() or notifyAll()
methods on the same lock. No question of regaining the lock as thread doesn�t
release the lock.
wait() method must be called within the synchronized block.sleep() method can be
called within or outside the synchronized block.
wait() method is a member of java.lang.Object class. sleep() method is a member of
java.lang.Thread class.
wait() method is always called on objects. sleep() method is always called on
threads.
wait() is a non-static method of Object class. sleep() is a static method of
Thread class.
Waiting threads can be woken up by other threads by calling notify() or notifyAll()
methods. Sleeping threads can not be woken up by other threads. If done so,
thread will throw InterruptedException.
To call wait() method, thread must have object lock. To call sleep() method,
thread need not to have object lock.
-----------------------------------------------------------
program to sort an array with some specific scenarios ?
import java.util.Scanner;
class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];
or
Java version of this program is given bellow :
for(int i=0;i<array.length;i++)
System.out.println("Array[" + i + "] = " + array[i]);
int search_element=55;
int find_index=-1;
for(int j=0;j<(array.length-1);j++){
if(array[j]==search_element){
find_index=j;
break;
}
}
if(find_index!=-1){
System.out.println(" The search element is : " + search_element);
System.out.println(" It is found in the array at position : " +
find_index);
}
else
System.out.println("\n The search element is not found in the array.");
}
}
or
ans
Java program to search an element in an array
package com.tcc.java.programs;
import java.util.*;
public class ArrayLinearSearch {
public static void main(String args[]) {
int count, num, i;
int[] inputArray = new int[500];
if(i == count)
System.out.println(num + " not present in input array");
}
}
Output
Enter number of elements
6
Enter 6 elements
3 8 7 2 9 4
Enter element to search
7
7 is present at index 2
Enter number of elements
7
Enter 7 elements
3 8 12 8 11 0 -4
Enter element to search
5
5 not present in input array
and
We can create a java program to sort array elements using selection sort.
we search for the lowest element and arrange it to the proper location. We swap the
current element with the next lowest number.
ex:
public class SelectionSortExample {
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
=================================================================
colls
----
---
AD
---
2- using eclipse:- r-click on 'server [below]' -> open / F3 -> goto Port menu ->
select -> HTTP/1.0- port- change port
-> then cancel tabe from and it will ask to save then yes.
-----------------------------------------------------------------------------------
---------
[<protocol>://]localhost:<port>/folder/resourceName
or
NOTE:-Later if you want to update changes for the application, you must both
replace the WAR file and delete the application�s unpacked directory, and then
restart Tomcat.
Q jee architecture ?
------------------------
ans - ecplain self
Following table lists out the nine Implicit Objects that JSP supports -
S.No. Object & Description
1 request
This is the HttpServletRequest object associated with the request.
2 response
This is the HttpServletResponse object associated with the response to the client.
3 out
This is the PrintWriter object used to send output to the client.
4 session
This is the HttpSession object associated with the request.
5 application
This is the ServletContext object associated with the application context.
6 config
This is the ServletConfig object associated with the page.
7 pageContext
This encapsulates use of server-specific features like higher performance
JspWriters.
8 page
This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
9 Exception
The Exception object allows the exception data to be accessed by designated JSP.
or
==
A list of the 9 implicit objects is given below:
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
HttpServlet:
HttpServlet class is the direct subclass of Generic Servlet.
HttpServlet is protocol dependent. It handles only http protocol.
HttpServlet supports public void service(ServletRequest req,ServletResponse res )
and protected void service(HttpServletRequest req,HttpServletResponse res).
HttpServlet supports also
doGet(),doPost(),doPut(),doDelete(),doHead(),doTrace(),doOptions()etc.
HttpServlet is Stateful.
spring
======
Q spring structure folder with maven ?
--------------------------------------
Q spring MVC work flow ? how recognize view extenstion if i want to go for html ?
---------------------------------------------------------------------------------
ans:-viewresolver resolve take this responsibility.
Q- @component ?
-------------
Q- spring scopes ?
------------------
Q-@repository
--------------
Q What is transaction?
----------------------
Q where we are using security in our project and what kind of security is it?
1- two spring security read......
what is the drawback of creating direct object of another class by using HAS-A
relation?
Advantage of HQL-
database independent
supports polymorphic queries
Query Interface
---------------
The object of Query can be created by createQuery() method of Session interface.
ex:-to get all the records
Query query=session.createQuery("from Emp");
List list=query.list();
[*****criteria :-***]
The Hibernate Session interface provides createCriteria() method, which can be used
to create a Criteria object.
use add() method to add restriction for a criteria query.
Criteria Interface:-
The Criteria interface provides many methods to specify criteria. The object of
Criteria can be obtained by calling the createCriteria() method of Session
interface.
example to add a restriction to return the records with salary is equal to 2000 -
Criteria cr = session.createCriteria(Employee.class);
cr.add(Restrictions.eq("salary", 2000));
List results = cr.list();
3-HQL doesn�t support pagination concept, but we can achieve pagination with
Criteria
4-Criteria used to take more time to execute then HQL
5-Criteria we are safe with SQL Injection because of its dynamic query generation
but in HQL as your queries are either fixed or parametrized, there is no safe
from SQL Injection.
**Note:-
@ModelAttribute annotation is used as part of a Spring MVC web app and can be used
in two scenarios.
Firstly, it can be used to inject data objects before a JSP loads. ...
Secondly, it can be used to read data from an existing model assigning it to
handler method parameters.
http://localhost:8080/springmvc/hello/101?param1=10¶m2=20
In the above URL request, the values for param1 and param2 can be accessed as
below:
Inversion of control means the way of managing the dependency the dependent object
will be injected to the target object
it is inverse process of managing the dependency that�s it is called Inversion of
control.
spring we can achieve inversion of control by configuring the spring bean in
�spring bean configuration file�.
? If spring framework is creating the object and establish the dependency with
other objects we call it as inversion of control.
? If spring need to take care of creating the object and establishes the dependency
we need to configure the spring bean in spring bean configuration
file(applicationContext.xml).
1 Setter Injection:
When the dependent object will be injected in to target object via setter method
then it is called setter injection.
2 Constructor Injection:
When the dependent object will be injected in to target object via constructor then
it is called constructor injection.
Constructor
1. In constructor injection the dependent object will be created and injected
while creating the target object through constructor. Means we can access the
dependent object in constructor of target object.
In setter injection the dependent object will be injected after the target object
will be created means we can�t access the dependent object in constructor.
2 Constructor injection is mandatory because it will not create the object until we
pass something to the constructor. Means if we want injection is mandatory then we
can use constructor.
Setter injection is optional means without setting the property tag also we can
create the objects.
2- if bean class contains more than one properties and there is no need to making
all properties participating in depedency injection
then go for Setter injection
Setter Constructor
-----------------------------------------------------------------------------------
------------------------------------------------
1- <property> tag is required 1- <constructor-arg> tag
is required
2- inject after creating bean so its delay 2- inject while
creating bean so no delay
3- support cyclic DI 3- no support
4- to n no setter n no of setter is req 4 to n no of
const , n no of const not req
5- if all properties are configured then container use 0 param const 5- if any
any property is configured container use
parameterized cosnt
6 Setter injection is optional means
without setting the property tag also we can create the objects.
6 Constructor injection is
mandatory because it will not
create the object until we pass something to the constructor.
merge:-
merge can be used to update existing values, however this method create a copy from
the passed entity object and return it. The returned object is part of persistent
context and tracked for any changes, passed object is not tracked. This is the
major difference with merge() from all other methods.
Merge: Suppose we are creating a session and load an employee object. Now object in
session cache. If we close the session at this point and we edit state of object
and tried to save using update() it will throw exception. To make object persistent
we need to open another session. Now we load same object again in current session.
So if we want to update present object with previous object changes we have to use
merge() method. Merge method will merge changes of both states of object and will
save in database.
Merge:-> if you want to save your modifications at any time with outknowing about
the state of an session, then use merge() in hibernate.
If we call merge() method, then it verifies whether the same object is existed in
the cache or not. If the object is existed in the cache then changes are copied in
to the cache. other wise it will load the values to cache.Hence it doesn�t throw
any exception
2. session.get()
It always hit the database and return the real object, an object that represent the
database row, not proxy.
If no row found , it return null.
Use this method if it is not sure that the objects exist.
Q JSTL tags?
------------
ans:- see in internet
Q tell me JDBC steps ?
----------------------
There are 5 steps to connect any java application with the database in java using
JDBC. They are as follows:
2-Creating connection:
ex:Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","pas
sword");
3-Creating statement:
Statement stmt=con.createStatement();
4-Executing queries
ex:
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5-Closing connection
ex: con.close();
--------------------
Import the packages: Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.
Register the JDBC driver: Requires that you initialize a driver so you can open a
communication channel with the database.
Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.
Extract data from result set: Requires that you use the appropriate
ResultSet.getXXX() method to retrieve the data from the result set.
Clean up the environment: Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.
Q collection herairchy ?
-----------------------
and:-
---------------------------
3 : Set(i) :
-------------
Map(i) [1.2]
|
-----------------------------------------------------------------------------------
----Dictionary(AC) [1.0]
| | | |
|
HashMap(i) WeakHashMap(i) IdentityHashMap(i) SortedMap(i)[1.2]
Hashtable [1.0]
[1.2] [1.2] [1.4] |
|
NavigableMap(i) [1.6]
Properties [1.0]
|
TreeMap(i) [1.6]
Q prepaired , connection , what these are class or interface in jdbc ?
----------------------------------------------------------------------
1 Connection interface:-
A Connection is the session between java application and database. The Connection
interface is a factory of Statement, PreparedStatement, and DatabaseMetaData
2 Statement interface:-
The Statement interface provides methods to execute queries with the database
3 ResultSet interface
The object of ResultSet maintains a cursor pointing to a row of a table.
4 PreparedStatement interface:-
The PreparedStatement interface is a subinterface of Statement. It is used to
execute parameterized query.
=>Why use PreparedStatement?
Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
Q @transient spring ?
---------------------
ans:-
JPA's @Transient annotation is used to indicate that a field is not to be persisted
in the database,
Q- spring MVC work flow ? how recognize view extenstion if i want to go for html ?
can i configure 2 extenstion ?
-----------------------------------------------------------------------------------
---------------------------------
ans:-
Client(1) --> Dispatcher Servlet(2) --> Handler Mapping(3) --> Controller(4) -->
ModelAndView(5) -->Dispatcher Servlet(6)--> viewResolver(7) --> View(8) -->
Client(1)
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter
{
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer)
{
configurer.defaultContentType(MediaType.APPLICATION_XML);
}
}
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="defaultContentType" value="application/xml" />
</bean>
-----------------------------------------------------------------------------------
----
Q what is @ModelAttribute ?
-----------------------------
I always use @ModelAttribute to catch object from spring form jsp
method argument indicates the argument should be retrieved from the model
ex:- public String controllerPost(@ModelAttribute("Book") Book book)
{
}
1.Method annotation
@ModelAttribute(�cities�)
public List<String> checkOptions()
{
return new Arras.asList(new[]{�Sofia�,�Pleven","Ruse�});
}
Purpose of such method is to add attribute in the model.
So in our case cities key will have the list new Arras.asList(new[]
{�Sofia�,�Pleven","Ruse�}) as value in the Model
(you can think of Model as map(key:value)).
@ModelAttribute methods in a controller are invoked before @RequestMapping methods,
within the same controller.
2.Method argument
Q how to read all data of object using HQL ? write HQL query ?
----------------------------------------------------------------
Query Interface:-
The object of Query can be created by createQuery() method of Session interface.
ex:-to get all the records
Query query=session.createQuery("from Emp");
List list=query.list();
Inversion of control means the way of managing the dependency the dependent object
will be injected to the target object
it is inverse process of managing the dependency that�s it is called Inversion of
control.
spring we can achieve inversion of control by configuring the spring bean in
�spring bean configuration file�.
? If spring framework is creating the object and establish the dependency with
other objects we call it as inversion of control.
? If spring need to take care of creating the object and establishes the dependency
we need to configure the spring bean in spring bean configuration
file(applicationContext.xml).
DI:-
Dependency injection means injecting the dependent object to the target class
through setter or constructor with the help of underlying ioc container.
Advantage of IOC:-
The IOC creates the spring bean objects and automatically injected to the target
class, Only you need to configure the beans with properties.
Your code is clean and readable.
Codes are loosely coupled.
More reusable as the implementations are configured in the XML file, it can be used
in a different context.
Code can be easily testable with different mock implementation.
Your application will be loosely coupled with the help of IOC and Strategic design
pattern.
DI drowback:
------------
Dependency Injection disadvantages:
=> forces developers to use an injection framework like Spring. This causes
dependency on a framework.
=> clients are dependent on the configuration data. This becomes extra task for
developers when the application does not need so many custom configuration values.
1) singleton: -
Returns a single bean instance per Spring IoC container.
Only one instance of the bean per spring container(Default Scope)
It returns a single bean instance per Spring IoC container.This single instance is
stored in a cache of such singleton beans, and all subsequent requests and
references for that named bean return the cached object.If no bean scope is
specified in bean configuration file, default to singleton.
2) prototype:-
Returns a new bean instance each time when requested.
A new instance every time a bean is requested
It does not store any cache version like singleton.
This bean scope just reverses the behavior of singleton scope and produces a new
instance each and every time a bean is requested.
3) request:-
Returns a single instance for every HTTP request call.
single bean instance per HTTP request
4) session:-
Returns a single instance for every HTTP session.
single bean instance per HTTP session
As soon as user ends its session, bean is out of scope.
5) global session:-
global session scope is equal as session scope on portlet-based web applications.
single bean instance per global HTTP session, it's using in portlet applications.
only valid when used in a portlet context. Only valid in the context of a web-aware
Spring ApplicationContext.
*default means when no scope is explicitly provided in the <bean /> tag.
If no bean scope is specified in bean configuration file, then it will be by
default 'singleton'.
@Scope("session")
public class DemoBean
{
//Some code
}
SQL INNER JOIN also known as simple join is the most common type of join.
1-(INNER) JOIN: Returns matching values in both tables
ex:
SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;
2-LEFT (OUTER) JOIN: Return all records from the left table, and matched records
from the right table
ex:
LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2 ON table1.column_name = table2.column_name;
3-RIGHT (OUTER) JOIN: Return all records from the right table, and the matched
records from the left table
ex:
SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
4-FULL (OUTER) JOIN: Return all records when there is a match in either left or
right table
ex:
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;
5-SELF JOIN
A self JOIN is a regular join, but the table is joined with itself.
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
3)what is group by clause in sql?
----------------------------------
SQL GROUP BY Statement
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN,
SUM, AVG) to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
or
The GROUP BY clause must follow the conditions in the WHERE clause and must precede
the ORDER BY clause if one is used.
-
4)what is method overridding? with use case? why we prefer Polymorphism over
inheritance?
-----------------------------------------------------------------------------------
------
Q where we are using security in our project and what kind of security is it?
------------------------------------------------------------------------------
ans:
we use filter security for User Login and
CODEC(Base64) security for Customer Operations using EDI.
filter security:-
what is Filters-> o A Filter is an interface. It provides request & response
filtering before processing.
o It works based on Servlet URL matching.
o Filter should be configured in web.xml, using Servlet URL pattern. It can /*
also to specify all request filtering.
o Filter also contains life-cycle methods
1. init()
2. doFilter()
3. destroy()
o init() and destroy() are executed only one time.
o Filter supports init parameters from web.xml
8)What is transaction?
Q what is immutaiblity ?
Q-what auto-wiring ?
Q- @component
Q-@repository
Q what is autowire ?
Q jee architecture ?
Q what is singleton class and how to create our own singleton class ?
---------------------------------------------------------------------
Q How to create our own immutaible class ?
**Advantages
**Disadvantages
Slow: SOAP uses XML format that must be parsed to be read. It defines many
standards .
So it is slow and consumes more bandwidth and resource.
WSDL dependent: SOAP uses WSDL and doesn't have any other mechanism to discover the
service.
or
SOAP:-
->soap is webservice to connect two diff apps using xml req and response
->it completely depend on xml
->soap follow SOA(service oriented architechtur) design.
->soap objects are created by using JAXB
->soap mainly works based on WSDL(web services discription language) , which
provide details of skelton(provider) like classes, method name, their
parameters , return type.
->JAX-WS: -> is a Java programming language API for xml web services,particularly
SOAP services.
JAX-WS is one of the Java XML programming APIs.
HTTP Methods
The following HTTP methods are most commonly used in a REST based architecture.
GET - Provides a read only access to a resource.
PUT - Used to create a new resource.
DELETE - Used to remove a resource.
POST - Used to update an existing resource or create a new resource.
OPTIONS - Used to get the supported operations on a resource.
or
Web services based on REST Architecture are known as RESTful Web Services.
These web services use HTTP methods to implement the concept of REST architecture.
A RESTful web service usually defines a URI (Uniform Resource Identifier), which is
a service that
provides resource representation such as JSON and a set of HTTP Methods.
or
Restfull web service is process of sending data in some format( Text, HTML, XML and
JSON.)
Rest full is light weight architectur./ it require less memory.
REST stands for REpresentational State Transfer.
REST is an architectural style .
In the REST architectural style, data and functionality are considered resources
and are accessed using Uniform Resource Identifiers (URIs)
**Advantages of RESTful Web Services
1 Fast: RESTful Web Services are fast because there is no strict specification like
SOAP.
It consumes less bandwidth and resource.
2 Language and Platform independent: RESTful web services can be written in any
programming language and executed in any platform.
3 Can use SOAP: RESTful web services can use SOAP web services as the
implementation.
4 Permits different data format: RESTful web service permits different data format
such as Plain Text, HTML, XML and JSON.
There are many differences between SOAP and REST web services. The important 10
differences between SOAP and REST are given below:
Soap Web-services :
If your application needs a guaranteed level of reliability and security then go
for SOAP.
Totally stateless operations: for stateless CRUD (Create, Read, Update, and Delete)
operations.
Caching situations: If the information needs to be cached.
WSDL:
WSDL is an acronym for Web Services Description Language.
WSDL is a xml document containing information about web services such as method
name, method parameter and how to access it.
WSDL is a part of UDDI. It acts as a interface between web service applications.
WSDL is pronounced as wiz-dull.
Note-using WSDL WE CAN UNDERSTAND-
Port / Endpoint � URL of the web service
Input message format
Output message format
Security protocol that needs to be followed
Which protocol the web service uses
UDDI:
UDDI is an acronym for Universal Description, Discovery and Integration.
UDDI is a XML based framework for describing, discovering and integrating web
services.
UDDI is a directory of web service interfaces described by WSDL, containing
information about web services.
------------
XML [extensible markup lanugae]-> used to transfer data from one app to another
DTD [document type definition]-> provides rules to xml file, and DTD contains of
Element and Attributes.
XSD [xml schema design]-> xsd provide rules to write xml file, and data type also.
-----------------------------------------------------------------------------------
---------------
Q- spring scopes ?
Q- what is JSON ?
Q- Autowired ?
Program:
Procedure name: myproc
SQL> create or replace procedure myproc
2 as
3 begin
4 insert into emp values(1,'eone',1000);
5 end myproc;
6 /
Procedure created.
Program: OurCallableStatementCreator.java
package org.students;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import org.springframework.jdbc.core.CallableStatementCreator;
4) If I want to make user defined class as a key within HashMap then which methods
do I need to override?
---> equals() and hashCode().
8) What is Serialization.
2) @autowired annotation
6) What is dependency injection? More places people don't know what is need of
dependency injection and why to use, we need to explain them.
-----------------------------
FINISH--------------------------------------------------------------------
default spring bean configuration every time when we use getBean() method it is
returns the same address bean object. By default the spring container creates only
one singleton object.
In the spring bean configuration file we can use an attribute scope. This attribute
can take any of the following four values. They are:
1) Singleton
2) Prototype
3) Session
4) Request
Note: session and request values are used in we
ased applications.
? By default the scope attribute value is singleton.
? When we run the same above java program by specifying scope=�prototype� everytime
--
How many objects will be created by the spring container for a bean(spring bean)?
? It�s based on a configuration of the spring bean.
15
? If scope=�singleton� it creates one object.
? If scope=�prototype� it creates multiple objects.
--
How do you establish one property dependent on the reference of other object?
? In the spring bean configuration file we use �ref tag� if a property dependent on
address of another object. (or)
? By using �ref tag� we can establish one property dependent on the reference of
other object.
What is a wiring?
? Connecting two different objects is called as wiring.
(Or)
? Establishing the dependency between the objects is called as wiring.
? By default the spring container checks for �reference tag�. If it is not
available then the spring container uses autowire.
? Autowire attribute takes 2 different values. They are:
1) byName
2) byType
What is an autowiring?
? Automatically establishing the dependency between the objects is called as
autowiring.
? By default the autowiring is not enabled. When we say autowire=default the spring
container internally consider autowire=no.
? Autowire is dependent on ref tag. That means if ref tag is not there then only
autowire is enabled.
When the autowiring happen?
? If ref tag is not there then only autowiring is done.
? Autowiring will be enabled only after the wiring is not satisfied.
The ModelAndView object can hold 2 different types of objects. They are:
1) View objects
2) Model objects
? In spring model objects hold the data. This data is used by the view component to
render the data.
In model objects we can store any type of objects like String, ArrayList, Map and
etc.
By default most of the times we display the content in html pages. Sometimes client
would like to render the data in a pdf file (or) ms-excel (or) ms-word.
70
? In majority of the projects we need to develop the reports. Generally the reports
will be in the form of pdfs (or) excel (or) ms-word etc.
? As part of the spring framework they have integrated all the reporting tools.
? As part of spring framework the spring framework has developed set of predefined
classes to simplify the report generations.
? The predefined classes are:
1) AbstractPdfView
2) AbstractExcelView��etc.
? These classes internally uses the reporting tools and generate the pdf document
(or) excel document (or) word document etc.
? The following class will be able to generate the pdf document
There are many differences between object and class. A list of differences between
object and class are given below:
A class is a user defined blueprint or prototype from which objects are created.
It represents the set of properties or methods that are common to all objects of
one type
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be
physical.
fields
methods
constructors
blocks
nested class and interface
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike,
marker, pen, table, car etc.
Object Definitions:
It is a basic unit of Object Oriented Programming and represents the real life
entities.
a object consist of state, behaviour, identity.
ANS:
STATIC:-> For storing data and operate that data common to all instances/references
of objects.
Non-Static:->For storing data and operate that data separately and specified to
every instace / reference of object.
Note:- When class is loaded, JVM provided individual single copy of mem location to
each static variable in method area
only once in a class life time.
Note:- we can not define duplicate name variable in same scope (means same method /
same class),
it may be possible in diff scope like same name in class var and same inside
methods.
NON STATIC MEMBERS:- class level members (vars, methods, blocks) which dont have
static kw in defintion is called
"non-static" member.
Note: - JVM will not provide mem location for these mem by default.
Q-when , where how, and by whom non-static var get memory location ?
ans ->
when-> get mem loc when obj is created
where -> in heap area and in continuous memory location by jvm.
how-> when obj is create with new kw and gets mem loc in continues mem location.
whom-> by JVM
Q-if we modify one object will another object data also be modified ?
ans: No, modification done for one object will not be affected to another object.
bcoz we change object data
using its reference variable.
---------------------