Vous êtes sur la page 1sur 92

A Programmers Guide to Java SCJP Certification A Comprehensive Primer First Edition

Mohd.Arshad Ali

CORE JAVA(SCJP)
=========================== Q.Why did they(Developer of JAVA) develop JAVA? Ans.To provide the concept of platform independency, thats why they develop JAVA.

Q.What is JAVA? Ans. STRICTLY NOTE ============== There is no fulform of JAVA. JAVA is the name of trademark of SUN MICRO SYSTEM . Java is a combination of 3 things: 1.OOPS 2.Plateform 3.Technology

Q.What is Program? Ans.Set of Instructor/Collection of Instruction,i.e Program. Q.What is Programming Language? Ans. A mode of human communication with the computer,i.e.Programming Language.

Q.What is HighLevel Language? Ans. 1.This is pure English language. 2.Human understandable language. 3.Source code ,also in HLL. Q.What is Middle Level Language? Ans. 1.It is intermediate language code. 2.It contains byte code. 3.MLL code like mnemonics. 4.Formate of mnemonics looks like a(micro processor commands)ADD,MOVE,MUL,SUB(low level). 5.Humand cannot understand ,that code. 6.But Assembly and micro processor commands in Low Level .

Q.What is Low Label Language? Ans. 1.Machine(OS) understandable code. 2.Pure binary(0/1) data. 6.But Assembly and micro processor commands(ADD,MOVE,MUL,SUB) in Low Level .

Q.What is Sourse Code? Ans. We(Human/programmer) write any code ,i.e.Source Code. Q.What is Byte Code? Ans. 1.Java Compiler create any code ,i.e.Byte code. 2.Byte code is pure intermediate language code. 3.Byte code format is mnemonics.

Why OOPS? Discuss later. Q.What is OOPS? Ans. 1.OOPS stands for OBJECT ORIENTED PROGRAMMING. 2.OOPS is the name of methodology/approach using which we create the program using Class and Object.

Feature of OOPS =============== Discuss later.

Q.What is Platform? Ans. Plateform is a collection of predefined program which are used to provide the run time environment for developing any application, Run time Environment like: 1.Memory management 2.Process management 3.IO management 4.Device Management i.e.Plateform. In C,Platefrom is only OS,

But in JAVA Plateform is=(OS+JVM(Garbage collector+JVM)). Q.What is Platform Independent Program? Ans. Those program which create and compile on one particular machine and those are able to execeute any where(Any OS),that type of program is known as PIP. Note === Only JAVA program is Platform Independent program.

Q.What is Platform Dependent Program? Those program which create and compile on one particular machine(OS) and those are able to execute only on same machine(OS),that type of program is known as PDP. NOTE ==== C and C++ program are PDP. Q.What is Technology? Ans.Technology is nothing but it is collection of predefined program which are used to develop certain logic/concept for any organization,i.e.Technology. Servlet/JSP=web development Like Servlet,JSP,EJP etc.

Q.What is Portability? Ans.Move the code from machine(OS) to another machine for success operation,i.e Portability. There are 2 type of Portability in Java 1.Source code portability 2.Byte code Portability But other language provide only source code portability.

Q.What is Compiler ? Ans. Compiler is a collection predefined program which convert the source code into the other code(in 'C' machine understandable/ 'JAVA' intermediate code). Job of JAVA compiler ====================

1.To load the source code from H/D to RAM. 2.Convert the source code into intermediate code if source code is syntactically correct. 3.Generate byte code(.class file). 4.By-default byte code saved in Current working directory. History of JAVA =============== Q.Who developed JAVA? Ans.James Gosling and five other member. 1992-JAVA Developed. 'Sun Micro System'-Name of java developed organization. Green Team=James Gosling + other five of the team. 'Sun' developed first project :Electronic Consumer project in '1993' After two year(1995) 'SUN' changed the name of Electronic Consumer project,i.e.'GREEN PROJECT' Features of JAVA ================ 1.JAVA is Simple =================Becoz of that java provide automatic memory mgnt using Garbage collector. 2)JAVA is pure OOPS ===================becoz of that each and every program must be use class/Object. 3)JAVA is portable ==================Becoz of that java provide portability. 4)JAVA is platform Independent =============================== 5)JAVA is Distributed =====================Using java ,we can develop very high level networking application. 6)JAVA is robust ================JAVA provide tightly coupled checking during compile time as well as run time.

7)JAVA support Multi Threading ============================== Edition of JAVA =============== J2SE=JAVA 2 Standard edition==>Using J2SE ,we can develop Windows based application. J2EE=>JAVA 2 Enterprises Application==>Using J2EE ,we can develop Web based application. J2ME=>JAVA 2 Micro Application==>Using J2ME ,we can develop Mobile based application. Version of JAVA =============== 1st version=1995 JDK1.0 2nd version=1997 JDK1.1 3nd version=1999 JDK1.2 4rt version=2000 JDK1.3 JDK1.4,JDK1.5,JDK1.6,JDK1.7

Q.What is JVM? Ans. 1.JVM stands for JAVA VIRTUAL MACHINE. 2.JVM,like as translator ,which translate byte code into machine code. 3.JVM is the specification of OS manufactured compony. 4.property of JVM are already installed in each and every OS. JVM ARCHITECTURE ================

Q.JDK,JRE,JSDK. Ans. JDK ===JDK stands for JAVA DEVEOPMENT KIT. JDK provides compilation tools for developing java application and perform other operation. JRE ===JAVA Runtime Environment, which consist JVM as well as run time .class file

library,i.e.JRE.

JSDK ====JAVA SOFTWARE DEVEOPMENT KIT, combination of JDK and JRE ,i.e. known as JSDK. Q.Architecture of JVM. Ans. 1)Class Loader Sub System ======================= To load the .class file(byte code) from h/D to RAM and stored into Method Memory Area. Note ====.class file is loaded only once. 2)Heap Memory Area OR Object Context Area OR Object Segment Area =============================================================== == 1.Inside this area objects are created. Inside Object: a)instance(non-static) variable b)instance method//calling place c)instance block//calling d)constructor Instance Context=IV+IB+IM 2.Inside this area Arrays are created. Note ==== 1)Object and Array hold one unique id which generated by the JVM,that id is known as HASHCODE. 2)format of hash code is HEXADECIMAL.

3)Method Memory Area ==================== 1.Inside this area .class files are stord. 2.Inside this area STATIC CONTEXTS ARE STORED. STATIC CONTEXT=STATIC VARIABLE + STATIC BLOCK + STATIC METHOD.

4)Stack Memory Area =================== Inside this area ,method's(instance/static) body and block's(instance/static) are stored. 5a)JIT Compiler ============ JUST-IN-TIME compiler ,to increase the execution speed of the java program. 5b)Interpreter ===========TO convert .class file into machine code. class A { } javac.exe B.java A.class Q.What is the Execution Process of JVM? Ans. invoke jvm using "java.exe A" commands. 1.To load the .class file from H/D to RAM and stored in MMA only once. 2.To allocate the memory for all static context in MMA only once. 3.If static variables are not initialized then set default value. 4.Execute All static Block(order Top to Bottom). 5.Control Move to the main() method. 6.If Main() method is not present then JVM will generate one Error "java.lang.NoSuchMethodError" in jdk1.6 or below version.

Q.Why OOPS? Ans.If we want develop real time application then we need OOPS methodology. Features of OOPS =============== 1.Class/object 2.Data Abstraction 3.Encapsulation 4.Inheritence 5.Polymorphism Q.What is Class? Ans.

1.Class is a blue print of an object. 2.Class is a logical view of an object. 3.Class is a imaginary boundary of an object. 4.Class is a planning before construct object. 5.Class is collection of methods and variables. 6.Class is a user defined data type. 7.Class ,looks like a 'C' structure . Q.Why Object? Ans. If we want to stored instance member into the memory in secured manner. that is why we need Object. member=variable+block+method Q.What is Object? Ans. 1)Object is real world entity. 2)Object is a physical view of a class. Q.What is Data Abstraction? Ans. 1.Hidding the unwanted things by reveling required things. 2.Hidding the unnecessary things but required things are visible.

Encapsulation ============= feature of Encapsulation 1.Data Binding 2.Data Hiding.

WHy ,What

Tokens ======= Tokens is very smallest unit of the program.i.e.Token. Diagram ======== softwareheiii.jpg

Program ======== Collection of Instruction. Keywords ======== Keyword is special word/reserve words which definition defined inside the compiler,i.e. known as Keyword. There 53 keywords in java 1.48 special words 2.3 reserve words 3.2 unused keywords 3 reserve words =============== 1.null 2.true 3.false 2 unused keywords ================== 1.goto 2.const 48 special words ================ keywords for flow control ======================== 1.if 2.else 3.do 4.while 5.for 6.return 7.switch 8.case 9.continue 10.break 11.default keywords for Exception Handling ============================== 1.try 2.catch

3.finally 4.throws 5.throw 6.assert keywords for Access specifier ============================= 1.public 2.protected 3.private keywords for Access modifier ============================ 1.static 2.final 3.abstract 4.synchronized 5.transient 6.strictfp 7.native 8.volatile

keywords for classes ==================== 1.class 2.interface 3.enum 4.package 5.import

keywords for object =================== 1.this 2.super 3.instanceof 4.extends 5.implements 6.new Keywords for data type ====================== 1.byte

2.short 3.int 4.long 5.float 6.double 7.char 8.boolean 9.void Identifier ========== You define any name in the program ,i.e. known as Identifier. Rule ==== 1.Cannot be start with digit ,but middle of identifier or end of identifier we can use. 2.Cannot be used any special symbol ,except underscore(_). 3.We can use any currency symbol, except Indian rupees. 4.Cannot be used any keywords as a identifier.

DATA Types ========== Data type is name of storage format which store specific type and corresponding range,i.e known as DATA TYPES. There are two type of Data Type =============================== 1.Primitive DATA TYPES 2.Reference(Non Primitive) DATA TYPE 1.Primitive DATA TYPES ====================== Store the value or value type ,i.e Primitive TYPE. There 8 type of PDT =================== Data type Range in byte 1.byte 1 2.short 2 3.int 4 4.long 8 5.float 4 6.double 8 7.char 2

Range in Bit Default Value 8 0 16 0 32 0 64 0l/OL 32 0.0F/O.0f 64 0.0/0.0D/0.0d 16 \u0000

