java workshop july

Upload: samarthnitkscribd

Post on 08-Apr-2018

224 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Java Workshop July

    1/113

    FastTrack toJava

    MohamedSanaulla

    SunCampusAmbassador

  • 8/7/2019 Java Workshop July

    2/113

    Essential

    LearningClasses

    eLanguage

    Started

  • 8/7/2019 Java Workshop July

    3/113

    WhatisJava?

    WhydoweneedtolearnJava?

    ToolsrequiredforlearningJava

  • 8/7/2019 Java Workshop July

    4/113

  • 8/7/2019 Java Workshop July

    5/113

    avaas rogramm ng anguage

    SimpleObject Architectural

    Portable Distributed

    Performance

    Multithreaded Robust Dynamic

  • 8/7/2019 Java Workshop July

    6/113

  • 8/7/2019 Java Workshop July

    7/113

  • 8/7/2019 Java Workshop July

    8/113

  • 8/7/2019 Java Workshop July

    9/113

    InterpretstheJavaByteCode

    Base

    for

    the

    Java

    Platform

    Canbeportedtoanyplatform(OS)

  • 8/7/2019 Java Workshop July

    10/113

    Interface(APIs)

    argeco ec ono rea yma e

    softwarecomponentsthat

    .

    Itisgroupedintolibrariesof

    relatedclassesandinterfaces;

    theselibrariesareknownas

    packages.

  • 8/7/2019 Java Workshop July

    11/113

  • 8/7/2019 Java Workshop July

    12/113

    WhydoweneedtolearnJava?

  • 8/7/2019 Java Workshop July

    13/113

    editor

    JavaLibraries,toolsandtheVirtual

    NetBeans IDE

    JavaSEDocumentation

  • 8/7/2019 Java Workshop July

    14/113

    Learning

    the

    Language

  • 8/7/2019 Java Workshop July

    15/113

    ar a es,Typesan

    O erators

  • 8/7/2019 Java Workshop July

    16/113

    Class NotHelloWorld

    {publicstaticvoidmain(String[]args)

    System.out.println(NotAHelloWorldProgram);}}

    DemoUsingNotepad

  • 8/7/2019 Java Workshop July

    17/113

    ProgramStructure

    Class {

    publicstaticvoidmain(String[]arguments)

    {

    }

  • 8/7/2019 Java Workshop July

    18/113

    DataTypes

    StronglyTypedLanguage

    SizesofallNumerictypesareplatformindependent

    , ,

    and1booleanIntegers:

    long 8bytes

    int 4bytes

    short 2bytesbyte 1byte

    FloatingPoint:

    double 8bytes Moreprecisionthanfloat

    char 2bytesItisUnsigned,Accommodatesallcharactersusedin

    a anguagesint ewor

    boolean 2Values false ortrue

  • 8/7/2019 Java Workshop July

    19/113

    Variables

    execution

    Declare Placingthetypefirstfollowedbythenameofvariable

    Primitives

    Once

    Declared

    Type

    cannot

    be

    changed,

    but

    value

    canReference Variables

    Declarin :

    int length,width,height;

    boolean status;

    CannotUseJavaKe Words asVariableNames mustnotbe inwithadi it

    canbeofanylength,case issignificant

    Initializing:CannotuseuninitializedLocalVariables

    int length=23;

    boolean status=true;Constants Declaredbyusingfinalkeyword Whichmeansvariablecannot

    beassignednewvalue

    finaldouble length=2.54;

  • 8/7/2019 Java Workshop July

    20/113

  • 8/7/2019 Java Workshop July

    21/113

    Methods

    class MethodDemo

    {

    publicstaticvoidmain(String[]args)

    showMessage(Sanaulla);

    }

    static void showMessage (Stringname)

    {

    System.out.println(Hi!!!+name);}

  • 8/7/2019 Java Workshop July

    22/113

    InputandOutput

    TakingInput:importjava.util.*;

    Scannerin=newScanner System.in ;

    in.nextInt(); //ForreadingInteger

    in.nextDouble(); //ForReadingDouble

    in.nextLine(); //ForReadingCompleteLine

    Output:S stem.out. rintln Not Hello WorldSimilarto printf(NotHelloWorld\n);

    . . Similarto printf(NotHelloWorld);

  • 8/7/2019 Java Workshop July

    23/113

    Arrays

    narray sanor ere co ec on a s ores manyelementsofthesametype withinonevariablename.

    Elementsaretheitemsinanarray.

    Eachelementisidentifiedwithanindexnumber.

    Indexnumbersalwaysstartat0forthefirstelement.

    Thelengthofanarrayisestablishedwhenthearrayis

    created.Aftercreation,itslengthisfixed.

  • 8/7/2019 Java Workshop July

    24/113

    DeclaringArray:

    int[]key; //Arrayofints

    Thread[]threads; //ArrayofObjectReferences

    ConstructingArrays:

    int[]key=newint[4];

    MultidimensionalArrays:

    int[][]myArray=newint[3][];

    Declaring,Constructing,InitializingonOneLine:

    int[]keys={5,6,7,8};

    Str ng names= qwer , qweqe , g s ;

    AnonymousArray:

    int[]testScores;

    testScores=newint[]{6,7,8};

  • 8/7/2019 Java Workshop July

    25/113

    =

  • 8/7/2019 Java Workshop July

    26/113

  • 8/7/2019 Java Workshop July

    27/113

    BasicControlStructures

    ifelseStructure

    forloopandforeachloop

    whileloop

    switch statements

    o

    w e

    oop

  • 8/7/2019 Java Workshop July

    28/113

    ifElseStructure

    {

    int age;InputforAge

    System.out.println(EntertheAgeoftheperson);Scanner in=newScanner(System.in);=k

    if(age

  • 8/7/2019 Java Workshop July

    29/113

    if(condition)

    Statementstobeexecuted

    elseif(condition)

    Statementstobeexecuted

    }

    else

    {Statementstobeexecuted

    }

  • 8/7/2019 Java Workshop July

    30/113

    OneCaution!!!!!!

    YouWanttodothis:

    if someBooleanVariable == true

    {

    Statements;

    But

    End

    up

    doing

    this:some oo ean ar a e = rue

    {

    Statements;

    }else

    Statements;

    }

  • 8/7/2019 Java Workshop July

    31/113

    forloop

    for int i=0 i

  • 8/7/2019 Java Workshop July

    32/113

    for initialization termination increment

    {

    }

    Demo

    f

  • 8/7/2019 Java Workshop July

    33/113

    SomeforLoopIssues:Noneofthethreesectionsofthefordeclarationarerequired

    for(;;){

    Statements;

    }

    Variablesdeclaredintheforstatementarelocaltotheforloopanc

    cant

    be

    used

    outside

    the

    scope

    of

    the

    loop

    for(int i=0;i

  • 8/7/2019 Java Workshop July

    34/113

    foreachloop

    AlsocalledastheEnhancedForloop,was

    addedinJava5.Itsimplifieslooping

    throughArraysandCollections.The

    enhancedforLoophas twocomponents.

    int[]

    a

    ={1,2,3,4,5,6};

    Declaration

    for( int i : a) Expressions

    System.out.println(i);

  • 8/7/2019 Java Workshop July

    35/113

    Declaration

    ,

    typecompatiblewiththeelementsofthe.

    beavailablewithintheforblock,anditselement.

  • 8/7/2019 Java Workshop July

    36/113

    This

    mustevaluatetothearrayonewantstoloopthrough.Thiscouldbeanarrayvariableoramethodcallthatreturnsanarray.Thearraycanbeanytype:primitives,objects,evenarrays

  • 8/7/2019 Java Workshop July

    37/113

    whileloop

    int x=2;Expression

    { System.out.println(x);

    ++

    }

  • 8/7/2019 Java Workshop July

    38/113

    while (expression )

    {

    //Dostuff

    }

    Usedwhenthenumberofiterationsofthe

    oc s a emen s

    are

    no

    nown

    Demo

  • 8/7/2019 Java Workshop July

    39/113

    switchstatements

    switch(expression)

    case constant1:codeblockcase constant2:codeblock

    }

    Demo

  • 8/7/2019 Java Workshop July

    40/113

    LegalExpressionsforswitch andcase:

    Aswitchsexpressionmustevaluatetoachar,byte,

    Acaseconstant mustevaluatetothesametypeas

    theswitchexpression canuse

    Thecaseconstantmustbecompiletimeconstants

    Compiletimeconstanthastoberesolvedatcompile

    t me,t atmeansonecanuseon yaconstantor na

    variablethatisassignedaliteralvalue.

    .

    Itsalsoillegaltohavemorethanonecaselabel

    usin thesamevalue

    d hil L

  • 8/7/2019 Java Workshop July

    41/113

    dowhileLoop

    Thedoloopissimilartowhileloop,except

    thattheexpressionisnotevaluateduntil

    afterthedoloopscodeisexecuted.

    Demo

    OO Programming Concepts

  • 8/7/2019 Java Workshop July

    42/113

    OOProgrammingConcepts

    WhatisanObject?

    WhatisaClass?

    WhatisEncapsulation?

    WhatisInheritance?

    a s o ymorp sm

    What is an Object?

  • 8/7/2019 Java Workshop July

    43/113

    WhatisanObject?

    consistsoftwocharacteristics:

    1.State

    2.Be avior

    State >Depictedbymeansoffields

    Behavior >Depictedbymeansofmethods

    Advantages of Using Objects

  • 8/7/2019 Java Workshop July

    44/113

    AdvantagesofUsingObjects

    Modularity:Thesourcecodeforanobjectcan

    be written and maintained inde endentl of the

    source

    code

    for

    other

    objectsInformationHiding:UsingMethodsfor

    interactingwillhidetheinternalimplementation

    details

    o e euse: eex s ng ec can ereuse

    Pluggability anddebuggingease:Ifaparticular

    corrected.SimilartoBoltinamachine

    What is a class?

  • 8/7/2019 Java Workshop July

    45/113

    Whatisaclass?

    Aclass isageneralspecificationor

    descriptionforasetofobjects that

    definestheircommonstructure(data),

    behavior (methods),andrelationships.

    Objects

    are

    instances

    of

    Class

    What is Inheritance?

  • 8/7/2019 Java Workshop July

    46/113

    WhatisInheritance?

    classisaparentofanother.

    Implements isarelationshipbetweenobjects

    Commona ityamongt eO jectsista enouttore uce

    complexityProvidestheideaofreusability

    What is Polymorphism?

  • 8/7/2019 Java Workshop July

    47/113

    WhatisPolymorphism?

    Abilitytotakemorethanoneforms

    havingmethodswiththesamenamesand

    dependingonthereceiver.

    Wh t i E l ti ?

  • 8/7/2019 Java Workshop July

    48/113

    WhatisEncapsulation?

    Encapsulation referstomechanismsthatallow

    eachobjecttohaveitsowndataandmethods

    i.e.wrappingupofdataandmethodsintoa

    singleunitcalledclass

    accesstothemthroughaccessorandmutator

    methods.

    Accessor Methods: Accessor methodsreturn

    informationMutator Methods:Mutator methodsmodify

    es a eo eo ec .

  • 8/7/2019 Java Workshop July

    49/113

    En o Sess on1

  • 8/7/2019 Java Workshop July

    50/113

  • 8/7/2019 Java Workshop July

    51/113

    Session2

    MohamedSanaulla

    SunCampusAmbassador

  • 8/7/2019 Java Workshop July

    52/113

    Theofficialwebsite+mailing listofNITKSunClub

    htt : rou s. oo le.com rou nitksunclub

    SubscribetothisGooglegrouptoregisterforNITKSunClub!

    Discussions

    :Feelfreetopostanyqueries,ideas,newsyouhaveto

    t ema ng st ta epart nt e scuss ons.

    Files,Links,Resources:Findandshareallimportant, , ,

    posters,brochures,etc relatedtotheclub'sactivities.

    Events&Achievements:Gettoknowaboutallthelatesthappeningsandupcomingeventsoftheclub.

  • 8/7/2019 Java Workshop July

    53/113

    Session1Contest

    Winners!!!!

    Mohit Kukre a

    .

  • 8/7/2019 Java Workshop July

    54/113

    O jectOrientationinJava

    Classes

  • 8/7/2019 Java Workshop July

    55/113

    InGeneralclassesinJavaaremadeu ofthree arts:

    1. Fields Definethestate/attributesoftheClass

    2. Constructors UsedforInitializingtheObjectsduring

    3. Methods

    Define

    the

    Behavior

    of

    a

    particular

    class,

    alsousedforaccessingthefields

    class

    Fields

    Constructor

    Methods

    }

  • 8/7/2019 Java Workshop July

    56/113

    AClasscanbemarked

    public default final abstract

    Thedefaultaccesslevelcannotbymarkedbyusingdefaultkeyword.Itstheaccesslevelbydefault

    Member Access Modifiers

  • 8/7/2019 Java Workshop July

    57/113

    MemberAccessModifiers

    ,

    protected,private,default

    Public memberscanbeaccessedbyallotherclasses

    Private memberscanbeaccessedbythecodeinthe

    sameclass

    Default memberscanbeaccessedonlybyclassesinthe

    same acka e

    Protected memberscanbeaccessedbyotherclassesin

    thesamepackage,plussubclassesregardlessofthe

    package.

    Nonaccess Member Modifiers

  • 8/7/2019 Java Workshop July

    58/113

    Nonaccess MemberModifiers

    Final methods cannotbeoverriddeninasubclass

    Abstract methods methodsdeclaredbutnot

    Synchronized methods methodscanbeaccessedby

    only

    one

    thread

    at

    a

    timeTransient Variable ThevariableismarkedasTransient

    isskippedduringserialization

    o at e ar a e et rea access ngt evar a euses

    itsownprivatecopy,withmastercopyinmemory

    Constructors

  • 8/7/2019 Java Workshop July

    59/113

    class andhasnoreturntype notevenvoid.

    EveryclassMUST haveaconstructor BydefaultJavaprovides

    NoArgConstructor.

    Constructorscanuseany accessmodifiers

    Everyconstructorhas,asitsfirststatement,eitheracalltoan

    overloaded constructorortothesuperclass constructor.

    Thecompilerbydefaultinsertanoarg calltosuper() asthevery

    firststatementintheconstructor.

    Interfaces donot haveConstructors

    Objects

  • 8/7/2019 Java Workshop July

    60/113

    Created b usin the new ke word

    Theyliveontheheap areaofthememory

    TheyareaccessedbyusingObject References that

    veon es ac

    MethodsandFieldsbyusingthe.operator

  • 8/7/2019 Java Workshop July

    61/113

  • 8/7/2019 Java Workshop July

    62/113

    StaticVariables

    StaticMethods

    StaticFields

  • 8/7/2019 Java Workshop July

    63/113

    Definedbyusingthekeywordstatic.

    Theresonlyonesuchfieldperclasswhich

    .

    Static

    constants

    are

    more

    popular

    publicstaticfinalisusedtodefinea

    constant.

    StaticMethods

  • 8/7/2019 Java Workshop July

    64/113

    haveathisparameter.

    Cannotaccessinstancevariablesbutcan

    accessonlystaticvariables.

    Theyareaccessedbyusingthenameofthe

    ,

    accessthestaticmethod.

  • 8/7/2019 Java Workshop July

    65/113

    :

    InitializationBlocks

  • 8/7/2019 Java Workshop July

    66/113

    Apart romConstructorsan met o s, n t a zat on oc s aret eonlyplacewhereJavaoperationscanbeperformed.Therearetwo

    typesofInitializationblocksinJava:

    InstanceInitializationBlocks Theyrunonceeverytimethenew

    .

    StaticInitializationBlocks Theyrunonce,whentheclassisfirst

    o a e . e ne yus ngt e eywor stat c .

    SomeRulestoremember:

    Init

    Blocks

    executeintheordertheyappear.StaticInitBlocksrunonce,whentheclassisfirstloaded.

    InstanceInitblocksrunaftertheconstructorscalltosuper().

  • 8/7/2019 Java Workshop July

    67/113

    DEMO:UsingInitializationBlocks

    Methodoverloading

  • 8/7/2019 Java Workshop July

    68/113

    Overloadedmethodsletsonetoreusethesamemethod

    nameinaclass,butwithdifferentarguments.

    TherulesforOverloadingare: .

    OverloadedmethodsCANchangethereturntype.

    Overloaded

    methods

    CAN

    change

    the

    access

    modifier.OverloadedmethodsCANdeclareneworbroader

    checkedexceptions

    DEMO:UsingOverloadedMethods

    InnerClassesInner Class is a class defined inside another class

  • 8/7/2019 Java Workshop July

    69/113

    InnerClassisaclassdefinedinsideanotherclass.

    WhyuseInnerClasses?Canaccessthedatafromthescopeinwhichtheyaredefined

    Canbehiddenfromtheclassesinthesamepackage

    Reducetheamountofcodinginvolved

    InnerClassescomein4flavors:

    1. StaticMemberClasses Markedwithstatic,cannotaccessnonstatic

    membersoftoplevelclass.,notaninnerclass TopLevelNestedclass

    . ,

    aninnerclassonehastohaveaninstanceofouterclassMyOuter.MyInner inner = (new MyOuter()).new MyInner();

    3. Loca C asses De ine wit inamet o o t ec ass,on y ina an a stract

    canbeapplied,localvariablescannotbeaccessed.

    . ,

    interface

  • 8/7/2019 Java Workshop July

    70/113

    DEMO:UsingLocalClasses

    Inheritance

  • 8/7/2019 Java Workshop July

    71/113

    Inheritanceinjavaisdoneusingthekeyword

    .

    Aclassthatisderivedfromanotherclassiscalled

    .

    Theclassfromwhichthesubclassisderivedis

    called

    a

    superclass.EveryClassextendsfromtheclassObject.

    MultipleInheritance inJavaisnot possible,but

    t ent eresanot erwayo o ng t.

  • 8/7/2019 Java Workshop July

    72/113

    ISAandHASArelationship

  • 8/7/2019 Java Workshop July

    73/113

    ISARelationshipisassociatedwith

    Inheritance.SupposeMySubClass

    extends/inheritsMySuperClass then

    MySubClass ISAMySuperClass

    HASARelationshipisbasedonUsage

    ratherthaninheritance.SupposeclassA

    HASAclassBifcodeinclassAhasareferencetoaninstanceofclassB.

    MethodOverriding

  • 8/7/2019 Java Workshop July

    74/113

    CanoverridethemethodinheritedfromtheSuper

    Classunlessitismarkedfinal.

    se to e ne e av orspec ctot esu c ass.

    Theargumentlistmustexactlymatchthatofthe

    Thereturntypemustbethesameasorasubtypeof

    the

    return

    t e

    declared

    in

    the

    ori inal

    overridden

    method.

    Accesslevelcantbemorerestrictive.

    Staticmethodscantbeoverridden Theyare

    actuallyhidden.

    DEMO:UsingMethodOverriding

  • 8/7/2019 Java Workshop July

    75/113

    InterfacesAninterface isareferencetype,similartoaclass,thatcancontain

  • 8/7/2019 Java Workshop July

    76/113

    onlyconstants,methodsignatures,andnestedtypes.

    The canbeim lemented unlikeconcreteclassesthatcanbe

    extended

    .

    Allinterfacemethodsareimplicitlypublic andabstract.Onecanuse

    anycombinationofpublic orabstract ornomodifiers.

    Allvariabledefinedintheinterfacemustbe ublic,static andfinal.

    Any

    combination

    of

    public,

    static,

    final

    or

    no

    modifiers

    is

    legal.

    .

    DEMO:

    Using

    Interfaces

    GarbageCollection

    u oma e emory anagemen e e e ec s a can e reac e

  • 8/7/2019 Java Workshop July

    77/113

    u oma e emory anagemen e e e ec s a can ereac e

    CanonlySuggestVMforGC

    NoparticularGCAlgorithmcanbeknownforsure

    ec smus ave ve,reac a ere erence

    MakingObjectseligibleforGC:

    Nulling aReference:

    MyClass obj = new MyClass();

    obj=null;

    Reassiging ReferenceVariable:

    MyClass obj1 = new MyClass();

    MyClass obj2 = new MyClass();

    obj1 = obj2;

    IsolatingaReference IslandsofIsolation

    ForcingGC Contradiction Cannotbeforcedbutsuggested

    System.gc();

    finalize() Runcodeb4GC,calledonlyonce inanObjectslifetime.

    NumbersandStrings

  • 8/7/2019 Java Workshop July

    78/113

    Numbers Strings

    Strings

  • 8/7/2019 Java Workshop July

    79/113

    Stringobjectsareimmutable butStringreferencevariables

    arenot

    StringclassisFinal Methodscantbeoverridden.

    JVMfindsaStringliteral ItsaddedtoStringConstantPool

    ,

    DEMO:UsingStrings

    Numbers

  • 8/7/2019 Java Workshop July

    80/113

    int,byte, float >Primitives,butJavaisOOLanguage

    Wra ers are rovided for each rimitive which wra the

    primitivesintoObjects

    Why?

    Classesprovideutilitymethodsforprimitives

    Autoboxing >Automaticallyconvertsprimitive intowrapper

    Objects andviceversa

    Wrappers

    are

    equal

    (equals())

    >

    Same

    type

    and

    have

    Same

    value

    . ,

    underjava.lang.Number

  • 8/7/2019 Java Workshop July

    81/113

  • 8/7/2019 Java Workshop July

    82/113

    Insummary,theessentialmethodsignaturesforWrapper

    primitivexxxValue() toconvertaWrappertoa

    primitiveparseXxx (String)

    Ex:

    parseInt()

    toconvertaStringtoaprimitive

    WrappervalueOf(String) toconvertaStringtoaWrapper

    Method

    s=static

    n=NFEexception Boolean Byte Character Double Float Integer Long Short

    byteValue x x x x x x

  • 8/7/2019 Java Workshop July

    83/113

    doubleValue x x x x x x

    floatValue x x x x x x

    longValue x x x x x x

    shortValue x x x x x x

    parseXxx s,n x x x x x x

    parseXxx

    (withradix)

    s,n x x x x

    valueOf s,n x x x x x x x

    valueOf

    with radix

    s,n x x x x

    toString x x x x x x x x

    toString s x x x x x x x x

    (primitive)

    toString

    (primitive,

    radix)

    s x x

    PassingVariablesintoMethods

  • 8/7/2019 Java Workshop July

    84/113

    Javaisalways PassbyValue

    WhilepassingLocal Variables ItsresemblesPassby

    Value

    WhilepassingReferenceVariables ItsresemblesPass

    ByReference,ButitspassbyValue

    DEMO:PassingObjectReferenceVariables

    DEMO:PassingLocalVariables

    TheStringBuilder Class

  • 8/7/2019 Java Workshop July

    85/113

    mutable i.e thevaluetheyarereferringtocanbechanged

    ns anceso r ng u er areno sa e oruse ymu p e

    threads i.e themethodsarenotsynchronized

    StringBuilders simpler code andbetter performance

    theStringinvolvesnewmemoryallocationandstringrelocation.

    so r ng u er an r ng u er aresame r ng u er

    wasintroducedinJDK5.0

    DEMO:UsingStringBuilder

  • 8/7/2019 Java Workshop July

    86/113

    UsingJDKDocumentation

  • 8/7/2019 Java Workshop July

    87/113

    En o Sess on2

  • 8/7/2019 Java Workshop July

    88/113

  • 8/7/2019 Java Workshop July

    89/113

    Session3

    MohamedSanaulla

    SunCampusAmbassador

    EssentialClasses

  • 8/7/2019 Java Workshop July

    90/113

    ExceptionHandling

    E ti h dli El t M h i f H dli

  • 8/7/2019 Java Workshop July

    91/113

    Exceptionhandling >ElegantMechanismforHandling

    Exception

    Separates

    Exception

    Generating

    and

    Exception Handlingcodes

    Exception Alters thenormal programflow.

    try andcatch keywordsusedforExceptionHandling

    Mechanism

    try >DefiningBlock ofcodewhereexceptions canoccur

    catch >DefiningBlock ofcodethathandles aspecific

    exception

    try

    //Ri k C d G h h ki d f i

  • 8/7/2019 Java Workshop July

    92/113

    //RiskyCodeGoesherethatcausessomekindofexception

    }

    catch(MyFirstException)

    {

    }

    catch(MySecondException)

    //HandlethisException

    }

    //NormalNonRiskycodecontinueshere

    Usingfinally

    Differentfromfinalize

  • 8/7/2019 Java Workshop July

    93/113

    Different from finalize

    Codeinsidethefinallyblockisexecutedatsomepointaftertry

    block Whetheranexceptionisthrownornot

    Iftheresareturnstatement Itsisexecutedimmediatelyafter

    e re urn sencoun ere u e ore e re urn execu es.

    IfNoExceptions Itisexecutedimmediatelyaftertry block

    IftheresExceptions Itisexecutedafterthecatchblock

    tr without acatch butwith finall isle al

    try without acatch andalsofinally isillegal

    try with catch andfinally islegal.

    DEMO:UsingExceptionHandling

    ExceptionHierarchy

  • 8/7/2019 Java Workshop July

    94/113

    BasicI/O

    Important I/O Classes:

  • 8/7/2019 Java Workshop July

    95/113

    ImportantI/OClasses:File >Anabstractrepresentationsoffileanddirectory

    pat name.

    FileReader >UsedtoreadCharacterFiles

    BufferedReader >WraparoundtheLowLevelreaders

    ReducestheNoofReadOperations

    e r ter > se towr tetoc aracter es.

    Buffered Writer >Wraparoundthelowlevelwriters

    import java.io.*; >Tobeused

    UsingclassFile

    A i f l Fil d

  • 8/7/2019 Java Workshop July

    96/113

    AnewinstanceofclassFiledoesnotmean

    ,

    name

    DEMO

    SomeMethodsUsed:

    boolean exists()>returnstrueifitcanfind

    theactualfile

    UsingFileReader andFileWriter

    > Most of the time they are used with wrapping them i e

  • 8/7/2019 Java Workshop July

    97/113

    >Mostofthetimetheyareusedwithwrappingthemi.e

    byusingitalongwithPrintWriter andPrintReader.Its

    alsocalledaschaining

    DEMO

    DEMO:UsingPrintWriter

    java.ioClass ExtendsFrom KeyConstructor(s)

    Arguments

    KeyMethods

    File Object File,String createNewFile()

    tr ng

    String,String

    e ete

    exists()

  • 8/7/2019 Java Workshop July

    98/113

    isDirectory()

    isFile()

    st

    mkdir()

    renameTo()

    FileWriter Writer File close()

    String flush()

    write()

    BufferedWriter Writer Writer close()

    flush

    newLine()

    write()

    PrintWriter Writer File(asofJava5) close()

    OutputStream

    Writer

    format()*,printf()*

    print(),println()

    write()

    e ea er ea er e

    String

    rea

    BufferedReader Reader Reader read()

    readLine()

    Serialization

    UsedforSavingtheState(InstanceVariables) ofoneormore

  • 8/7/2019 Java Workshop July

    99/113

    Used for Saving the State (Instance Variables) ofone or moreObjects

    Variablesmarkedtransientcannotbesavedduringobject

    Serialization

    BasicSerializationinvolvesonlytwomethods

    Serializetheobjectsandwritethemtothestream

    Readthestreamanddeserialize theobjects

    .

    ObjectOutputStream.readObject()

    DEMO: UsingSerialization

  • 8/7/2019 Java Workshop July

    100/113

    ObjectGraphs

    Multithreading

    InJava,threadmeans

  • 8/7/2019 Java Workshop July

    101/113

    In Java, thread meansAninstanceofclass.java.lang.Thread

    Athreadofexecution

    Athreadofexecutionisanindividualprocessthathas

    itsowncallstack.

    JVMactslikeaminiOS >Schedulesitsownthreads

    Theprogramsmustnotbedesigneddependenton

    particularimplementationoftheJVM.

    MakingaThread

    ns anceo ava. ang. rea

  • 8/7/2019 Java Workshop July

    102/113

    ImportantMethods:

    start()

    yield()

    run()

    u w

    Thethreadofexecutionalwaysbeginswiththerun()

    method

    Extendthejava.lang.Thread class

    ImplementtheRunnable Interface

    DefiningaThread:

    ByExtendingthejava.lang.Thread class:

    l h d d h d

  • 8/7/2019 Java Workshop July

    103/113

    class MyThread extends Thread

    {

    public void run()

    {

    System.out.println(Job Running inMyThread);

    }

    }

    Thethreadwithrun methodwillbeexecutedasthestartin forthread.

    Implementingjava.lang.Runnable:

    {

    public void run(){

    . .

    MyRunnable);

    }

    }

    InstantiatingaThread:

    ne as o ave rea o ec orun e rea egar esso su c ass ng or

    implementing

  • 8/7/2019 Java Workshop July

    104/113

    IftheThreadclassisextendedthen

    MyThread t = new MyThread();

    MyRunnable r = new MyRunnable();

    Thread t =new Thread(r); //Passing Runnable to Thread

    The samejobcanbegiventomultiplethreads

    public class TestThreads

    {

    pu c s a c vo ma n r ng args

    {

    MyRunnable r =new MyRunnable();Thread foo = new Thread(r);

    Thread bar= new Thread(r);

    Thread bat = new Thread(r);

    }

    }

    StartingaThread:

    Tostartexecutingathread start()Methodisused

  • 8/7/2019 Java Workshop July

    105/113

    g ()

    t.start();

    Aftercallingstart():

    AnewThreadofexecutionstarts

    ThreadmovesfromnewstatetoRunnable state

    run()methodisreadytorun

    DEMO:StartingandrunningaThread

  • 8/7/2019 Java Workshop July

    106/113

    StartingandRunningMultipleThreads:

  • 8/7/2019 Java Workshop July

    107/113

    DEMO:Startin andRunnin Multi leThreads

    The order threads executin cannot be uaranteed The onl

    Guaranteedthingis

    Eachthreadwillstartandeachthreadwillrunto

    ThreadStates

    TheDifferentthreadstatesare:New

  • 8/7/2019 Java Workshop July

    108/113

    New

    Running

    Waiting/blocked/sleeping

    SunClub NITK

  • 8/7/2019 Java Workshop July

    109/113

    http://groups.google.com/group/nitksunclub

    OfficialBlog:

    http://sunclubatnitk.wordpress.com/

    MyJavaBlog:

    . .

    Theofficialwebsite+mailing listofNITKSunClub

  • 8/7/2019 Java Workshop July

    110/113

    htt : rou s. oo le.com rou nitksunclub

    SubscribetothisGooglegrouptoregisterforNITKSunClub!

    Discussions:Feelfreetopostanyqueries,ideas,newsyouhaveto

    t ema ng st ta epart nt e scuss ons.

    Files,Links,Resources:Findandshareallimportant, , ,

    posters,brochures,etc relatedtotheclub'sactivities.

    Events&Achievements:Gettoknowaboutallthelatesthappeningsandupcomingeventsoftheclub.

  • 8/7/2019 Java Workshop July

    111/113

  • 8/7/2019 Java Workshop July

    112/113

  • 8/7/2019 Java Workshop July

    113/113