Friday, August 26, 2016

Accolite
Can u Have Static/FInal fields in Abstract and Interface.


PineLabs
Springs Tranaction management
If M1 has transactional and M2 is transactional and M1 call M2 and M2 throws exception what will happen.

Hibernate
What is the Use of 1st Level Cache.
If i call employee using id and again i call it will be stored in First level cache.
Difference Between load and get ?

Where have u implemented the Exception Handling in the Project ?? In Which Layer.
http://www.wikijava.org/wiki/10_best_practices_with_Exceptions#Throw_early_catch_late
Throw Early Catch Late.
Exceptional Handling In Webservices.

RBS
Permgen ?
How to Remove Permgen ?
Class Loaders ?
Java Memory Model ?
Type of Refrences - Weak String Phantom
Thread Loacal and weakhashmap Implementation.
Differnece Between Thread Dump and Heap Dump ?

Written
Given  a binary search tree find the sum of nodes at each level.
Design a Car PArking system

Single Ton Desing and its issues.
Given an Array
101001010101 sort it in constant time.

What is D/B Collections.remove and Iterater.remove.
Why not use Static instead of singleton


Safenet.
Union and INtersection of 2 Arrays.
Given an Array find the Max sum of each given tuple
1 2 3 4 5 for touple 2 viz 12 23 34 45 find the max sum

Design of Gui panel of 1Billion floors building
ISV personality test

Amex
Dead Code
String a = null;
if(a!=null && a.lentgh>0)
Reinterant Locks
Find the 2nd Largest sum of unsorted array.


How spring create proxy classes.
Can cuncurrent hashmap throw concurrent modification exception.

How to sort a very big data.
----------------------------------------- Java-----------------------------------------
{
1.)Hash Code :
Hash Code Contract
The hashcode returned in any invocations must return the same HC
If two objects are equal using EQUALS method than their HC shud be same
Equals : Implements Equivalence operation
Reflexive  x.equals(x) should return true
Symetric x.equals(y) should return true if and only if y.equals(x) returns true.
Transitive  x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true
Consistent  multiple invocations of x.equals(y) consistently return true

It is not mandatory if for 2 unequal objects to have different hashcode.

What are the cases where different object can have same hashcode?
System.out.println("Aa".hashCode()); // 2112
System.out.println("BB".hashCode()); // 2112

2.) Difference b/w equals and == method
== checks for identity. That is whether the two objects are the same object
and point to the same address in memory.

.equals() by default does the same thing, but can be overridden to perform
different equality comparisons.
(i.e. strings are considered equal if they have the same characters in the same order)

Internally first checks with == is equal return true
else check their value char by char

string1 = "Delta";string2=new String("Delta");
string1==string2// False

3.)Collections
{

*******************************************LIST*******************************************
What Data Structre will you use to Store a Dictionary ?

*******************************************LIST*******************************************

What is loadFactor : measure of how full the hash table is allowed to
 get before its capacity is automatically increased.
  Vector(< Java 1.2): Implementation of synchronized ,resizable array.
Default Capacity is 10
When Size is Full capacity Increazes by Double
Can obtain and set the capacity at the runtime
Extends AbstractList
Implements RandomAcces interface
Supports Iterators and Enumerations

Question:How random access interface works internally ??

ArrayList(>Java 1.2): Implementation of Unsynchronized,rezisable Array.
 private transient Object[] elementData
 Default Capacity of 10
 Fast Traversal
 When Size is Full it Increazes by fifty %
 int newCapacity = oldCapacity + (oldCapacity >> 1);
 There is no concept of Dynamic Capacity as in Vector but
initial  capacity can be set in construcor
 Extends AbstractList
 Implements RandomAcces interface

Linked List () : Non Synchronized serializable Doubly-linked list
List and  Deque interfaces.
Best For Quick Insertion and Deletion But Slow For Traversal
Link list has no concept of Capacity or LF and its default size is 0
Extends AbstractSequentialList
Doesnot Implements RandomAcces interface but List/Deque/Clonable/Serializable

*******************************************MAP*******************************************

HashTable(Since Java 1):Synchronized non nullable key/value implemntationof map
Synchronized - Any non key or vallue can be used
(Moved tomap > java2) Must Implement HashCode and Equals
If same key is added it will overwrite
Default Load factor is .75 and Capacity 11
threshold = (int)(newCapacity * loadFactor);
If threshhold is reached new capacity is doubles+1
newCapacity = (oldCapacity << 1) + 1;
Iterators are Failsafe but not guranteed
hastable.elements returns the enumeration of values
hashtable.keys will return the enumeration of keys


HashMap(> Java 1.2) :UnSynchronized - Allows 1 Null key and 1 null value only
Doesnot allows duplicate keys(If same key is added it will overwrite same in case of null)
Default Load factor is .75 and Capacity 16
Internally Uses a Data Structre names as Entry<K,V> which is a kind of Linked List
which is filled when filling the multiple elements with single key
Iterators are Fail Fast
Ordering/Storing of Keys in Hash
Ways to Iterate a HashMap
Get KeySet and Values as Set and
System.out.println(customKeyhashMap.keySet()+":"+customKeyhashMap.values());
Get Iterator on KeySet or Values
Iterator<UserKey> iterator = customKeyhashMap.keySet().iterator();
Get entrySet
Set<Map.Entry<UserKey, Integer>> set = customKeyhashMap.entrySet();
Get Iterator entrySet
Iterator<Map.Entry<UserKey, Integer>> iterator = customKeyhashMap.entrySet().iterator();

Qurstion: What happens when we put values with same key ?
Answer :
Map mymap = new HashMap();
    System.out.println(mymap.put("1","one"));// Null
    System.out.println(mymap.put("1","not one"));//one
    System.out.println(mymap.put("1","surely not one"));//not one
    System.out.println(mymap.get("1"));//surely not one


TreeMap : Is an ordered HashMap[Implements Sorted Map Interface]
: Non Synchronised
:Iterators are Fail Fast

LinkedHashMap : Ordered implementation of HashMap
Will iterate in the order in which the entries were put into the map
Iterators are Fail Fast

ConcurrentHashMap : ConcurrentHashMap doesn't allow null as key or value.
provides better performance over Hashtable and synchronizedMap
Performs better than earlier two because it only locks a portion of Map, instead of whole Map
ConcurrentHashMap is best suited when you have multiple readers and few writers
Iterators are Fail Safe

SynchronisedHashMap :

*******************************************SET*******************************************
HashSet : default initial capacity (16) and load factor (0.75).
Internally Uses hashMap
This class permits the  one null element becoz values
are added as keys of the Hash Map.
Not synchronized
When you iterate through a HashSet the order is unpredictable
Connot sort the elements Using Comparable Interface
Set s = Collections.synchronizedSet(new HashSet(...));
Converting HashSet to sorted set:
TreeSet<Object> treeSet=new TreeSet<>(hashSet);
Converting HashSet to Synchronised sorted set:
SortedSet<Object> sortedSet=
Collections.synchronizedSortedSet(new TreeSet<>(hashSet));

TreeSet : Sorted Set ie TreeSet is maintaining the  Sorting order
this implementation is not synchronized
SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));
If a general Userdefine Objects that are added to TS will be added but
they will not be iterated if its not implementing compareto()
The elements are ordered using their Natural Ordering , or by a Comparator