8.boolean

false

Note ==== All the data type of java are signed, except Boolean and char. There are 3 character set format ================================ 1.ASCII==>C and C++ support 7 bit 256 character a=97 2.UNICODE===>JAVA support 16bit 65535 character a=\u0061=binary 3.Latin formula to find the range of JAVA DATA TYPE except boolean and char =============================================================== ====

range=-2^(Range in bit -1) to 2^(Range in bit -1) -1 eg. byte range= -2^7 to (2^7)-1 =-128 to 127 formula for char range ======================= 1.char is unsigned data type, that we cannot store negative value. char range=0 to 2^(Range in bit ) -1 =0 to (2^16)-1 =0 to (65536)-1 =0 to 65535

Reference DATA TYPE =================== Those data type which hold address of an object,i.e.Reference Data type. Note ==== address means hashcode of an object/Array. hashcode format is Hexadecimal.

TYPES OF REFERENCE DATA TYPE ============================= There are 4 type of reference data typesDATA TYPES Default Value 1)class 2)interface 3)enum 4)array null null null null

Variable ======== Variable is name of place in the memory which hold some data/address.i.e.variable. Types ===== 1.static variable 2.instance variable 3.local variable 4.block level variable 5.Pimitive variable 6.Reference variable Discuss later. Literals ======== Any data value is known as Literals. type of Literals ================ 1.Integer literals .byte literals valid=-128 t0 127 .short literals .int literals a=range; .long literals a=12L; 2.Floating Literals .float literals .double literals 3.Boolean literals boolean literals boolean b=true; 4.Character literals char literals char a='a' 5.String literals

String literals "ARSGS";

Operator(Unari,Bynary,Ternary and precedence chart) =================================================== Operator is symbol which perform certain task. There are 3 types of Operator. 1.Unary Operator 2.Binary Operator 3.Ternary Operator 1.Unary Operator =============== Those operator which operator on one operands. --a; ++a; a++; a--; -2 +2; boolean b=!(true); e.g.++,--,+,-,! 2.Binary Operator =============== Those operator which operator on two operands. c=a+b; +,-,*,/,%,&&,||,&,|,^,= etc. 3.Ternary Operator ================= Those operator which operator on three operands. condition operator '?:' data type variable =(boolean expression) ? value1 : value2; Precedence chart ================ S.No. Operator 1. (),[] 2. ++,--

3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.

*,/,%,!,~(Multiplicative operator) +,-,new (Additive operator) <<,>>, shifting <,>,<=,>=,instanceof (relational operator) ==,!= equality operator & bit wise AND | bit wise OR ^ bit wise XOR && Logical AND || Logical OR ?: conditional operator =,+=,-=,*=,%=,/=,...etc(Assignment Operator) ,

Method ====== Method is an operation which define the behavior of particular abstraction,i.e.method. Note ==== Method looks like a function of C prog.

Document Section(Comments) ========================== 1.Single line comments // 2.Multi line comments /* */ Access Specifier ================AS is nothing but it define the scope ans visibility of the class member,i.e.AS. 1)public 2)protected 3)private Access Modifier =============== AM is nothing but it define the characteristics of the member,i.e.AM 8 type ===== 1.final 2.static

3.abstract 4.transient 5.strictfp 6.synchronized 7.native 8.volatile

JAVA Convetioning Rule ====================== 1.Rule for Variable 2.Rule final variable final double PI=3.14; 3.Rule for method 4.Rule for class/interface class Software Engineer 5.Rule for package all letter small. package. jpg 1.Structure of JAVA program structureofjavaprogram.jpg 2.Write first java program with great explanation. NOTE ==== 1.if class declare as a 'public' then we must save the program with class name. 2.if class is not declare as a 'public' then we can save the program with any logical name. 3.if we don't declare any access specifier with class name then class called 'default class' Escape Sequnce. 4. name of .class file is ClassName.class. Q.Who is the caller of main() method? Ans. JVM.

Explanation of First JAVA PROGRAM ================================== Q.Why main() method declare public ,static and String[]? Ans.

public ====== 1.If any member of a class which called by JVM,then we need set 'public' with main method. 2.Actually there are 2 environments 1.JDK,2,JVM,if JVM called JDK environment member then we need to declare main() method as a public.

static ====== 1.if we dont declare 'static' with main method, then method is called Instance method., but unfortunately JVM will not create object of any class automatically, so any instance member will not instantiated in the life time of program. Note ==== static member instantiated in memory during loading of the class time but instance member instantiated in the memory whenever we create an object of a class. String[] array ============== 1.purpose of String[] is for taking the command line argument ,which could be in any types.

Q.How many ways to declare main() method? ANs. === There are so many ways to declare or so many predefined signature which could understand by JVM =============================================================== ======== p=public s=static v=void m=main for JDK1.0 up to all above version. ================================= 1.psvm(String[] a)

2.spvm(String[] a) 3.psvm(String []a) 4.psvm(String a[]) 5.spvm(String []a) 6.spvm(String a[])

for JDK1.5 up to above version(VAR-ARGS) ======================================= 1.psvm(String... a) 2.psvm(String...a) 3.psvm(String ...a) 4.spvm(String... a) 5.spvm(String...a) 6.spvm(String ...a) Q.How to set temporary path? ans. D:\Morning Batch>set path=C:\Program Files\Java\jdk1.6.0_24\bin; D:\Morning Batch>set path=C:\Program Files\Java\jdk1.6.0_24\bin; D:\Morning Batch>javac.exe FJava.java D:\Morning Batch>java.exe FJava output will display.

Q.How to Set permanent path? Ans. step 1.Copy the path of bin directory. 2.Right click on MYCOMPUTER. 3.Click on property. 4.Select "Advance" tab. 5.Click on "Environment variable" button. 6.If we set path on user-variable then 6a)click on 'new' button 6b)variable-name=path variable-vale=C:\Program Files\Java\jdk1.6.0_24\bin then click on OK button 7)If we set path on system-variable then

Q.How to create an object of class? Ans. using 'new' operator, we create the object of class. coding ====== new FJava(); new FJava(); new FJava(); new FJava(); Q.What happens in the memory ,whenever we create an object of class OR JOB of 'new' operator Ans. 1.To load the .class from H/D to RAM, if .class is not loaded. 2.Create the context/segment of the object in Heap memory area and generate unique hash code. 3.Allocate the memory for all instance context. IC=IV+IM+IB 4.If instance variables are not initialized then set the default value. 5.execute the constructor. 6.retun the hash code to the corresponding variable, if present, other-vise no problem.

Q.What is Instance Variable? Ans. Definition =========== Those variables which declare inside class as well as without using 'static' keyword, i.e. known as Instance Variable. 1.Instance variable is also known as non static variable. 2.Instance variable instantiated in the memory, whenever we create an object of class. 3.Instance variable instantiated in the memory, how many number of of time we create an object of class. 4.Instance variable cannot use directly inside any static context. 5.Instance variable supports default value. 6.Instance variable is the part of an object. 7.Instance variables are stored inside object context. 8.Instance variable can be access inside directly any instance context.

Q.What is Instance Method? Ans. Definition =========== Those method which declare without using 'static' keyword, i.e. known as Instance Method. 1.Instance Method is also known as non static Method. 2.Instance method instantiated in the memory, whenever we create an object of class. 3.Instance method instantiated in the memory, how many number of of time we create an object of class. 4.Instance method cannot use directly inside any static context. 5.Instance method is the part of an object. 6.Instance method(calling place) are stored inside object context. 7.Instance method can be call inside directly any instance context.

Q.What is Static Variable? Ans. 1.Those variable which declare as a static ,that type of variable is known Static Variable. 2.Static variable instantiated in the MMA memory, only once. 3.Static variable instantiated in the memory, whenever class is loaded. 4.Static variable can be use directly inside any context(static/instance). 5.Static variable supports default value. 6.Static variable is the part of an Class. 7.Static variable can be access through the Class Name as well as Object. 8.Static variables are stored inside MMA. 9.Static variable share more than one object.

Q.What is Static Method? Ans. 1.Those method which declare as a static ,that type of method is known Static method. 2.Static method instantiated in the MMA memory, only once. 3.Static method instantiated in the memory, whenever class is loaded. 4.Static method can be call directly inside any context(static/instance). 5.Static Method is the part of an Class. 6.Static method can be access through the Class Name as well as Object. 7.Static method are stored inside MMA. 8.Inside static method, we can not use any instance context directly, but indirectly it is possible.

NOTE ==== java.lang.Object class is a super class of all classes. 1.local variable ================= What ==== Those variable which declare inside the method(instance/static) ,that types of variale is known as Local Variables. Rule ==== 1.Local variable doesn't supports default value. 2.Local variable must be initialize before using/reading. Scope and Visibility ==================== With in the same(itself) method.

2.Block Level variable ======================= What ====

Those variable which declare inside the block and block declare inside the method, ,that types of variable is known as Block Level Variables. Rule ==== 1.Block Level variable doesn't supports default value. 2.Block Level variable must be initialize before using/reading. Scope and Visibility ==================== With in the same (itself) block. 3.magic of concatenation with '+' operator 4.instance with ........... ==================== 1.IM with zero parameter with null(void) return type. 2.IM with primitive parameter with null(void) return type. 3.IM with reference parameter with null(void) return type. 4.IM with zero parameter with primitive return type. 5.IM with primitive parameter with primitive return type. 6.IM with reference parameter with primitive return type.

7.IM with zero parameter with reference return type. 8.IM with primitive parameter with reference return type. 9.IM with reference parameter with reference return type.

5.static with ........... ==================== 1.SM with zero parameter with null(void) return type. 2.SM with primitive parameter with null(void) return type. 3.SM with reference parameter with null(void) return type. 4.SM with zero parameter with primitive return type. 5.SM with primitive parameter with primitive return type. 6.SM with reference parameter with primitive return type.

7.SM with zero parameter with reference return type. 8.SM with primitive parameter with reference return type. 9.SM with reference parameter with reference return type. 6.Type casting

============== Widening and Narrowing with Primitive and Reference

byte===>short===>int===>long====>float===>double ^ | | | char Note ==== By default any floating value's type is 'double'.

WIDDENING AND NARROWING REFERENCE TYPECASTING ============================================= Discuss in INHERITENCE.

final keyword ============== 1.'final' is the keyword of java. 2.'final' is access modifier. 3.'final' keyword is use in three places. 1.with variable 2.with method 3.with class Note ==== 2 & 3 discuss in INHERITENCE.

