You are on page 1of 100

Topic name Concept: Java features are given below:1. 2. 3. 4. 5. 6. 7. 8. 9.

Platform independent High performance Robustness Multithreading Portability Security Distributed Dynamic Interpreted

Java Features

Platform Independent:Platform independent means once you compile your code, need not to be compile next time on another machine because java complier convert java code to byte code (means .class file) or (more meaning full OO based class) Which makes java code to platform independent? High performance:Java is much better in terms of performance. Performance means time, space and algorithms (means time to execute your code, space taken place and efficient algorithm) which make java as high performance. Robustness:How to make program reliable. It is main issue. Java is strictly typed language. Java checks code at compile and runtime which makes program reliable and java did not allow to program which is behaving unpredictable. Java is strictly typed language Languages where variables must be declared to contain a specific type of data. If your variable declarations look like:

String myString = "Fred"; Then your language is strictly typed, variable "myString" is explicitly declared to contain only string data. If the following works: x = 10; x = "Fred"; then it's loosely typed (two different types of data in the same variable and scope).

Multithreading:Java code can create one or more thread of same process for different purpose like One thread for spell check, you can make to run in background for spellchecking as well as you are typing. Thread synchronization, thread polling. And better way to deal real world problem and performance because thread is cheaper. Portability:Portability is main issue over the internet there are different types of computers and operating system connect to it. Why java program is robust Two reasons given below:1. Memory management mistakes 2. Mishandled exception conditions Security:In Java, you can write two types of program:1. Application program you know very well what is it? 2. Applet Applet is special type of program which transfer across the network, java did not allow applet to access computer resource which is downloading this applet. Distributed:-

Java is designed for the distributed environment of the internet because it handles TCP/IP protocols. In fact, accessing a resource using a URL is not much different form accessing a file. Java also supports Remote Method Invocation (RMI). This feature enables program to invoke methods across the network. Dynamic:Java program is dynamic because java link many things at runtime which is not happen at compile time. Dynamic linking code is safe and gives performance. Interpreted:Java is interpreted language What is mean of that because after compiling the code java complier converts that code into byte code and during execution JVM use JIT (Just-intime) compiler and then interpreted into machine code. JIT take your code as piece by piece which require during execution.

1. no global variables. 2. no global functions. 3. no operator overloading. 4. no multiple inheritance. 5. no scope resolution operator. 6. Local variables are not initialized by default, if used without initializing, will result in compilation error. 7. non local variables are always initialized. 8. true/false means true/false only i.e. Boolean data type enforcement, number not considered for Boolean. 9. any big data types cannot be created on stack , they are only heap. big data types arrays and objects. A obj1; // obj1 is object of class A in C++ this wont work like this in java. here A obj1, is obj1 is a reference of class A data types in java:10. data types in java and they are fixed there is nothing called mood of

couple of things about java:-

compiler, mood of o.s. etc in java. 4 - Numeric types cannot hold decimals 1 2 4 8 byte short int long

2 - Floating types 4float 8 double 2 why Unicode 1 - char 1 byte 1 - Boolean all numeric types are signed.

Array

1. Two step process. Array declaration (pointer) Memory allocation. 2. No matter whatever we do , array cannot be created on stack. Example:Array declaration Int x[] Memory allocation x=new int [3];

Here x is an array of integer object. (SCRAP)

But x is array of the integer pointer.(GOOD)

Topic: Concept:-

casting

There are two types of casting, 1. casting between primitive numeric types and 2.casting between object references.

Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

Topic

modifiers

There two types of modifiers:1. Access modifiers:- public, private, protected, static. 2. Non access modifies: - final.

Static block:-

1. static block gets executed only once during the execution of the program. Can there be many static blocks answer is yes. What is purpose of it answer is not known.

we have two environment variables


1. path - used by os 2. classpath. - used by jvm.

1. path - used by o.s., its gives the location where the JDK is installed. Example:- c:\JDK1.5.1 2. classpath. - used by jvm, classpath gives the location of .class files which is intern stored in the lib folder these class file contains byte codes. Example:- c:\JDK1.5.1\lib

Topic name

Encapsulation

Concept: Definition: - Its a wrapper that protects data from unwanted changes. Some points about encapsulation:1. Encapsulation is a process to grouped data and methods into a single unit called class. 2. Its a wrapper that protects data from unwanted changes. 3. Encapsulation means data must be change some particular fashions. 4. In other words its a process of the creation of the class. Example: Dept class files - data people - functions. Combine to into a class. Topic name Some points about abstraction:1. Abstraction means hide the complexity in such a way that one code can not predict that what is going inside other code. 2. Abstraction achieves by abstract class and interface in java. 3. Abstraction is powerful concept of OOPs. Example:Abstraction

Topic name:

Inheritance

Definition: - Inheritance is a mechanism through which one class acquires the property of existing another class. Some points about inheritance:1. Inheritance is very good feature of OO. 2. Getting the property the of an exist class into another class This is known as inheritance. Super class A class which is being inherited. Sub class - A class which is being inheriting.

No multiple inheritance in java but a way to look up as multiple inheritance. Two most important things come when inheritance come:1. Extensibility 2. Substitutability Extensibility: Extensibility means adding some feature into the super class without making any changes to sub class the sub class object can access the new feature of the super class. Substitutability:Substitutability means run-time polymorphism. Super class reference can be assigned to either a super class object or a sub class object. Substitutability is used with overriding. Overriding :- Hiding super class feature from the sub class object. Reason for doing so can be that the super class feature may not be making sense to the sub class or may be incomplete. But the drawback of this is that we can take some important feature of the super class and kill it in the sub class.

Topic name Concept:

Polymorphism

Some points about polymorphism:1. 2. 3. 4. Polymorphism means one name many forms. Polymorphism is very important concept in each object-oriented language. Polymorphism means one interfaces multiple methods. One method can do more than one job (function overloading).

Example: -Println () method in System packages which can be use to print short, int, double, float, string and also objects. That is the power of overloaded method.

Topic name: Concept:

Class