LinkedHashSet :This implementation spares its clients from the unspecified,
generally chaotic ordering provided by HashSet,
without incurring the increased cost associated with TreeSet.
:Unsynchronised
:,LInkedHashSet maintaining the insertion Order
Collections
before running Collections.binarySearch the elements must be sorted in ascending manner

Question1:If hashset Adds value As keys to the HashMap then what goes to the Value Part??
Hash Set internally declared HashMap as private transient HashMap<E,Object> map;
When A value is added to HashSet it will put the E in the Key Part
and a Static Dummy Object in Second Part.
10.) Diff Between Comparator and Comparable

Comparable(java.lang)  :
Any User Defined Class that Need to Sort any of the Object
must override this class
Exposes public int compareTo(Object o) method
If a class overrides this class than elemnts can be sorted
by Collections.sort() which internall calls Arrays.Sort()
Objects Which Implement Comparable method can be used as Keys in
SortedSet like TreeSet or SortedMap like TreeMap

Ascending this.prop - object.prop

HashSet that relies on the object’s hashCode() and equals() methods,
but the other is TreeSet and relies only on the Comparable interface,
which we didn’t implement for the subclass.


Comparator(java.util) : Any User Defined Class that Need to Sort any of the Object
must not override this class , any third class can override this
It is used to compare to different objects
Exposes public int compare(Object o1,Object o2) method
Also used in cinjuction with Collections.sort(List,Comparator);
It can also be declared anonymously in Collections.sort(List,Comparator);
Used in the scenario where only the class file is available


EnumSet :

Enumeration: Both Defined in java.util
Has only Two Methods - hasMoreElement , nextElement
Used With legacy Classes Vector and HashTable
Doesnot Check for Data Changes while iteration
2 times Faster than iterator

Iterator It is an interface and implemented in each of the collections using them
like linked list.
Array List Implementation Provide
return Iterator Implementations
Has 3 Methods - next, hasNext , remove
return ListIterator Implementations
Allows to traverse in backword direcction
Has  Methods - next, hasNext , remove , previous , haspreviuos , set and Add
What is Difference Between Set and Add Method in LI??
Set Updates the last elemnt returned by next or prevous method

Are iterators thread safe ??
How to make iterators thread safe ??

Iterable : Implementing this interface allows an object to be the
target of the "foreach" statement.

Allows to traverse in backword direc

What is different between Iterator and ListIterator?
We can use Iterator to traverse Set and List collections whereas ListIterator can
be used with Lists only.
Iterator can traverse in forward direction only whereas ListIterator can be used to
traverse in both the directions.
ListIterator inherits from Iterator interface and comes with extra functionalities
like adding an element, replacing an element, getting index position for previous and next elements.

What is a PriorityQueue

An unbounded priority queue based on a priority heap.
The elements of the priority queue are ordered according to their natural ordering[Ordered on the Basis of Ascii],
or by a Comparator provided at queue construction .
A priority queue does not permit null elements.
Does not permit insertion of non-comparable objects (doing so may result in ClassCastException).

What is a difference between Concurrent hash map and Synchronised hash map ?

}
4.)String
{
4.1)String    Immutable amnd Final
Immutable data is data which cannot changed , so it is good to use it in threading.
To make Java Memory more efficient - java set aside an area of memory called
STRING CONSTANT POOL , when a compiler encounters a String Literal , it checks for the
pool first , if exists then the refrence is passed.
4.2) StringBuffer is
Mutable and  all the methods are Synchronized not the class , a class is not synchronised
but all the methods
Deafult Capacity16
Deafult length is 0
Offers function to reverse the string
Doesnot Override Equals and HashCode Method.
4.3) StringBuilder is Mutable but not Synchronized
It is Introduced after Java 1.5
Deafult length0
Deafult Capacity16
Doesnot Override Equals and HashCode Method.
Offers function to reverse the string
Why String buffer and String builder doenot override hashcode and equals method?
while SB and SB are both mutable that means they can change with creating another object.
StringBuffer aa = new SB("aa");
aa.concat("bb"); // aabb
String aa = new String("aa");
aa.concat("bb"); // aa

4.4) StringTokenizer(java.util.*)
Legacy Class since 1.1
Doesnot works on Regex
4.5) String Philisoohy

String string = "ram ram g";
When string is created with double quotes JVM will it in the String Pool
String string = new String("ram ram g");
JVM will create an objects instead of putting it in a String Pool
intern() is used to put the object in String Pool
String Pool is pool of strings stored in Heap Memory
String Pool is based on the Philosophy of Fly Weight Design Pattern
When number of Objects created are huge
Objects Properties are divided into Intrinsic[Unique] and Extrinsic[Set by Client]
4.6) Write a program to print all permutations of String?
}
5.)Serializable
5.1) Serilizable is a marker Interface
5.2  It tells the compiler that the following object can be serialzed
5.3) The object State can be written and transferred over a network
What is the purpose of default serial version id?
The purpose of the serialization version UID is to keep track of different versions
of a class in order to perform valid serialization of objects.
The stream-unique identifier is a 64-bit hash of the
class name, interface class names, methods, and fields.
What Happpens when Serial Version UID is not implemented?
When you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException
How Can you see the suid of an object?
serialver to see serialVersionUID of a serialized object provided by jdk
What are the legal Changes in class after being seralized ?
Add fields
Change a field from static to non-static
Change a field from transient to non-transient
Add classes to the object tree
What are the Illegal Changes in class after being seralized ?
Delete fields
Change class hierarchy
Change non-static to static
Change non-transient to transient
Change type of a primitive field
How can u add serialVersioUID to array of objects.

Are these valid statments ?
private static final int serialVersionUID = 1;
private  final int serialVersionUID = 1;
private static  int serialVersionUID = 1;
All above statments are valid however they wont be used in serialization process.
static final long serialVersionUID = 1L;
This statement is Valid.
Conclusion:If a serializable class have explicit serialVersionUID then this field should be of type long and must be static and final.


5.4) What is the difference between Serializable and Externalizable in Java?
by implementating java.io.Serializable, you get "automatic" serialization capability for objects of yourz class
java.io.Externalizable interface was provided, which is like java.io.Serializable but with custom-written mechanisms to perform the marshalling and unmarshalling functions (you need to implement readExternal and writeExternal methods on your class)
5.5) How collections are seralized?
Collections are all serialized , however any custom object must be seralizable.
For example ArrayList has transiet elements of array hence however it implements its own
readObject and writeObject functions for custom serialization.
5.6) What happens when Seralized object has refrence to the non serialzed object?
It will throw an NotSerializableException
5.7)Static Variables
Are not part of serialization process
Becaouse they are shared by all instances of that class
After unmarshalling - will have Its default initialized values in the class;