Q.What is final variable. Ans. -->Those variable which declared as a final ,i.e. final variable. -->final variable's value will never changed/modified. -->final variable must be initialize during declaration time. type of final variable =======================

1.final instance variable 2.final static variable 3.final local variable 4.final block level variable 5.final parameterized variable 1.final instance variable =========================Those variable which declared as final instance,i.e. known as final instance variable. 2.final static variable =======================Those variable which declared as final static,i.e. known as final static variable. 3.final local variable ======================Those variable which declared as final local,i.e. known as final local variable. Note ==== final local variable may or may not be initialize during declaration time. use === in program. 4.final block level variable ============================ Those variable which declared as final block level,i.e. known as final block level variable. 5.final parameterized variable ============================== Those variable which declared as final parameter in the method,i.e. known as final parameterized variable.

NOTE ===='final' is the one of the unique access modifier in java ,that can be use inside method or method parameter. ***** ********************

'this' reference =============================================================== ========================== 1.'this' is a keyword of java. 2.'this' is a reference/pointer to locate the object. 3.Each object contains 'this' reference. 4.'this' reference refer to the current class's object.

5.'this' reference cannot be inside any static context. Diagram ======= Example =======

Method Overloading ================== Need ==== If we want to perform similar operation with different behavior ,then we need Method Overloading. void add(int i,float a) { } void add(float a,int b) { } What is Method Overloading? Ans. Defining more than one method with same name with different parameter, i.e. Method Overloading. Rule ==== 1.Name of Methods must be same. 2.Types of parameter must be different, if types of parameter are same, then we go to step 3. 3.Number of parameter must be different, if number of parameter are same, then we go to step 4. 4.Sequence of parameter must be different, if sequence of parameter are same then overloading failed. 9.Constructor ============= Why Constructor ================ 1.If we want to very initial state of an object, then we need Constructor. 2.If we want to update the instance variable value during creation of object time,

then we need Constructor. 3.If we want to create resource allocation code ,then also we need Constructor.

Q.What is Constructor? Ans. Constructor is the special member of a class which is automatically executed, when ever we create an object of a class,i.e. Constructor. NOTE ==== Each and every java class contains at least one constructor. Characteristics of Constructor ============================ 1.Name of the constructor same as class name. 2.Constructor doesnt have any return type. 3.Constructor supports all access specifiers(p,p,p,d). 4.Constructor doesnt support any access modifier. 5.Constructor looks like a method ,but follow above characteristics.

Difference b/w Constructor and Method ===================================== Assignment. Types of Constructor ==================== There are 2 types of constructor. 1.Default Constructor 2.Parameterized Constructor Q.What is Default Constructor? Ans . A constructor which contains zero parameter of null parameter,i.e.Default Constructor. There are 2 types of Default Constructor ======================================== 1. COmpiler Define Default Constructor/Implicit Constructor 2.Programmer Define Default Constructor Q.What is Compiler Define Default Constructor/Implicit Constructor? Ans.

A constructor which created by java compiler,i.e. Compiler Define Default Constructor/Implicit Constructor. Note ==== When ever we dont create any types of constructor in the class, then its duty of java compiler to create one default constructor, that constructor is known as Compiler Define Default Constructor/Implicit Constructor. 2.Programmer Define Default Constructor ======================================= A constructor which created by programmer,i.e.Programmer Defind Default Constructor. Q.What is Parameterized Constructor? Ans.Those constructor which constains parameter,i.e.Parameterized Constructor. There are 2 type of Parameterized Constructor. 1.Primitive Parameterized Constructor 2.Reference Parameterized Constructor Real time example of Constructor in the term of Computer ======================================================== startup How to watch compiler defind default constructor ================================================= 1)javac.exe filename. java 2)javap.exe Class File constructor overloading ======================= Defining more than constructor with same inside the class with differed parameter ,i.e. Constructor Overloading. Rule ==== Same as Method Overloading this() ====== 1)this() call can be use only inside the constructor. 2)this() call must be first statement of the constructor. 3)this() call may be zero parameter or reference/primitive parameterized. 4)at a time we can use only one call this() call/super() call 5)this() cannot be use recursively.

6)this() call is used to call the same class constructor. Note ====Each and every constructor by default contains 'super()' call as a first statement of the constructor, but when ever we don't use 'this()' call. b)super()==>discuss in Inheritance c)this reference, super reference==>discuss in Inheritance static block ============ 1)Those blocks which are automatically executed, after loaded the class from H/D to RAM by the class loader sub system and instantiated it. 2)We can create nth number of static block in the class. 3)Static blocks are executed sequentially. 4)Inside static block we cannot use any instance context directly. 5)static block is anonymous.

e)instance block(non static block) ================================= 1.Those blocks which are executed just before constructor execute,i.e.Instance Block. 2.Instance block is the part of object. 3.There is no name of instance block. 4.We can create nth number of instance block inside class. 5.Instance block instantiated in the memory ,when ever we create an object of class.

Why instance block ================== If we want to share any statement with each constructor, then we need instance block. program ======== 1.more than one constructor with instance block and there is no this() call. 2.more than one constructor with instance block and there is this() call. 3.more than one constructor with instance block and there is this() call and static block. 4.more than one constructor with instance block and static block.

f)constructor chaining//discuss in Inheritance

10.Inheritence 11.Polymorphism 12.Garbage Collector

f)constructor chaining//discuss in Inheritance

*******************************************Inheritance******************** ****************************** =============================================================== ========================================= Why Inheritance =============== 1.To overcome the problem of composition, then we need INHERITENCE. 2.Code Reusability 3.Code Extensibility(method overriding) 4.For getting the property of parents class in child class, then also we need INHERITENCE. 5.If we want to create hierarchy of classes which belongs to the similar family, then also we need INHERITENCE.

Q.What is COMPOSITION and What type of relation is establish through the COPOSITION? Ans. Creating the object of one class inside another class,i.e.COMPOSITION. class A { int j=15; } class B { int i=12; public static void main(String[] a) { A s=new A();//COMPOSITION B s1=new B();//COMPOSITION Sop(s.j); Sop(s1.i); } } What type of relation is establish through the COPOSITION

========================================================== 1.HAS-A relationship 2.USE-A relationship class Cat { } class Human { Cat a;//HAS-A relationship psvm(Str.....) { new Cat();//USE-A relationship } } Human has a Cat. WHAT IS HAS-A RELATIONSHIP 2.Code Reusability ================== Creating the code by one programmer ,but that code used by the many other programmer, i.e.CODE RESUSABILITY. 3.CODE EXTENSIBILTY(Overriding) ============================= Adding the new feature in existing class method ,without any signature modification, i.e.CODE EXTENSIBILTY. What is METHOD SIGNATURE? Ans. METHOD SIGNATURE=METHOD NAME+METHOD PARAMETER.

Q.What is Inheritance? 1.Inheritence is a name of mechanism/feature of OOPS,using which we derived new class from existing class, that is known as Inheritance.

2.Aquaring the property of super class inside sub class. that is INHERITENCE. 3.Inheritence establish the IS-A relation ship. that relation ship is known as Aggregation. Types of Inheritance ==================== 5 types 1.SINGLE LEVEL 2.MULTI LEVEL 3.MULTIPLE 4.HIERARICAL 5.HYBRID

Types of JAVA supported Inheritance =================================== 3 only, strictly writing 1.SINGLE LELEL 2.MULTI LEVEL 3.HIERARICAL Advantage of Inheritance ========================= 1.Avoiding code redundancy problem 2.Overcome the drawback of Composition 3.Code Reusability 4.Code Extensibility. class loading diagram in Inheritance ==================================== classloading.jpg Object creating diagram in Inheritance ====================================== objectcreating.jpg using 'extends' keyword ======================== 1.'extends' is the keyword of java. 2.'extends' keyword is used to inherit the class from existing class. what is Generalization==ASSIGNMENT What is specialization==ASSIGNMENT Q.What is IS-A RELATIONSHIP?

Ans. 1.IS-A is the name of relationship which is generated though the INHERITANCE. eq. class Animal { } class Cat extends Animal { } IS-A ===== Cat IS-A Animal. example of all types inheritance ================================ constructor chaining ===================== super reference ============= super() call ============ What is Composition? ===================== 1.Creating the object of one class inside another class ,that is known as Composition. 2.It is also known as Association. class A1 { int i; } class B1 { int i; psvm(......) { new B1(); new A1(); } } Need of Inheritance ===================

If we want to create hierarchy of class which belong to the similar family then we need Inheritance.

Person Person IS-A student. Person IS-A Employee.

WHat is Inheritance =================== 1.Inheritence is a name of mechanism of OOPS,using which we derived new class from existing class, that is known as Inheritance. 2.Aquaring the property of super class inside sub class. that is INHERITENCE. 3.Inheritence establish the IS-A relation ship. that relation ship is known as Aggregation. Advantage ========= 1.Avoiding code redundancy problem 2.Overcome the drawback of Composition 3.Code Reusability 4.Code Extensibility. Meaning of "extends" keyword ============================ getting property (but not force super class to sub class)

3/24/2012 ============ What is Code Reusability ======================== Those code which written by other programmer and that code used by third party programmer,i.e Code Reusability.

What is Code Extensibility(Method Overriding) ============================================= Adding new feature from existing classs method without any signature modification, i.e. known as CE.

What is Method Signature ======================== Method Signature=Name of the method Method Parameter

Java Supported Inheritance ====================== 1)Single level inheritance class A { } class B extends A { }

2).multi level inheritance class A { } class B extends A { } class C extends B { }

3)hierarical inheritance class A { }

class B extends A { } class C extends A { } Unsupported Inheritance ====================== Multiple Inheritance ==================== class A { } class B { } class C extends A,B { } Hybrid Inheritance ===================

class A { } class B extends A { } class C extends A { } class D extends B,C { } Class loading Diagram ==================== Memory Allocating for creation of objcet Diagram

================================================ searching mechanism FOR VARIABLE,METHOD =========================================== sub to super EXECUTION Mechanism =================== Example of Single level Inheritance(Person and Student) 25/03/12 ======== Example of Multi level Inheritance Example Hierarical