1. Class is a template for an object. 2. It is a way to bind data and code into a single unit. This single unit is known a class. Class is a implementation way of encapsulation and make changes in an organized way. 3. Each class in java is a sub class of java.lang.Object. 4. java.lang.Object, this is a package which comes by default inside each program of java. Syntax: class classname (valid identifier acceptable in java) { //modifier Instance variable; //modifier Methods to access to locker }

Example: Class Account{ //all is default type by default Int acc_no; String name; String acc_type; public static void main(String args[]){ acc_no = 1001;name = John; acc_type = Current; System.out.println(acc_no,name,acc_type); } }

Topic name:

Object

Concept: Definition: - Object is an instance of the class. we can create object in the

same way as we create the variable of the structure.


Some points about objects in java:What comes first object or class. Dont think object comes first. 1. Object should have a unique identity. 2. Object there should be something which is unique there could be some thing which is common but important thing is something should be unique. 3. Objects have separate instance variables. Syntax: Classname objectname; \\declare reference to object

Objectname =new classname(); \\ allocate class object. //only reference is getting created not an object means object //reference need to be assign of class type classname objectname = new classname();

//creating an object and assigning the reference to objectname Example: Class Account { Int acc_no; String name; String acc_type; Void setAccountno(int); Int getAccountno(); Void setName(String); String getName(); Void setAccountType(String); String getAccountType();

} Account cust1 = new Account();//cust1 have an reference of Account type object. Account cust2 = new Account();//cust2 have an reference of Account type object. Now cust1 and cust2 have unique identity and separate instance variables.

Topic name Concept:

nested class

Some points about nested class:1. It is possible to define a class within another class; such classes are known as nested classes. 2. The scope of a nested class is bounded by the scope of its enclosing class. 3. Thus, if class B is defined within class A, then B is known to A, but not outside of A. 4. A nested class has access to the members, including private members, of the class in which it is nested. 5. The enclosing class does not have access to the members of the nested class even public. 6. Typically nested class has access to two this. 1. Outer class this 2. Inner class this. 2. To prevent outer class this from being available to the inner class, make the inner class static. 7. If you want to prevent outer class instance variables from being available to the inner class than we need to make the inner class as static. 8. Outer class has to be public or default. 9. Inner class can be private, public, default, protected and static. Example:- public class A
{ private int x, y; public class B private/protected { Public int i,j; void show() { x=10; y=20; }

} void print() { //i=10; // can not access } }

In java, you can define two type of nested class. 1. static class 2. non-static class Inner Static class :1. 2. 3. 4. Static class concept in java is same as in c++. Static class can access only static members of outer class. We can define both static and non static method in side the inner static class. We can also create the object of the inner static nested class inside the outer class, but the methods of the inner class can be called from outer class methods not from the outer class. 5. Only the inner class can be made as a static class.

Inner Non-Static class:Non-static concept in java doesnt exist in c++. 1. Non-static class can access all member of outer class. 2. You can create an object of nested class inside the method of the outer class. 3. Outer class object can not access member of inner class not even public. Syntax: public class Window { private int size;

private String title; public class Mouse { int x,y; this.x = xcor; this.y = ycor; } }

public void setXPosition(int xcor){ public void setYPositon(int ycor){

public int getXPostion(){

return this.x;}

public int getYPosition(){ return this.y; } } public void setSize(int size) { this.size = size; } public void setTitle(String title) { this.title = title; } } class Main { public static void main(String args[]) { Window win = new Window();//creating an object of window class(outer class) Window.Mouse mouse = win.new Mouse(); //creating an object of inner mouse //class using outer class object win.setSize(20); win.setTitle("Nested class example"); mouse.setXPosition(23); mouse.setYPositon(56);

System.out.println(mouse.getXPostion()); System.out.println(mouse.getYPosition()); //win.getXPosition(); //can not access without an object as member of mouse class } }

Topic name Concept: Some points about abstract classes:-

abstract class

1. Abstract class must contain at least one or more abstract method. 2. It can also contain concrete methods (method with body). 3. We can not create the instance (object) of the abstract class(compile time error). 4. abstract class designed only for inheritance because class is nonfinal class. 5. abstract class gives something and expect something gives instance variables expect to implement the methods of abstract class which is inheriting to abstract class. 6. They can be used to create the reference of that class because java`s approach to run time polymorphism 7. An abstract class is a class that is incomplete, or to be considered incomplete. Normal classes may have abstract methods, that is methods that are declared but not yet implemented, only if they are abstract classes. If a normal class that is not abstract contains an abstract method, then a compile-time error occurs. Freak point: Abstract class can have static method and final non static method. And also final static method also together but with body.

Syntax:
public abstract class Employee { final static void funcA() { } static int funcB(){ return 0; } final String funcC(){ return null;} }

Syntax: abstract class Employee{//abstract class abstract int getSalary();//abstract method must be //implement int printNumber(int number)//concrete method { return number; } } Example: abstract class Employee { abstract int getSalary(); int printNumber(int number) { } public class SE extends Employee { static Employee emp; public void addSalary() { return number; }

System.out.println(getSalary()); } public static void main(String[] args) { emp = new SE();//assigning reference to emp SE se = (SE)emp;//casting Employee reference to sub class //reference se.addSalary(); System.out.println(emp.printNumber(677)); System.out.println(emp.getSalary()); //se and emp both are pointing to same object } @Override int getSalary() { return 245; } } Topic name Concept: Some points about abstract method:1. 2. 3. 4. 5. Abstract method is a pure virtual method as in c++. Abstract method must be declared as abstract and will not contain any body. Which class declares an abstract method must be an abstract class. Abstract class should be always a superclass with abstract method. Implementation or definition of an abstract method must be in sub class of that class which is being inherited. Abstract method

Syantax: Example:

abstract return type methodname();//abstract method

abstract class Employee { abstract int getSalary();//abstract method } public class SE extends Employee { static Employee emp; public static void main(String[] args) { emp = new SE();//assigning reference to emp SE se = (SE)emp;//casting Employee reference to sub class //reference se.addSalary(); System.out.println(emp.getSalary()); //se and emp both are pointing to same object } public void addSalary() { System.out.println(getSalary()); } @Override int getSalary() { return 245; } } Note:(1.) Pass by Value= passing the primitive data types; (2.) pass by reference = passing the object . no I want pass primtive by reference or object by value, how to do it, forget it. enemy of pass by address is = operator.

Topic Name: Concept:

Static variable

Some point about static variables:1. 2. 3. 4. Some thing which is common. Each object accesses only one copy of static variables. Each static variable can access via class name and also through the object. They are independent to object. static typename(datatype) varialblename;// declaration Example: Class A { Public: Static int I; // static variable }A a ; a.I = 10; // you are accessing through object A::I = 20; // you can also accessing through class name.

Syntax:

Topic name: Concept:

Non-Static variable

Some point about static variables:1. 2. 3. 4. Some thing which is unique. Each object has separate copy of non-static variables. Each non-static variable can only access through object. These are dependent to object (means no existence without an object). datatype variablename;//declaration

Syantax: Example:

Class A { Public: int I; // non-static variable }; A a; a.I = 10; // you are accessing through object

Topic name: Concept:

static functions

Some freak point about static variable:1. 2. 3. 4. Static functions can only deal with static variables static function can not be overridden instead they can redefine in sub class. Static functions expose (show) static variables. Static functions can be invoked outside the class with an object but also with class name. 5. Static functions can never access something which is non static, i.e. specific to the object.

Syntax:

static void setValues(int value);//static function A.setValues(13); \\calling

Example: Class A{ Public: Static void setValues(int value); // static function }; A a; a.setValues(12); // you are accessing through object A.setValues(20); // you can also accessing through class name

Topic name:

non-static functions

Concept: Some freak point about static variable:1. non- static functions can be invoked through only object. 2. non- static functions can access non static and static also. Syntax: void setValues(int value);//non-static function Obj.setValues(13); Example: Class A{ Public: void setValues(int value); // non-static function }; A a; a.setValues(12); // non-static can access through object.

Topic name Concept:-

final classes

Some points about final classes:1. final class is a class which you can not be inherit. 2. Make the class as final, means these classes do not want to involve in inheritance (Substitutability). 3. all methods inside a final class are final by default. But not variables are final by default. 4. Means, making a method as final inside a final class, very stupid. 5. Final class can have instance variable. Syantax: public final class Account { } Example:

final class Utility { int x,y; public static void printNumber(int number) { System.out.println(Entered number is + number); } } Public Class Main // extends Utility remove commit slap guaranteed { public static void main(String args[]) { //Utility util = new Utitlity(); Utility.printNumber(Integer.parseInt(JOptionPane.showInputDialog(E neter a number)); } }

Topic Syntax: Concept:

Final variable final datatype variableName;

1. final variable is more sensible way to make a variable as constant. 2. Final variable can not be modified. 3. Final variable must initialize at the time of declaration otherwise it lead to the compile time error. 4. It can be inherited in the derived class but it can not be again initialized in base class as well as in derived class. Example:Final int a; \\ compile error. Final int a=9; \\ no error.

Topic Syntax:Concept:-

final method final return Type methodName (paraList) {}

Def:- final methods are non overridden methods of the class. 1. Final method can not be override in the derived class. 2. They provides performance enhancement because compiler is free to inline calls to them because it knows they will not be override by the subclass. 3. They can use both final and non final variables. Example:(1.) Class A { final void show() { sys (hello); { } } \\ error }

Class B extends A

void show( ) {sys( by); }

Topic Sysntax:Concept:

final class final class classname

Definition: - Final class is complete class it does not require inheritance 1. 2. 3. 4. Final class is complete class it does not require inheritance. Final class can not be inherited. Declare the class final implicitly declares all its method as final. Make the final class abstract is illegal, because abstract class is incomplete itself so we makes the subclass (that extends abstract class) to give the complete implementation. 5. A class can be declared final if its definition is complete and no subclasses are desired or required. A compile-time error occurs if the name of a final class appears in the extends clause of another class declaration; this implies that a final class cannot have any subclasses. A compile-time error occurs if a class is declared both final and abstract, because the implementation of such a class could never be completed. 6. Because a final class never has any subclasses, the methods of a final class are never overridden.

Example: Final Class A { . . . . Class B extends A {. . . } } \\ error can not be subclass.

Topic name: Concept:

Constructor

Some freak points about constructor:1. it is a special function of the class because it has same name of the class. 2.It does not have any return type. 3. it is a special function that gets called automatically when the object is created. 4. Difference between normal function and constructor i.e. we can keep calling normal function any number of times we want. Where a constructor we are calling it, is ruled out, system will call it when an object of the class is created. 5. Syntax wise, for a function to call it as constructor no return type, same name as the class name. 6. Need for constructor is to create objects conditionally. 7. Constructor can be overloaded. Syntax: Example: Class Example{ Public Eample(){System.out.println(Default constructor at work);} // default constructor Example(int a) //parameterized constructor { System.out.println(parameterized constructor at work); } Public static Void main(String args[]) { Example obj = new Example(); //default constructor is getting called. Example obj1 = new Example(23); } classname();// constructor declaration

Topic name: Concept:

this pointer

Some points about this pointer:-

1. it refer to the calling object so type of this pointer, depends on the calling object type. 2. It available only inside non-static functions not in static functions of the class. 3. it can be also used to differentiate between instance variable of object and local variable of function. Syntax: this.x = x; This.x = means refer to calling object x x = local variable of calling member function Example: class User { private int value; public void setValue(int value) { this.value = value;//this refer to user object } public int getValue() { return this.value; } } public class Example{ public static void main(String args[]) { User user = new User(); user.setValue(34);

System.out.println(user.getValue()); } }

Topic name Concept:

super keyword Some points about super:-

1. Super is a keyword not a function. 2. super has two general form (1.) To call the parameterized constructor of super class. 3. TO call super class constructor from subclass constructor and super class method from subclass method or constructor, it should be first statement in the subclass constructor and in method, otherwise compile error. Syntax: Example: class Employee { int empId; public Employee(int empId) { this.empId = empId; } public int getEmpId() { return empId; } } public class Example extends Employee{ int deptId; super(valu1,value2);//super class constructor calling

public Example(int e, int d) { super(e); this.deptId = d; } public static void main(String args[]) { Example ex = new Example(12,17); System.out.println(ex.getEmpId()); } } (2.) To access member of super class which is hidden by a member of a sub class When members name of a super class hidden by the same name of the member in the sub class then we use the super keyword the access these hidden member of the super class. Syntax: = super. Member \\ member can be either method or instance \\ variable. Example:Class A {int I ; Void show(){cout<<hello;} } Class B extends A { Int I; \\ it hides the I in A B (int a, int b) { super.i=a; \\ i of A I = b; } Void show() { \\ i of B

Super.show(); \\ this calles A`s show() } } Topic: Concepts: Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at run time rather than at compile time. dynamic dispatch

Topic name Concept: Some point about packages:-

Package

1. Package is a collection of classes and interface in java. Package is nothing but a folder which can not hold duplicate file. 2. Package is different from namespace in c++. 3. Concept of package is for avoiding the naming collisions. 4. Package creation code must be first line in your program. If you omit package statement, the class name is put into the default package. 5. Class inside a package no longer a class, now it will be qualified by package name. 6. We can also create the hierarchy of the packages means packages inside the package. 7. Package names starting with java or sun or javax is banned, because these things are used by java internally. We will get runtime slap. company.java ok java.company //not ok. 8. creating classes without a package is a sin. Access within packages and b/w packages:default - accessible in same package, outside the package not accessible .

Public-

accessible in same package as well outside the package.

Protected -

accessible to all classes present in the same package and only

subclasses present in other packages.

Syntax: Example: Package mypak; Class Example {

package mypack;// creation of package in java

Public class void main (String args[]) { System.out.println (Example class inside package mypak); } } Now class will qualified with mypack.Exmaple otherwise compiler will complain an error.

Topic name Concept:

access specifiers

Some points about access specifier:1. Specifier controls the access between different class and packages. 2. It depends upon need which method, variable, interface what should be. Table of access specifier:Private Same class Same package subclass Same package nonsubclass Yes No No modifier Yes Yes Protected Yes Yes Public Yes Yes

No

Yes

Yes

Yes

Different package subclass Different package nonsubclass

No

No

Yes

Yes

No

No

No

Yes

Topic name Concept: Some points about interface:-

Interfaces

Definition: - interface is a keyword which is used to create the class pure


abstract. Using interface we can specify what an interface must do, but not how it
does it. 1. Interfaces in java is very good concept for achieving abstraction and loose coupling. 2. Interface can be created via declare as interface keyword. 3. Interface can not have a method with definition. 4. All methods inside interface must be public. 5. Class can implements many interfaces. 6. Interfaces can extend interfaces. 7. Interface`s methods are abstract method by default. 8. All the variables in the interface are public, static and final. 9. Interface can only be public or default. Default interface can be used only inside the same package but public can be used anywhere. 10.Interface is not for inheritance because we can not get extensibility though interface. Syntax: accessspecifier interface interfacename { Final variables //methods } Example: Public interface C {

public int show(); } Public interface A extends C { public int display(); } Public interface B extends A { public void getshow(); } Public class User implements B { int val; public User(){val = 18;} public void getshow() { System.out.println(val); } public int display() { System.out.println(val); return 0; } public int show() { System.out.println(val); return 0; } } public class Example{ public static void main(String args[]) { B b = new User(); b.show();

b.display(); b.getshow(); } } Topic nested interface

Concepts: 1. Interface can be declared as a member of a class or another interface. Such interface is called a member interface or nested interface. 2. A nested interface can be declared as public, private or protected. 3. This differs from a top level interface which must be declared as public or default access level. Example:Class A{

Public interface nestedinterface \\ member interface { Void show(); } } Class B implements A.nestedinterface { Void show() {. } }

Topic name Concept: Some points about instanceof:-

instanceof

1. Instanceof operator checks whether a super class reference is pointing to which object at runtime. 2. Instanceof return true or false value. Return true, which you are looking otherwise false. Syntax: Example: instanceof classname

class Employee { int empId; public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } } public class Example extends Employee{ public static void main(String args[]) { int choice = Integer.parseInt(javax.swing.JOptionPane.showInputDialog("Enter your choice")); Employee e = getObject(choice); if(e instanceof Employee) System.out.println("e pointing to Employe object"); else if(e instanceof Example) System.out.println("e pointing to Example object"); } private static Employee getObject(int choice) { Employee temp = null; if(choice == 1) temp = new Employee(); else if(choice == 2) temp = new Example(); return temp;

} }

Topic :Concept:

this working as a function call

1. this can also be used as a function call. 2. It is rarely require in program. 3. This as function call not in c++. Syntax: Example: public class Example{ int value1,value2; public Example(int v) { this(v,23); } public Example(int x, int y) { this.value1 = x; this.value2 = y; System.out.println(value1 + " " + value2); } public static void main(String args[]) { Example ex = new Example(12); } } Topic name Concept:importance of import Some point about import statement:this(value);

1. import used to import packages classes in your program.

2. import statement is different from include in c++. 3. import is runtime phenomena and include is compile time phenomena. 4. import does not increase size of your program but include statement is increase size of your code. Import java. swing. * ; Import java. swing. JOptionPane; What is difference between both above statement? Both statements are similar because both are runtime entity. But star (*) statement may increase the compilation time especially if you import large packages. For this reason it is a good ideal to explicitly give the name of the class or classes that we want to use rather than importing whole packages.

Topic:

Exception Handling

Concept:- 1. all about dealing with runtime trouble. 2. functions cause exceptions not classes. 3. Separation of normal flow from error rectification flow. (Benefit) Some points about exception handling:Exception means runtime error like DivideByZero. Throwable is a super class for all exception. Throwable divided into two parts 1. Exception 2. Error Exception is super class for all exception. Exception can be handled but error can not be handled. Class never throw an error, function throw an error. (Unlike c++). throw an exception must be an object of sub class of exception means you can not throw everything. 8. Java handles the exception through try/catch block. 9. Runtime exception is subclass of exception also known as unchecked exception. 10.The exception that is not subclass of the Exception but subclass of runtime Exception is called unchecked Exception or runtime Exception and these are checked by the compiler. 11.Throwing an exception is good if your code used by many people. Very stupid way is to handle the exception in your code. Means no one can predict what error was. 1. 2. 3. 4. 5. 6. 7.

throwable class

Exception

error class

checked

runtime

Throwable means we are having a person with us. Error - dead situation. (Next formality to do):nothing to do to handle the exception just show some message Exception - injured Situation. (dont treat it like dead situations, but be open to the idea of injured do some times die) printStackTrace() printStackTrace() , this is a function present in the Throwable class. this function is very very useful function, because it gives the reasons why the program got error. Q. if at from the catch block you want to go to the try block? A. then ensure that try and catch block is put in some loop. Q. how does the control switch from try block to the catch block. ? A. an object of the exception class which occurred is created and then thrown in the try block only then the control comes to the catch block. Example:if NumberFormatException is occurring. inside the try block, the object of NumberFormatEXception is getting created and then getting thrown only then we are catching it in the catch block. NumberformatException and ArrayIndiexOutofBounds Exception are both system known exceptions 1. System knows that it is a Exception

2. System also knows when it occurs 3. what system does not know it what to do when it occurs. so our job is restricted typically to do only 3.

Topic name Concept: Some points about throwable class:-

Throwable class

1. Throwable class exists inside java.lang package. 2. The Throwable class is the superclass of all errors and exceptions in the Java language. 3. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. 4. Similarly, only this class or one of its subclasses can be the argument type in a catch clause. 5. Instances of two subclasses, Error and Exception, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data). Topic name Exception class

Concept: Some points about Exception class:1. The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. 2. This class used to define user defined exception. Constructor of Exception class:Exception() Constructs a new exception with null as its detail message. Exception(String message) Constructs a new exception with the specified detail message. Exception(String message, Throwable cause) Constructs a new exception with the specified detail message and cause. Exception(Throwable cause)

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

Topic name Concept: Some points about Error class:-

Error class

1. An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The Thread Death error, though a "normal" condition, is also a 2. subclass of Error because most applications should not try to catch it. 2. A method is not required to declare in its throws clause, any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

Constructor of Error class:Error() Constructs a new error with null as its detail message. Error(String message) Constructs a new error with the specified detail message. Error(String message, Throwable cause) Constructs a new error with the specified detail message and cause. Error(Throwable cause) Constructs a new error with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

Topic name Concept:

try/catch block

Some points about try/catch block:1. 2. 3. 4. If you are not sure about your code then write your code inside try block. if an exception occur then error rectification code executed. try can be nested. try must be followed by catch or finally block and one try block can be followed by one or more catch blocks. try { }catch(exceptionclassname e) { //exception handled } Runtime Exception (Unchecked):Exception Meaning

Syntax:

1. Arithmetic Exception = divided by zero. 2. ArrayIndexOutOfBoundsException = Array index is out of bound. 3. IllegalArgumentException = illegal argument used to invoke a method. 4. NullPointerException = invalid use of null reverence. 5. NumberFormatException = Invalid conversion of a string to a numeric format.

NonRuntime Exception (checked) :1. 2. 3. 4. 5. 6. ClassNotFoundException Class not found. illegalAccessException access to a class is denied. Interrupted Exception one thread has been interrupted by another thread. NoSuchMethodException A requested method does not exist. IOException SQLException

Something to remember:-

1. Every class is a subclass of this class called Object. 2. Throwable which is a subclass of Object.

3. Exception and Error which are subclasses of Throwable. There are classes which are exceptions but not a subclass of Runtime Exception. These are called Non Runtime Exceptions or checked Exceptions.

PrintStackTrace (), this is a function present in the Throwable class. this


function is very very useful function, becuase it gives the reasons why the program got injured. It`s a overloaded function. PrintStackTrace () ; //useful debatable PrintStackTrace (PrintWriter pw) ;//surely very useful.

Topic name Concept:

User defined Exception

Some points about user defined exception:1. User defined Exception can be defined via class which is inheriting Exception class. 2. User defined exception throw by user and handled. 3. System only knows system defined exception when to throw and how to handle. 4. But for user defined exception you explicitly need to tell the system when to throw and how to handle it. Syntax: class Example extends Exception Benefits:- handling the exception by us ,it provides two benefits:1. It allows us to fix the error. 2. It prevents the program from automatically termination. Example:
class MyException extends Exception { private int detail; MyException(int a) { detail =a; } @Override public String toString() {

// TODO Auto-generated method stub return "MyExceptionDetail: "+detail; } } public class Example{ static void compute (int a) throws MyException { System.out.println("called compute: "+a); if(a>10) throw new MyException(a); System.out.println("normal exit"); } public static void main(String args[]) { int num = Integer.parseInt(JOptionPane.showInputDialog("Enter no.greater than 10")); try{ compute(num); } catch (MyException e) { System.out.println("caught } } }

"+e);

Q.UserDefined Exception will be NonRuntimeException? A. depends on the User. Because,

Example:1.class classname extends exception// NonRuntimeException class classname extends runtimeexception// RuntimeException

*System.out.println will show error at compile time itself. Compile time if anything is showing an error it is because of the skill of the programmer.

Always handling an exception may not be a good idea. Sometimes we have to let the person calling the function handle the exception.
Example:A , B and C are building networking applciation. A job to write connects code. B and C job is use connect code of A and do a job called X and Y respectively.

Using throw:so what should A do. A put try { }catch(ConnectionNotFouhnd) { } catch(FireWallProblem x) { } This is called stupidity by A? whenever our function is going to be used by lot of people, then our job is to only detect the trouble and let the end user of our function, know what the trouble has occured. and let that person decidde how to handle it. this is becuase we dont know the context in whcih our function will be used. Example:detects network problem and handles it by himself its a wrong way.

correct thing for A to do , detect the trouble and let B and C handle the trouble. this is English, how do you technically Connect (c1,c2) throws ComputerNotFound,FireWallProblem { Throw new ComputerNotFound () } Syntax:void f1() throws ExceptionClassName1, ExceptionClassName2. void f1() throws NullPointerException, NumberFormatException

using throws does not mean you should not use try and catch. it simply means use throws compulsorily in your code.

Runtime and non RuntimeExceptions. Defination:- read from javainterview Question-1 pdf

when we catch unnecessarily a nonRuntimeException, it will lead to a compiler error. but this is not the case with RuntimeExceptions. whenever we deal with a checked exception the compiler will complain if the exception is handled unnecessarily or if the exception is not handled when it occurs.

during overriding. the overridden method can throw new runtime Exceptions but not new non runtime exceptions.

1. when we are writing code, we should know whether we are the inner layer or in the outer layer of the architecture. 2. if we are inner layer, we should always throws the exceptions .

3. during overriding what happens class A public void m1() throws CE1 class B extends A public void m1() //ok public void m1() throws CE1 //this is also ok public void m1() throws CE1, CE2//not ok.

convert CE2 to RE and then throw it. public void m1() throws CE1,RE1 // ok. CE:=CHECKED EXCEPTION RC: =RUNTIME EXCEPTION When new nonRunTime Exception throws from base class then in the derived class we can not thows new nonRunTime Exception but we can throws RunTime Exception.

Topic:

finally

Concept:- finally is a block which can be used with try.


finally is a block that gets executed whether exception occurs or does not occur. usually useful whenever there is spawning of exception. (or) 1. finally is used primarily to avoid resource leaks . 2. Finally is a block used in context of exception handling to enforce things which need to be happen irrespective of whether exception occurs or does not occur. 3. it is used to write any common code that needs to be executed irrespective of whether exception occurs or does not occur.

4. Typically comes into picture when we are throwing exceptions from the function.

SEE example:import java.io.IOException; public class SpawningofException extends InnerLayerClass { public static void main(String[] args) { try { f1(args.length); } finally { System.out.println ("file closed"); } } private static void f1(int i) { try { System.out.println ("file opened"); if(i == 0) throw new NullPointerException(); } catch (NullPointerException e) { System.out.println("Hello"); } } }

Some additional info by me Exceptions:An exception is an unexpected event, which occurs during execution of a program, that disrupts normal flow of programs instruction. This leads to halt of execution or some time crashing of program. To overcome this issue, a code must be written that can detects and handle the exceptions. Java allows to create o own exception handler.

Exception handler:It a section of code, that responds to exceptions when they are thrown. This process of intercepting and responding to the exceptions is called exception handling. How:- When an error occurs within methods, it creates an object and hands off it to the runtime system. The object is called exception object, contain information about:-

Error Its type

State of program when exception occurred Throwing an excepting:Creating an exception and handling it to runtime system is called throwing the exception. The method which throws the exception may choose to handle the exception on its own or pass it on. In java 5 keywords to handle the exceptions:-] Try catch throw throws finally

Benefits of handling exceptions yourself:1. Allows you to fix the error 2. Prevents to automatically terminates the code General syntax of exception:Try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally

{ }

//The finally block always executes.

Basically, you try to execute a block of code, error occurs, throws exception which may be catch by which type of exception and finally dealt with default handler. Try can not be used in single line statement. Hierarchy of classes:Object

Throwable Exception InterruptedExpection Error ThreadDeathead *****

RuntimeException ****

Null PointerException ArithmeticException IllegalArgumentsException NumberFormatException

IndexOutOfBoundException ArrayIndexoutOfBoundException

All the class belongs to the object class. throwable class is the super class of all the exceptions and error class in java.lang package. instance `

Topic:Concept:-

chained exception

A. An application often responds to an exception by throwing another exception. In effect, the first exception causes the second exception. It can be very helpful to know when one exception causes another and this process is c/d chained exception

The following example shows how to use a chained exception. try { } catch (IOException e) { throw new SampleException("Other IOException", e); } In this example, when an IOException is caught, a new SampleException exception is created with the original cause attached and the chain of exceptions is thrown up to the next higher level exception handler.

Topic name Concept: Some points about Object class:-

Object class

1. Object is a super class of all classes in java. 2. Object class exists in the top hierarchy java.lang. Object. 3. There are some methods like toString(), equals() , hashcode() which are non final methods. 4. The methods getClass(), notify(), notifyAll() and wait() are declared as final.

Object class provides three important non final methods 1. toString 2. equals 3. hashcode
Some methods of Object class:Methods String toString() boolean equals(Object arg) Int hashCode() Working It is a way to represent an object in form of string. Equals method used to compare two objects. Returns a hash code vale for an

object Protected void finalize() Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. Creates and returns a copy of this object. Returns the runtime class for an object

Protected object clone() Class getClass()

Topic name Concept: Some points about toString ():1. 2. 3. 4.

toString() method

toString () is a non final method defined in Object class. Object is a super class of all class in java. So our own class may override it. Main use is when you want to represent your object to string form.

Process of toString:Whenever the system looks at an object let us say obj1, if it finds there is a need to represent it as a string, it will come to the class to which the obj1 belongs to and invoke it s toString method. Many a times string representation is required only for display purposes. Syntax: Example:public class ToStringExample { public static void main(String[] args) { ToStringExample ex = new ToStringExample(); System.out.println(ex); public String toSting();

} @Override public String toString() { return "ToStringExample class object"; } }

Q. need is always to represent an object in form of a string and not to convert. why? A. Strings are the only things human beings understand, because in what form object is present in the computer we dont know, we can understand only string form of that object.

Topic:Concept:-

equals() and equalsIgnoreCase()

Some points about equals method:1. Equals is also non final method defined in super class Object, now we may be override it. 2. equals used to check whether two objects are same or not. if same than it will return true otherwise false. 3. Its a case sensitive method. 4. Ex:- hello and HELLO both are not same for this method. 5. equalsIgnorecase() is not a case sensitive method. Ex:- hello and HELLO both are same for this method. 6. equals method is expensive becuase it involes object comparison.

Power of equals is:1. system tells you define what is the meaning of equality between two objects and when need comes I will use it 2. How to teach it, override the equals method from the object class. 3. During overriding, it is understood, what you write inside the method is left

to you, only thing system can do is call the method when object is found of your type. Syntax:Example:public class equalsExample { int key; equalsExample(int key) { this.key = key; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final equalsExample other = (equalsExample) obj; if (key != other.key) return false; return true; } } public static void main(String[] args) { equalsExample ex = new equalsExample(45); public Boolean equals(Object obj);

equalsExample ex1 = new equalsExample(45); if(ex.equals(ex1)) System.out.println("Equal"); else System.out.println("Not Equal"); }

Topic:-

hashCode()

Concepts:1. its a function which is defined in object class it gives actual address of an object in memory. Example:- when we use hash code with object than it gives integer value that value is address of that object. When we use hash code with object than it tells the system you need to call equals method or not (filter).

1. To compare whether objects are equal or not equal, it odes not use equals method first. Rather uses hashcode first and then depending on result of hashcode, calls the equals method.

2. if you have overridden the hashCode() method , and still you want to
get the original hashCode of a particular class then we can use the method System.identityHashCode(obj) example: int originalHashCode = System.identityHashCode(emp1);

Example.:there are objects, obj1 and obj2. what system will do is to compare whether these are equal or not

equal.what system does is. 1. int x = obj1.hashCode() 2. int y = obj2.hashCode() if( x != y ) objects are not equal. else { boolean valid = obj1.equals(obj2); if(Valid) objects are equal else objects are not equal. }

Topic:Comparable:-

Comparable and Comparator

Concept:- Comparator and Comparable are both interfaces used when we want to do sorting primarily on DS. When we are using Comparable we can use it for sorting.
1. Classes that implements comparable contain object that can be

compared in some meaning manner. 2. The comparable interface declares one method that is used to determine what java calls natural ordering of the instance of the class. 3. The signature of the method:int compareTo(Object obj) \\ this is used for natural sorting. 4. This method compares the invoking object with OBJ.

It returns 0 if both values equal. But returns negative if invoking object has lower value and otherwise returns positive value 5. natural sort can be decided at compile time itself, By using Comparable. 6. when we print by default we want it to be sorted by userid. This is what we call natural sorting. 7. by using comparable we cannot decide the sorting criteria at runtime. Collections. Sort (list); Comparator:-

1.

Comparator which is used for runtime sorting or unnatural sorting. If we want to mention sort at runtime, On a particular field then we need to go for unnatural sort:- Comparator

int compare(Object e1 , object e2) \\this is used for unnatural sorting. by using comparator we can use:collections.sort(list,comparatorobject) here this comparator object is what we term by telling sorting criteria can be determined at runtime

Classes should implement the Comparable interface to control their natural ordering. Objects that implement Comparable can be sorted by Collections.sort() and Arrays.sort() and can be used as keys in a sorted map or elements in a sorted set without the need to specify a Comparator. Interface Comparable + compareTo(Object) : int

compareTo() compares this object with another object and returns a negative integer, zero, or a positiveinteger as this object is less than, equal to, or greater than the other object. Use Comparator to sort objects in an order other than their natural ordering. Interface Comparator + compare(Object, Object) : int + equals(Object) : boolean compare() compares its two arguments for order, and returns a negative integer, zero, or a positiveinteger as the first argument is less than, equal to, or greater than the second. Comparable should be used when you compare instances of same class. Comparator can be used to compare instances of different classes. Comparable is implemented by class which need to define a natural ordering for its objects. Like String implements Comparable. In case one wants a different sorting order then he can implement comparator and define its own way of comparing two instances.

TOPIC:Concept:-

Binary search with user defined objects.

1. get your comparator object working in case you feel some element is null in between. 2. create a object which are trying to locate.

a. pos =Arrays.binarySearch(arrayname,objectToFind, comparatorobject);

TOPIC:Concept:-

Input/output

Streams:-A stream is an abstraction that either produces or consumes


information. It is linked to a physical device by the java I/ O system. Two types of streams 1. Byte stream:-it defined by the two class hierarchies. at the top two abstract classes, Inputstream and Outputstream These classes define several key methods that other stream classes implement. Like read (), write() 2. Character stream:- it defined by the two class hierarchies. at the top two abstract classes, Reader and Writter.

BufferedReader:-it supports a buffered input stream. Its most commanlly


used constructor. Bufferedreader(Reader inputreader)

Topic: Cocept:-

Thread

Thread:- A thread is an independent path of execution within a program. Threading is the facility to allow multiple activities to coexist within a single process. Every thread in Java is created and controlled by the java.lang.Thread class. Thread is sometime referred to as light weight process. Because it share the same address space which is given to the process. But Thread has its own stack, its own program counter and its local variable. A process can support multiple threads, which can be executed simultaneously. Multiple threads within a process share same memory address space, which means they have access to the same variable and object; they allocate objects from the same heap.

Thread Creation:There are two ways to create thread in java


Implement the Runnable interface (java.lang.Runnable) By Extending the Thread class (java.lang.Thread)

Runnable Interface Signature: public interface Runnable { void run(); } One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. We need to override the run () method into our class which is the only method that needs to be implemented. The run () method contains the logic of the thread. The procedure for creating threads based on the Runnable interface is as follows: 1. A class implements the Runnable interface, providing the run () method that will be executed by the thread. An object of this class is a Runnable object. 2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run () method. 3. The start () method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned. 4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception. Class RunnableThread implements Runnable { Thread runner; public RunnableThread () { } Public RunnableThread (String threadName) { runner = new Thread (this, threadName); // (1) Create a new thread.

System.out.println (runner. getName()); runner. start(); // (2) Start the thread. public void run(){ //Display info about this particular thread System.out.println(Thread.currentThread()); } } public class RunnableExample{ public static void main(String[] args){

Thread thread1 = new Thread(new RunnableThread(),"thread1"); Thread thread2 = new Thread(new RunnableThread(),"thread2"); RunnableThread thread3 = new RunnableThread("thread3"); //Start the threads thread1.start(); thread2.start(); try{ //delay for one second Thread.currentThread().sleep(1000); }catch(InterruptedException e){} //Display info about the main thread System.out.println (Thread.currentThread()); } } Extending Thread Class The procedure for creating threads based on extending the Thread is as follows: 1. A class extending the Thread class overrides the run () method from the Thread class to define the code executed by the thread. 2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super () call. 3. The start () method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.

Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start () method on your object.
class XThread extends Thread { XThread() {} XThread(String threadName) { super(threadName); // Initialize thread. System.out.println(this); start(); } public void run() { //Display info about this particular thread System.out.println(Thread.currentThread().getName()); } } public class ThreadExample { public static void main(String[] args) { Thread thread1 = new Thread(new XThread(), "thread1"); Thread thread2 = new Thread(new XThread(), "thread2"); // The below 2 threads are assigned default names Thread thread3 = new XThread(); Thread thread4 = new XThread(); Thread thread5 = new XThread("thread5"); //Start the threads thread1.start(); thread2.start(); thread3.start(); thread4.start(); try { //The sleep() method is invoked on the main thread to cause a one second delay. Thread.currentThread().sleep(1000); } catch (InterruptedException e) { } //Display info about the main thread System.out.println(Thread.currentThread()); } }

Output Thread[thread5,5,main] thread1 thread5

thread2 Thread-3 Thread-2 Thread[main,5,main]

thread is the part of the process.


what is the drawback of OS level threads, simple they are not portable. java claims it is portable that means it cannot be OS level thread, it needs to be a application level thread very simple. What is a threadgroup? It is a class which can help you to logically group threads. but this is a useless thing to use in real life. what is better way to group threads? use map to group threads than using ThreadGroup that is the reason they tell ThreadGroup is deprecated. to know which thread our function is getting executed in we can use a method called Thread.currentThread() it returns a thread object. Thru which we can come to know threadname, priority, threadgroupname. do you know how to tell in thread your function is getting executed? good by default our program begins with a thread called main. Thread.currentThread returns us the Thread class object. Thread class is heart of threading api in java. NO thread class object, no threads in java. what is the technical meaning of stopping the thread.? come out of the run method. when will you come out of run method, when the last line in the run method gets executed.

TOPIC:-

Synchronization or mutex

Concept:- its a modifier


Synchronization is best use with the Multi-Threading in Java, Synchronization is the capability to control the access of multiple threads to share resources.

Example:- if there are two threads A and B , both applied on the same
object. One thread read values from object and another thread set values on that object. So if we dont use synchronization than both the treads perform their operation simultaneously and we get invalid results. But with the help of synchronization we take the key of an object (every object has a key) so any other tread can not any perform any operation on that object until the first thread completed its works and release the key of an object on which it is operated.

Note:- synchronization means security or body guards for the resource, first
thing we should know it makes code very slow because it enforce that only one Thread can use common resource at a time. Q. synchronization is required if two threads access a resource A. True or False? False. Q. synchronization is required if two threads access a resource concurrently? A. True or False? False Q. synchronization is required if two threads access a non sharable resource concurrently? True or false. A. True.

Topic: Concept:-

mutable and immutable

Mutable Objects: When we have reference to an instance variable of an object, the contents of that instance variable can be altered, means we have setter method to modify the contents of the object. All the simple classes are mutable because these classes have setter and getter methods so we can modify the state (contents of instance variable) of the object by using the setter and getter method. Example:Class A { Setter method()

Getter methods() } A obj1; obj1.setter method (contents); Obj1.setter method (different contents); \\changing the state of the object. Immutable Objects: - When you have a reference to an instance of an object, the contents of that instance cannot be altered, means we dont have setter method. In Immutable class can have only getter methods and constructors. so if we want to modify the contents of the instance variable of that class than each time we have to create new object with the help of constructor. ImMutable:String myString = new String (old String" ); System.out.println (myString ); myString.replaceAll ( "old", "new" ); System.out.println ( myString ); In case you can't see what the output is, here it is: java.awt.Point[0.0, 0.0] java.awt.Point[1.0, 0.0] old String old String String myString = new String( "old String" ); System.out.println( myString ); myString = new String( "new String" ); System.out.println( myString ); The output from this is: old String new String

Topic:-

Annotation

Concept:Annotations are like meta-tags that you can add to your code and apply them to package declaration ns, type declarations, constructors, methods, fields, parameters, and variables. As a result, you will have helpful ways to indicate whether your methods are dependent on other methods, whether they are incomplete, whether your classes have references to other classes, and so on

Topic:Concept:1. 2. 3. 4. 5. 6.

Applet

Applets are small programs transferred through Internet, automatically installed and run as part of web-browser. Applets implements functionality of a client. Applet is a dynamic and interactive program that runs inside a Web page displayed by a Java-capable browser. The most important thing is that applet program does not have main method. Applets can be invoked either through browser or through Applet viewer utility provided by JDK. This applet begins with two import statement. AWT (Abstract Window Toolkit) . 6.1. Applet interact with user(either directly or indirectly) through the AWT, not

through the console-based I /O classes. 6.2. The second statement applet package, this package contains Applet class 7. Every applet that we create must be a subclass of the Applet. 8. It present in the java. Applet package. when applet gets executed in the browser than it provides 5 methods:the first 3 methods are called sequentially at the time of loading of the applet. 1) 2) 3) 4) Init Start Paint Stop: - when the user leaves the page and goes to the other page.

then user comes back to the old page, then again start and paint Methods get called. 5) destroy : -user closes the browser, then destroy method gets called. Basic:- suppose we write an applet 1. constructor. 2. init 3. start which method will get called first? answer is constructor, that is basic.

Example:public class MyApplet extends Applet { }

To make an applet work, we need to the following steps.


1. Write class that must extends Applet write our business logic in that class. 2. Write applet code and compile it. 3. Write a html page, put the applet tag in the html and mention the class name. Example:-<HTML> <BODY> <Applet code=MyApplet width=50 height=60> </applet> </BODY> </HTML>

There are 2 ways to run this program


1. open the html file in the jvm present browser, applet should be visible. 2. We can run it with the help of AppletViewer command in the CMD.

Topic:Concept:

Collections

A collection (sometimes called a container) is an object that groups multiple elements into a single unit.

Collections are used to store, retrieve and manipulate data, and to transmit data from one method to another.

Dynamic Collections vs. Arrays Arrays


The Array is the simplest way that Java provides to store and randomly access a sequence of objects. The Array is a simple linear sequence, which makes quick insertion and element access fast. The speed of accessing data comes with a drawback; the size of an array is fixed and cannot be changed for its lifetime. The other drawback includes insertion of an element at a particular position is slow.

Collections
Unlike arrays the collection classes do not have a fixed size, the size is dynamically expanded. Handle insertion, deletion and resizing better, even though few implementations will be backed by an array. The drawbacks include, random access of elements is not always as fast when compared to an array.

The Java collections framework is made up of a set of interfaces and classes for working with groups of objects.

Benefits of Collection Framework:Reduces programming effort: Provides useful data structures and algorithms. Thereby, programmer concentrates on the business logic.

Increases program speed and quality:

Provides high-performance, high-quality implementations of useful data structures and algorithms.

Reduces effort to learn and to use new APIs: No need to learn each API from scratch.

Reduces effort to design new APIs: Don't have to reinvent the wheel. Instead, use the standard collection interfaces.

Collections Framework

Collection Interface
There are nine collection interfaces. The most basic interface is Collection. Five interfaces extend Collection: Set, List, SortedSet, Queue, and BlockingQueue. The other three collection interfaces, Map, SortedMap, and ConcurrentMap do not extend Collection, as they represent mappings rather

than true collections. However, these interfaces contain collection-view operations, which allow them to be manipulated as collections. Collection Interface is the root interface in the collection hierarchy. Collection interface has no direct implementations; it has sub interfaces like Set and List.

Collection Implementations - The general purpose implementations are summarized in the table below:

List interface
List is an ordered collection (also called a sequence). Lists may contain duplicate elements. In addition to operations inherited from Collection, the List interface includes operations for Positional access, Search, Iteration, Range View.

Syntax:Public interface List extends Collection Methods used with list interface: void add(int index, Object element)
Inserts the specified element at the specified position in this list.

Object get(int index)


Returns the element at the specified position in the list.

Object set(int index , Object element)


Replaces the element at the specified position in this list with the specified element.

int indexOf(Object o)
Returns the index in this list of the first occurrence of the specified element, or 1 if this list does not contain the element.

ListIterator listIterator()
Returns a list iterator of the elements in the list.

ArrayList class Concept:- public class ArrayList implements List ArrayList is a generic class that has declaration:Class ArrayList<E>implements List
ArrayList is the resizable array implementation of the List interface. An Array List can dynamically increase or decrease in size. Array List is created with initial size, when the size exceeded, the collection automatically enlarged. When objects are removed the array can be shrunk.

Set interface
Set interface extends collection and declares the behavior of the collection. A Set is a Collection that cannot contain duplicate elements. The Set interface contains only methods inherited from the Collection, it doesnt define any additional method of its own and adds the restriction that duplicate elements are not allowed. The add method returns false if attempt to add duplicate element otherwise it returns true.

Public interface Set extends Collection Set is a generic interface and declaration:Interface Set<E> \\E specifies the type of objects.

SortedSet interface Concept:1. It extends the set interface and declares the behavior of the set and stored in ascending order.

2. Its a generic interface Interface SortedSet<E> NavigateSet Interface Concept:1. It extends SortedSet interface and declares the behavior of the collection that support the retrieval of elements based on the closest match to a given value or values. 2. Its a generic interface

Interface NavigateSet<E> TreeSet Class Concept:1. 2. 3. 4. TreeSet extends AbstractSet implements the NavigableSet interface. It creates a collection that uses tree for storage. Objects are stored in the sorted, ascending order. Access and retrieval time fast, which makes treeSet an excellent choice when storing large amount of sorted information that must be found quickly. 5. TreeSet is a generic class that declares:Class TreeSet<E>

6. It has following constructor:TreeSet() TreeSet(Collection<? Extends E>c) TreeSet(Comparator<? Super E>comp) TreeSet( SortedSet<E>ss)

HashSet class Concept:1. It implements the Set interface . 2. It creates collection that uses hash table for storage. 3. Its a generic type:-

Class HashSet<E>
4. Has table stores the information by using a mechanism called hashing. in hashing, the informational contain of a key is used to determine a unique value, called its hash code. 5. HashSet does not specify any additional method beyond those provided by its super classes and interfaces.

VVIMP: - Hash Set does not guarantee the order of its element, because the process of hashing doesnt usually lend itself to the creation of the sorted set.

CONSTRUCTORS 1. Hash Set() 2. Hash Set(Collection c)


Constructs a new set containing the elements in the specified collection.

3. HashSet(int initialCapacitys)
Constructs a new set, the backing HashMap instance has the specified initial capacity.

Map interface
1. A map is an object that stores associations between keys and values, or key/value pairs. 2. By given key we can find its value. 3. Both keys and values are object. 4. The key must be unique but value may be duplicated. 5. Some map can accept null key and null value. 6. Map does not extend collection interface but map is still consider part of the collection framework (also k/n as collection API). 7. Map is generic and is declared as Interface Map<K, V> \\k specifies type of key, v specifies type of value VVIMP: =The key point about maps is they dont extends the iterable interface .this means that you can not cycle through a map using a for-each loop. Declaration: -

Public interface map

Methods used in the map: Object put(Object key , Object value)


Put an entry in the invoking map, overrides any previous value associated with the key. returns null if key didnt already exist. Otherwise the previous value linked to the key is returned.

Object get(Object key)


Returns the value to which this map maps the specified key. Return null if key is not found.

Object remove(Object key)


Removes the mapping for this key from this map if it is present.

int size()
Returns the number of key-value mappings in this map.

Collection values()
Returns a collection view of the values contained in this map.

Set keySet()
Returns a set view of the keys contained in this map.

Sorted Map interface

1. The sorted map interface extends map. 2. It ensures that entries are maintained in ascending order based on the keys. 3. SortedMap is generic and is declared :Interface SortedMap<k, v> 4. A NullPointerException is thrown if an attempt is made to use null object when null is not allow in the map.

NavigateMap Interface
1. it extends SortedMap and declares the behavior of the map. 2. That supports the retrieval of the entries based on the closed match to a given key or keys. 3. Navigate Map is generic and is declared :Interface navigateMap<k, v> 4. A NullPointerException is thrown if an attempt is made to use null object when null is not allow in the map.

HashMap Class Concept:1. HashMap class extends AbstractMap and implements the Map. it doesnt add any methods of its own. 2. The HashMap is the hash table based implementation of the Map interface. 3. HashMap does not guarantee the order of its elements, therefore the order in which elements are added to a HashMap is not necessary the order in which they are ready by an iterator. VVIMP:4. Constructs an empty HashMap with default initial capacity of 16. 5.

public class HashMap<K,V> extends abstractMap<K,V>

6. The implementation provides all of the optional map operations, and permits null values and the null key. CONSTRUCTORS HashMap ()
Constructs an empty HashMap with default initial capacity of 16.

HashMap(Map<K,V> m)
Constructs an empty HashMap with the same mappings as the specified Map.

HashMap(int initialCapacity)
Constructs an empty HashMap with the specified initial capacity.

Hashtable class Concept:1. Like hashMap, hashtable stores the key/value pairs in the hash table. 2. Neither key nor value can be null. 3. In table we specify an object that is used as a key and the value that we want linked to that key. The key is than hashed and the resulting hash code is used as the index at which the value is stored. 4. The default size is 11 5. It is declared like this: Class hashtable<k,v> The hashtable constructor:-

Hashtable ()
The default constructor.

Hashtable (int size)

This creates hash table that has initial size specified by size. The default size is 11

Hashtable(int size, float fillRatio)


This creates hash table that has initial size specified by size and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0 and it determine how full the Hash table can be before it is resized upword. Specifically, when the number of elements is greater than the capacity of the hash table multiplied by its ratio, the hash table is expaneded.if we dont specify a fill ratio, than 0.75 is used.

Hashtable(Map<?exytends K, ? extends V>m)


It creates hash table that is initialized with the elements in m. the capacity of hash table is set to twice the number of element in m. the default load factor is 0.75 used.

Dictionary class Concept:1. Dictionary is an abstract class that also stores key/value pair like map. 2. Once the value is stored we can retrieve it by using its key. 3. Like map, dictionary can be thought of as a list of key/value pairs. 4. Although not currently deprecated, dictionary is classified as obsolete, Declaration:Class Dictionary<k,v>

Methods used in the Dictionary: Object put(Object key , Object value)


Put an entry in the invoking Dictionary, overrides any previous value associated with the key. returns null if key didnt already exist. Otherwise the previous value linked to the key is returned.

Object get(Object key)

Returns the value to which this Dictionary maps the specified key. Return null if key is not found.

Object remove(Object key)


Removes the mapping for this key from this Dictionary if it is present.

int size()
Returns the number of key-value mappings in this map.

Collection values()
Returns a collection view of the values contained in this Dictionary.

Set keySet()
Returns a set view of the keys contained in this Dictionary.

Properties class
Concept:1. Properties are a sub class of the hashtable. 2. It is used to maintain list of values in which the key and value both are strings. 3. The properties class is used by many other java classes. 4. Although the properties class itself is not generic 5. Properties defines one instance variable:-Properties default; This variable holds default properties list associated with properties object.

Properties defines constructor:Properties () Its a properties object that has no dfault values. Properties(properties propDefult) Its creates an properties object that uses propDefault for its default values. In both cases the properties list is empty. VVIMP:-we can specify a default property that will be returned if no value is associated with a certain key.

Example:- default value can be specified along with the key in the getProperty() method. getproperty(name,defaultvalue). If the name value is not found than default value will returned.

Topic: -

JDBC (Java Database Connectivity)

Concept:1. JDBC is a platform- independent interface b/w a Relational database and a java programming language. 2. It allows java program to execute SQL statement and retrieve the results according to the statement. 3. JDBC also provides methods to return an error message while accessing a database. JDBC provides the following characteristics, which makes it more efficient in comparison to ODBC. a) JDBC simple and easy to use. b) JDBC support a wide level of portability. c) JDBC provides java interfaces compatible with java application and responsible for representing the drivers services. JDBC Drivers Type-1 Driver:- Type-1 driver acts as a bridge b/w JDBC and other database connectivity mechanism such as ODBC and this is sun JDBC-ODBC bridge driver implementation. This driver helps to java programmers to use JDBC and program java application to communicate with existing data sores. Type-2 Driver:-Type-2 driver converts JDBC call into DB vendor specific native call in a client machine. this type of driver is implemented specific for database and usually delivered by a DBMS vendor. it is not mandatory that type-2 driver have to be implemented by DBMS vendor. Example:-Web logic driver implemented by BEA Web logic.

This type of driver is not recommended for use when java applications required with auto-installation application, such as applet. Type-3 Driver:- Type-3 driver translate JDBC calls into database server independent and middleware server specific net protocol calls (n/w calls), which are then translate into database server specific calls by the middleware server. Type-3 driver is recommended to be used with applet since this type of driver is auto downloadable. Type-4 Driver: - The type-4 driver is a pure java driver, which implements the database protocol to interact directly with a database. This type of driver does not require any native database libraries to retrieve the record from the database. This type of driver translates JDBC calls into Database specific n/w calls. These can be used when we want to auto downloaded option for client side application. It is also recommended to be used with server side application.

Topic:-

The java.sql package

Concept:1. The java.sql package is also k/n as the JDBC core API. 2. This package includes the interfaces and methods to perform JDBC core operations, such as creating and executing SQL queries. 3. The java.sql package consists of the interfaces and classes that need to be implemented in an application to access database. 4. Based on the different operations, the classes in the java.sql Can be categorized in the following categories:a) Connection Management b) Database Access c) Data type d) Database Metadata

e) Exception and warning. Topic: The javax.sql package

Concept:1. The javax.Sql package is also k/n as JDBC extension API. 2. This API provides classes and interfaces for accessing serverside data sources and processing java programs. 3. The JDBC extensions package supplements the java.sql package. 4. This is the special platform for the java EE. 5. The javax.sql package provides the following features. a) Data Source b) Connection and statement pooling c) Distributed transaction d) Row Sets.

Topic:Concept:-

DriverManager Class

1. DriverManager is a non-abstract class in the JDBC- API. 2. It contains only one constructor, which is declared private, which implements that this class can not be inherited or initialized directly. 3. All the method and properties of this class are declared as static. 4. The main responsibility of this class :a) Maintains a list of Driver info objects, where each Driver Info object holds one Driver implementation class object and its name. b) Prepares a connection using the Driver implementation that accepts the given JDBC URL.

Topic: -

Connection Interface

Concept:1. The connection interface is a standard type that defines an abstraction to access the session established with a database server. 2. JDBC driver provider must implement the connection interface. 3. Connection type of object (i.e. an instance of the class that implements the connection interface) represents the session established with the data store. 4. The connection interface provides the methods for handling a connection object.

Topic: -

Statement Interface

Concept:1. The statement interface defines a standard abstraction To execute SQL statements requested by user and return the Result by using ResultSet object. 2. A Statement object contains a single ResultSet object at a time. 3. Therefore, if the reading of one ResultSet object is interleaved with the reading of other, each must have generated by different Statement objects. 4. The execute () method of all statements implicitly close a statement`s current ResultSet object if it is open. 5. The statement interface provides specific methods to execute and retrieve the result from the database. NOTE:- in case of Statement the excecuteUpdate method takes sql query as a parameter because the query is not passed as parameter in Statement. EX:- Statement stmt = con.createStatement(); stmt.executeUpdate(sqlCmd);

Topic: -

Prepared Statement Interface

Concept:1. The Prepared Statement interface is used to represent precompiled quires, which can be executed multiple times without compiling it again and again. 2. So their execution is much faster than that of the statement object. 3. PreparedStatement is a subclass of the statement interface 4. A PreparedStatement object must be associated with one object. 5. A PreparedStatement object represents the execution plan of query, which (query) is passed as a parameter while creating the PreparedStatement object. Therefore the query can be parameterized query in this case. 6. The Execute methods do not take any parameter while using PreparedStatement. 7. The main advantage of PreparedStatement is that it can represent only one SQL statement. That is we can not execute more than one statement by a single PreparedStatement. NOTE:- in case of preparedStatement the excecuteUpdate method does not take any parameter because the sql query is passed as parameter in PreparedStatement . Ex:PreparedStatement stmt = con.prepareStatement(sqlCmd); stmt.setString(1, args[0]); //observer no argument during execute upate rowsAffected = stmt.executeUpdate(); //constraint is violated we will have an exception but if no rows is selected we get zero and not an exception When to use it:1. When a single query is being executed multiple times. 2. When a query consists of multiple number of parameters and complex types (SQL 99 types).

Topic: -

ResultSet

Concept:1. A ResultSet is an interface packed in java.sql package provided by the JDBC core API. 2. A ResultSet object encapsulates resultant data obtained when query is executed. 3. A ResultSet object hold Zero or more objects, where each of the object represents one row that may span over one or more columns. 4. ResultSet interface is used to represent the data in tabular form, which is generated by executing the SQL query. EX:- List<User> users =new ArrayList(); ResultSet rs = stmt.executeQuery(); while(rs.next()) { String userid = rs.getString(1); String password = rs.getString(2);

String email = rs.getString(3); User user =new User(userid,password,email); users.add(user); } VIMP points:1. We can obtain a ResultSet object by using the executeQuery or getResultSet method of a statement. 2. Using one statement, we can obtain any number of ResultSet, but at a time, only one ResultSet can be opened. 3. When we try to open a new ResultSet using a statement that is already associated with opened ResultSet, the existing ResultSet is implicitly closed. 4. ResultSet is automatically closed when a statement that generated it is closed. Connection Example:-

public static Connection getOrcl() throws llegalArgumentException { // include classes12. jar in your project /know your userid, password, databasename, ip address of database.

Connection con = null; try { Class.forName (oracle.jdbc.driver.OracleDriver); //driver loading String url =jdbc:oracle:thin:@localhost:1521:XE"; String userid ="hr"; String password ="hr"; con = DriverManager.getConnection(url, userid, password); if( con == null) throw new IllegalArgumentException ("connection is null"); } Catch (ClassNotFoundException e) {throw new IllegalArgumentException ("story for you, database could not be contacted",e); } Catch (SQLException e) {throw new IllegalArgumentException ("story for you, database could not be contacted",e); } return con; }

Explanation Of database code:1. Class.forName(oracle.jdbc.driver.OracleDriver); Invoke Class.forName (< driver class name>) method, which is used to explicitly load the driver class. 2. Con = DriverManager.getConnection(url, userid, password);

Registering a driver with DriverManager class makes the registered driver available to the DriverManager class. so DriverManager object can be used to establish a connection. when a driver is registered with Driver Manager class, the DriverManager class creates driverInfo object to maintain a driver details and store it into its class variable. URL, which represents a unique name used to identify the driver and obtain the connection.

Topic: Concept:-

JSP (java server pages)

Difference b/w jsp and HTML


jsp = html + lot of things Q. what do you lot of things. ? A. it gets access to lot of implicit objects. Like request, response, session. all of them are objects.

request belongs HttpSErvletRequest. response belongs HttpSErvletResponse. session belongs HttpSession.

Using the <% %> Tags in a JavaServer Page

the <% and %> tags in a JSP file are used to indicate the presence of Java code within the HTML or JSP. <html> <body> <% out.println("<h1>Hello World!</h1>"); %> </body> </html> //o/p:- Hello World! As you can see, the page is composed of standard HTML with a dash of Java contained between the <% and %> character sequences. The <% and %> along with the code inside is called a scriptlet. Whatever we are writing in the scriplet is going into the service method.

Expression: Displaying a Value with <%= %>


<%= request. getAttribute ("xyz"); %> used in jsp is called expression. Expression is used to print the value of a variable (or) <% out.Write (timeOfDay); %> out. Write(timeOfDay) must still end with a semicolon because it must be a legal Java statement. NOTE: - 1. Make sure you don't put any space between the <% and the = sign. 2. we cannot use scriplet within expression or vice versa use both of them independently.

entire JSP page. There are three types. Page Directive Include Directive Taglib Directive

Directive: Directive is the element that provides the global information, about an

<%@page import="java.util.*, java.util.text.* " %> Typical directive being used.

<%@taglib

Life cycle of jsp:1. jspInit 2. jspDestroy 3.jspService. 1 and 2 called only once, when the jsp gets loaded for the first time. 3 gets called frequently as when the request comes. NOTE: - 1. For every jsp, java class is created what we write in scriplet goes into the service method. 2. if you want something to go to the class. then prefer using declaration and not scriplet.

Example:- %@page import="arch.basics.User" %

Declaration:Declaration declares and defines variables and methods that can be used in the JSP page. Example:- <%! int count=0; %> The variable is initialized only once when the page is first loaded by the JSP engine and retains its value in subsequent client request.

Note:- Since the declaration contain JAVA declaration , each variable's declaration must be terminated with a semicolon.

You might want to put an entire Java method into a JSP. If you try to declare a method within the <% %> tags, the Java compiler reports an error. After all, Java doesn't like it if you try to declare a method within another method. Use the <%! %> tags to enclose any declarations that belong outside the expression Example:how will declaration look.

Example:1. <%! int i =3; %> 2. <% void f1() { System.out.println("great"); // will we get slap } %>

&
<%! void f1() { System.out.println("great");// we will not get slap. } %>
Summary: Scriptlets and expression and declaration elements are ultimately all
part of a servlet that is produced by a JSP container when a request for a JSP is made

<html> <body> <%! public String myMethod(String someParameter) {

} %>

return "You sent me: "+someParameter;

<%= myMethod("Hi there") %> </body> </html>

ACTION
suppose the user enters 4 words in the list, then we want to go a page stop.html, else we should come back to freakexample1.html.

ok we can use action for this. <jsp:forward page="whereToGo"/>

Notice board 1. request notice board 2. session notice board 3. application notice board 4. page notice board. all these notice boards are like maps. Interesting like maps. Why typically in map is key is object, value is object. But, in these notice boards key has to be string value can be any object. four notice boards dont know which one to use answer is use request notice board.

request
If you ask the request object for the value of a form variable that does not

exist, it returns null. Note that getParameter always returns a string. If you are expecting a number, you have to convert it yourself.

Session notice board


Q. why do we need a session A. if you want store information over multiple requests. Session, in jsp, we could use session because session is an implicit object available in jsp. Syntax:-HttpSession session = request.getSession(); session is a Session object. When the person tells logoff, remove the userid from the session. Q. What is the meaning of login? A. Means putting the userid in the session.

simple freak example.


1. 2. 3. 4. 5. we are writing a page called one.html it will go to two.jsp from two.jsp we got to three.html. in three.html we got a link to three.jsp. in three.jsp we have to show the userid entered in one.html.

there are only two requests.


1. one.html to two.jsp. 2. going to two.jsp to three.html is not a request it is response. 3. going from three.html to three.jsp via a link is request.

Some story regarding JSP with JDBC:


1. you have to copy classes12.jar into tc\common\lib folder of tomcat. 2. proove connection is working. or 1. mysqlrelated.jar into the common\lib for mysql the jar file name is mysql-connector-java-5.0.3-bin.jar will copy this to common\lib of tomcat. 2. Connection is got.

3. many a times we need to pull out details from the database and show it in the jsp. for this the correct thing go to the database pull out things put that in some ds. and put that ds in the notice board and come to the jsp and read from the notice board.

Application notice board SErvletContext c= getServletContext(); c.setAttribute("","");

applciation.setATtribute(""); // in jsp how to get applicaton in servlet.

Comments
HTml comments are read by the compiler. <!-- This is an HTML comment. --> However, because the Java statements are surrounded by /* */, they are ignored by the compiler. /* I m java comments */

Servlets
Definition: - Servlet is a server- side component, which is used to service
the Web-clients using HTTP protocol and generates dynamic Protocol. Life cycle of servlet:1. When the first client calls the init() method fires. 2. Then the service method () fires. 3. Then for all other client calls only the service () method fires.

4. then the web server is shut-down the Destroy () method fires. For writing a servlet do write your class which extends httpSErvlet. and then override doGet or doPost methods in it. After that we make present class and object of this class is created inside MyServlet class. Through this object we call the method of the presentation class which method contains HttpServletRequest object as parameter. In the presentation class we can get the parameter of the JSP page by using request.getParameter (userid) method. At the time of login we will use session object and will put the useid in the session object. Syntax: - HttpSession session = request.getSesion(); Session.setAttribute(xyz,userid)

why write doGet method, to respond to get mode of request. why write doPost method, to respond to post mode of request. Both doGet and doPost metods contains HttpServletrequest and
HttpServletResponse as a parameter.

Q.what is HttpSErvletREquest, HttpSErvletREsponse class or interface?


A. both of them are actually interfaces only, why jee is all about specifications. Specifications mean it is all about interfaces.

HttpSErvletREquest

is a pipe from the client to the servlet. is a pipe from the SErvlet to the client.

HttpSErveltREsponse

HttpServlet
1. HttpServlet can recognize doget and doPost because it is an

HttpServlet get and post are http mechanisms and it is capable to recognize the http mechanism. 2. In HttpServlet there are two service methods that mean service in Httpservlet is overloaded. In httpServlet. 1. init1 2. service(SErvletREqeust,SErvletRes) 2 3. servcie(HttpServletRequest, HttpSErvletREs) 3 4. doGet 4 5. doPost 4 6. destroy 5

what happens when we call a servlet.


1. the system looks for the url pattern. 2. then it comes to the web.xml 3. then in web.xml it looks for the classname associated with the url pattern. 4. Then it looks for the class associated with the classname. 5. Creates an object of the class. 6. Creates an object of the class which implements HttpServletResponse. 7. Creates an object of the class which implements Using 5, 6 and 7, it calls our servlet. HttpSErvletREquest.

Servlet and SErvletConfig both are interfaces.


ideally speaking to tell something is a servlet we need to implement these interfaces. but difficult to implement so we use

Adatpers like GenericServlet or HttpServlet. SERvlet interface


dictates life cycle of the servlet. have information regarding a particular servlet.

SERvletConfig interfaces

******

GenericSerlvet implements SErvletConfig, SErvlet httpSErvlet extends GenericServlet.

Q.how did we that this is life cycle of servlet ? A. open the methods of SErvlet interface. *********

Q.GenericServlet is abstract, why ? A.It has got an abstract method in it. what is that method answer is service.

GenericSErlvet implements SErvlet defines all the methods except service. that means it becomes abstract.

custom tag.
Life cycle of custom tags doStartTag 1 doEndTAg 3

doBody 2 there are tonnes of free as well as commercial custom tag libraries:example JstL display tags jFreechart

Basics and Sysntex for custome tag :1. custom tag can be used only in jsp. 2. to see custom tag at work we need three things. 1. jsp 2. tld file (mere xml file) 3. java class for any custom tag all the 3 are reuired.

what is the role of jsp in custom tag.


1. it is in the jsp we are using a custom tag. 2. how do we know jsp is using a custom tag. answer is we got to look for a directive called taglib. 3. no taglib directive that means jsp is not using a custom tag. <%@taglib prefix="junk" uri="\WEB-INF\a.tld" %> taglib has got two attributes prefix and uri. prefix can be anything you want. uri, will typically point to the location of the tld file. 4. one jsp can be use many tld files. for each tld file you need a separate taglib directive. 5. for every custom tag there must be a java class.

Q. so what does the java class does?


A. It determines the functionality of the custom tag.

tld file tells the container which java class is associated with which custom tag. by looking at tld file we also can make out the properties of the custom tag.

Q. what do you mean by properties of custom tag.


1. weather tag has got a body or not. 2. whether tag has got attributes or not 3. whether these attributes are compulsory or optional.

if there will be clashing between request/response then we can resolve by using scope.
<c:out write="x"/> x key is found in both request and session default it will read from request. but you want from session. <c:out write="x" scope="session"/>

Struts Concept:1. Struts is a web based which forces user to use mvc (model view controller) arctecture. 2. It has got tones of custom tags. 3. It also provides tons custom yaks configuration. 4. in Struts, we got two concepts. 5. ActionForm - input to the business logic 6. Action class. - business logic codes ActionForm or ValidatorForm:Write a class that extends ActionForm and write instance variables generate getters and setters. Action class:Write a class that extends Action class and override Execute method. Than write code of business logic in that method. @Override public ActionForward execute( ActionMapping arg0, ActionForm arg1, HttpServletRequest req, HttpServletResponse res)

throws Exception {

Custome tags:-

<html:form action="whatever path we had mentioned for the action in


the struts-config.xml file"

<html:text = this will create box </html:text> </html:submit> //submits the form. no we can do it JavaScript, why use struts.
JavaScript we may use or we may not use that depends on clients requirements.

Some steps regarding the Structs:1. copy struts related jar files into the web-inf\lib folder only. Why only, jee contract. 2. Copy all struts related tld files into your web-inf folder. 3. Copy all the struts related xml files especially Struts-config.xml, validation.xml, validator_rules.xml , web.xml file into your web-inf. 4. Open the web.xml of yours and ensure struts related serlvet can be used Web.xml :<load-on-startup>2</load-on-startup> \\very important for struts to work, why typically our servlet what happened tomcat never creates the object of our servlet until we made a request for the servlet In struts, custom tags of struts uses the ActionSERvlet of struts from the beginning, so it expects that object of the Struts servlet should be created even before it is called for the first time. This thing can be achieved by using this tag called load-on-startup in web.xml file

Struct stapes:1. start from the java class. 2. go to the tld. 3. go to the jsp and then use the custom tag.

4. go and use the tag lib directive. 5. restart the web application 6. test the custom tag by running the jsp.

Q. what is the difference between server side parameter and client side parameter apart from one is on server side other comes form the client?
cleint side parameter can differ from client to client. server side parameter is same for all clients.

we have to crate the server side parameter in web.xml <init-param> <name>url</abc> <value>abc@def.com</value> <init-param>
how you read this parameter in the servlet or in your business logic, you need the object of this interface called ServletConfig

Listner all listeners in any world will alwasy be interfaces SErvletListner: use SErvletListner to know when your web application started when your web application ended.

Session Listener
when session object was created. when it was removed. when attribute was added

when attribute was removed.

SessionAttributeListener: when an attribute is put into a session when an attribute is removed from a session.

Filter.
before going to the servlet if you want to do some action then you can think of using a filter. Security enforcement can be done thru filters.

Life cycle of filter:


1. Filter 2. destroy

<A href="xyz? purpose=logoff">logoff </A> what is xyz url pattern purpose=logoff, parameter given to the servlet. how come we are able to give this parameter? becuase the servlet supports doGet.

<A href="xyz?purpose=logoff">logoff </A> it goes to the servlet. that is again good design enfrocement. any body who comes here should always visit the servlet first, why serfvlet is reception point.

IOException it is a checked exception. classnames ending with writer or REader are text based classes. clasnames ending with streams are binary based classes.

TOPIC:Concept:-

serializable

1. serializable interface is called as marker interface or null interface or singling interface. 2. what does, the system looks if the class implements the interface, it behaves in one way, if the class does not implement the interface it behaves in other way means the object of this class needs to be treated differently. 3. by default system does not like making backup of the object, it takes time. 4. if you want the system to take backup of your object, system tells then you better implement the interface Serializable. Example:-Serializable, Remote, Cloneable. An object state can be saved by serializing an object. To serialize an object we need an object output stream. Serialization of an object means writing the value of its all data fields into a stream of bytes. A class can be de-serialized by using object input stream. Serialization is the process of writing the current state of an object to a stream. To serialize an object the class must implement either java.io.serializable or java.io.externalizable.

Questions

Please give answer with example 1. What is hasCode() ? 2. What is the chained exception ? 3. What is the Thread 4. What is Runnable ? 5. What is mutable and immutable ? 6. Synchronization ? 7. What is Annotation ,what is the use of it? 8. What is obsrever and observable ?
9. Observer Design pattern. 10. Adapter Design pattern. 11. What is the name map which can contain duplicate key and v alue ?

Design pattern: Design principle:


Open Close Principle
many changes are involved when a new functionality is added to an application. Those changes in the existing code should be minimized The Open Close Principle states that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged. Software entities like classes, modules and functions should be open for extension but closed for modifications.

Example
Bellow is an example which violates the Open Close Principle. There are several disadvantages: for each new shape added the unit testing of the GraphicEditor should be redone. when a new type of shape is added the time for adding it will be high since the developer who add it should understand the logic of the GraphicEditor. adding a new shape might affect the existing functionality in an undesired way, even if the new shape works perfectly. In order to have more dramatic effect, just imagine that the Graphic Editor is a big class, with a lot of functionality inside, written and changed by many developers, while the shape might be a class implemented only by one developer. In this case it would be great improvement to allow the adding of a new shape without changing the GraphicEditor class.

// Open-Close Principle - Bad example class GraphicEditor { public void drawShape(Shape s) { if (s.m_type==1) drawRectangle(s); else if (s.m_type==2) drawCircle(s); } public void drawCircle(Circle r) {....} public void drawRectangle(Rectangle r) {....} } class Shape { int m_type; } class Rectangle extends Shape { Rectangle() { super.m_type=1; } }

class Circle extends Shape { Circle() { super.m_type=2; } }

Bellow is a example which supports the Open Close Principle. In the new design we use abstract draw() method in GraphicEditor for drawing objects, while moving the implementation in the concrete shape objects. Using the Open Close Principle the problems from the previous design are avoided, because GraphicEditor is not changed when a new shape class is added: no unit testing required. no need to understand the sourcecode from GraphicEditor. since the drawing code is moved to the concrete shape classes, it's a reduced risk to affect old functionallity when new functionallity is added.

// Open-Close Principle - Good example class GraphicEditor { public void drawShape(Shape s) { s.draw(); } } class Shape { abstract void draw(); } class Rectangle extends Shape { public void draw() { // draw the rectangle } }

Conclusion
Like every principle OCP is only a principle. Making a flexible design involves additional time and effort spent for it and it introduce new level of abstraction increasing the complexity of the code. So this principle should be applied in those area which are most likely to be changed. There are many design patterns that help us to extend code without changing it. For instance the Decorator pattern help us to follow Open Close principle. Also the Factory Method or the Observer pattern might be used to design an application easy to change with minimum changes in the existing code.

You might also like