5.8)What if you have base class as serializable and don want child class to implement serializable
because child class will autmoatically serialized?
class MySubClass extends SomeSerializableSuperClass {
private void writeObject(java.io.ObjectOutputStream out)
throws IOException {
throw new NotSerializableException(“Can not serialize this class”);
}
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
throw new NotSerializableException(“Can not serialize this class”);
}
private void readObjectNoData()
throws ObjectStreamException; {
throw new NotSerializableException(“Can not serialize this class”);
}
}
5.9)What if the Base class doesnot implement the Serializable and child class does.
The Base class wont be serialized.
5.9) Serialized class
5.10)Serialization provides an easy way for Deep Cloning
5.11)Look for Transient Keyword for more on serialization.
5.12) Array classes cannot declare an explicit serialVersionUID, so they always have the default computed value, but the requirement for matching serialVersionUID values is waived for array classes.
6.)Object's Method
NonFinal Methods ---> equals(), hashCode(), toString(), clone(), and finalize()
6.1) Equals o1.equals(o2) implies o1.hashCode() == o2.hashCode()
6.2) Object.clone() ?? Shallow or Deep Cloning = Shallow Cloning

7.)
Changes in  Java 1.5[Tiger]
Generics
Annotations
Autoboxing and unboxing

Integer int_autoboxing = 10;
this case autoboxing will happen , what will happen is the following
set of java statment
Integer integer = Integer.valueOf(10);
Auto Boxing will happen in 2 cases
Assigment operation - like above
And Function Call - Which is a kind of Assignment operation
Things gets more confusing when "==" comparison is combined with other logical operators
like > and < which does auto unboxing before comparison

int i1 = 1;
int i2 = 1;
System.out.println("i1==i2 : " + (i1 == i2)); // true
// Example 2: equality operator mixing object and primitive
Integer num1 = 1; // autoboxing
int num2 = 1;
System.out.println("num1 == num2 : " + (num1 == num2)); // true
// Example 3: special case - arises due to autoboxing in Java
Integer obj1 = 1; // autoboxing will call Integer.valueOf()
Integer obj2 = 1; // same call to Integer.valueOf() will return same
System.out.println("obj1 == obj2 : " + (obj1 == obj2)); // true
// Example 4: equality operator - pure object comparison
Integer one = new Integer(1); // no autoboxing
Integer anotherOne = new Integer(1);
System.out.println("one == anotherOne : " + (one == anotherOne)); // false
Cached Objects
Since much object is created - there is a need to call garbage collection

Changes in  Java 1.6[Mustang]
Not Much
Changes in  Java 1.7
7.1) JDBC 4.1
7.2) UnderScores Between Numeric Leterals like comma for big number
ling number = 12_324_12323L;
7.3) String as Expression in Switch Statement
7.4) Declaring Resources in Try (only those that implements java.lang.AutoClosoable)
7.5) Multiple Exception in Catch Block
7.6) Any mothod depricated ?
7.7) Introduce a new parallel mechanism for compute intensive tasks, the fork-join framework.
7.8) Objects Class with Extended functions like
requireNonNull();Default To String
Changes in  Java 1.8
1. Lambda expressions
2. Parallel operations
3. Java + JavaScript =
4. New date / time APIs
5. Concurrent accumulators

8.) Generics: . Generics in Java are compile-time constructs,
Stronger type checks at compile time.
Elimination of casts.
Enabling programmers to implement generic algorithms.
8.1)Way To Avoid Overloaded MEthods
8.2) Example  public void <E> static print(T[] a) {for (T z : a) sysout(z);}
8.3)  What is the difference between  A<T extends B> and A<? extends B>?

11.) ObjectLock and Class Lock

12.) What is Fail Safe and Fail Fast
Concurrent Modification ?
When one or more thread is iterating over the collection, in between, one thread changes the structure of the collection
Fail Fast
Fail fast iterator while iterating through the collection , instantly throws Concurrent Modification Exception if there is structural modification  of the collection .
Fail Safe
Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure
13.) Annotations

14.) Transient Key Word : used to indicate that a field should not be serialized.
  When the Transient Keywords are deserialized the are initalized to thier
  default value for example 0 in case of int null for object.
  It is a way to tell the compiler that donot serialize and custom serialization may happen on this variable.b                          
What is a strictfp modifier?
Strictfp ensures that you get exactly the same results from your floating point calculations on every platform. If you don't use strictfp, the JVM implementation is free to use extra precision where available.
It can be applied on Interface Classes , Methods , Abstract classes but not abtract methods..

15.) Volatile Key Word :
The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
Access to the variable acts as though it is enclosed in a synchronized block, synchronized onitself.
Any thread reading volatile field will see the most
recently written value. The volatile keyword will not
perform any mutual exclusive lock on the variable.
Declaring a volatile Java variable means:
What is Difference between Volatile and Synchronised keyword?
Volatile is used on fields while synchronised is used on code blocks and methods.
Synchronise obtaims and release lock on a monitor where as volatile doesnt.
Threads Can got into wait while accessing the Monitor in case of Synchronised,that is not
the case with vloatile.
Synchronize effects the performance.
Synchronize cannot be done on null objects whille Volatile Can be done on null objects
What are the Uses of Volatile Key Word ?
We can use the volatile keyword to R/W on the 64Bit data types becouse many of the platforms will write the 64 Bit in 2 stages i.e 32bit each.In this case it is possible
for the thread to see the 33bit value in between write.
It can be used to achieve the schnronization.
It can be used to Inform the compiler to not do any kind of restructuring or code
optimization - which it doesnot do on volatile keywords, also it will also tell
the compiler to read the value from the main memory and not to cache thread locally.
It can be used for double locking singleton desing pattern.
Volatile Arrays. Declaring an array doesnot means its data is Volatile.
Only the reference is volatile.
16.) Exceptions : Base Class is throwable
Checked :
   Unchecked : Under Error or Runtime ArithmeticException
Errors
Throwable
|
|
------------------
|  |
 ERROR        EXCEPTION
| | |
 [Unchecked] [Checked] |
|
[RunTime Excpetion](Unchecked)
Runtime
Difference Between ClassNotFoundException and NoclassDefferror exception.
String always
Can u catch throwable?
Can u throw a thowable?
In which case Finally block wont execute?

Return
17.) Regular Expression

18.)Difference between abstract and interface
Java interface are implicitly abstract and cannot have implementations.
A Java abstract class can have instance methods that implements a default behavior.

Variables declared in a Java interface is by default final and public.
An  abstract class may contain non-final variables any access modifier.

IMplements
Extends

An interface can extend another Java interface only,
An abstract class can extend another Java class and implement multiple Java interfaces.

Interface is absolutely abstract and cannot be instantiated;
A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.

Interfaces are slow as it requires extra indirection