formula of public,private,protected,default =========================================== super() call ============ super reference ============== REFERNCE typecasting ====================== Constructor chaining ===================== final class ============ polymorphism ============ super reference =============== 1.'super' reference refer to the just immediate super class. 2.'super' reference cannot be use directly inside any static context. 3.'super' is keyword of java. ***************************Polymorphism*************************** =============================================================== === POLY =MANY MORPHISM =FORM 1."Defining one things in many form". i.e. POLYMORPHISM.

2.The ability to change the behavior of reference variable during runtime,i.e. POLYMORPHISM. There are two types Polymorphism. 1.Compile time polymorphism==Same behavior during compile time as well as run time. OR eg. Method Overloading OR Early Binding OR Static Binding 1.Run time polymorphism==>Change the behavior during run time. OR eg.Method Overriding OR Late Binding OR Dynamic Binding Reference Typecasting ===================== NOTE ====RT possible in INHERITENCE. 1.Typecast the reference of an object into the other type reference varible.i.e RT. 2.Both reference variable must be maintain IS-A relationship. There are 2 types of RT. 1.Widdening REFERNCE type casting =================================To convert the object reference of sub class into super class. Super Class rv=new Subclass(); 2.Narrowing Reference type casting ================================== Note ===Directly it is not possible, to convert super class reference into sub class. To convert super class reference variable into sub class type.i.e.Narrowing RT.

Overridding ===========

What is Method Overriding? Ans. => Redefining the method of super inside sub class without any signature modification ,i.e. Method Overriding.

Why === To achieving the run time polymorphism. Rule ==== 1.name of the method must be same. 2.parameter must be same. 3.return type of the method must be same, but if we change the return type of the method then we must follow concept of CO-VARIANT RETURN TYPE. 4.access specifier either same or stronger but not weaker. public protected default private Note ==== Must be maintain IS-A relationship.

Q.What is Dynamic method Dispatching? Ans. DMD is nothing but method of super class bind with super class reference and automatically during run that method bind with sub class reference,i.e DMD. class A { void m1() { System.out.println("Hello"); } }

class B extends A { void m1() { System.out.println("Hello1"); } psvm(String[] a) { A s=new B();//widening reference t s.m1();//DMD }} op =Hello Note ==== Compiler always bind with reference variable But JVM always bind with object reference. Note ==== 1.static method cannot be override. 2.private method cannot be override.(Data hiding) Q.What is Concrete class? Ans.Those class which is instantiated(object create) in the memory,i.e.Concrete class.

Q.What is Abstract Class? Ans.Those class which is not instantiated(cannot create the object) in the memory and use abstract modifier with class,i.e.Abstract Class. eg. abstract class A { }

What is Concrete method? Ans.Those method which contains body,i.e.Concrete method. void m1() { } What is Abstract method?

Ans.Those method which doesn't contains body,i.e.Abstract Method Note ====AM cannot be static. void m1();

Rule of Abstract Class ====================== 1.Inside Abstract class we can create 0 to nth number of concrete method and 0 to nth number of abstract method. 2.We cannot create the object of Abstract class. 3.Abstract contains methods(static/instance),variables(static/instance),block(static/instance) and constructor also.

Interface ========= Why? ===If we know about the entity, but dont know about behaviors then we need INTERFACE. interface Animal { void eat(); } class Goat implements Animal { void eat() { Sop("Goat eats the grass"); } } class Dog implements Animal { void eat() { Sop("Dog eats the meat"); } }

Note ==== Some people says, interface is used to implement the concept of MULTIPLE inheritance, but purpose of Interface is not implement the concept of MULTIPLE inheritance in java, but it looks like the MULTIPLE inheritance. Q.What is Interface? Ans. 1.Interface is a contract. 2.Interface is a contract in between service provider and service utilizer. 3.interface is a keyword of java. 4.Interface is a user define data type. 5.Interface is a reference data type. 6.Interface is also structure of java,becoz it generated .class file(byte code). 7.Interface is the collection of zero or more than zero abstract method and zero or more than zero final variable. 8.object of interface cannot be created. 9.Interface is a pure abstract class,becoz it only constains abstract method, not concrete method. 10.interface is a pure super class.

characteristics =============== 1.method of interface by default as an abstract. 2.each and every method of interface by default declared as a 'public abstract, if you dont use then its duty of java compiler to use 'public abstract' with each method of interface. if we use any other Access Specifier with interface's method then CTE. 3.each and every variable of interface must be declared as 'public static final, if you dont use then its duty of java compiler to use 'public static final' with each variable of interface.

meaning of 'extends' keyword and 'implements' keyword ===================================================== extends==getting(but not force) implements==giving(forcely) i.e. must be override in there sub class. 'implements' keyword is used to implement the property of interface in the class.

working with one interface with another interface(related syntax) =============================================================== == 1.one interface extends another interface. interface I1 { } interface I2 extends I1 { } 2.one interface can extends zero or more than zero interface. interface I1 { } interface I2 { } interface I3 { } interface I4 extends I1,I2,I3 { } 3.one interface cannot extends/implement any class. 4.one class extends only one class and implements zero or more than zero interface. class H {

} class J extends H implements I1,I2,I3,I4 { } with interface keyword we can use keywords ========================================= 1)public 2)abstract 3)default(by default) 4)strictfp 5)public abstract/abstract public java.lang.Object ================ God class of JAVA. 11 method. 1)String toString() 2)int hashCode() 3)booelan equals(Object a) 4)Class getClass() 1.What happens in the memory whenever we print the reference variable Ans.Internally call toString() method of Object class. 2.What is difference between '==' operator ans equals(Object e) method before learn the concept of String handling and Wrapper class? Q.In which memory arrays is created? Ans.HEAP memory area Q.What is an Array? Ans.An Array is the index collection of similar of of data that is knows as an Array.

Advantage of an array ====================== Only grouping of data

Disadvantage of an array =======================

an array is static in the size, Static means we can not increase/decrease the size of an array during run time, this is the biggest problem with an array.

Size of Array =============May or may not be constant,becoz of that we can take the size from keyboard also. Type of an Array =============== 1.Single Dimension Array 2.Mutli Dimension Array/2D array

Q.What is 1D array? Ans.An array of single sub script ,that is known as 1D array. There are 2 types of 1D array 1.Primitive 1D array 2.Reference 1D array

Note ====Array supports concept of default value, array either static ,instance or local or block level there is no problem to supports default value. How to declare Single Dimension Array ===================================== Syntax1.

1) DT[] vn=new DT[size]; 2) DT []vn=new DT[size]; 3) DT vn[]=new DT[size]; eg. of primitive 1D array ==========================

int[] a=new int[5]; eg. of reference of 1D array ============================ class/interface[] vn=new class/interface[size]; Abc[] a=new Abc[4]; a[0]=new Abc(); a[1]=new Abc();

Abc a=new Abc(); How to initialize Single Dimension Array ======================================== Syntax2. 1) DT[] vn={ele1,ele2,.....}; 2) DT vn[]={ele1,ele2,.....}; 3) DT []vn={ele1,ele2,.....}; eg. int[] a={1,2,3,4,5}; eg. Abc[] a={null,new Abc(),new SubClassOfAbc()}; Syntax number 3(Anonymous array) ================================ dt[] vn=new dt[]{ele1,ele2,ele3,...}; or new dt[]{ele1,ele2,ele3,...}; mostly use of this array is passing the argument of array type. eg. int []a=new int[]{1,2,3,4,5}; eg. Abc[] a1=new Abc[]{null,new Abc(),new SubClassOfAbc()}; Sop(a1[0]);//null Sop(a[1]);//Ab@somecode Sop(a1[2]);//Sub@somehashcode

Q.What happens in the memory when ever we create an array? Ans. 1Darray.jpg Q.What is 2D array? Ans.An array of an arary ,that is known as 2D array. Q.What happens in the memory when ever we create an array? Ans. 2Darray.jpg How to declare 2Dimension Array ===================================== Syntax1.

1) DT[][] vn=new DT[size][size]; 2) DT [][]vn=new DT[size][size]; 3) DT vn[][]=new DT[size][size]; 4) DT []vn[]=new DT[size][size]; 5) DT[] vn[]=new DT[size][size]; 6) DT[] []vn=new DT[size][size];

How to initialize 2Dimension Array ===================================== Syntax2. 1) DT[][] vn={{ele1,ele2,.....},{ele1,ele2,....},{ele1,ele2......}........}; 2) DT vn[][]={{ele1,ele2,.....},{ele1,ele2,....},{ele1,ele2......}........}; 3) DT [][]vn={{ele1,ele2,.....},{ele1,ele2,....},{ele1,ele2......}........};

*/

String Handling Syllabus ======================= 1.String class 2.StringBuffer class 3.StringBuilder 4.What is command line Argument 5.How to use Command line arguments in String Handling

STRING HANDLING =============== A)String=collection of character. B)Internally String is array of character. 1.String is the name of class which is present in "java.lang" package. 2.String class declared as a final, that means we can't inherit. 3.String class's object is immutable object. 4.String class's method is immutable method. 5.String class's method is non-synchronized. 6.String class is not thread safe, so we can't develop multithreaded application using String class but can develop single threaded application. What is Immutable Object ========================An object which doesn't change the state of our own object. i.e. Immutable object. What is Immutable Method ========================Those method which doesn't change the state of our own object,i.e. Immutable method. ->It is also know as getter method. -->constant object statement, means not changeable class A { int i=12; int get() { return i; } }

Q.Mutable object? Ans.changeable. Q.Mutable Method? Ans.setter method class A { int i=12; void set() { i=16; } }

How to create an object of String class ======================================== There are 2 mechanism in java to create the object of string . 1.Using 'new' operator 2.Using string literals. How to create object of String class using string literals ========================================================== String a="INTEGRAL";

Note ==== 1.When ever we create the object of String class using string literals then this String class's object create in POOL AREA. POOL AREA= STRING CONSTANT POOL + FINAL CONSTANT POOL POOL AREA is in Method memory Area. 2.If the object of String class created in POOL area then ,if String class object is repeated then JVM will not create another object,JVM refer to same object of String class in POOL.

How to create object of String class using new operator =======================================================

String a=new String("INTEGRAL"); String a1=new String("INTEGRAL"); Note ==== 1.When ever we create the object of String class using new operator then this String class's object create in POOL AREA as well as HEAP AREA also,that means two object will create.

2.If the object of String class created in HEAP area then ,if String class object is repeated then JVM will create another object in Heap memory area.

