a programmer core java

Upload: mohd-arshad-ali

Post on 03-Apr-2018

235 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 A Programmer Core Java

    1/92

    A ProgrammersGuide to

    Java SCJP

    CertificationA Comprehensive

    Primer

    First Edition

    Mohd.Arshad Ali

  • 7/28/2019 A Programmer Core Java

    2/92

    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.OOPS2.Plateform3.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 processorcommands)ADD,MOVE,MUL,SUB(low level).5.Humand cannot understand ,that code.6.But Assembly and micro processor commands in Low Level .

  • 7/28/2019 A Programmer Core Java

    3/92

    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 programusing Class and Object.

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

    Q.What is Platform?Ans.

    Plateform is a collection of predefined program which are used toprovide the run time environment for developing any application,Run time Environment like:

    1.Memory management2.Process management3.IO management4.Device Management

    i.e.Plateform.

    In C,Platefrom is only OS,

  • 7/28/2019 A Programmer Core Java

    4/92

  • 7/28/2019 A Programmer Core Java

    5/92

    1.To load the source code from H/D to RAM.2.Convert the source code into intermediate codeif 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 Consumerproject,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 useclass/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 networkingapplication.

    6)JAVA is robust================JAVA provide tightly coupled checking during compile time aswell asrun time.

  • 7/28/2019 A Programmer Core Java

    6/92

    7)JAVA support Multi Threading==============================

    Edition of JAVA===============J2SE=JAVA 2 Standard edition==>Using J2SE ,we can develop Windows basedapplication.

    J2EE=>JAVA 2 Enterprises Application==>Using J2EE ,we can develop Web basedapplication.

    J2ME=>JAVA 2 Micro Application==>Using J2ME ,we can develop Mobile basedapplication.

    Version of JAVA===============1st version=1995 JDK1.02nd version=1997 JDK1.13nd version=1999 JDK1.24rt 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 performother operation.

    JRE===JAVA Runtime Environment, which consist JVM as well as run time .class file

  • 7/28/2019 A Programmer Core Java

    7/92

    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 intoMethod 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) variableb)instance method//calling place

    c)instance block//callingd)constructorInstance 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 isknown 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.

  • 7/28/2019 A Programmer Core Java

    8/92

    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/object2.Data Abstraction3.Encapsulation4.Inheritence5.Polymorphism

    Q.What is Class?Ans.

  • 7/28/2019 A Programmer Core Java

    9/92

    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 weneedObject.

    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 Encapsulation1.Data Binding2.Data Hiding.

    WHy ,What

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

  • 7/28/2019 A Programmer Core Java

    10/92

    Program========Collection of Instruction.

    Keywords========

    Keyword is special word/reserve words which definition defined inside thecompiler,i.e.

    known as Keyword.There 53 keywords in java1.48 special words2.3 reserve words3.2 unused keywords

    3 reserve words===============1.null2.true3.false

    2 unused keywords==================1.goto2.const

    48 special words================keywords for flow control========================1.if2.else3.do4.while5.for6.return

    7.switch8.case9.continue10.break11.default

    keywords for Exception Handling==============================1.try2.catch

  • 7/28/2019 A Programmer Core Java

    11/92

    3.finally4.throws5.throw

    6.assert

    keywords for Access specifier=============================1.public2.protected3.private

    keywords for Access modifier============================1.static

    2.final3.abstract4.synchronized5.transient6.strictfp7.native8.volatile

    keywords for classes====================

    1.class2.interface3.enum4.package5.import

    keywords for object===================

    1.this2.super3.instanceof4.extends5.implements6.new

    Keywords for data type======================1.byte

  • 7/28/2019 A Programmer Core Java

    12/92

    2.short3.int4.long

    5.float6.double7.char8.boolean9.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 wecan 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 TYPES2.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 Range in Bit Default Value1.byte 1 8 02.short 2 16 03.int 4 32 04.long 8 64 0l/OL5.float 4 32 0.0F/O.0f6.double 8 64 0.0/0.0D/0.0d7.char 2 16 \u0000

  • 7/28/2019 A Programmer Core Java

    13/92

    8.boolean 1 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=972.UNICODE===>JAVA support 16bit 65535 character a=\u0061=binary3.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.

  • 7/28/2019 A Programmer Core Java

    14/92

    TYPES OF REFERENCE DATA TYPE=============================

    There are 4 type of reference data types-DATA TYPES Default Value

    1)class null2)interface null3)enum null4)array null

    Variable========

    Variable is name of place in the memory which hold some data/address.i.e.variable.

    Types=====1.static variable2.instance variable3.local variable4.block level variable5.Pimitive variable6.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 literals3.Boolean literals

    boolean literals boolean b=true;4.Character literals

    char literals char a='a'5.String literals

  • 7/28/2019 A Programmer Core Java

    15/92

    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 Operator2.Binary Operator3.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. Operator1. (),[]2. ++,--

  • 7/28/2019 A Programmer Core Java

    16/92

    3. *,/,%,!,~(Multiplicative operator)4. +,-,new (Additive operator)5. , shifting

    6. ,=,instanceof (relational operator)7. ==,!= equality operator8. & bit wise AND9. | bit wise OR10. ^ bit wise XOR11. && Logical AND12. || Logical OR13. ?: conditional operator14. =,+=,-=,*=,%=,/=,...etc(Assignment Operator)15. ,

    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 classmember,i.e.AS.1)public

    2)protected3)private

    Access Modifier===============AM is nothing but it define the characteristics of the member,i.e.AM8 type=====1.final2.static

  • 7/28/2019 A Programmer Core Java

    17/92

    3.abstract4.transient5.strictfp

    6.synchronized7.native8.volatile

    JAVA Convetioning Rule======================1.Rule for Variable2.Rule final variablefinal double PI=3.14;

    3.Rule for method4.Rule for class/interfaceclass Software Engineer5.Rule for packageall letter small.

    package. jpg

    1.Structure of JAVA programstructureofjavaprogram.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.

  • 7/28/2019 A Programmer Core Java

    18/92

    public======

    1.If any member of a class which called by JVM,then we need set 'public' with mainmethod.2.Actually there are 2 environments 1.JDK,2,JVM,if JVM called JDK environmentmember thenwe 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

    memberwill not instantiated in the life time of program.

    Note====static member instantiated in memory during loading of the class time but instancememberinstantiated 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 anytypes.

    Q.How many ways to declare main() method?ANs.===There are so many ways to declare or so many predefined signaturewhich could understand by JVM

    =======================================================================p=publics=staticv=voidm=main

    for JDK1.0 up to all above version.=================================1.psvm(String[] a)

  • 7/28/2019 A Programmer Core Java

    19/92

    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.step1.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' button6b)variable-name=path

    variable-vale=C:\Program Files\Java\jdk1.6.0_24\binthen click on OK button

    7)If we set path on system-variable then

  • 7/28/2019 A Programmer Core Java

    20/92

    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 classOR

    JOB of 'new' operatorAns.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 uniquehash code.3.Allocate the memory for all instance context.IC=IV+IM+IB4.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 anobjectof 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.

  • 7/28/2019 A Programmer Core Java

    21/92

    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 anobjectof 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.

  • 7/28/2019 A Programmer Core Java

    22/92

    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 ispossible.

    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====

  • 7/28/2019 A Programmer Core Java

    23/92

    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

  • 7/28/2019 A Programmer Core Java

    24/92

    ==============Widening and Narrowingwith 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 variable2.with method3.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=======================

  • 7/28/2019 A Programmer Core Java

    25/92

  • 7/28/2019 A Programmer Core Java

    26/92

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

    Example=======

    Method Overloading==================Need====

    If we want to perform similar operation with different behavior ,thenwe 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,

  • 7/28/2019 A Programmer Core Java

    27/92

    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 everwe 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 Constructor2.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 Constructor2.Programmer Define Default Constructor

    Q.What is Compiler Define Default Constructor/Implicit Constructor?Ans.

  • 7/28/2019 A Programmer Core Java

    28/92

  • 7/28/2019 A Programmer Core Java

    29/92

    6)this() call is used to call the same class constructor.

    Note

    ====Each and every constructor by default contains 'super()' call as a firststatement of the constructor, but when ever we don't use 'this()' call.

    b)super()==>discuss in Inheritancec)this reference, super reference==>discuss in Inheritance

    static block============1)Those blocks which are automatically executed, after loaded the class from H/D toRAM bythe 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

  • 7/28/2019 A Programmer Core Java

    30/92

    10.Inheritence11.Polymorphism12.Garbage Collector

    f)constructor chaining//discuss in Inheritance

    *******************************************Inheritance**************************************************========================================================================================================Why Inheritance===============

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

    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();//COMPOSITIONB s1=new B();//COMPOSITIONSop(s.j);Sop(s1.i);

    }}

    What type of relation is establish through the COPOSITION

  • 7/28/2019 A Programmer Core Java

    31/92

  • 7/28/2019 A Programmer Core Java

    32/92

    2.Aquaring the property of super class inside subclass. that is INHERITENCE.

    3.Inheritence establish the IS-A relation ship.that relation ship is known as Aggregation.

    Types of Inheritance====================5 types1.SINGLE LEVEL2.MULTI LEVEL3.MULTIPLE4.HIERARICAL

    5.HYBRID

    Types of JAVA supported Inheritance===================================3 only, strictly writing1.SINGLE LELEL2.MULTI LEVEL3.HIERARICALAdvantage of Inheritance=========================

    1.Avoiding code redundancy problem2.Overcome the drawback of Composition3.Code Reusability4.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==ASSIGNMENTWhat is specialization==ASSIGNMENTQ.What is IS-A RELATIONSHIP?

  • 7/28/2019 A Programmer Core Java

    33/92

    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===================

  • 7/28/2019 A Programmer Core Java

    34/92

    If we want to create hierarchy of class whichbelong 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 isknown as Inheritance.

    2.Aquaring the property of super class inside subclass. that is INHERITENCE.

    3.Inheritence establish the IS-A relation ship.that relation ship is known as Aggregation.

    Advantage=========

    1.Avoiding code redundancy problem2.Overcome the drawback of Composition3.Code Reusability4.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 andthat code used by third party programmer,i.eCode Reusability.

  • 7/28/2019 A Programmer Core Java

    35/92

  • 7/28/2019 A Programmer Core Java

    36/92

    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

  • 7/28/2019 A Programmer Core Java

    37/92

  • 7/28/2019 A Programmer Core Java

    38/92

    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.

    OReg. Method Overloading

    OREarly Binding

    ORStatic Binding

    1.Run time polymorphism==>Change the behavior during run time.OR

    eg.Method OverridingOR

    Late BindingOR

    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===========

  • 7/28/2019 A Programmer Core Java

    39/92

    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 methodthen we must follow concept of CO-VARIANT RETURN TYPE.

    4.access specifier either same or stronger but not weaker.publicprotected

    defaultprivate

    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.eDMD.

    class A{void m1(){System.out.println("Hello");}}

  • 7/28/2019 A Programmer Core Java

    40/92

  • 7/28/2019 A Programmer Core Java

    41/92

    Ans.Those method which doesn't contains body,i.e.Abstract MethodNote====AM cannot be static.

    void m1();

    Rule of Abstract Class======================1.Inside Abstract class we can create 0 to nth number of concrete method and0 to nth number of abstract method.

    2.We cannot create the object of Abstract class.

    3.Abstract containsmethods(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 needINTERFACE.

    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");}}

  • 7/28/2019 A Programmer Core Java

    42/92

    Note====Some people says, interface is used to implement the concept of MULTIPLE

    inheritance, butpurpose of Interface is not implement the concept of MULTIPLE inheritance in java,

    butit 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 ormore 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 concretemethod.

    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 youdont use then its duty of java compiler to use 'public abstract' with each methodof 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 youdont use then its duty of java compiler to use 'public static final' with each variableof interface.

  • 7/28/2019 A Programmer Core Java

    43/92

    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{

  • 7/28/2019 A Programmer Core Java

    44/92

    }class J extends H implements I1,I2,I3,I4{

    }

    with interface keyword we can use keywords=========================================1)public2)abstract3)default(by default)4)strictfp5)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 theconcept 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=======================

  • 7/28/2019 A Programmer Core Java

    45/92

    an array is static in the size, Static means we can not increase/decreasethe 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 fromkeyboard also.

    Type of an Array===============1.Single Dimension Array2.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 array1.Primitive 1D array2.Reference 1D array

    Note

    ====Array supports concept of default value, array either static ,instance or local orblock levelthere 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==========================

  • 7/28/2019 A Programmer Core Java

    46/92

    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]);//nullSop(a[1]);//Ab@somecodeSop(a1[2]);//Sub@somehashcode

  • 7/28/2019 A Programmer Core Java

    47/92

    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.jpgHow 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......}........};

  • 7/28/2019 A Programmer Core Java

    48/92

    */

    String Handling Syllabus=======================1.String class2.StringBuffer class3.StringBuilder4.What is command line Argument5.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 ownobject.i.e. Immutable object.

    What is Immutable Method========================Those method which doesn't change the state of ourown object,i.e.Immutable method.->It is also know as getter method.

    -->constant object statement, means not changeableclass A{int i=12;int get(){return i;}}

  • 7/28/2019 A Programmer Core Java

    49/92

    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' operator2.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 thenthis String class's object create in POOL AREA.

    POOL AREA= STRING CONSTANT POOL + FINAL CONSTANT POOLPOOL AREA is in Method memory Area.

    2.If the object of String class created in POOL area then ,if String class object is repeatedthenJVM 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=======================================================

  • 7/28/2019 A Programmer Core Java

    50/92

    String a=new String("INTEGRAL");String a1=new String("INTEGRAL");

    Note====1.When ever we create the object of String class using new operator thenthis String class's object create in POOL AREA as well as HEAP AREA also,that meanstwo object will create.

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

    ==>There are so many instance method in String class which are given below1.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 singlethreaded 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()

  • 7/28/2019 A Programmer Core Java

    51/92

    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 becozStringBuffer class supports concept of mutability,and object is mutable.

    ==>There are so many instance method in StringBuffer class which are given below1.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 assingle

    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

  • 7/28/2019 A Programmer Core Java

    52/92

    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 method2)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 givenstring.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 withjava program execution command,i.e.Command Line Arguments.

  • 7/28/2019 A Programmer Core Java

    53/92

    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 Package2.User Defined PAckage

    1.What & Example of Pre Defined Package.=======================================PRE DEFINED PACKAGE===================Those packages which are created by SUNprogrammer,i.e.PRE DEFINED PACKAGE.

    eg.

  • 7/28/2019 A Programmer Core Java

    54/92

  • 7/28/2019 A Programmer Core Java

    55/92

    1)class may or may not be public, if class is public, then that can be accessoutside the package, if class is not public then can not beaccess outside the package.

    2)class(top level class) cannot protected, private.class A{

    protected class A{}

    private class V{}

    }A.javapackage p1;public class A{}

    Z.javapackage 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 protectedmethod 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.=====================================================

  • 7/28/2019 A Programmer Core Java

    56/92

    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 whichcontains .class files.

    3.Technically package is a library, library may be PRE-DEFINED

  • 7/28/2019 A Programmer Core Java

    57/92

    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 Package2.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.

  • 7/28/2019 A Programmer Core Java

    58/92

    ==================================

    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 execution3.Avoiding abnormal termination.

    Q.What is Exception?Ans.An exception is nothing but, any problem which occur during run time,that problemis known asException.

    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 problemwhich occurduring 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 crash2.Memory Exhaust3.Keyboard problem4.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.

  • 7/28/2019 A Programmer Core Java

    59/92

    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 Exception2. Unchecked Exception3. Caught Exception4. Uncaught Exception

    What happens in the memory when Exception occur================================================1)JVM create the object of corresponding exception type in the memory and getthe hash code of an object by the JVM.

    2)AND JVM search the user defined exception handler block of correspondingexception 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 inmemory anddisplay the exception handling message and terminate the program andfurther 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 EHB1.User Defined Exception Handler Block2.Default (JVM Defined) Exception Handler Block

  • 7/28/2019 A Programmer Core Java

    60/92

    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 correspondingexception type, then JVM will create DEHB.

    2.User define Exception Handler Block(try, catch)=================================================Those block whichcreated 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 subclasses,except RuntimeExceptionError 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 itssub classes,

    i.e.UnChecked Exception.

    Rule====UnChecked Exception may or may not be handle before compilation.

    3. Caught Exception4. Uncaught Exception

    How to Handle Exception

  • 7/28/2019 A Programmer Core Java

    61/92

  • 7/28/2019 A Programmer Core Java

    62/92

    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 thecaller.

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

  • 7/28/2019 A Programmer Core Java

    63/92

    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 needWrapper 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===================

  • 7/28/2019 A Programmer Core Java

    64/92

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

    2)ShortConstructor Details===================Short(short value)Short(String shortString)throws NumberFormatException

    3)IntegerConstructor 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

  • 7/28/2019 A Programmer Core Java

    65/92

    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 classof 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);

  • 7/28/2019 A Programmer Core Java

    66/92

    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.5version.

    Q. What is Autoboxing conversion?Ans.To convert the primitive into its corresponding wrapper type,i.e.AutoboxingConversion.

    Q. What is Auto-Unboxing conversion?Ans.To convert the wrapper into its corresponding primitive type,i.e.Auto-UnboxingConversion.

    eg.Integer j=new Integer(12);int i=j;//auto-unboxing conversion

    Integer k=i;//autoboxing boxing conversion

    Integer i=12;//autoboxingint j=i;//AUB

    *************************************************************

    GENERIC*************************************************************

    Q. What is Generic?Ans.Generic is nothing but it provides abstraction over the type like class, interfacedeclared 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 objecttime).

  • 7/28/2019 A Programmer Core Java

    67/92

    -->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 similaroperation , 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 operationwith different data type.

    1)Q.Generic Class==>

    Ans.if a class which are declared asparameterized by Type called Generic class.

    Syntax======

    [A_S] class class name{}

    type==>may be as interface or class.

    class A{}

    2) Q.Generic Interface==>

    Ans.if a interface which are declared asparameterized by Type called Generic Interface.

    Syntax======

    [modifier] interface nameofinterface

    type==>may be as interface or class.

  • 7/28/2019 A Programmer Core Java

    68/92

    interface I1{}

    3) Q.Generic Method==>

    Ans.If a method which are declared asparameterized by Type called Generic Method.

    Note====

    Method can not be static.class must be generic.

    Syntax

    ======

    [modifier] 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] variable name;

    type==>may be as interface or class.

    Programming part

    ===============

    Predefined ClassUser defined ClassHow to use Inheritance in Generics

    Key and Value Pair concept==========================

    Sub typing

  • 7/28/2019 A Programmer Core Java

    69/92

    =========

    *************************************************************

    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 whyreadymade 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 manipulatedcollection(DS) i.e. known as Collection Framework.

    Note====CF contains following things.....1)Interface2)Implementation(implemented class)3)Algorithms(rule and regulation)

  • 7/28/2019 A Programmer Core Java

    70/92

    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.

  • 7/28/2019 A Programmer Core Java

    71/92

  • 7/28/2019 A Programmer Core Java

    72/92

    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 threadedapplication using ArrayList.and ArrayList class is not Thread safe.

    7)ArrayList provide get(index) method,if index not found then

    ArrayIndexOutOfBoundsException8)ArrayList ,default capasity is 10.9)Allow hemogenious and hetrogenious elements.10)ArrayLis is the index based collection(ArrayList also maintain theelement 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 developmulti and single threaded application using Vector and Vector class is Thread Safe.7)Vector provide get(index) method,if index not found thenArrayIndexOutOfBoundsException

  • 7/28/2019 A Programmer Core Java

    73/92

    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.

  • 7/28/2019 A Programmer Core Java

    74/92

    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

  • 7/28/2019 A Programmer Core Java

    75/92

  • 7/28/2019 A Programmer Core Java

    76/92

  • 7/28/2019 A Programmer Core Java

    77/92

  • 7/28/2019 A Programmer Core Java

    78/92

    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 forIterator interface.

    Contract of collection framework with Overriding of equals() with hashCode() method========================================================================================

    Condition Required NotRequired1.x.equals(y)== true x.hashCode() == y.hashCode() no

    2.x.hashCode() == y.hashCode() x.equals(y)==true(norequirement)

    3.x.hashCode() != y.hashCode() x.equals(y) == false no

    4.x.equals(y) == false x.hashCode() == y.hashCode()requirement.

    ********The Content/Object of collection can be read using 3 differenttechnique**************================================================================================================1.Using Enhance 'for' loop2.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

  • 7/28/2019 A Programmer Core Java

    79/92

    ==========================for(datatype variable : array reference/collection reference){

    }

    eg1.int i[]=new int[5];for(int k:i){Sop(k);}

    o/p===

    00000

    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

  • 7/28/2019 A Programmer Core Java

    80/92

    variable and call the iterator() method of Set interface.

    Method

    ======Only 3 method1.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

  • 7/28/2019 A Programmer Core Java

    81/92

    =======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 maintainunique 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 noexception 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 interfacetechnique.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 isexception '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.

  • 7/28/2019 A Programmer Core Java

    82/92

    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 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 andoverride 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.

  • 7/28/2019 A Programmer Core Java

    83/92

    Example=======

    Banking Application(Before came to the concept of database, developer usedSTREAM 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 interfacesto performi/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 datadestination(either file or console),i.e. OUTPUT STREAM.

  • 7/28/2019 A Programmer Core Java

    84/92

    =========| | OUTPUT STREAM ||PROGRAM |=======================| |

    | | | || |10101010101010101010101| FILE/CONSOLE|| | | || |=======================| || |---> ---> ----> ---->||==========

    TYPE OF STREAM==============

    There are two types of STREAM.

    1)BYTE STREAM2)CHARACTER STREAM

    Q.What is BYTE STREAM?Ans.1.A Program that uses byte stream to perform I/O operation of8-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)

  • 7/28/2019 A Programmer Core Java

    85/92

    3)BufferedInputStream4)DataInputStream

    OutputStream(abstract class)===========================

    1)FileOutputStream2)ObjectOutputStream(Serialization Part)3)BufferedOutputStream4)DataOutputStream

    File=OuputstreamFILE=InputStream

    Q.What is Character STREAM?Ans.1.A program that uses character stream in place of byte stream automatically to that localcharacter 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)FileWriter2)BufferedWriter3)PrintWriter

    Reader(abstract class)=====================1)FileReader2)BufferedReader

  • 7/28/2019 A Programmer Core Java

    86/92

    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 intothe 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 IOExceptionor

    InputStreamReader f=new InputStreamReader(System.in);BufferedReader br=new BufferedReader(f);throws IOException

    br.readLine();//String Inputint 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 doneby the JVM to remove unused object, is known as Garbage Collector.

  • 7/28/2019 A Programmer Core Java

    87/92

  • 7/28/2019 A Programmer Core Java

    88/92

    eq.new A();

    orA s=new A();s=null;//unreachable

    4.finalize() method is protected method ,whenever Garbage Collectorare executed then Garbage Collector firstly called finalize() methodand then reclaim the object memory.

    5.finalize() method are executed just before

    object removed by Collector.

    6.finalize() method gives one chance to the programmerto 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.Algo1)sweep algo2)mark algo

    Q.Can an object finalize() method be involvedwhile it is reachable?Ans.NO

    Q.How many time finalize() method will executed?

    Ans.How many number of time object of any classwill unreachable those many number of time finalize()method will execute of object class.

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

  • 7/28/2019 A Programmer Core Java

    89/92

    method will executed.

    2)How many time garbage collector destroy the object of same class

    and those many number time finalize() method will executeof 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 application1.Sinle task Application(DOS)2.Multi task Application(WINDOWS)

    ==>JVM is not communicate with processor,JVM communicate with OS and OScommunicatewith 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 developweb based application, all the web application executed by Server,& server is alreadymultitreaded,so there is no need to use multithreading in server side application.

  • 7/28/2019 A Programmer Core Java

    90/92

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

    Example.wordpad,etc

    Benefit of MULTITHREADING=========================

    1.Avoiding the CPU idle time or minimize CPU idle time.2.Resource utilization3.Sharing Resources4.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 isstored in the h/d,i.e.Program.

    Use of Thread=============In Server side application, to serve more than one client request at the samepoint 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.Thread2.implementing java.lang.Runnable

    1.Extending the java.lang.Thread class

  • 7/28/2019 A Programmer Core Java

    91/92

  • 7/28/2019 A Programmer Core Java

    92/92

    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 unlesscurrent 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 threadcan access a resource in a particular time of instance, no other thread can interruptfor that resource.

    Q. Interrupted Method?