How can you instantiate the abstract class?
19.) int i;sysout(i) will not compile -
20.)Static Variable cannot be delcared inside static method or block only final is permitted
Are intitalized to 0
Invoking the Static Function from a refrence variable ?
21.)JDBC:It is a standard api for database connectivity
Steps
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
rs.close();
stmt.close();
conn.close();
A prepared statement is an SQL statement that is precompiled by the database.
Callable statements are used from JDBC application to invoke stored procedures and functions.
21.1) What is Class.for.Name
21.2) What are scenarios Where You can Load Your Classes
Class.forName("XYZ"); : to load and initialize the class.It uses classloader of current class.
ClassLoader.getSystemClassLoader().loadClass("XYZ"); :  to load class, but doesn't initialize.You can get an instance of ClassLoader and invoke loadClass()
Class.forName(String name, boolean initialize, ClassLoader loader) : Spcifiy which Class to initialise
21.3) How to call a procedure in JDBC?
Class.forName("com.mysql.jdbc.Driver");
Connection con = getConnection();
CallableStatement cs =con.prepareCall("{call proc_to_call(?,?)}");
Register Variable
ResultSet rs = cs.executeQuery();

22.) Connection Pool Design Pattern
In this mechanism client are not required every time make new connection
and then interact with database instead of that connection objects are stored
in connection pool and client will get it from there

23.) Life Cycle of Servlet

26.) Static and Dynamic Binding
When there is Inheritance , binding comes into picture.
Static Binding is done in the Case of Overloaded Functions.
Also Private ,Static and Final Methods are Binded at compile time.
27.) Constructor Chaining
Calling a constructor from the another constructor of same class is known as Constructor chaining.
28.) System.out.println() ?
Variables define in System Class.
public final static InputStream in = null;
public final static PrintStream out = null;
public final static PrintStream err = null;

PrintStream is having all the print statments.
29.) What is difference in using instanceof and getClass() method for checking type inside equals?
While using Instance of the operator the Object Class is equals the other same object class
and its subclasses - so it breaks the symmetric rule.
IF we use getClass with equals - then only the object must equal to other object
30.) How can u avoid Null Pointer Exception when using equals
Strin str=null;
"abc".equals(str)   -- Will Return False
str.equals("abc")   -- Will throw NPE
What will be the O/P null==str
31.)Why character array is better than String for Storing password in Java
Strings are immutable in Java - they will be stored in memory unless it is garbage collected.
Since String are used in String pool for reusability there is pretty high chance that it
will be remain in memory for long duration, which pose a security threat.
Java itself recommends using getPassword() method of JPasswordField which returns a char[]
With Char Array you won't print contents of array instead its memory location get printed.
32.) How will i get the Memory Dump in Java and How to Analyse that ?
Simple tools like jmap
JVisualVM
commerical tools as JProfiler.
33.) PolyMorphism.
34.)What is difference between Stack and Heap Memory.
35.) What are proxy classes in Java?
36.)
Transient
Static
Final
Volatile

All of the below in a non static context

Can Transient key words be Final ?
Yes Logically :because their behaviuors are different.
For instance, maybe you do not want to serialize your class' logger, then you declared it this way:

private transient final Log log = LogFactory.getLog(EJBRefFactory.class);
Now, when you deserialize the class your logger(log) will be a null object, since it was transient. Then you should initialize the logger manually after serialization or during the serialization process. But you can't, because logger is a final member as well.

Hence the serialVersionUID is always static and final.
Static is becaouse it should not be serialized and final not to be changed.


Can Transient key words be Static ?
Yes - Compiler wont complain - Hypthetically it is for those
conditions were we have our serializing mechanism and static keywords are
schnchronised.
Logical Explanation:Both Transient and Static varible are not serialized.
So while deserialization static variable value will loaded from the class.(Current value will be loaded.) and Transient will be loaded to their default value for example null for object and 0 for int.
In Above Case case which value will be default or from class ?

Can Transient key words be Volatile ?
Yes - Logically Becaouse their behaviours are different.
And Compiler Wont Complain lols :0.
Need to do the actual programm.

Can Static Variables Be Transient ?
Yes Compiler wont compain - see above
Can Static Variables Be Final ?
Yes - they are used all the time with serialversionuid.
Can Static Variables Be Volatile ?
Compiler wont complain - however static variable are stored in class memory and volatile in main memory.

Can Final Variables Be Transient ?
Yes Compiler Wont Complain - see above.
Can Final Variables Be Static ?
Yes - See above.
Can Final Variables Be Volatile ?
No - They behavour are different and they contradict each other.

Can Volatile Variables Be Transient ?
Yes
Can Volatile Variables Be Static ?
Yes
Can Volatile Variables Be Final ?
No

37.)
How Class Loader Works in Java ?
Java class loaders are used to load classes at runtime.
There are three default class loader used in Java,
Bootstrap or Premordial Class Loader : Load Classes from JRE/lib/rt.jar
Extension : JRE/lib/ext or any directory denoted by java.ext.dirs
System or Applicaion class loader : - CLASSPATH environment variable, -classpath or -cp option, Class-Path attribute of Manifest inside JAR file.

ClassLoader in Java works on three principle: delegation, visibility and uniqueness.
Delegation Principle
Suppose you have an application specific class called Abc.class
First request of loading this class will come to Application ClassLoader which will delegate to its parent. Extension ClassLoader which further delegates to Primordial or Bootstrap class loader.
Primordial will look for that class in rt.jar and since that class is not there
Request comes to Extension class loader which looks on jre/lib/ext directory
If class is found there than Extension class loader will load that class
Application class loader will never load that class but if its not loaded by extension class-loader than Application class loader loads it from Classpath in Java.
Visibility Principle
Child ClassLoader can see class loaded by Parent ClassLoader but vice-versa is not true.
Which mean if class Abc is loaded by Application class loader than trying to load class ABC explicitly using extension ClassLoader will throw either java.lang.ClassNotFoundException

Uniquiness Principle
According to this principle a class loaded by Parent should not be loaded by Child ClassLoader again.
Though its completely possible to write class loader which violates Delegation and Uniqueness principles and loads class by itself,

Different Ways of Loading a Class ?
java.java
Different between ClassNotFoundException and NoClassDefFoundError.
1) ClassNotFoundException comes in java if we try to load a class at run-time using with Class.forName() or ClassLoader.loadClass() or ClassLoader.findSystemClass() method and requested class is not available in Java.
NoClassDefFoundError class was present during compile time and let's application to compile successfully and linked successfully but not available during run-time due to various reason.

2) ClassNotFoundException is a checked Exception derived directly from java.lang.Exception class
Class.forName() throws ClassNotFoundException exception,
NoClassDefFoundError is an Error derived from LinkageError.

3) If you are using ClassLoader in Java and have two class loaders then if a ClassLoader tries to access a class which is loaded by another classloader will result in ClassNotFoundException.

4) ClassNotFoundException comes up when there is an explicit loading of class is involved by providing name of class at runtime using ClassLoader.loadClass(), Class.forName(),
while NoClassDefFoundError is a result of implicit loading of class because of a method call from that class or any variable access.