==>There are so many instance method in String class which are given below 1.String toUpperCase() 2.String toLowerCase() 3.String concat(String) 4 String subString(int) 5 String subString(int,int) 6.boolean equalsIgnoreCase(String) 7.boolean equals() etc. Q.D/f b/w '==' operator and equals(Object) method?

StringBuffer ============ 1.StringBuffer is the name of class which is present in "java.lang" package. 2.StringBuffer class declared as a final, that means we can't inherit. 3.StringBuffer class's object is mutable object. 4.StringBuffer class's method is mutable method. 5.StringBuffer class's method is synchronized as well as non synchronized also. 6.StringBuffer class is thread safe, so we can develop multithreaded as well as single threaded application using StringBuffer.

How to create an object of StringBuffer class ================================================= There is only one mechanism to create an object of StringBuffer class,i.e. 'new' operator StringBuffer sb=new StringBuffer(int) StringBuffer sb=new StringBuffer(String) StringBuffer sb=new StringBuffer()

Rule ===== 1.If StringBuffer class object state are repeated then it means ,JVM will another object of StringBuffer class. 2.StringBuffer class object state may be changed change ,why becoz StringBuffer class supports concept of mutability,and object is mutable. ==>There are so many instance method in StringBuffer class which are given below 1.StringBuffer reverse() 2.StringBuffer append(),with different data types. 3.StringBuffer replace(),with different data types. 4.StringBuffer insert(),with different data types. 5.int indexOf(String) 6.StringBuffer delete(int ,int) 7.char charAt(int) etc.

StringBuilder ============= 1.StringBuilder is the name of class which is present in "java.lang" package. 2.StringBuilder class declared as a final, that means we can't inherit. 3.StringBuilder class's object is mutable object. 4.StringBuilder class's method is mutable method. 5.StringBuilder class's method is non synchronized. 6.StringBuilder class is not thread safe, so we can't develop multithreaded as well as single threaded application using StringBuffer.

How to create an object of StringBuilder class ============================================== 1)StringBuilder variablename=new StringBuilder(); 2)StringBuilder variablename=new StringBuilder("Stringdata");

Rule ==== 1.If StringBuilder class object state is repeated then it means ,JVM will

another object of StringBuilder class. 2.StringBuilder class object state will change ,why becoz StringBuilder class supports concept of Mutability, and its object is Mutable. ==>There are so many instance method in StringBuilder class which are given below

1)StringBuilder append()//overloaded method 2)StringBuilder deleteCharAt(int) 3)StringBuilder delete(int,int) 4)int indexOf(String,int) 5)int lastIndexOf(Strig) 6)char charAt(int) 7)int length() 8)String substring(int,int) 9)AbstractStringBuilder reverse() 10)AbstractStringBuilder replace(int,int,String) 11)AbstractStringBuilder insert()//overloaded

Assignment ========== 1.WAP to check given string is palindrome or not ,without string class method. 2.WAP to check given string is palindrome or not using string class method. 3.WAP to count how many number of vewels,consonants and special symbol in given string. 4.WAP to count number of spaces.

HINT for First, third and fourth program ======================================= String s="INTEGRAL";//char[] int i=s.length();//8 char a[]=s.toCharArray(); Sop(a[1]);//N

Q.What is Command Line Argument? Ans. An Arguments which passes during run time though the command prompt with java program execution command,i.e.Command Line Arguments.

class CLA { public static void main(String[] a) { Sop(a[0]); Sop(a[1]); Sop(a[2]); } }

Package ======= Need ==== 1.If we want to set access protection then we need Package. 2.MODULARITY 3.SECURITY 4.REUSABILITY Package ======= 1.Package is the collection of .class file. 2.Non technically package is a folder/directory. 3.Technically .package is a bundle or library of pre defined classes/interfaces. 4.Package is a grouping of classes that provide access protection.

Types of package ================ There are two type of packages. 1.Pre Defined Package 2.User Defined PAckage 1.What & Example of Pre Defined Package. ======================================= PRE DEFINED PACKAGE ===================Those packages which are created by SUN programmer,i.e.PRE DEFINED PACKAGE. eg.

java.lang. java.util java.io javax.servlet etc.

2.What & Example of User Defined Package. ======================================== USER DEFINED PACKAGE ====================Those packages which are created by user,i.e.USER DEFINED PACKAGE.

what is "package" keyword. ========================== package is the name of keyword of java, when ever we want to create the user defined package then we use 'package' keyword. How to create package. ===================== package packagename; structure-type name { } How to execute one package program. =================================== Q.What is Path? Ans.Path is an environment variable of the operating system which find the actual location of .exe file.

Q.What is Class Path? Ans.ClassPath is an environment variable of the operating system which find the actual location of .class file. /*Rule ==== Inside Package ==============

1)class may or may not be public, if class is public, then that can be access outside the package, if class is not public then can not be access outside the package. 2)class(top level class) cannot protected, private. class A { protected class A { } private class V { } } A.java package p1; public class A { } Z.java package p1; public class Z { } 3.methad can be declared as public,private,protected & default. but only public method are call in outside the package ,but protected method also call through power of Inheritance.

4.Constructor can be declared as public,private,protected & default. but only public constructor are call in outside the package , but protected Constructor also call through power of Inheritance.

5.Variable can be declared as public,private,protected & default. but only public variable are accessible in outside the package , but protected variable also accessible through power of Inheritance.

*/ How to access one package in to the unknown package. =====================================================

How to access one package in to the another package. ===================================================== Practically proved protected member in package. ================================================ Nested Package ============== INTERFACE,CLASS in same package =============================== Assignment ========== Third type of comment ===================== /** */ ***************************************************** PACKAGE ***************************************************** Need & Advantage of package =========================== 1.If we want to acheive modularity then we need package. 2.If we want to set access protection then we also need package. 3.Reusability 4.Security 5.Name space management

What is package =============== 1.Package is a collection of classes, interfaces and enums. 2.Non technically Package is a folder or directory which contains .class files. 3.Technically package is a library, library may be PRE-DEFINED

or USER DEFINED. 4.Package is a grouping of classes that provide access protection.

Types of package ================ There are two type of packages. 1.Pre Defined Package 2.User Defined Package 1.What & Example of Pre Defined Package. ======================================= 2.What & Example of User Defined Package. ========================================= what is "package" keyword. ========================== How to create package. ====================== How to execute one package program. =================================== what is "import" keyword ========================= How to access one package in to the unknown package. ===================================================== How to access one package in to the another package. ===================================================== Practically proved protected member in package. ================================================ Nested Package ============== INTERFACE,CLASS in same package ===============================

How to create JAR file in package.

================================== Static import in java. ====================== ***************************************************** EXCEPTION HANDLING ***************************************************** Need of Exception Handling -------------------------1.To avoid any problem which during run time, then we need Exception Handling. 2.Precaution before execution 3.Avoiding abnormal termination. Q.What is Exception? Ans.An exception is nothing but, any problem which occur during run time,that problem is known as Exception. eq.(COLLEGE=compiler, STUDENT=source code,COMPONY=JVM) Q.What is exception handling? Ans.Exception handling is the name of mechanism using which we handle the problem which occur during run time,i.e.Exception Handling.

Q.What is Error? Ans. Note ====Error is not related to the syntax error, Syntax error is separate thing and Error is separate thing. Error -----Those problem which can't be handle though the program, that type of problem is known as Error. eq. 1.Hard disk crash 2.Memory Exhaust 3.Keyboard problem 4.Stack overflow ,(memory full becoz number of object are creating infinite) Q.What is Syntax Error? Ans.Those problem which recognized by the compiler ,i.e. Syntax Error.

Advantage of Exception Handling ============================== 1.To avoid run time problem. 2.Avoiding abnormal termination. 3.To maintain proper separation in b/w business logic and exception message. Types of Exception ================== 1. Checked Exception 2. Unchecked Exception 3. Caught Exception 4. Uncaught Exception

What happens in the memory when Exception occur ================================================ 1)JVM create the object of corresponding exception type in the memory and get the hash code of an object by the JVM. 2)AND JVM search the user defined exception handler block of corresponding exception type, if UDEHB(user defined exception handler block) found, then give the object hash code of an exception to the user defined exception handler block. if not found then JVM create ONE DEFAULT EXCEPTION HANDLER BLOCK in memory and display the exception handling message and terminate the program and further statement will not execute.

What is Exception Handler block =============================== Those block which handling exception,i.e.Exception Handler Block.

Types of Exception Handler Block ================================ There are 2 types of EHB 1.User Defined Exception Handler Block 2.Default (JVM Defined) Exception Handler Block

1.Default Exception Handler BLock =================================== A block which is created by JVM,i.e.Default Exception Handler Block. When do JVM create DEHB =======================Whenever there is no user defined exception handler block of corresponding exception type, then JVM will create DEHB.

2.User define Exception Handler Block(try, catch) =================================================Those block which created by the user/programmer ,i.e.UDEHB(i.e. try-catch)

eq.try-catch Types of Exception =================== 1. Checked Exception =====================java.lang.Throwable,java.lang.Exception and its sub classes,except RuntimeException Error and its sub classes,i.e.Checked Exception. Rule ==== Checked Exception must be handle before compilation. 2. UnChecked Exception =======================java.lang.RuntimeException and java.lang.Error and its sub classes, i.e.UnChecked Exception. Rule ==== UnChecked Exception may or may not be handle before compilation. 3. Caught Exception 4. Uncaught Exception How to Handle Exception

======================= There are 2 mechanism in java to handle the exception 1.try-catch 2.throws

Programming =========== 1)what is try block =================== 1.try block contains pure business logic. 2.Those statement which may or may not be throw an exception, we write those code inside try block. 3.try block is also known as USER DEFINED EXCEPTION HANDLER BLOCK. Use === If any statement throw exception , we include those statement inside try block.

2)what is catch block ===================== 1.catch block is a pure exception handler block. 2.catch block is used to display exception related message. rule of try & catch block ========================= 1.one try block hold zero or more than zero catch block. 2.if try block contains zero catch block then we must create one finally block. 3.If there are more than one catch block with single try block then ,if catch block's exception class maintain the inheritence relationship then we must include catch block into subexceptionclass to superexceptionclass order. 4)sequence of(try-catch-finally/try-catch/try-finally/try-catch-catch-catch..../ try-catch-catch-catch-finally). 5)if one try block contains more than one catch then, a)all catch block contains different type of Exception(can not be same) b)if catch block Exception maintain IS-A relationship then follow SUB-TYPE-Exception and then SUPER_TYPE_Exception