************************************* Maven ************************************************
{
1.) Is their any super pom file in maven ?
What is Effective POM and Super POM ?
2.) How will you define the Scope of Dependencies in Maven ?
3.)

}
----------------------------------------- Threading -----------------------------------------
{
Since version 5.0, the Java platform has also included high-level concurrency
Processes java.util.concurrent.*;
Most implementations of the Java virtual machine run as a single process.
A Java application can create additional processes using a ProcessBuilder object.
Two basic strategies for using Thread
Instantiate Thread e
Pass the application's tasks to an executor
Runnable
An interface with only one method run
Thread
Implements Runnable.
When run is called it checks for
Worker Thread - Any class that implements runnable
If target is not null - run the run mathod
When start is called it checks for
Thread status if it is not 0 exception(0 for new born)
Add to thread group
Call native method start0
Set started flag to true
when thread.run is called?
it calls runnables run method
thread.Join
allows one thread to wait for the completion of another.
for Join(t1,t2)  t2 will wait until t1 completes
thread.yield
cuurent executing thread waits until other threads complete
(It is use instead of thread.stop)
Thread Scheduler
It is a part of JVM
It uses preemptive or time slicing scheduling
JVM threads are green threads, or user threads.
Main thread has priority of 5 MAX-10 and MIN- -1
Default thread name is Thread-0 and Priority 5
Daemon Thread
It provides service to user threads
It has no lifecycle and when user thread dies JVM terminates it
It is low priority thread howeve its priority is also 5
Main thread cannot be a daemon thread
Used by jvm for grabage collection and House Keeping
Thread created by default extend the status of parent thread
Differ from user thread the way they exit
Shut Down Hook
Use to perform clean up before shutting down the JVM
A thread can be added as hook by setting the addShutDownHook
to runtime :Runtime.getRuntime().addShutdownHook(new Thread(new ShutDownHookExample()));
Garbage Collection
System.gc() Starts a daemon thread that calls object Class finalize() method then
Runtime.getRuntime.gc()

Class Lock
Since a static method is associated with a class,not an object.
In this case, the thread acquires the intrinsic lock for the
Class object associated with the class.
Thus access to class's static fields is controlled by a lock
that's distinct from the lock for any instance of the class.

Synchronize
It is used to implement Has-before relationship.
hb(W,R)
W is executed before R
When W exits R can see the change made by R
Atomic Operations
An atomic action cannot stop in the middle: it either happens completely,
or it doesn't happen at all.
Operations variables of type long or double are only atomic if they declared
with the volatile keyword.
The i++ (increment) operation it not an atomic operation in Java
Since Java 1.5 the java language provides atomic variables, e.g. AtomicInteger or AtomicLong
Internally atomic datatypes are declared as Volatile.
How to Avoid problems with concurrency?
Simply share only immutable data between threads

Defensive Copies
Copy recived data and only return copies of data to calling code.
return Collections.unmodifiableList(list);
How to stop a thread ?

How can a thread return a value?
java.util.concurrent package
Creating a new thread causes some performance overhead
Too many threads can lead to reduced performance, as the CPU needs to switch between these threads.
You cannot easily control the number of threads.
The java.util.concurrent package offers improved support for
concurrency compared to the direct usage of Threads
Executor Framework
{
Executors
In large-scale applications, it makes sense to separate thread management
and creation from the rest of the application.
Objects that encapsulate these functions are known as executors.
Executors is a Factory and have utility methods
Executor
public interface Executor
Has Only One Method     void execute(Runnable command);
ExecutorService
public interface ExecutorService extends Executor
Futures and Callables
Executor framework works with Runnables. Runnable do not return result.
The Callable object allows to return values after completition.
When callable is passed to an Executor it returns java.util.concurrent.future.
Future object can be used to
check the callable status
Obtain Results
How to create a thread Pool ?
executer.newFixedThreadPool();
}
}
}
----------------------------------------- Design Patterns-----------------------------------------
{

Design Patterns as per spring Source
Observer
Singleton
25.) How to Implement SingleTon Design Pattern

Make Constructor Private - so the class cannot be instantiated.
Make the Access Variable Private and static.
And Use static getInstance Method to get  Instance

How singleton class is used with static class

Singleton object stores in Heap but, static object stores in stack
We can clone the object of Singleton but, we can not clone the static class object
Singleton class follow the OOP(object oriented principles) but not static class
We can implement interface with Singleton class but not with Static class.

How to make singleton Class thread safe.

The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time

public static synchronized Singleton getInstance() {
/* Lazy initialization, creating object on first use */
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();}} }
return instance;

}

Singleton and Object Cloning
To implement cloning, we have to implement java.lang.Cloneable interface and override clone() method from Object class. It is a good idea to prevent cloning in a singleton class. To prevent cloning on singleton object, let us explicitly throw CloneNotSupportedException exception in clone() method.

package com.javatechig.creational.singleton;

import java.io.Serializable;

class Singleton implements Cloneable, Serializable {

private static Singleton instance;

private int value;

/* Private Constructor prevents any other class from instantiating */
private Singleton() {
}

public static synchronized Singleton getInstance() {
/* Lazy initialization, creating object on first use */
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
/* Restrict cloning of object */
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
public void display() {
System.out.println("Hurray! I am display from Singleton!");
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
How to Serialize the the SingleTon Classes ?
If a singleton class is meant to be serialized, it will end up creating duplicate objects.
Once A singleton is serialiazed , the Object state can be changes and Once it is serialized
we have another object with other state.
To solve this issue, we need to include readResolve() method in our DemoSingleton class.
protected Object readResolve() {
return getInstance();
}
Steps
1.) Implement Serializable Interface
2.) Add serialVersionUID
3.) implement readResolve

Exact Signature is

ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;

What is D/B writeObject writeReplace?
What is D/B readObject readResolve?


ClassLoader and SingleTon classes.
Immutable
How to Create Immutable Classes ?
Create a final class.
Set the values of properties using constructor only.
Make the properties of the class final and private
Do not provide any setters for these properties.
If the instance fields include references to mutable objects, don't allow those objects to be changed:
Don't provide methods that modify the mutable objects.

Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies.

Immutable Objects are automatically thread safe.
public final class FinalPersonClass {
        private final String name;
        private final int age;
 
        public FinalPersonClass(final String name, final int age) {      
         this.name = name;
         this.age = age;
        }
        public int getAge() {
          return age;
        }
        public String getName() {
         return name;
        }
      }