6)one try block can contain only zero or one finally block. 7)can not be repeat same exception type catch block.

what is finally block ===================== 1.Those block which is executed ,either exception occur or not. 2.That means, finally block must be excecuted,either exception occur or not.

why do we use finally block =========================== USE ===To create resource deallocation code inside finally block.

Real time example ================ ATM machine

Nested Try block ================ Creating one or more than one try block inside try block,i.e.Nested Try Block.

throws ====== 1.throws is the name of keyword of java. 2.throws is used to forward the exception to caller. 3.each unchecked exception internally use this mechanism. Need ====If the method is unable to handle the exception ,then it forward to the caller.

1)printStackTrace()//java.lang.Throwable(non-static) 2)getMessage()

throw ===== 1.If we want to generate(create the object) any exception explicitly, then we use 'throw' mechanism. 2.'throw' is the clause or keyword of java.

Need ==== mostly we use this 'throw' mechanism, when ever we generate the custom exception.

D/f b/w throws and throw ======================== Assignment Mechanism of getMessage() ========================= How to create custom exception(either checked or unchecked) =========================================================== ************************************************************************ WRAPPER CLASSES =============== ************************************************************************ Q.What is Wrapper Class? Ans.Wrapper class is nothing but it is the wrapper of all primitive data type, i.e.known as Wrapper Class. Q.Why do we need Wrapper Class? Ans. To prepare the object model of primitive data values, that is why we need Wrapper Class. int i=12; i.hashCode()//wrong technique(CTE) Integer d=new Integer(i); i.hashCode();//

There are total 8 wrapper class in JAVA ======================================= 1)Byte Constructor Details ===================

Byte(byte value) Byte(String byteString)throws NumberFormatException

2)Short Constructor Details =================== Short(short value) Short(String shortString)throws NumberFormatException 3)Integer Constructor Details =================== Integer(int value) Integer(String intString)throws NumberFormatException 4)Long Constructor Details =================== Long(long value) Long(String longString)throws NumberFormatException 5)Float Constructor Details =================== Float(float value) Float(String floatString)throws NumberFormatException 6)Double Constructor Details =================== Double(double value) Double(String doubleString)throws NumberFormatException 7)Boolean Constructor Details =================== Boolean(boolean value) Boolean(String booleanString)throws NumberFormatException 8)Character

Constructor Details =================== Character(char value)

Characteristics =============== 1.All the wrapper class follow the concept of Immutability. 2.All wrapper class object is immutable Object. 3.All wrapper class method is immutable method. 4.All wrapper class declared as final,so we cannot createthe sub class of Wrapper class. ***************************************************************** TYPE CONVERSION ***************************************************************** 1.primitive to String ===================== int i=12;float j=12.23f; String a =String.valueOf(i); String a1 =String.valueOf(j); int x=100; String a=a+x;//static or instance(create object) 2.String to primitive ====================== int x=Integer.parseInt(a); float x1=Float.parseFloat(a1); 3.primitive to Wrapper ====================== Integer i=new Integer(x);; Integer i1=Integer.valueOf(x);

4.Wrapper to primitive ======================= int b=i.intValue();

5.String to Wrapper =================== String i="12"; Integer a=new Integer(i);

Integer a1=Integer.valueOf(i);

6.Wrapper to String =================== String a=a1.toString();

****************************************************************** Autoboxing and Auto-Unboxing Conversion ======================================= ****************************************************************** Note ====Autoboxing and Auto-Unboxing Conversion concept was introduced in jdk1.5 version. Q. What is Autoboxing conversion? Ans.To convert the primitive into its corresponding wrapper type,i.e.Autoboxing Conversion. Q. What is Auto-Unboxing conversion? Ans.To convert the wrapper into its corresponding primitive type,i.e.Auto-Unboxing Conversion. eg. Integer j=new Integer(12); int i=j;//auto-unboxing conversion Integer k=i;//autoboxing boxing conversion

Integer i=12;//autoboxing int j=i;//AUB ************************************************************* GENERIC ************************************************************* Q. What is Generic? Ans.Generic is nothing but it provides abstraction over the type like class, interface declared as parameterized by the type called Generic.(In the same way Java type(class, interface) declared with parameterized of the type an instance of it (during creation of object time).

-->Generic concept introduced in JDK 1.5 version. -->Generic Concept is looks like a C++ language's concept Templates. -->Generic use as parameterized of Type only Reference Type(That means Only object (class, Interface))and not any primitive type.

Q.Why do we need Generic? Ans.When more than one class perform similar operation , but only data types are change instead of this, we develop only single class as a parameterized of type, which perform similar operation. Use of Generic ============== Family of classes which perform similar operation with different data type.

1)Q.Generic Class==> Ans.if a class which are declared as parameterized by Type called Generic class. Syntax ====== [A_S] class class name<type> { } type==>may be as interface or class. class A<T> { } 2) Q.Generic Interface==> Ans.if a interface which are declared as parameterized by Type called Generic Interface. Syntax ====== [modifier] interface nameofinterface<type> type==>may be as interface or class.

interface I1<T> { } 3) Q.Generic Method==> Ans.If a method which are declared as parameterized by Type called Generic Method. Note ==== Method can not be static. class must be generic. Syntax ====== [modifier] <TYPE> return type method_name([parameter]) { } type==>may be as interface or class.

Generic Variable ================ Those varaible which declared as a type of generic ,i.e. known as GV Syntax Of Variable ===================== [access specifier] <type> variable name; type==>may be as interface or class.

Programming part =============== Predefined Class User defined Class How to use Inheritance in Generics Key and Value Pair concept ========================== Sub typing

========= ************************************************************* COLLECTION FRAMEWORK ************************************************************* Q.Why do we need CF? Ans. 1.If we want to overcome the drawback of an array then we need CF. 2.If we want to use underlying Data Structure in java then also we need CF. 3.If we want to perform group of element or group of object, then also we need CF. What is limitation of An Array? Ans. An Array is the index collection of fixed number of homogeneous data,i.e.An Array.

limitation ========== 1.An Array is static in the size. 2.An array can hold homogeneous data element or object. 3.There is no underlying data structure provide by the array ,thats why readymade method doesnt available. 4.For any DS operation, we write the explicitly code. 5.To overcome above problem "SUN" has introduced COLLECTION FRAMEWORK.

Q.What is Collection? Ans. 1)A collection is a data structure for holding the elements(data/object). 2)A "Collection" object=called Container. ->"is simply an object that group of multiple element into a single unit."

Q.What is Collection Framework? Ans.Collection framework is a unified architecture for representing the manipulated collection(DS) i.e. known as Collection Framework. Note ==== CF contains following things..... 1)Interface 2)Implementation(implemented class) 3)Algorithms(rule and regulation)

Q. Advantage of Collection Framework? Ans. 1.To provide underlying DS. 2.To provide dynamic insertion element concept.

Q.What is the difference b/w Array and Collection? Ans. 1.Array can hold primitive and reference type elements. 2.Array is collection of only homogeneous elements. 3.Array is the static in the size. 4.Array doesnt provide underlying data structure. 5.There is no method support by the array. 1.Collection can hold only reference type elements. 2.Collection is collection of homogeneous elements and Heterogeneous elements. 3.Collection is dynamic in the size. 4.Collection provides underlying data structure. 5.There are so many readymade method supports by collection.

Q.When do people prefer Array/Collection? Q.What is Homogeneous collection? Q.What is Heterogeneous collection? Q.What is the difference b/w CF1.4 and CF1.5? Ans. CF1.4 ===== 1.There is no concept of Generics. 2.Thats why CF1.4 is not type safe. 3.There is no concept of Autoboxing and Autounboxing. CF1.5 ===== 1.There is concept of Generics. 2.Thats why CF1.5 is type safe. 3.There is concept of Autoboxing and Autounboxing.

Q.Heirarchy of Collection Framework? heirarchy.jpg java.util. Collection(interface) 1)java.util.List(interface) extends Collection 2)java.util.Set(interface) extends Collection 3)java.util.Queue(interface) extends Collection 4)java.util.Map(interface) does not extends Collection interface.

Q.What is List? 1.List is name of interface which extends the property of Collection interface and present "java.util" package. 2.List provide an ordered collection object. 3.List is a index based collection like array. 4.Order is preserved. 5.List allow null. Q.Heirarchy of List interface. Ans. List ArrayList extends AbstractList implements List Vector implements List Stack extends Vector LinkedList implements List Method of List interface ======================== 1)boolean add(E d) 2)Object set(int index,E d) ===========================Update the index element 3)boolean isEmpty() 4)E get(int index) 5)void clear() 6)List subList(int fromIndex,int toIndex) 7)boolean remove(Object d) 8)boolean add(int index,Object d) 9) boolean removeAll(Collection d) 10)ListIterator listIterator() 11)ListIterator listIterator(int) 12)int indexOf(Object o) 13)Object remove(int index) 14)int size() ==============return the total number of element in the collection.

Q.What is ArrayList,Vector , Stack and LinkedList with programming. Ans.ArrayList ============= 1)ArrayList is the name of concrete class. 2)ArrayList is a List. 3.ArrayList is an ordered collection(maintain insertion order). 4)ArrayList allow duplicate elements. 5)ArrayList allow "null" and also we can insert "null" . many number of time. 6)ArrayList method are not synchronized ,that is why we can not develop multi threaded application using ArrayList.and ArrayList class is not Thread safe. 7)ArrayList provide get(index) method,if index not found then ArrayIndexOutOfBoundsException 8)ArrayList ,default capasity is 10. 9)Allow hemogenious and hetrogenious elements. 10)ArrayLis is the index based collection(ArrayList also maintain the element based on Index). formula of increasing capacity of ArrayList Object is =================================================== new_capacity=(old_capacity * 3)/2 + 1; (10*3)/2+1=16 (16*3)/2+1=25

Constructor of ArrayList ====================== 1)ArrayLis()==>emplty list with initial capacity is 10. 2)ArrayLisy(int initialCapacity)==>emplty List with specified initial capacity.