What if the Immuatable object need to wrap the mutable object.
Share a copy of the Mutable object instead of refrencing an actual object in the getter method

}
----------------------------------------- Struts  -----------------------------------------
{
Flow

1.)When a client request is given, a web container will receive request
2.) Web container loads web.xml and verifies the url-patterns
if matches web-container transfer the request to FilterDispatcher
3.) FilterDispatcher hand over the request to ActionProxy,
it is a proxy class which is responsible to apply before and after services
to original business logic
4.) ActionProxy contacts ConfiguraionManager class, to know the suitable Action
for the request and the needed services for the request
5.) ConfigurationManager class loads structs.xml and provides the required
information back toActionProxy
6.) ActionPorxy delegates the request along with its information to ActionInvocation
7.) ActionInvocation executes the interceptors added to an Action from 1 – N,
after that it will calls the business logic implemented from N – 1 in reverse order
8.) ActionInvocation receives finally result produced by an action aclass
9.) ActionProxy transfers the result back to FilterDispatcher
10.) FilterDispatcher selects an appropriate view, basing on the result
11.) Finally FilterDispatcher uses RequestDispatchers forwarding mechanism and forward a
view as a response back to the client
}
----------------------------------------- Springs   -----------------------------------------
{

**Note**: To Study Springs you would need the TechM PPTs with these Notes

Springs FrameWork
The essense of Spring Frame Work is to Provide the Enterprise
service to the Plain old java Objects Non Evasively.

What is Spring Non Evasive NEss?
Means I am not forced to Import or Extends any Spring APIs

Hoy Many Modules Spring Has ?
Spring Core
Spring Context
Spring DAO
Spring ORM
Spring MVC
Spring Web
Spring AOP

Spring IOC
IOC refers to the creation and management of Object inverted from application code to the container
Design pattern - describe not create
HollyWood Principle : Dont call me i will call you
Depency Injection is form of IOC : Managment of Complete object lifecycle

IOC Container can be implemented using
BeanFactory - Deprecated Interface
ApplicationContext - This interface implements Implements Bean Factory ,
 It is wrapper and provides more features like JNDI,Remoting and EJB
 Basically it adds more enterprise functionality.
BeanFactory<---- ApplicationContext<----- ClassPathXMLApplicationContext,XMLWebApplicationContext, XMLPortal
|
|
v
XMLBeanFactory

Difference between Bean ID  and Name ??
The only difference between an id and a name is that a
name can contain multiple aliases separated by a comma, semicolon or
whitespace, whereas an id must be a single value.

Bean Scope - SingleTon (Default), Prototype , Sessions/Global Session and Request

Dependency Injection:It is a Form of IOC
1.)Setter Based:Use setter based injection over constructor based.
Have to Create a Interface to use any data ,in implementing class by
getter and setter.
2.)Constructor Based:Good for small and stable constructors
3.)Method Based:
Used When protytpe bean is injected into singleton bean.
How Spring Resolves Cyclic Dependencies Bean A has bean B and Bean B has A.
1st) Use contextAwareInterface and Intializing Beabd
2nd) Use Lookup method in Method Based Injections.

Nead CGLib jars : Springs does a lot of proxying if class has interface
  it extends if not then it will create proxy using cglib jars
 
Example : Address is Protype and Employee is Singleton
 step 1.) Define an Abstract method in Employee returning Address
public abstract Address getAddress();
 Step 2.) After setting the property in XML add lookup method
<bean>
......
<property name="eName" value="Akash" />
<lookup-method name="getAddress" bean="add5" />
</bean>
Design Patterns as per spring Source
Factory :Bean is not to be created by the constructor approach,
but with a static  factory method
: Uses factory-method in bean <.....factory-method="createInstance"/>
Service Locator:Factory Approach with Non Static Method
: Uses Factory-method and factory-bean in bean
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
<bean id="clientService"factory-bean="serviceLocator"factory-method="createClientServiceInstance"/>
AbstractFactory:
Builder:
  Decorator:

AutoWiring:Collaborators Resolver,means the dependent beans lookup
  Spring also provide auto-wiring-candiate feature for dependent beans
 byName
 byType :If there is exactly one bean of the property type in the container. If there is
more than one, a fatal error is raised, and you cannot use byType
autowiring for that bean.
 Constructor,
 No AW ,
 Default/Autodetect
Question: What is flow of
LifeCycle Methods:
1.) Implement Interface InitializingBean and DisposableBean
2.) Init Me1thod(Any Name) and provide it in xml
<bean id="exampleInitBean" class=“ExampleBean“ init-method="init"/>
<bean id="exampleInitBean" class=“ExampleBean“
destroy-method ="cleanup"/>
3.)By using annotations postconstruct and predestroy

Annotations:
XML will Override the Annotation conf.
2.0 :@Required
 (ARPP)2.5 :@Autowired JSR250[@Resource, @PostConstruct, @PreDestroy]
 (IQNP)3.0 :JSR330[Inject Qualifier] Named Provider
Scope Lazy
Configuration and Bean
Service Repository Controller

Spring AOP

AOP is like triggers in programming languages
Unit of modularity in OOP is class in AOP is aspect
Logging Security Auditing Locking Event handling Transaction management

(Aspect)<---makes-an---(Named PointCut Using PCD)<--is-applied-on---(Advice)
(Aspect)<-----is-applied-on(Using UnNamed PointCut)---(Advice)


Example
(When userAddrss is not verified
1.) Make user connection offline
2.) Send Confirmation SMS to user
3.) Notify Admin

PointCut :  An expression that select JP
Named:Can be declared seperately using annotation
Example:
@Pointcut("execution(*transfer(..))")
Anonymus:Can be declares inside an Advice
Is declared using PCD(Point Cut designators) , Example excetution target within etc

Advice: It is applied on Method which Takes atleast JointPoint as Argument
Advice Are : Before , After , AfterReturning , AfterThrowing , After , Around
All of the above are applied on Classes , then a function is declared stating what needs to be done
Around Advice is important , beacouse when a function is defined on what needs to be done
- It take ProcceedingJointPoint as an argument
- PJP declare a method proceed which when called will allow the method execution.
- Example
@Aspect
public class AroundExample {
@Around("com.xyz.businessService()")
public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
Object retVal = pjp.proceed();
return retVal;
} }
JointPoint: Point during an execution of a program
Exception or a method
Weaving: Assembling aspects for advicable objects

Springs Transaction Management

From Springs Source. http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html
Section 16.5.1



Spring MVC Flow

1.)When a client request is given, a web container will receive request.
2.) Web container loads web.xml , web.xml defines 3 main things
2.1)<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
It looks for applicationContext.xml, it defines transactions etc
2.2)servlet-lass>org.springframework.web.servlet.DispatcherServlet</servlet-class>
It looks for the
2.3)<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>*.spring</url-pattern>
</servlet-mapping>
It looks for servlet-name-servlet.xml for varous information like
Location of packages having controller classes
ViewResolver
Resource Bundle
Database Configurations
2.4) Welcome File

Springs ORM :Integrating Springs With Hibernate
-------------------- Without Annotion With CFG-------------
step1)LocalSessionFactoryBean
ConfigLocation ---> CFG File
step2)HibernateTemplate
step3)UserDao
-------------------- Without Annotion Without CFG-------------
step1)DataSource
setp2)LocalSessionFactoryBean
Mapping Resource --> HBM File
Hibernate Properties
step3)HibernateTemplate
step4)UserDao
-------------------- With Annotion Without CFG-------------
step1)DataSource
step2)AnnotationSessionFactoryBean
AnnotatedReource --> ClassFile
Hibernate Properties
step3)HibernateTemplate
step4)UserDao


}

----------------------------------------- Hibernate   -----------------------------------------
{
Difference between hibernate and JPA
JPA is the dance, Hibernate is the dancer.
Jpa is the Specification and Hibernate is the Implementation

What does Session.evict does ?
SCA Technologies
Hibernate Table per Class

}
----------------------------------------- Maven and Ant -----------------------------------------
{
Difference Between Ant and Maven
High-level Comparison

The differences between Ant and Maven in this example? Ant...

Ant doesn't have formal conventions like a common project directory structure, you have to tell Ant exactly where to find the source and where to put the output. Informal conventions have emerged over time, but they haven't been codified into the product.
Ant is procedural, you have to tell Ant exactly what to do and when to do it. You had to tell it to compile, then copy, then compress.
Ant doesn't have a lifecycle, you had to define goals and goal dependencies. You had to attach a sequence of tasks to each goal manually.
Where Maven...
Maven has conventions, it already knew where your source code was because you followed the convention. It put the bytecode in target/classes, and it produced a JAR file in target.
Maven is declarative. All you had to do was create a pom.xml file and put your source in the default directory. Maven took care of the rest.
Maven has a lifecycle, which you invoked when you executed mvn install. This command told Maven to execute a series of sequence steps until it reached the lifecycle. As a side-effect of this journey through the lifecycle, Maven executed a number of default plugin goals which did things like compile and create a JAR.

}
----------------------------------------- Oracle -----------------------------------------
{

Oracle 8i9i(i:intrenet)
10G11G(G:Grid)

Views
Steps to create a View
Specify Schema --> Create View
If you omit schema, then Oracle Database creates the view in your own schema.
A view is a named and validated SQL query which is stored in the Oracle data dictionary
Views are useful for security and information hiding example
Hide the NAME and OWNER of the base table
Types of Views
Read Only Views
Read Write Views
Write with Check option
Updating a View Using with Check Option :
Specifies the level of checking to be done when doing DML against the view
Materialized Views
Data is actually stored on disk
make a snapshot of a table available on a remote system
Kind of offline computing
A MV must be refreshed when the data in the underlying tables is changed
EXEC dbms_mview.refresh('MY_TEST_MV', method=>'C');
Pipe Line View
A view on Views
Force :Creates the view regardless of whether or not the base tables exist
If the table is removed force view will not become invalid
SQL>  create force view invalid_view as
select * from table_that_does_not_exist;

Index
Lets you quickly Locate particular records based on key column values
Data Type Extended OOOOOOFFBBBBBBRRR   O6F2B6R3(Data-Object Data-File Data-Block Rownumber)
Normal
Composite Index
Bitmap Index
That uses a string of bits to quickly locate rows in a table.
Good for low cardinality colums i.e Nuber of distinct values is small
compared to the number of rows
Function Based Index
What is the benifit of FBI?

Cardinality
Nuber of distinct values compared to the number of rows
Debugging
Use DBMS_OUPUT.PUT_LINE
Use Exception and dbms_output.put_line('backtrace: '||DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
for knowing the line number
Use show errors by setting SET_SERVEROUT on
Null
Null has no datatype
It is unknown it is maximum in descending order and minimum value in ascending order.

Can a table have two primary keys?
The constraint name with primary keys can only be one
Howeve many columns can be added in a primary key
ALTER TABLE AKASH.EMP1 ADD (
CONSTRAINT EMP1_PK
PRIMARY KEY
(JOB, ENAME, EMPNO));

Difference between 10G and 11G
Joins
Cartesian join(Aka Cross Join)
if table A with 100 rows is joined with table B with 1000 rows,
a cartesian join will return 100,000 rows.
ANSI: select count(*) from emp CROSS JOIN  dept
ORACLE:select count(*) from emp ,ept
Equi join(Aka Inner Join)
Uses an equivalence operation (i.e: colA = colB)
to match rows from different tables
It is an Cross Join with where clause
Nonequi join
uses an unequal operation (i.e: <>, >, <, !=, BETWEEN, etc.)
to match rows from different tables
Natural join
compares the common columns of both tables with each other.
SELECT dname, ename FROM dept NATURAL JOIN emp
equivalent to equi join
Outer join
 An outer join is similar to the equi join,
 but Oracle will also return non matched rows from the table.
Left Outer / Right Outer / Fill Outer
Self join

Second Highest Salary
select level, max(sal) from emp
where level = 3
connect by prior sal > sal
group by level;

SELECT   RANK, SAL
FROM (SELECT   ROWNUM AS RANK, SAL
FROM   (  SELECT   DISTINCT SAL
    FROM   EMP
    WHERE   SAL IS NOT NULL
    ORDER BY   SAL DESC))
WHERE   RANK = 2

select max(sal) from emp
where sal < ( select max (sal)from emp)

Remove Duplicates
Delete * from emp where rowid in (
select max(ename) r from emp  a
group by ename,sal having count(*) > 1)

HAVING clause
used with group function and it is written after GROUP BY clause

Union and Union All
UNION removes duplicates, whereas UNION ALL does not.
UNION does not support BLOB (or CLOB) column types, UNION ALL does.
The no colums and data types should be same

Procedures and Functions
IN :Default
OUT :Must Be specified
SQL> VARIABLE    name    VARCHAR2(20)
SQL> VARIABLE    salary   NUMBER
SQL> EXECUTE  query_emp(1001,:name,:salary)
SQL> PRINT   name   salary

INPUT : Must Be specified
Advantage of Replace:When REPLACE is used the object privileges remain unchanged
Difference between a FUNCTION, PROCEDURE
Function must return a value. Can be called inside a query.
Procedure may or may not return value.
Functions are normally used for computations
where as procedures are normally used for executing business logic.
You can have DML (insert,update, delete) statements in a function.
But, you cannot call such a function in a SQL query.
Stored procedure is precompiled execution plan where as functions are not
Stored Procedure: supports deferred name resolution. Example while writing
a stored procedure that uses table named tabl1 and tabl2 etc.
But actually not exists in database is allowed only in during creation
but runtime throws error Function wont support deferred name resolution.

USER_SOURCE
Is used to obtain the text of a stored procedure or a stored function
USER_PROCEDURES
Is used to get the details of all procedures in that user’s schema


PRAGMA :keyword signifies that the statement is a compiler directive,
which is not processed when the PL/SQL block is executed

Exceptions
Named Exception
1.NO_DATA_FOUND  ORA-01403  - You executed a SELECT INTO statement and no rows were returned.
2. TOO_MANY_ROWS ORA-01422  -You tried to execute a SELECT INTO  statement and more than one row  was returned.
3. ZERO_DIVIDE  ORA-01476  -You tried to divide a number by zero.
Unnamed Exceptions:It is used to trap an internal error raised by PL/SQL or the SQL engine,
which is not been given a predefined name.
Although this error is identified only by its internal error number,
exception handlers need a name by which they can check for a match .
ORA-00001(Unique Key ) ORA-2292(Integrity Constrains)
Names can be created and assigned with the error number by the user
by using PRAGMA EXCEPTION_INIT
It can also be used to rename the predefined named exceptions to another name.
User Defined Exception

SQLCODE : Returns error number
 1 for User defined
 v_code := SQLCODE;
SQLERM : Returns Error Message
 Returns “USER DEFINED EXCEPTION” for user-defined exceptions
 v_errm := SQLERRM(SQLCODE);
Throwing an Exception
RAISE_APPLICATION_ERROR(-1111,"");
Error numbers should be between -20000 and -20999
Triggers
TIME : BEFORE AFTER
EVENTS : INSERT UPDATE DELETE
TYPE: STATEMENT ROW

DATAOP OLD NEW
INSERT N Y
UPDATE Y Y
DELETE Y N

When clause can be applied at row level triggers.
OLD and New Variables with : should not be used in when clause
OLD and New  are pseudo var and accesed in when using old.sal>new.sal
Sequence:
BEFORE Statement
BEFORE ROW
Execute Dml statments and Data Integrity
AFTER ROW
AFTER Statement
Conditional Predicates: Inserting , Updating,Deleting.

Commits and Rollback are not allowed
Can be done by declaring  PRAGMA AUTONOMOUS_TRANSACTION;
Mutating Table: When a row level trigger attempts to change the data
on row which it has already acquired a lock
Can be solved by using statement level(By creating a flag in pakg and after stmnt trgr)
or Using PRAGMA AUTONOMOUS_TRANSACTION

INSTEAD OF Triggers to Update Non-Updateable Views

Cursor
To process any DML or SELECT queries, Oracle allocates an area of memory
on the database server, known as context area

Cursor is a pointer to the context area
Static
Implicit  : Can be used for DDL,DML,DCL
Explicit :Can be used for DCL(Select) only
: Declare --Open -- Fetch --Check --Close
Cusror While Loop:
Fetch the value first and then go for WHILE
Since now the condition is satisfied, the loop is entered.
Inside the loop, we have to declare one more fetch statement.
Explicit wid Params
Dynamic
Refrence Cursor

For Update : Exclusive row locks are taken on the rows in the active set
before the OPEN returns
CURSOR emp_cursor IS
SELECT empno,ename,sal FROM emp
WHERE deptno=30
FOR UPDATE OF sal NOWAIT;
NOWAIT: OPEN will return immediately with Oracle error if rows are locked
WAIT n: If rows are locked by another session and are not released in “n” seconds
then OPEN will return with Oracle error

Where Current of: It use to fire any DDL or DML on current refrnced row by cursor
 Used with For Update Clause Only
 UPDATE and DELETE statements can use a WHERE CURRENT OF clause

 DECLARE
 CURSOR emp_cursor IS
 SELECT sal FROM emp WHERE deptno=30
 FOR UPDATE OF sal NOWAIT;
BEGIN
 FOR emp_record IN emp_cursor
 LOOP
 UPDATE  emp
 SET  sal=emp_record.sal*0.1
 WHERE CURRENT OF emp_cursor;
 END LOOP;COMMIT;END;
If cursor is open and data is changes what happens?

Packages:
Groups together PROCEDURES, FUNCTIONS, CURSORS, types and variables
Package has two components:
Package Specification:Declares types, variables, constants, exceptions, cursors and subprograms
 Constructs declared in the package specifications are public and global
CREATE  OR REPLACE  PACKAGE  package_name IS

Package body: It is used to declare objects defined in PS.
  The Objects not defined in PS and declared here are Private.
  It will comile unless PS is.
  Private objects can be accessed by any object in pckg ethr pblc/prvt
  CREATE  OR REPLACE  PACKAGE  BODY  package_name IS
Forward Declaration:Forward declaration is used in declaring subprograms that
can be used in packages.
In a Package body if one function is calling another then called
function must be declared before hand.

Objects: Objects represent OOPS design pattern in Oracle.
Just the way the class is created objects can be created
with attributes and functions.

1.)Declare type specification
create or replace type Employee12 as object(employeeId varchar(25),
             employeeName varchar(25),
             member function toString return varchar2);
2.)Declare type body
 create or replace type body Employee12 as
             member function toString return varchar2
             as
             begin
             return employeeId ||' ' ||employeeName;
             end toString;
             end;