java.util.Vector ================ 1)Vector is the name of concrete class. 2)Vector is a List. 3.Vector is an ordered collection(maintain insertion order). 4)Vector allow duplicate elements. 5)Vector allow "null" and also we can insert "null" . many number of time. 6)Vector method are synchronized and non-synchronized ,that is why we can develop multi and single threaded application using Vector and Vector class is Thread Safe. 7)Vector provide get(index) method,if index not found then ArrayIndexOutOfBoundsException

8)Vector ,default capasity is 10. 9)Allow hemogenious and hetrogenious elements. 10)Vector is the index based collection(ArrayList also maintain the element based on Index). 11)Vector is a legacy class,becoz Vector class was introduced in JDK1.1 version. 12)Vector class provide capacity method is 10.

formula of increasin capacity of ArrayList Object is ==================================================== new_capacity=(old_capacity * 2) Constructor =========== 1)Vector() ========null parameterized,default capacity is 10. 2) Vector(int initialcapacity) ========SET initial capacity. 3)Vector(int initialcapacity,int increment capacity) ==================================================== Method(other than List interface) ================================= 1)void addElement(E obj) 2)int capacity() 3)E elementAt(int index) 4)E firstElement() 5)void insertElementAt(E obj,int index) 6)E lastElement() 7)int lastIndexOf(Object o) 8)int lastIndexOf(Object o,int index) 9)void removeAllElement() 10)boolean removeElement(Object i) 11)void removeElementAt(int index) 12)protected void removeRange(int fromIndex,int toIndex) 13)void setElementAt(E obj,int index)(means update karna) Q.D/f b/w Vector and ArrayList class. Ans. ArrayList ========= 1.methods are not synchronized.

2.object is not Thread Safe. 3.deveop only single threaded application. 4.class introduced in JDK1.2 version that is why ArrayList is not legacy class. 5.not provide any capacity method. 6.Performance is high Vector ======== 1.methods are synchronized as well as non synchronized. 2.object is Thread Safe. 3.deveop multi and single threaded application. 4.class introduced in JDK1.0 version, that is why Vector class called Legacy class. 5. provide capacity method. 6.Performance is low.

java.util.LinkedList ==================== Every thing -every thing are same as ArrayList.

java.util.Stack =============== 1.Stack is the name of class which extends the property of Vector class. 2.Stack class supports LIFO(last in first out) manner. Note ==== 1.Allow duplicate element. 2.Allow null, 0 or more than zero time. 3.dynamically resizable. 4.accept hemogenious elements as well as hetrogenious elements. 5.Index based collection. 6.Ordered collection.

Constructor ============ public java.util.Stack();//Create an empty stack

Method ====== public java.lang.Object push(java.lang.Object);//push the item on the top of the stack. public synchronized java.lang.Object pop();//Remove the item on the top of the stack. public synchronized java.lang.Object peek();//return the object which is on the top of the stack. public synchronized int search(java.lang.Object);//return the position where an object is on this stack. public boolean empty();//tests if this stack is empty.

D/f b/w LinkedList and ArrayList ================================ LinkedList ========== 1.There is no initial capacity concept in LinkedList. 2.Best suitable for frequent insertion and deletion operations. 3.Not suitable for frequent element retrieval operation becoz of that LinkedList class doesn't implements RandomAccess interface. ArrayList ========= 1.There is initial capacity concept in ArrayList(default capacity is 10). 2.not suitable for frequent insertion and deletion operators becoz internally it requires lot of sifting operation.. 3.Best suitable for frequent element retrieval operation becoz of that ArrayList class implements RandomAccess interface.

Constructor =========== LinkedList()//empty list

Exatra method in LinkedList class ================================= 1)void addFirst(Object e)//insert the element in the begining of the list. 2)void addLast(Object e)//insert the element in the end of the list. 3)E getFirst()//return the 1st element of the list. 4)E getLast()//return the last element of the list. 5)E removeFirst()//remove the 1st element from the list.

6)E removeLast()//remove the last element from the list. Q.Why do we need Set interface? Ans.To identify the collection uniquely(avoid duplicacy).

Q.What is Set? Ans. 1.Set is the name of interface in util package. 2.Set is unordered collection. 3.Set is not index base collection. 4.Ordered is not preserved,becoz it is not index based. 6.Set is based on Mathematics Set theory. 6.Set doesn't allow duplicate object. if we try to insert 'duplicate object' multiple time ,then 'duplicate' will add in the Set only one time. 7.Set doesn't allow 'null' multiple time, but one time is allowed. if we try to insert 'null' multiple time ,then 'null' will add in the Set only one time.

Method ====== There is no special method in Set interface. 1)public abstract int size(); 2)public abstract boolean isEmpty(); 3)public abstract boolean contains(java.lang.Object); 4)public abstract java.util.Iterator iterator(); 5)public abstract boolean add(java.lang.Object); 6)public abstract boolean remove(java.lang.Object); 7)public abstract boolean containsAll(java.util.Collection); 8)public abstract boolean addAll(java.util.Collection);//union 9)public abstract boolean retainAll(java.util.Collection);//intersection 10)public abstract boolean removeAll(java.util.Collection); 11)public abstract void clear(); 12)public abstract boolean equals(java.lang.Object); 13)public abstract int hashCode(); Q.What is Hashing? Ans. Hashing is a technique to set and retrieve the data in very frequent and faster manner.

Q.Inheritance chart of Set "java.util" HashSet implements Set TreeSet implements Set LinkedHashSet extends HashSet

Q.What is HashSet,TreeSet and LikedHashSet with programming. Ans. HashSet ======= 1.HashSet is the name of class in util package. 2.HashSet is unordered collection(maintain in Random order). 3.HashSet is not index base collection. 4.HashSet object is resizable object. 5.HashSet allow homogeneous and heterogeneous collection. 6.HasSet doesn't allow duplicate element. if we try to insert 'duplicate object' multiple time ,then 'duplicate' will add in the Set only one time. 7.HashSet allow 'null' only once. if we try to insert 'null' multiple time ,then 'null' will add in the Set only one time. 8.HashSet doesn't provide any get() method, so we go for Iterator interface. 9.Default capacity is 16 and load factor is 0.75, so filling capacity is 16*0.75=12 16+12=28 So whenever we adding 17th element then capacity of hash will increase. formula is[new capacity=old capacity + old capacity*0.75] 10.There is no capacity method.

Constructor =========== public java.util.HashSet(); public java.util.HashSet(int inintial_capacity, float load_factor); public java.util.HashSet(int inintial_capacity); Method ====== public java.util.Iterator iterator(); public int size(); public boolean isEmpty(); public boolean contains(java.lang.Object);

public boolean add(java.lang.Object); public boolean remove(java.lang.Object); public void clear(); public java.lang.Object clone(); NOTE === There is no getter method in HashSet ,so we go for Iterator interface. Contract of collection framework with Overriding of equals() with hashCode() method =============================================================== ========================= Condition 1. x.equals(y)== true Required NotRequired no

x.hashCode() == y.hashCode()

2. x.hashCode() == y.hashCode() requirement) 3. x.hashCode() != y.hashCode() 4. x.equals(y) == false requirement.

x.equals(y)==true(no

x.equals(y) == false

no

x.hashCode() == y.hashCode()

********The Content/Object of collection can be read using 3 different technique************** =============================================================== ================================= 1.Using Enhance 'for' loop 2.Method provide by Collection(Set interface doesn't provide any get() method ,but List interface provide get() method to read object). 3.Cursors Q.What is Enhance 'for' loop? Ans. 1.enhance 'for' loop was introduced in JDK1.5 version. 2.enhance 'for' loop used to reading the content of only array and collection. 3.it is also known as FOR-EACH-LOOP. Syntax of Enhance 'for' loop

========================== for(datatype variable : array reference/collection reference) { } eg1. int i[]=new int[5]; for(int k:i) { Sop(k); } o/p === 0 0 0 0 0 eg1. int i[]=new int[5]; int k; for(k:i)//compile time error,becoz datatypes of variable 'k' declare inside the loop. { Sop(k); } Q.What is Cursor and define whole implementation(Iterator interface) Ans. Cursor ====== 1.Cursor is a pointer to point memory location. 2.Cursor is a reference, which refer to the collection object. 3.Cursor is used to reading the object from memory. Iterator interface ================== Q.What is java.util.Iterator interface. Ans. 1.Iterator is the name of interface. 2.Iterator interface is used to provide getter for reading set elements. 3.Iterator interface is implement in 'HashMap$KeyIterator' inner class. 4.Iterator interface works forward direction only. 5.getting the reference of Iterator implemented class using 'Set' interface type

variable and call the iterator() method of Set interface. Method ====== Only 3 method 1.boolean hasNext() 2.Object next() 3.void remove()//remove the last element of the set.

Q.What is LinkedHashSet class. Ans. java.util.LinkedHashSet ======================= 1.LinkedHashSet is sub class of HashSet. 2.LinkedHashSet is same as HashSet but It contains elements in linked representation. 3.It gives more performance when compared with HashSet. Method =====No special method in LinkedHashSet class. Note =====It maintain insertion order but not duplicate.

Constructor =========== 1.LinkedHashSet()=>empty set with default capacity is 16 and loadFactor 0.75. 2.LinkedHashSet(int initialCapacity) 3.LinkedHashSet(int initialCapacity,float loadFactor) Example ======= Q.D/f b/w HashSet and LinkedHashSet? ans. HashSet =======It doesn't maintain insertion order. LinkedHashSet =============It maintaina insertion order.

Q.What is TreeSet. Q.D/f b/w HashSet and TreeSet. HashSet

======= 1.It allow homogeneous collection as well as heterogeneous collection. 2.It is unordered collection. 3.Order of HashSet is not preserved. 4.Underlaying data structure is 'HashMap'. 5.Order of HashSet's element canot be changed by using any technique. 6.If we want to add other object(except Wrapper classes,String) in HashSet to maintain unique information/data in set then we must override hashCode() and equals() method. 7.We can set the 'null' more than one ,but internally 'null' will add only once,there is no exception and error.

TreeSet ======= A.TreeSet is the name of class in util package. 1.It allow only homogenious collection ,other wise ClassCastException. 2.It is ordered collection(By default provide Ascending order). 3.Order of TreeSet is preserved. 4.Underlaying data structure is 'TreeMap'. 5.Order of TreeSet's element can be changed by using any Comparator interface technique. 6.If we want to add other object(except Wrapper classes,String) in TreeSet in sorted order then we must implement Comparable interface and override compareTo() method. 7.We can set the 'null' only once ,but internally 'null' will add only once,there is exception 'java.lang.NullPointerException".

Contructor ========== TreeSet() =========empty set and maintain natural ordering(ascending order). Method ====== 1.boolean add(E e) 2. void clear() 3. Object clone() 4.boolean isEmpty() 5.boolean remove(Object o) 6.int size() 8. E pollFirst() =================== Retrieves and removes the first (lowest) element, or returns null if this set is empty.

9.E pollLast() ============== Retrieves and removes the last (highest) element, or returns null if this set is empty. 10. E last() ============= Returns the last (highest) element currently in this set. 11. E lower(E e) ================= Returns the greatest element in this set strictly less than the given element, or null if there is no such element. 12. Iterator<E> iterator() 13.E higher(E e) 14.E floor(E e) 15.E first() 16.boolean contains(Object o) 17.E ceiling(E e)

Note ====All the Wrapper classes and String class implements Comparable interface and override the compareTo() method. meaning "int compareTo(){}" method is ============================== 1)Ist Object > IInd object then return = 1. 2)Ist Object < IInd object then return = -1. 3)both object are equal then return = 0.