Collections:
Associative Arrays/Index-by-tables:
Values are stored as key value pairs
It is not stored in the database hence executed ni anonymous block
Can be indexed by binary_integer , pls_integer and varchar
On 8i and 9i, PLS_INTEGER was noticeably faster than BINARY_INTEGER.
PLS_INTEGER operations use machine arithmetic, but after oracle G edition they are same

DECLARE
  type employeeId is table of varchar2(233) index by pls_integer;
  TYPE my_type is table of emp.empno%type index by binary_integer;
  akashId employeeId;
BEGIN
  DBMS_OUTPUT.PUT_LINE(akashId.first);
END;

Error..ORA-06532: Subscript outside of limit
Oracle index starts from 1
ORA-0000: normal, successful completion
Declaring sqlerrm before exception

Nested Table:
Implementation of Index By tables - can be databased.
They have to be initialized by construtors
Usage :
1.)Anonymous Block
DECLARE
  TYPE myType is table of varchar2(111);
  foo myType;
BEGIN
--foo := myType('one','two','three');
foo(1) := '111';
if foo.exists(1) then
DBMS_OUTPUT.PUT_LINE(sqlerrm(sqlcode));
end if;

EXCEPTION
  WHEN OTHERS THEN
 DBMS_OUTPUT.PUT_LINE(sqlerrm(sqlcode));
END;

2.)Database
Create Object type --> Create Table Type --> Create Table

2.1)create or replace type page as
object(pageNumber varchar(100),pageContent varchar(100))

2.2)create type pageTable as table of page
2.3)create table myBook(bookName varchar2(100),pages pageTable)
nested table pages store as pagetabletable

Varrays:
They have to be initialized by construtors
Usage :
1.)Anonymous Block
DECLARE
  type eid is varray(100) of varchar2(1212);
  myeid eid;
BEGIN
myeid := eid('one');
DBMS_OUTPUT.PUT_LINE(myeid(1));  

EXCEPTION
  WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(sqlerrm(sqlcode));
END;
2.) Database Schema
create or replace type aaaa as varray(11) of
varchar2(100);

create table bbbb
(a1 aaaa);

Bulk Collect
Bulk Binding
Bulk binding reduces the context switches between SQL and pl/SQL engines.
It enhances the performance but the memory consumption would be high.
Limit
}

----------------------------------------- Agile -----------------------------------------
{
Swift ------------> Speed
Responsive ------------> Speed

Nimble ------------> Flexible
Supple ------------> Flexible
Last minute modifications

Waterfall Model
Need to capture every thing
Waterfall MEntality - BDUF Big design Up Front
Upfront modelling is a liblity
Agile
Required when the Requirments are not clear.
Requirments keep changing from time to time.
2001 Workshp in snowbird Utah

Agile Manefesto
 Process:Individuals and Intercation over process and tools
 Product:Working s/w over comprhensive doccumentation
 Price:Customer collboration over contract negotiation
 Place:Responding to change over following a plan

Agile must deliver frequently from weeks to months
Most effective method of conveying information is F2F

Agile Methodologies
Scrum
XP
DSDM
RUP

Agile Matrix
}