************************************************************************ ** STREAM(file handling) ************************************************************************ ** Q.Why do we need Stream? Ans. 1)In order to perform input/output operation ,we need Stream. 2)Without Stream ,we cannot perform input/output operation. 3)To save your output and input in the hard-disk permanently,we need Stream.

Example ======= Banking Application(Before came to the concept of database, developer used STREAM for developed bank application or etc). Q.What is STREAM? Ans. 1)STREAM is a flow of data having source to destination. 2)STREAM is a mediator in between SYSTEM and DATA. 3)STREAM looks like a pipe in between WATER TANK to KITCKEN. 4)Stream(java.io) is a name of concept which provide many more classes and interfaces to perform i/o operation. 5)STREAM is sequence of data having Source to destination and destination to source. Q.What is Input? And.Data ,which flow inside the program or data given to the program ,i.e. INPUT. Q.What is Output? And.Data ,which flow outside the program ,i.e OUPUT.

Q.What is INPUT STREAM? Ans.A program that uses an input stream to read the data from source to program ,i.e. INPUT STREAM. ========= | | INPUT STREAM | | DATA |=======================| | | | | | | | 0101010101010101010101| PROGRAM | | | | | | SOURCE |=======================| | | | ---> ------> ------->| | ==========

Q.What is OUTPUT STREAM? Ans.A program that uses an output stream to write the data from program to data destination(either file or console) ,i.e. OUTPUT STREAM.

========= | | OUTPUT STREAM | |PROGRAM |=======================| | | | | | | |10101010101010101010101| FILE/CONSOLE| | | | | | |=======================| | | |---> ---> ----> ---->|| ========== TYPE OF STREAM ============== There are two types of STREAM. 1)BYTE STREAM 2)CHARACTER STREAM

Q.What is BYTE STREAM? Ans. 1.A Program that uses byte stream to perform I/O operation of 8-bit bytes format. 2.All byte stream class are descended from InputStream and OutputStream classes.

Q.Why do we need BYTE STREAM? Ans. 1)In order to perform I/O operation in 8bit bytes format, we required BS. 2)If we want to perform any operation as a plateform independent. Becoz of that Byte Stream perform binary operation. 3)Binary format means like vedio,image,audio etc.

Inheritance Chart OF Byte Stream ================================= ==>Byte Stream ========== InputStream(abstract class) =========================== 1)FileInputStream 2)ObjectInputStream(Deserialization Part)

3)BufferedInputStream 4)DataInputStream

OutputStream(abstract class) =========================== 1)FileOutputStream 2)ObjectOutputStream(Serialization Part) 3)BufferedOutputStream 4)DataOutputStream

File=Ouputstream FILE=InputStream

Q.What is Character STREAM? Ans. 1.A program that uses character stream in place of byte stream automatically to that local character set . 2.All Character stream classes are descended from Reader and Writer classes.

Why do we need Character STREAM? Ans. 1)In order to perform I/O operation in Character format(2 bytes),we required CS. 2)If we want to perform any operation as a platform dependent. 3)Character format means creating text file . Inheritance Chart OF Character Stream ================================= ==>Character Stream =============== Writer(abstract class) ===================== 1)FileWriter 2)BufferedWriter 3)PrintWriter Reader(abstract class) ===================== 1)FileReader 2)BufferedReader

3)Reader d=new FileReader("filename.txt"); BufferedReader br=new BufferedReader(d); String f=br.readLine(); Serialization ============= If we want to store the state of an object into the harddisk,then we need Se........ java.io.File ============== How many ways to take input from keyboard in java ================================================== many more ways 1)Scanner class(java.util) 2)BufferedReader and InputStreamReader BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); throws IOException or InputStreamReader f=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(f); throws IOException br.readLine();//String Input int i=Integer.parseInt(br.readLine()); float f=Float.parseFloat(br.readLine()); double d=Double.parseDouble(br.readLine()); boolean b=Boolean.parseBoolean(br.readLine()); etc. char c= System.in.read();//for character input

***************************************************** GARBAGE COLLECTION ***************************************************** What is Garbage Collector? Ans. Garbage Collector is a services or mechanism which is done by the JVM to remove unused object, is known as Garbage Collector.

What is Garbage Collection? Ans. Garbage Collection is a process of collect the unused object by JVM ,is known as Garbage Collection. How it can be done? ==================== 1)finalize() is protected method ,which is present in java.lang.Object class

Complete signature of the method is:= protected void finalize() throws java.lang.Throwable

2.How it can be called in program? A) java.lang.System.gc(); B) java.lang.Runtime.getRuntime().gc(); 3). if the object are no more longer uses or object are unreachable or object reference variable contains 'null' then Garbage collector will remove the unreachable object or unused object.

What is Reachable object? Ans. If the object are refer to any reference variable that object is knows as Reachable object. eq. A s=new A();

What is Unreachable object? Ans. If the object are not refer to any reference variable that object is knows as Unreachable object.

eq. new A(); or A s=new A(); s=null;//unreachable 4. finalize() method is protected method ,whenever Garbage Collector are executed then Garbage Collector firstly called finalize() method and then reclaim the object memory. 5. finalize() method are executed just before object removed by Collector. 6. finalize() method gives one chance to the programmer to perform some clean up operation at the time of GC. Q.How many object can be destroyed by the GC? Ans.How many number of object created in the program , those many number of object will be GC. Note ====There is no guarantee to remove all the object from memory. Q.Algo 1)sweep algo 2)mark algo Q.Can an object finalize() method be involved while it is reachable? Ans.NO Q.How many time finalize() method will executed? Ans.How many number of time object of any class will unreachable those many number of time finalize() method will execute of object class.

NOTE ===== 1)which class object will garbage collected ,those class finalize()

method will executed. 2)How many time garbage collector destroy the object of same class and those many number time finalize() method will execute of same class or may not be.

************************************************************* MULTI-THREADING ************************************************************* Q.What is Program? Ans. Program is the passive entity in the hard-disk in sleeping mode,i.e Program. Q.What is Process? Ans. Process is a instance of the Program. Q.What is Thread? Ans. Thread is the instance of the process. "Thread is an independent sequence path of execution with in the program".

Note ==== Very familier example is: WEB BROWSER. MULTITHREADING ============== ==>Java is a multi thread portable programming language. ==>Multithreading is the important feature of the java. There are 2 type o application 1.Sinle task Application(DOS) 2.Multi task Application(WINDOWS) ==>JVM is not communicate with processor,JVM communicate with OS and OS communicate with scheduler. ==>Each and every stand alone program contains at least one thread,i.e."main". which is executed very firstly. ==>Multithreading doesn't use in J2EE,becoz of that using J2EE , we develop web based application, all the web application executed by Server,& server is already multitreaded,so there is no need to use multithreading in server side application.

Q.What is Multithreading? Ans. Multithreading is the part of multitasking ,using which, it execute more than one thread simultaneously, i.e. MULTITHREADING.

Example.wordpad,etc Benefit of MULTITHREADING ========================= 1.Avoiding the CPU idle time or minimize CPU idle time. 2.Resource utilization 3.Sharing Resources 4.fastest use of CPU. What is Thread ============== Thread is the instance of process. Process ========process is the instance of program. Program =======Program is nothing but it is sleeping entity which is stored in the h/d,i.e.Program. Use of Thread ============= In Server side application, to serve more than one client request at the same point of time.

Life cycle of the Thread ======================== Threadlifecycle.jpg How to Create thread in JAVA ============================ There are 2 mechanism in java to create thread. 1.extending java.lang.Thread 2.implementing java.lang.Runnable 1.Extending the java.lang.Thread class

====================================== 1.creating the sub class of Thread class and override the run() method. Actually Thread class internally implements Runnable interface. 2.And creating the object of sub class . 3.and calling the start() to the sub class object for execution of thread. 2.Runnable interface

Q.what is start() method and run() method? Q.How many time start() method can call using single(one) thread? Ans.Only one time,other wise java.lang.IllegalThreadStateException. Q.What is very internal mechanism with start() method. Mechanism of start method ========================= start()//java.lang.Thread native start0()//java.lang.Thread run();//java.lang.Thread Q.What is Time Slicing? Ans.It is nothing but, Time slicig is the small part of process time,i.e.Time slicing. Q.Write a java program to create thread using extends Thread and implements the Runnable interface. Q.Why we use Runnable interface over the Thread class? Q.setName() and getName(). Q.Thread interuting method 1.sleep() public static void sleep(long milisec) 2.join() public void join()

throws(checked exception) ,i.e.InteruptedException. Q.Why do we use Thread interuting method? Ans.To give the change to another thread. Note ==== Each thread have seperate execution path. Q.Priority MAX_PRIORITY(psf int MAX_PRIORITY)//10 NORM_PRIORITY(psf int NORM_PRIORITY)//5

MIN_PRIORITY(psf int MIN_PRIORITY)1 public final void setPriority(int) public final int getPriority() Q.Which thread is executed in very last. Ans.main thread. Q.Why do we need Synchronization? Ans. 1.Locking purpose(To lock the particular thread until and unless current thread execute then other thread will execute). 2.Create thread safe application. Q. What is Synchronization? Ans. Synchronization is nothing but it is a feature by which, only thread can access a resource in a particular time of instance, no other thread can interrupt for that resource. Q. Interrupted Method?

Vous aimerez peut-être aussi