java evolution

Upload: ravi-singh

Post on 08-Apr-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Java Evolution

    1/258

    Java HistoryJavaJava isis aa generalgeneral purpose,purpose, ObjectObject OrientedOrientedProgrammingProgramming languagelanguage developeddeveloped byby SunSunMicrosystemsMicrosystems ofof USAUSA inin 19911991.. OriginallyOriginally CalledCalled OaKOaKbyby JamesJames Gosling,Gosling, oneone ofof thethe inventorsinventors ofof thethelanguage,language, javajava waswas designeddesigned forfor thethe developmentdevelopmentofof softwaresoftware forfor consumerconsumer electronicelectronic devicesdevices likelikeTVs,TVs, VCRs,VCRs, toasterstoasters andand suchsuch otherother electronicelectronic

    machinemachine..TheThe goalgoal hadhad strongstrong impactimpact onon thethe developmentdevelopmentteamteam toto makemake thethe languagelanguage simple,simple, portableportable andandhighlyhighly reliablereliable.

  • 8/7/2019 Java Evolution

    2/258

    Java Features

    FeaturesFeatures havehave mademade JavaJava thethe firstfirst applicationapplication LanguageLanguage

    ofof thethe WorldWorld WideWide WebWeb.. JavaJava willwill alsoalso becomebecome thethepremierpremier languagelanguage forfor generalgeneral purposepurpose standstand--alonealone

    applicationsapplications..

    Compiled and Interpreted

    Usually a Computer language is either compiled or

    interpreted, Java combines both these approaches thus

    making java a two-stage system. First, Java compiler translates

    source code into what is known as bytecode instructions.

    Bytecodes are not machine instructions and therefore, in thesecond stage, Java interpreter generates machine code that

    can be directly executed by the machine that is running the

    Java program. We can thus say that java is both compiled and

    an interpreted language.

  • 8/7/2019 Java Evolution

    3/258

    Java Features

    Platform- Independent and PortableThe Most significant contribution of java over other

    languages is its portability. Java programs can be

    easily moved from one computer system to another,

    anywhere and anytime.

    Changes and upgrades in operating systems,

    processors and system resources will not force any

    changes in java programs.This is the reason why java has become a popular

    language for programming on internet which

    interconnects different kinds of systems worldwide.

  • 8/7/2019 Java Evolution

    4/258

    Java Features

    Object OrientedJava is trust object-oriented language.

    Almost everything in java is an object. All

    program code and data reside withinobjects and classes. Java comes with an

    extensive set of Classes, arranged in

    packages, that we can use in ourprograms by inheritance. The Object

    model in java is simple and easy to

    extend.

  • 8/7/2019 Java Evolution

    5/258

    Java Features

    Robust and SecureJava is robust language. It provides many

    safeguards to ensure reliable code. It has

    strict compile time and run time checkingfor data types. It is designed as a garbase-

    collected language relieving the

    programmers virtually all memorymanagement problems.

  • 8/7/2019 Java Evolution

    6/258

    Java Features

    Distributed

    Java is designed as a distributed language

    for creating applications on networks. It

    has the ability to share both data andprograms. Java application can open and

    access remote objects on internet as

    easily as they can do in local system. Thisenables multiple programmers at

    multiple remote locations to collaborate

    and work together on a single project.

  • 8/7/2019 Java Evolution

    7/258

    Java Features

    Simple, Small and FamiliarJava is small and simple language. Many

    features of C and C++ that are either

    redundant or sources of unreliable codeare not part of Java.

    For Example:- Java does not use Pointers,

    preprocessor header files, goto statementand many others.

  • 8/7/2019 Java Evolution

    8/258

    Java Features

    Multithreaded and InteractiveMultithreaded means handling multiple tasks

    simultaneously. Java supports Multithreaded

    programs. This means that we need not waitfor the application to finish one task before

    beginning another.

    For Example:-We can listen to an audio clip while scrolling a

    page and at the same time download applet

    from a distant computer

  • 8/7/2019 Java Evolution

    9/258

    Java Features

    High Performance

    Java performance is impressive for an

    interpreted language, mainly due to theuse of intermediate bytecodde.

    According to SUN. Java speed is

    comparable to the native C/C++.Java architecture is also designed to

    reduce overheads during runtime.

  • 8/7/2019 Java Evolution

    10/258

    Java Features

    Dynamic and Extensible

    Java is dynamic language. Java is capable of

    dynamically linking in new class libraries,

    methods, and objects. Java can also determine

    the type of class through a query, making it

    possible to either dynamically link of abort the

    program, depending on the response.Java programs support functions written in

    other language such as C, C++. These function

    are known as native methods.

  • 8/7/2019 Java Evolution

    11/258

    Differs From C and C++

    Java was modeled after C and C++

    languages. It differs from C and C++ in

    many ways. Java does not incorporate anumber of features available in C and

    C++. For the benefit of C and C++

    programmers, we point out here a fewmajor differences between C/C++ and

    java languages.

  • 8/7/2019 Java Evolution

    12/258

    Java is lot like C but the major difference

    between Java and C is that Java is an

    Object-Oriented Language and hasmechanism to define classes and objects.

    Java does not include the C uniquestatement keywords, sizeof, and

    typedef.

    Java and CJava and C

  • 8/7/2019 Java Evolution

    13/258

    Java does not contain the data typesStruct and union

    Java does not define the type modifiers

    keywords auto, extern, register, signed,and unsigned.

    Java does not support an explicit Pointer

    type Java does not have preprocessor and

    therefore we can not use #define,

    #include

    Java and CJava and C

  • 8/7/2019 Java Evolution

    14/258

    Java requires that the functions with noarguments must be declared with empty

    parenthesis and not with the void

    keywords as done in C. Java add new operators such as

    instanceof and >>>

    Java adds labelled break and continue

    statements.

    Java and CJava and C

  • 8/7/2019 Java Evolution

    15/258

    Java is true Object Oriented Languagewhile C++ is basically C with Object

    Oriented Extension. That is what exactly

    the increment operator ++ indicates.C++ maintained backward compatibility

    with C. it is therefore possible to write an

    old style C program and run itsuccessfully under C++. Java appears to

    be similar to C++ when we consider only

    the Extension part of C++

    Java and C++Java and C++

  • 8/7/2019 Java Evolution

    16/258

    Listed below are some major C++ features that wereintentionally omitted from java of significantly Modified.

    Java does not support Operator

    Overloading.

    Java does not have template classes as in

    C++

    Java does not support multipleinheritance of classes. This is

    accomplished using a new feature called

    Interface

    Java and C++Java and C++

  • 8/7/2019 Java Evolution

    17/258

    Java does not support GlobalVariables. Every variable and method

    is declared within a class and forms

    part of the class.

    Java does not use pointers.

    Java has replaced the destructorfunction with a finalize() function.

    There are no header files in Java.

    Java and C++Java and C++

  • 8/7/2019 Java Evolution

    18/258

    Overlapping of C, C++, and JavaOverlapping of C, C++, and Java

    CC

    C++C++

    JAVAJAVA

  • 8/7/2019 Java Evolution

    19/258

    Java is strongly associated with theInternet because of the fact that the

    first application program written in

    Java was HotJava, a web browser to

    run applets on Internet. Internet user

    can use Java to create applet

    programs and run them locally using

    a Java enabled Browser such as

    HotJava.

    Java and InternetJava and Internet

  • 8/7/2019 Java Evolution

    20/258

    Java environment includes a largenumber of development tools and

    hundreds of classes and methods. The

    development tools are part of the systemknown as Java Development Kit(JDK) and

    the classes and the method are part of

    the Java Standard Library(JSL), alsoknown as the Application Programming

    Interface(API).

    Java EnvironmentJava Environment

  • 8/7/2019 Java Evolution

    21/258

    TheThe JavaJava DevelopmentDevelopment KitKit comescomes withwith aa collectioncollection ofof toolstools thatthatareare usedused forfor developingdeveloping andand runningrunning javajava programsprograms.. ThenThen

    includeinclude::

    Appletviewer(for viewing java applet)

    Javac (Java compiler)

    Java (Java Interpreter)

    Javap (Java disassembler)

    Javah (For C header file)

    Javadoc (For creating HTML Document)

    Jdb (Java debugger)

    Java Development Kit (JDK)Java Development Kit (JDK)

  • 8/7/2019 Java Evolution

    22/258

    JavaJava isis generalgeneral purposepurpose ObjectObjectOrientedOriented ProgrammingProgramming LanguageLanguage..

    WeWe cancan developdevelop twotwo typestypes ofof javajava

    programsprograms..

    StandStand alonealone applicationapplication WebWeb AppletsApplets

    IntroductionIntroduction

  • 8/7/2019 Java Evolution

    23/258

    Two ways of using JavaTwo ways of using JavaJava

    Soruce

    Code

    Java

    Compiler

    JavaEnabled

    Web

    Browser

    Java

    Interpreter

    Output Output

    Applet TypeApplet Type Application TypeApplication Type

  • 8/7/2019 Java Evolution

    24/258

    U

    seJ

    DK 1.5 version.U

    seJ

    DK 1.5 version.Environment Variable.Environment Variable.

    Variable Name:Variable Name: ClasspathClasspath

    value:value: bin;lib;Cbin;lib;C:;D:;:;D:;Variable Name:Variable Name: javahomejavahome

    value:value: bin;libbin;lib;;

    Variable Name: pathVariable Name: pathvalue:value: bin;libbin;lib;;

    Installation & Environment Variable SettingInstallation & Environment Variable Setting

  • 8/7/2019 Java Evolution

    25/258

    classclass SampleOneSampleOne

    {{

    publicpublic StaticStatic voidvoid main(Stringmain(String argsargs [])[])

    {{

    SystemSystem..outout..println(Javaprintln(Java isis betterbetter thanthan C++C++..));;

    }}}}

    Simple Java ProgramSimple Java Program

  • 8/7/2019 Java Evolution

    26/258

    import java.lang.Math;

    classclass SampleOneSampleOne

    {{

    publicpublic StaticStatic voidvoid main(Stringmain(String argsargs [])[])

    {{

    doubledouble x=x=55;; //declaration//declaration andand initializationinitialization

    doubledouble yy;;

    y=y= MathMath..sqrt(x)sqrt(x);;

    SystemSystem..outout..println(y=println(y= +y)+y);;

    }}

    }}

    A Java Program with multiple statementA Java Program with multiple statement

  • 8/7/2019 Java Evolution

    27/258

    ImplementationImplementation ofof aa javajava applicationapplication programprogram

    involvesinvolves aa seriesseries ofof stepssteps.. TheyThey includeinclude

    CreatingCreating aa programprogram

    CompilingCompiling thethe programprogram

    RunningRunning thethe programprogram

    RememberRemember that,that, beforebefore wewe beginbegin creatingcreating thethe

    program,program, thethe javajava DevelopmentDevelopment KitKit (JDK)(JDK) mustmust

    bebe properlyproperly installedinstalled onon ourour systemsystem..

    Implementing a Java ProgramImplementing a Java Program

  • 8/7/2019 Java Evolution

    28/258

    classclass TestTest

    {{

    publicpublic staticstatic voidvoid main(Stringmain(String args[])args[])

    {{

    SystemSystem..outout..println(println(hellowhellow!)!);;

    SystemSystem..outout..println(Welcomeprintln(Welcome toto thethe worldworld ofof java)java);;

    SystemSystem..outout..println(Letprintln(Let usus LearnLearn Java)Java);;

    }}

    }}

    Another simple program for testingAnother simple program for testing

  • 8/7/2019 Java Evolution

    29/258

    To Compile the program, we must run the javacompiler javac, with name of the source file on

    the command line as shown below.

    CC::/>/>javacjavacTestTest..javajava

    ifif everyevery thinkthink ok,ok, thethe javacjavac compilercompiler createscreates aa filefile

    calledcalled TestTest..classclass containingcontaining thethe bytecodesbytecodes ofof thethe

    programprogram.. NoteNote thatthat thethe compilercompiler automaticallyautomatically

    namesnames thethe bytecodebytecode filefile asas .. ClassClass

    TestTest..classclass

    Compiling the programCompiling the program

  • 8/7/2019 Java Evolution

    30/258

    We need to use the java interpreter to run astand-alone program. At the command prompt,

    type

    CC::/>java/>java TestTest

    NowNow thethe interpreterinterpreter lookslooks forfor thethe mainmain methodmethod inin thethe

    programprogram andand beginsbegins executionexecution fromfrom therethere.. WhenWhen

    executed,executed, ourour programprogram displaysdisplays thethe followingfollowing::

    HellowHellow!!WelcomeWelcome toto thethe worldworld ofofJavaJava

    LetLet usus LearnLearn JavaJava

    Running the programRunning the program

  • 8/7/2019 Java Evolution

    31/258

    All language compilers translate sourcecode into machine code for a specific

    computer. Java compiler produces an

    intermediate code known as byte code fora machine that does not exist. This

    machine is called the Java Virtual Machine

    and it exists only inside the computermemory.

    Java Virtual Machine (JVM)Java Virtual Machine (JVM)

    Java

    Program

    Java

    Compiler

    Virtual

    Machine

  • 8/7/2019 Java Evolution

    32/258

    Command line arguments are the

    parameters that are supplied to

    the application program at time ofinvoking it for execution. These are

    passed as parameters to the

    main() function.

    Command line argumentsCommand line arguments

  • 8/7/2019 Java Evolution

    33/258

    Command line argumentsCommand line argumentsclass ComLine

    {Public static void main(String args[])

    {

    Int count, i=0;

    String string ;count =args.length; //Property of String array

    System.out.println(Number of Arguments= +count);

    While(i

  • 8/7/2019 Java Evolution

    34/258

    Class add

    {

    public static void main (String args[])

    {Double a=10,b=20;

    System.out.println(Addition= +(a+b));

    }}

  • 8/7/2019 Java Evolution

    35/258

    public class evenOdd

    {

    public static void main(String args[]){

    int num=10;

    if(num%2!=0)

    { System.out.println(num+ is Odd.);

    }

    else

    { System.out.println(num+ is Even.);

    }

    }

    }

  • 8/7/2019 Java Evolution

    36/258

    class areaCircle

    {

    public static void main(String args[])

    {

    double r=10;final double PI=3.14; //Constant

    System.out.println(Area= +(PI*r*r));

    }

    }

  • 8/7/2019 Java Evolution

    37/258

    class SimpleInterest

    {

    public static void main(String args[])

    {

    double p=1500, r=10, t=4;System.out.println(SI= +(p*r*t)/100);

    }

    }

  • 8/7/2019 Java Evolution

    38/258

    class power

    {

    public static void main(String args[])

    {

    int b=4, p=3;int res=Math.pow(b , p );

    System.out.println(b+ power +p+ = +res)

    }

    }

  • 8/7/2019 Java Evolution

    39/258

    class table5

    {

    public static void main(String args[])

    {

    int i, num=5;for(i =1;i

  • 8/7/2019 Java Evolution

    40/258

    class CountEven

    {

    public static void main(String args[]){

    int count=0;

    for( i =1;i

  • 8/7/2019 Java Evolution

    41/258

    class Printsequence

    {

    public static void main(String args[]) {

    int i=1 ,n=1;

    char ch=a;

    while(i

  • 8/7/2019 Java Evolution

    42/258

    VariablesAA variablevariable isis anan identifieridentifier thatthat

    denotesdenotes aa storagestorage locationlocation usedused toto

    storestore aa datadata valuevalue.. UnlikeUnlike

    constantsconstants thatthat remainremain unchangedunchangedduringduring thethe executionexecution ofof aa

    program,program, aa variablevariable maymay taketake

    differentdifferent valuesvalues atat differentdifferent timestimes

    duringduring thethe executionexecution ofof thethe

    programprogram..

  • 8/7/2019 Java Evolution

    43/258

    Data Types

    E

    veryE

    very variablevariable inin javajava ofof aadatadata typetype.. DataData typetype

    specifyspecify thethe sizesize andand typetype ofofvaluesvalues thatthat cancan bebe storedstored..

    JavaJava languagelanguage isis richrich inin itsits

    datadata typetype..

  • 8/7/2019 Java Evolution

    44/258

    Data Types

    in JAVA

    Primitive

    (Intrinsic)

    Non-Primitive

    (Derived)

    Numeric Non-numeric Classes Arrays

    Interface

    IntegerFloating

    Point Character Boolean

    Data Types in Java

    Note: Boolean Data type Value is TRUE or FALSENote: Boolean Data type Value is TRUE or FALSE

    but Default Value is FALSEbut Default Value is FALSE

  • 8/7/2019 Java Evolution

    45/258

    Integer TypesJavaJava supportssupports fourfour typestypes ofof

    integersintegers areare byte,byte, short,short, int,int,

    andand longlong.. JavaJava doesdoes notnot

    supportsupport thethe conceptconcept ofofunsignedunsigned typestypes andand thereforetherefore

    allall javajava valuesvalues areare signedsignedmeaningmeaning theythey cancan bebe positivepositive

    oror negativenegative..

  • 8/7/2019 Java Evolution

    46/258

    Size and Range of Integer Types

    Type Size Minimum value Maximum Value

    Byte One Byte -128 127

    Short Two bytes -32,768 32,767

    int Four bytes -2,147, 483, 648 2, 147, 483, 647

    long Eight bytes -9, 223, 372, 036,

    854, 775, 808

    9, 223, 372, 036,

    854, 775, 807

  • 8/7/2019 Java Evolution

    47/258

    Floating Point Types

    IntegerInteger typestypes cancan holdhold onlyonlywholewhole numbersnumbers andand

    thereforetherefore wewe useuse anotheranothertypetype knownknown asas ((floatingfloating

    pointpoint constant)constant)..

  • 8/7/2019 Java Evolution

    48/258

    Floating

    Point

    Float Double

    Floating point data types

    Type Size Minimum Value Maximum Value

    Float 4 Bytes 3.4e-038 3.4e+038

    Double 8 Bytes 1.7e-308 1.7e+308

    Size and Range of Floating Point Types

  • 8/7/2019 Java Evolution

    49/258

    Character TypeInIn javajava thethe datadata typetype usedused toto storestore charactercharacter isis

    charchar.. HoweverHowever C,C, C++C++ programmersprogrammers bewarebeware:: charcharinin javajava isis notnot thethe samesame asas charchar inin C,C, C++C++.. InIn

    C/C++,C/C++, CharChar isis anan integerinteger typetype thatthat isis 88 bitsbits ((11

    Byte)Byte) widewide.. ThisThis isis notnot thethe casecase inin javajava.. Instead,Instead,javajava usesuses UnicodeUnicode toto representrepresent characterscharacters foundfound

    inin allall humanhuman languageslanguages.. InIn javajava charactercharacter isis aa 1616--

    bitbit typetype.. TheThe rangerange ofof charchar isis 00 toto 6565,,536536.. therethere

    areare nono negativenegative charschars.. TheThe standardstandard setset ofof

    charactercharacter knownknown asas ASCIIASCII stillstill rangerange fromfrom 00 toto

    127127 asas always,always, andand thethe extendedextended 88--bitbit charactercharacter

    set,set, ISOISO--LatinLatin--11,, rangesranges fromfrom 00 toto 255255..

    //D h d

  • 8/7/2019 Java Evolution

    50/258

    //Demonstrate char data type.

    Class CharDemo

    {

    public static void main(String args[])

    {

    char ch1, ch2;

    ch1=8; //code for Xch2=Y;

    System.out.print(Ch1 and ch2: );

    System.out.println(ch1+ +ch2);

    }

    }

  • 8/7/2019 Java Evolution

    51/258

    Boolean Type

    BooleanBoolean TypeType isis usedused whenwhen wewewantwant toto testtest aa particularparticular

    conditioncondition duringduring thethe executionexecutionofof thethe programprogram.. ThereThere areare onlyonly

    twotwo valuesvalues thatthat aa BooleanBoolean typetypecancan taketake:: TRUETRUE oror FALSEFALSE..

    DefaultDefault valuevalue isis FALSEFALSE..

    //Demonstrate Boolean values

  • 8/7/2019 Java Evolution

    52/258

    //Demonstrate Boolean values.

    Class BoolTest

    {

    public static void main(String args[])

    {

    b=false;

    System.out.println(b is +b);

    b=true;

    System.out.println(b is +b);// a boolean value can control the if statement

    if(b) System.out.println(This is executed.);

    b=false;

    if(b) System.out.println(This is not executed.);

    //outcome of a relational operator is a boolean value

    System.out.println(10>9 is +(10>9));

    }

    }

  • 8/7/2019 Java Evolution

    53/258

    Standard Default Values

    Type of Variable Default Value

    Byte Zero : (byte) 0

    Short Zero : (Short) 0

    Int Zero: 0

    Long Zero:0L

    Float 0.0f Char Null Character

    Boolean False

    Reference null

    In Java, every variable has a default value. If we dontinitialize a variable when it is first created, java providesdefault value to that variable.

  • 8/7/2019 Java Evolution

    54/258

    LabelledLoops

    InIn java,java, wewe cancan givegive aa labellabel toto aablockblock ofof statementsstatements.. AA labellabel isis

    anyany validvalid javajava variablevariable namename.. totogivegive aa labellabel toto aa loop,loop, placeplace itit

    beforebefore thethe looploop withwith aa coloncolon atatthethe endend..

    class cb

  • 8/7/2019 Java Evolution

    55/258

    class cb

    {

    public static void main(String args[]) {

    LOOP1: for(int i=1;i=10) break;

    for(int j=1; j

  • 8/7/2019 Java Evolution

    56/258

    Arrays, Strings and Vectors

    AnAn arrayarray isis aa groupgroup ofof contiguouscontiguous ororrelatedrelated datadata itemsitems thatthat shareshare aa

    commoncommon namename..

    OneOne DimensionalDimensionalarraysarrays

    TwoTwo DimensionalDimensionalarraysarrays

    MultiMulti DimensionalDimensionalarraysarrays

    AnonymousAnonymous ArrayArray

  • 8/7/2019 Java Evolution

    57/258

    Creating anArray

    LikeLike anyany otherother variables,variables, arraysarrays mustmust bebedeclareddeclared andand createdcreated inin thethe computercomputer

    memorymemory beforebefore theythey areare usedused.. CreationCreation ofof

    anan arrayarray involvesinvolves threethree stepssteps.. DeclaringDeclaring thethe arrayarray

    CreatingCreating MemoryMemory locationslocations

    PuttingPutting valuesvalues intointo thethe memorymemory locationslocations

  • 8/7/2019 Java Evolution

    58/258

    Declaration ofArrays

    ArraysArrays inin JavaJava maymay bebe declareddeclared inin twotwo waysways..

    FormForm11

    FormForm11

    ExamplesExamples::

    intint number[number[ ]];;

    floatfloat average[average[ ]];;

    intint [[ ]=]= countercounter;;

    float[float[ ]=marks]=marks;;

    Type arrayname[ ];

    Type [ ]arrayname;

    Remember, we do not enter

    the size of the arrays in thedeclaration

  • 8/7/2019 Java Evolution

    59/258

    Creation ofArrays

    AfterAfter declaringdeclaring anan array,array, wewe needneed toto createcreate itit inin thethememorymemory.. JavaJava allowsallows usus toto createcreate arraysarrays usingusing newnew

    operatoroperator only,only,

    ExamplesExamples::

    numbernumber == newnew int[int[55]];;

    averageaverage == newnew float[float[1010]];;

    TheseThese lineslines createcreate necessarynecessary memorymemory locationslocations forfor thethe arraysarraysnumbernumber andand averageaverage andand designatedesignate themthem asas intint andand floatfloat

    respectivelyrespectively.. Now,Now, thethe variablevariable numbernumber refersrefers toto anan arrayarray ofof 55

    integersintegers andand averageaverage refersrefers toto anan arrayarray ofof 1010 floatingfloating pointpoint

    valuesvalues..

    Arrayname=new type [size];

  • 8/7/2019 Java Evolution

    60/258

    ItIt isis alsoalso possiblepossible toto combinecombine thethe twotwo stepssteps-- declarationdeclaration

    andand creationcreation-- intointo oneone asas shownshown belowbelow..

    StatementStatement ResultResult

    intint numbernumber [][];;

    Number=newNumber=new intint [[55]];;

    int number[ ]=new int [5];

    PointsPoints nowherenowhere

    NumberNumber [[00]]

    NumberNumber [[11]]

    NumberNumber [[22]]

    NumberNumber [[33]]

    NumberNumber [[44]]

    f

  • 8/7/2019 Java Evolution

    61/258

    Initialization ofArrays

    TheThe FinalFinal stepstep isis toto putput valuesvalues intointo thethe arrayarray createdcreated..ThisThis processprocess isis knownknown asas initializationinitialization..

    ExamplesExamples::intint number[number[ ]={]={3535,, 4040,, 2020,, 5757,, 1919}};;

    ItIt isis possiblepossible toto assignassign anan arrayarray objectobject toto anotheranother.. ExampleExample::

    intint a[a[ ]=]= {{11,, 22,, 33}};;

    intint b[b[ ]];;b=ab=a;;

    AreAre validvalid inin javajava.. BothBoth thethe arraysarrays willwill havehave thethe samesame valuesvalues..

    Arrayname[ subscript]=value

    A h

  • 8/7/2019 Java Evolution

    62/258

    Array length

    InIn java,java, allall arraysarrays storestore thethe allocatedallocatedsizesize inin aa variablevariable namednamed lengthlength.. WeWe

    cancan obtainobtain thethe lengthlength ofof thethe arrayarray aa

    usingusing aa..lengthlength..

    intint aSize=aSize= aa..lengthlength;;

    ThisThis informationinformation willwill bebe usefuluseful inin thethemanipulationmanipulation ofof arraysarrays whenwhen theirtheir

    sizessizes areare notnot knownknown..

    //Average an array of values

  • 8/7/2019 Java Evolution

    63/258

    //Average an array of values.

    Class Average

    {

    public static void main(String args[])

    {

    double nums[ ]={10.1, 11.2, 12.3, 13.4, 14.5};

    double result=0;

    int i;

    for(i=0;i

  • 8/7/2019 Java Evolution

    64/258

    Two dimensionalArrayTwoTwo dimensionaldimensional arraysarrays areare storedstored inin memorymemory asas withwith

    thethe singlesingle dimensionaldimensional arrays,arrays, eacheach dimensiondimension ofof thethearrayarray isis indexedindexed fromfrom zerozero toto itsits maximummaximum sizesize

    minusminus oneone;; thethe firstfirst indexindex selectsselects thethe rowrow andand thethe

    secondsecond indexindex selectsselects thethe columncolumn withinwithin thatthat rowrow..

    For creating two-dimensional arrays, we must follow the same

    steps as that of simple arrays. We may create a two-

    dimensional array like this.

    int myArray[ ][ ];

    myArray=new int [3][4];

    Or

    int myArray[ ][ ]=new int[3][4];

    //Demonstrate a two-dimensional array.

    O t t

  • 8/7/2019 Java Evolution

    65/258

    Class TwoDArray

    {

    public static void main(String args[])

    {intTwoD[ ][ ]=new int [4][5];

    int i, j, k=0;

    for(i =0;i

  • 8/7/2019 Java Evolution

    66/258

    //Manually Allocate differing size second dimensions

    Class TwoDAgain

    {public static void main(String args[])

    {

    intTwoD[ ][ ]=new int [4][ ];TwoD[ 0]=new int [1 ];

    TwoD[ 1]=new int [2 ];

    TwoD[ 2]=new int [3 ];

    TwoD[ 3]=new int [4 ];

    int i, j, k=0;

    To be Continue..O t t

  • 8/7/2019 Java Evolution

    67/258

    To be Continue..

    int i, j, k=0;

    for(i =0;i

  • 8/7/2019 Java Evolution

    68/258

    // y

    Class threeDMatrix

    {

    public static void main(String args[]){

    int threeD[ ][ ][ ]=new int [3][4][5];

    int i,j,k;

    for( i =0;i

  • 8/7/2019 Java Evolution

    69/258

    for( i =0;i

  • 8/7/2019 Java Evolution

    70/258

    Anonymous Array

    In java it is perfectly legal to create an anonymousIn java it is perfectly legal to create an anonymous

    array using the following syntax.array using the following syntax.

    new [] { };

    Anonymous array exampleAnonymous array example

    new int[]{1,2,3};

    The above given example creates a nameless array and

    initializes it. Here, neither name of the array nor the

    size is specified. It also creates a array which can be

    assigned to reference or can be passed as a parameter

    to any method.

    //Anonymous array program

  • 8/7/2019 Java Evolution

    71/258

    // y y p g

    public AnonymousArrayExample{

    public static void main(String args[]){System.out.println(Length of array is + findLength(new int[]{1,2,3}));

    }

    public static findLength(int[] array){

    return array.lentgh;

    }

    }

    The above given program will print the length of theThe above given program will print the length of the

    anonymous array which is being passed to the staticanonymous array which is being passed to the static

    method.method.

    ForFor--each Loopeach Loop

  • 8/7/2019 Java Evolution

    72/258

    ForFor--each Loopeach LoopPurposePurpose

    The basic for loop was extended in Java 5 to makeiteration over arrays and other collections more

    convenient. This newer for statement is called the

    enhanced foror for-each (because it is called this in other

    programming languages).The for-each loop is used to access each successive value

    in a collection of values.

    Arrays and Collections.Arrays and Collections.

    It's commonly used to iterate over an array or a

    Collections class (eg, ArrayList).

    General FormGeneral Form

  • 8/7/2019 Java Evolution

    73/258

    GeneralFormGeneralForm

    The for-each and equivalent forstatements have these forms.

    For-each loop Equivalent for loop

    for (type var: arr)

    {

    body-of-loop

    }

    for (int i= 0; i < arr.length; i++)

    {

    type var= arr[i];

    body-of-loop}

    for (type var: coll)

    {

    body-of-loop

    }

    for (Iterator iter= coll.iterator();

    iter.hasNext(); )

    {

    type var= iter.next();body-of-loop

    }

    //For Each loop with anonymous Array//For Each loop with anonymous Array

  • 8/7/2019 Java Evolution

    74/258

    //For Each loop with anonymous Array//For Each loop with anonymous Array

    public class MainClass

    {public static void main (String args[])

    {

    int array1[] = {1, 2, 3, 4, 5};

    for(int i: array1){

    System.out.println(i);

    }

    }

    }

    St i

  • 8/7/2019 Java Evolution

    75/258

    StringIn Java a string is a sequence of characters , but,

    unlike many other languages that implement string ascharacter arrays, java implements strings as objects

    of the String class.

    In java string are class objects and implemented

    using two classes, namely, String and StringBuffer. A

    java string is an instantiated object of the String

    Class. Java Strings, as compared to C strings, are more

    reliable and predictable. This is basically due to Cs

    lack of bounds-checking. A java String not a

    character array and is not NULL terminated.

    Th t i l d St i B ff d fi d

  • 8/7/2019 Java Evolution

    76/258

    The string class and StringBuffer are defined

    in java.lang. thus, they are available to all

    programs automatically.The String Constructors

    The String class support several constructors.

    To create an empty String, you call the

    default constructor.

    Example:

    String s=new String();// will create an instance of String

    with no character with it.

    Syntax:

  • 8/7/2019 Java Evolution

    77/258

    Syntax:

    String stringname;

    StringName=new String(String);Example:

    String firstName;

    firstName =new String(JAVA);

    These Two Statements may be combinedas follows:

    String firstName =new String(Java);

    Note the use of parentheses here. Java strings can be

    concatenated using the + operator.String fullName=name1+name2;

    String city1=New+Delhi;

    System.out.println(firstName+Kumar);

    //Construct one String from another

  • 8/7/2019 Java Evolution

    78/258

    Class MakeString

    {public static void main (String args[])

    {

    char c[ ]={J, A, V, A};String s1=new String(c);

    String s2=new String(s1);

    System.out.println(s1);System.out.println(s2);

    }

    }

    Output:

    Java

    Java

    //Construct string from subset of char array.

  • 8/7/2019 Java Evolution

    79/258

    Class SubStringCons

    {

    public static void main (String args[]){

    byte ascii[ ]={65,66,67,68,69,70};

    String s1=new String (ascii);

    System.out.println(s1);String s2=new String(ascii,2,3);

    System.out.println(s2);

    }

    }

    Output:

    ABCDEF

    CDE

    HERE, asciiChars specifies the array of bytes. The second form

    allows you to specify a subrange. In each of these constructors,

    the byte-to-character conversion is done by using the default

    character encoding of the flateform.

    Note about String

  • 8/7/2019 Java Evolution

    80/258

    Note about String

    TheThe ContentsContents ofof thethe arrayarray areare copiedcopied wheneverwhenever youyou createcreate aaStringString objectobject fromfrom anan arrayarray.. IfIf youyou modifymodify thethe contentscontents ofof thethe

    arrayarray afterafter youyou havehave createcreate thethe string,string, thethe StringString willwill bebe changedchanged..

    StringString LengthLength

    TheThe lengthlength ofof aa stringstring isis thethe numbernumber ofof characterscharacters thatthat ititcontainscontains.. ToTo obtainobtain thisthis valuevalue callcall thethe length()length() methodmethod..

    charchar chars[]={a,chars[]={a, b,b, c}c};;

    StringString s=news=new String(chars)String(chars);;SystemSystem..outout..println(println( ss..length())length());;

    String Methods

  • 8/7/2019 Java Evolution

    81/258

    String MethodsTheThe StringString classclass definesdefines aa numbernumber ofof methodsmethods thatthat allowallow usus toto

    accomplishaccomplish aa varietyvariety ofof stringstring manipulationmanipulation taskstasks.. ListsLists somesome ofof

    thethe mostmost commonlycommonly usedused stringstring methodsmethods andand theirtheir taskstasks;;

    Method Call Task performed

    S2=s1.toLowerCase; Converts the string s1 to all lowercase

    S2=s1.toUpperCase; Converts the string s1 to all Uppercase

    S2=s1.replace(x, y); Replace all appearances of x with y

    S2= s1.trim(); Remove White Spaces at the beginning

    and end of the string s1

    S1.equals(s2); Returns True if s1 is equal to s2.

    S1.equalsIgnoreCase(s2); Returns True if s1=s2, ignoring the case

    of characters

    S1.length; Gives the length of s1

    String Methods

  • 8/7/2019 Java Evolution

    82/258

    String MethodsMethod Call Task performed

    S1.charAt(n) Gives the nth character of s1

    S1.compareTo(s2); Returns negative if s1s2, and zero if s1 is equal s2.

    S1.concate(s2); Concatenates s1 and s2

    S1.substring(n); Gives substring starting from nth

    character

    S1.substring(m, n); Gives substring starting from nth

    character up to mth (Not including mth)

    S1.indexOf(x) Gives the position of the first occurrence

    of x in the String s1

    S1.indexOf(x, n) Gives the position of x that occurs after

    nth position in the String s1

    StringBuffer Class

  • 8/7/2019 Java Evolution

    83/258

    StringBufferClassStringBufferStringBuffer isis aa peerpeer classclass ofof StringString.. WhileWhile StringString createscreates

    stringsstrings ofof fixed_lengthfixed_length,, StringBufferStringBuffer createscreates stringsstrings ofof flexibleflexible

    lengthlength thatthat cancan bebe modifiedmodified inin termsterms ofof bothboth lengthlength andand contentcontent..

    CommonlyCommonly usedused StringBufferStringBuffer methodsmethods

    Method Tasks

    S1.setCharAt(n, x) Modifies the nth character to x

    S1.append(s2) Appends the string s2 to s1 at the end

    S1.insert(n,s2) Inserts the string s2 at the position n of the

    string s1

    S1.SetLength(n) Sets the length of the string s1 to n. if

    ns1.length() zeros are added to s1

    //Manipulation of string

    l l

  • 8/7/2019 Java Evolution

    84/258

    Class StringManipulation

    {

    public static void main (String args[]){

    StringBuffer str= new StringBuffer(Object Language);

    System.out.println(Original String:+str);

    //obtaining String Length//obtaining String LengthSystem.out.println(Length of String:+str.length());

    //Accessing Character in a String//Accessing Character in a String

    for(int i=0; i

  • 8/7/2019 Java Evolution

    85/258

    //Inserting a string in the middle

    String aString=new String(str.toString());

    int pos=aString.indexOf( language);str.insert(pos, Oriented );

    System.out.println(Modified string : +str);

    //Modifying Characters

    Str.setCharAt(6, -);System.out.println(String Now: +str);

    //Appending a string at the end

    Str.append( improves security. );

    System.out.println(Appended string:+str);

    }

    }

    //Alphpabetical Ordering of Strings

    class StringOrdering

  • 8/7/2019 Java Evolution

    86/258

    class StringOrdering

    {

    static String name[]={Madras, Delhi,

    Ahmedabad,Calcutta,Bombay};

    public static void main (String args[ ])

    {

    int size=name.length;

    String temp=null;

    for(int i=0;i

  • 8/7/2019 Java Evolution

    87/258

    VectorUseUse ofof thethe VectorVector ClassClass containedcontained inin thethe javajava..utilutil

    packagepackage.. ThisThis classclass cancan bebe usedused toto createcreate aagenericgeneric dynamicdynamic arrayarray knownknown asas vectorvector thatthat cancan

    holdhold objectsobjects ofof anyany typetype andand numbernumber.. ArraysArrays

    cancan bebe implementedimplemented asas vectorvector.. VectorsVectors areare

    createdcreated likelike arraysarrays asas followsfollows..

    vectorvector intVectintVect == newnew vector()vector();;

    //declare//declare withoutwithout sizesize

    vectorvector list=newlist=new vector(vector(33));;

    //// declaringdeclaring withwith sizesize

    Vectors Advantages over arrays

  • 8/7/2019 Java Evolution

    88/258

    VectorsAdvantages over arrays11.. ItIt isis convenientconvenient aa numbernumber ofof advantagesadvantages overover

    arrayarray..22.. AA vectorvector cancan bebe usedused toto storestore aa listlist ofof objectsobjects

    thatthat maymay varyvary inin sizesize..

    33.. WeWe cancan addadd deletedelete objectsobjects fromfrom thethe listlist asasandand whenwhen requiredrequired..

    AA majormajor constraintconstraint inin usingusing vectorsvectors isis thatthat wewe

    cancan notnot directlydirectly storestore simplesimple datadata typetype inin aa

    vectorvector;; wewe cancan onlyonly storestore objectsobjects.. Therefore,Therefore, wewe

    needneed toto convertconvert simplesimple typestypes toto objectsobjects.. ThisThis cancan

    usingusing withwith wrapperwrapper classclass..

    Vector Methods

  • 8/7/2019 Java Evolution

    89/258

    Vector Methods

    Method Tasks

    list.addElement(item) Adds the item specified to the list at the end

    list.elementAt(10) Gives the name of the 10th objects

    list.size() Gives the number of objects present

    list.removeElement(item) Removes the specified item from the list

    list.removeElementAt(n) Removes the item stored in the nth position

    of the list

    list.removeAllElements( ) Removes all the elements in the list.

    list.copyInto(array) Copies all items from list to array

    List.insertElementAt(Item, n) Insert the item a nth position

    //Program illustrates the use of arrays, string and vectors. This

  • 8/7/2019 Java Evolution

    90/258

    program converts a string vector into an array of strings and

    displays the strings.

    import java.util.*; //importing vector classclass languageVector

    {

    public static void main (String args[ ])

    {

    Vector list =new Vector();

    int length=args.length;

    for(int i=0;i

  • 8/7/2019 Java Evolution

    91/258

    list.insertElementAt( COBOL , 2);

    int size=list.size();

    String listArray[]=new String[size];list.copyInto(listArray);

    System.out.println(List of languages);

    for(int i=0;i

  • 8/7/2019 Java Evolution

    92/258

    WrapperClasses

    AsAs pointedpointed outout earlier,earlier, vectorsvectors

    cannotcannot handlehandle primitiveprimitive datadata typestypeslikelike int,int, float,float, long,long, charchar andand

    doubledouble.. PrimitivePrimitive datadata typestypes maymaybebe convertedconverted intointo objectobject typestypes byby

    usingusing thethe wrapperwrapper classesclasses

    containedcontained inin thethe javajava..langlangpackagepackage..

    Wrapper Classes for Converting Simple Types

  • 8/7/2019 Java Evolution

    93/258

    WrapperClasses forConverting Simple Types

    Simple Type Wrapper Class

    boolean boolean

    Char Character

    double Double

    float Float

    int Integer

    long Long

    The wrapper classeshave a number of uniquemethods

    f h dli i i i d d bj Th

  • 8/7/2019 Java Evolution

    94/258

    forhandling primitive data types and objects. There are

    listed in the following tables.

    Converting PrimitiveNumbers to objectsNumber using

    Constructormethods

    Constructor Calling Conversion Action

    Integer IntVal=new Integer(i); Primitive integer to integer object

    Float FloatVal= new Float(f); Primitive Float to Float object

    Double DoubleVal=newDouble(d) Primitive Double to Double object

    Long LongVal=new Long(l); Primitive long to long object

    Note: i, f, d and l are primitive data values denoting int,

    float, double, and long data types. They may be

    constants or variables.

    Converting Object Numbers to Primitive Numbers

  • 8/7/2019 Java Evolution

    95/258

    Converting ObjectNumbers to PrimitiveNumbers

    using typeValue()method

    Method Calling Conversion Action

    Int i=intVal.intValue(); Object to primitive integer

    Float f=FloatVal.floatValue() Object to primitive float

    Long l=longVal.longValue(); Object to primitive long

    Double d= DoubleVal.DoubleValue(); Object to primitive Double

    Note: i, f, d and l are primitive data values denoting int,

    float, double, and long data types. They may be

    constants or variables.

    C ti N b t St i U i t St i () M th d

  • 8/7/2019 Java Evolution

    96/258

    ConvertingNumbers to Strings Using to String() Method

    Method Calling Conversion Action

    Str=Integer.toString(i) Primitive integer to string

    Str=Float.toString(f) Primitive float to string

    Str=Double.toString(d) Primitive double to string

    Str=Long.toString(l) Primitive long to string

    Note: i, f, d and l are primitive data values denoting int,

    float, double, and long data types. They may be

    constants or variables.

    Converting String Objects toNumeric Objects Using the

  • 8/7/2019 Java Evolution

    97/258

    C e g S g O jec s e c O jec s Us g e

    Static Method ValueOf()

    Method Calling Conversion Action

    DoubleVal=Double.Valueof(str); Converts string to Double objects

    FloatVal=Float.ValueOf(str); Converts string to Float object

    IntVal=Integer.Valueof(str); Converts string to integer object

    LongVal=Long.ValueOf(str); Converts string to Long object

    ConvertingNumeric Strings to PrimitiveNumbers Using

  • 8/7/2019 Java Evolution

    98/258

    g g g

    Parsing Methods

    Method Calling Conversion Action

    Int =Integer.parseInt(str); Converts string to primitive integer

    long i=Long.parseLong(str); Converts string to primitive long

    parseInt() and parseLong( )methods throw a numberformatException if the value of the str does not

    represent an integer.

    //Use of wrapper class methods

  • 8/7/2019 Java Evolution

    99/258

    import java.io.*;

    class Invest

    {

    public static void main (String args[ ])

    {

    float principalAmount=newFloat(0); //Converting number to object

    float intrestRate=new float(0);

    int numYears=0;

    try

    {

    DataInputStream in=new DataInputStream(System.in);

    System.out.print(Enter Principal Amount:);

    System.out.flush();

    String principalString=in.readLine();

    principalAmount=Float.valueOf(principalString);

  • 8/7/2019 Java Evolution

    100/258

    // String object to number object

    System.out.print(EnterInterest Rate:);

    System.out.flush();

    String interestString=in.readLine();

    interestRate=Float.valueOf(interestString);

    System.out.print(Enter Number Of Years:);

    System.out.flush();

    String yearsString=in.readLine();

    numYears=Integer.parseInt(yearsString); //Numeric strings to numbers

    } //Try brace closing

    Catch (IOException e) //Exception Handling

    {

    System.out.println(I/O Error);

    System.exit(1);

    }

    Float value=loan(principalAmount.floatvalue(),interestRate.floatValue(),

    numYears);

  • 8/7/2019 Java Evolution

    101/258

    numYears);

    printline();

    System.out.println(final Value=+value);

    Printline();

    } //main function closing Brace

    static float loan(float p, float r, int n) //User definedFunction

    {

    int year=1;float sum=p;

    while(year

  • 8/7/2019 Java Evolution

    102/258

    Co pos te atatypesTheThe datatypedatatype thatthat areare basedbased onon

    fundamentalfundamental oror primitiveprimitive datatypes,datatypes, areareknownknown asas CompositeComposite DatatypesDatatypes.. SinceSince

    thesethese datatypesdatatypes areare createdcreated byby users,users, thesethese

    areare alsoalso knownknown asas UserUser--DefinedDefined DatatypesDatatypes..ClassClass::--

    sincesince thesethese datatypesdatatypes areare createdcreated

    throughthrough classes,classes, wewe shallshall bebe exploringexploringhowhow classesclasses formform thethe platformsplatforms forfor

    creatingcreating useruser--defineddefinedtypestypes..

    Defining aClass

    AA ll ii d fi dd fi d dd i hi h

  • 8/7/2019 Java Evolution

    103/258

    AA classclass isis aa useruser defineddefined datadata typetype withwith aa

    templatetemplate thatthat servesserves toto definedefine itsits propertiesproperties..

    syntaxsyntax::

    classclass class_nameclass_name

    {{

    datadata membermember;;

    membermember functionfunction;;

    }}

    OnceOnce thethe classclass typetype hashas beenbeen defined,defined, wewe cancan createdcreatedvariablesvariables ofof thatthat typetype usingusing declarationsdeclarations thatthat areare

    similarsimilar toto thethe basicbasic declarationsdeclarations.. InIn java,java, thesethese

    variablesvariables areare termedtermed asas instancesinstances ofof classes,classes, whichwhich areare

    thethe actualactual objectobject..

    JavaAccess Specifier

    AA M difiM difi

  • 8/7/2019 Java Evolution

    104/258

    AccessAccess ModifiersModifiers

    oo

    PrivatePrivateoo ProtectedProtected

    oo DefaultDefault

    oo PublicPublicPublicPublic accessaccess modifiermodifier::-- Fields,Fields, methodsmethods andand

    constructorsconstructors declareddeclared publicpublic (least(least restrictive)restrictive)

    withinwithin aa publicpublic classclass areare visiblevisible toto anyany classclass ininthethe javajava program,program, whetherwhether thesethese classesclasses areare inin

    thethe samesame packagepackage oror inin anotheranother packagepackage..

    JavaAccess Specifier

  • 8/7/2019 Java Evolution

    105/258

    PrivatePrivate accessaccess modifiermodifier::-- thethe privateprivate (most(most

    restrictive)restrictive) fieldsfields oror methodsmethods cannotcannot bebe usedused forfor

    classesclasses andand interfacesinterfaces.. Fields,Fields, methodsmethods oror

    constructorsconstructors declareddeclared privateprivate areare strictlystrictly

    controlled,controlled, whichwhich meansmeans theythey cannotcannot bebe accessesaccesses

    byby anywhereanywhere outsideoutside thethe enclosingenclosing classclass..NoteNote::--

    AA standardstandard designdesign strategystrategy isis toto makemake allall

    fieldsfields privateprivate andand provideprovide publicpublic gettergettermethodsmethods forfor themthem..

    JavaAccess Specifier

  • 8/7/2019 Java Evolution

    106/258

    protectedprotected accessaccess modifiermodifier::-- TThehe protectedprotected

    fieldsfields oror methodsmethods cannotcannot bebe usedused forfor classesclasses andand

    interfacesinterfaces.. ItIt alsoalso cannotcannot bebe usedused forfor fieldsfields andand

    methodsmethods withinwithin anan interfaceinterface.. Fields,Fields, methodsmethods

    andand constructorsconstructors declareddeclared protectedprotected inin aa

    superclasssuperclass cancan bebe accessedaccessed onlyonly byby subclassessubclasses ininotherother packagespackages..

    classesclasses inin thethe samesame packagepackage cancan alsoalso accessaccess

    protectedprotected fields,fields, methodsmethods andand constructorsconstructorsasas well,well, eveneven ifif theythey areare notnot aa subclasssubclass ofof

    thethe protectedprotected membersmembers classclass

    JavaAccess Specifier

    d f ld f l difidifi JJ

  • 8/7/2019 Java Evolution

    107/258

    defaultdefault accessaccess modifiermodifier::-- JavaJava

    provide

    sprovide

    s aade

    fau

    ltde

    fau

    lt spe

    cifie

    rspe

    cifie

    rw

    hichw

    hich isisusedused whenwhen nono acccessacccess modifiermodifier isis

    presentpresent.. AnyAny class,class, field,field, methodmethod oror

    constructorconstructor thatthat hashas nono declareddeclared

    accessaccess modifiermodifier isis accessibleaccessible onlyonly byby

    classessclassess inin thethe samesame packagepackage..

    NoteNote::TheThe defaultdefault modifiermodifier isis notnot usedused forfor

    fieldsfields andand methodsmethods withinwithin anan

    interfaceinterface..

    //Application of classes and objects

  • 8/7/2019 Java Evolution

    108/258

    class rectangle

    {

    int length, width; //Declaration of variables

    void getData(int x, int y) //Definition of method

    {

    length=x;

    width=y;

    }

    int rectArea()

    {

    int area = length * width;

    return(area);

    }

    }

    //Program Continue

    Class RectArea

  • 8/7/2019 Java Evolution

    109/258

    {

    public static void main (String args[ ])

    {

    int area1, area2;

    Rectangle rect1=new Rectangle();

    Rectangle rect2=new Rectangle();rect1.length=15;

    rect2.width=10;

    area1=rect1.length*rect1.width;

    rect2=rect2.rectArea();System.out.println(Area1=+area1);

    System.out.println(Area2=+area2);

    }

    }

    //A simple Class Example.

    l b

  • 8/7/2019 Java Evolution

    110/258

    class box

    {

    double width;

    double height;

    double depth;

    void volume()

    {

    System.out.print( Volume is );

    System.out.println(Width * height * depth );

    }

    }

    //Program Continue

    Class boxDemo3

  • 8/7/2019 Java Evolution

    111/258

    {

    public static void main (String args[ ])

    {

    box mybox1=new box();

    box mybox2=new box();

    //assign values to mybox1s instance variables

    mybox1.width=10;

    mybox1.height=20;

    mybox1.depth=15;

    //assign different values to mybox2s instance variablesmybox2.width=3;

    mybox2.height=6;

    mybox2.depth=9;

    //display volume of first box

  • 8/7/2019 Java Evolution

    112/258

    Mybox1.volume();

    //display volume of second box

    mybox2.volume();

    }

    }

    Constructor

  • 8/7/2019 Java Evolution

    113/258

    JavaJava supportssupports aa specialspecial typetype ofof

    method,method, calledcalled aa constructor,constructor, thatthatenablesenables anan objectobject toto initializeinitialize itselfitself

    whenwhen itit isis createdcreated..

    SomeSome rulesrules asas followsfollows..

    ConstructorsConstructors havehave thethe samesame namename asas thethe

    classclass itselfitself.. TheyThey dodo notnot specifyspecify aa returnreturn type,type, notnot eveneven voidvoid..

    ThisThis isis becausebecause theythey returnreturn thethe instanceinstance ofof thethe

    classclass itselfitself..

    Constructor

  • 8/7/2019 Java Evolution

    114/258

    ThereThere areare ThreeThree typestypes constructorconstructor

    defaultdefault constructorconstructor

    ParameterizedParameterized constructorconstructor CopyCopy constructorconstructor

    //Application of classes and objects with constructor

    class rectangle

  • 8/7/2019 Java Evolution

    115/258

    class rectangle

    {

    int length, width; //Declaration of variables

    rectangle(int x , int y) //Constructor method

    {

    length=x;

    width=y;

    }

    int rectArea()

    {

    int area = length * width;

    return(area);

    }

    }

    //Program Continue

  • 8/7/2019 Java Evolution

    116/258

    Class RectArea

    {public static void main (String args[ ])

    {

    Rectangle rect1=new Rectangle(15, 10); //Calling Constructor

    int area1=rect1.rectArea();

    System.out.println(Area1= +area1);

    }

    }

    Methods Overloading

  • 8/7/2019 Java Evolution

    117/258

    InIn javajava itit isis possiblepossible toto createcreate methodsmethods

    thatthat havehave samesame name,name, butbut differentdifferentparameterparameter listslists andand differentdifferent

    definitionsdefinitions.. ThisThis isis calledcalled methodmethod

    overloadingoverloading.. MethodMethod overloadingoverloading isisusedused whenwhen objectsobjects areare requiredrequired toto

    performperform similarsimilar taskstasks butbut usingusing

    differentdifferent inputinput parametersparameters..

    //method overloading

    class Room

  • 8/7/2019 Java Evolution

    118/258

    {

    float length;

    float breadth;

    Room(float x, float y) //constructor 1

    {

    length=x; breadth=y;

    }Room (float x) //constructor 2

    {

    length=breadth=x;

    }

    int area()

    {

    return(length*braadth);

    }

    Here, we are overloading the constructor

  • 8/7/2019 Java Evolution

    119/258

    method Room(). An object representing a

    rectangular room will be created asRoom room1 = new room (25.0, 15.0);

    //using constructor1

    On the other hand, if the room is square,

    then we may create the corresponding

    object as.

    Room room2 = new room (20.0);

    //using constructor1

    Static MembersStatic Members

  • 8/7/2019 Java Evolution

    120/258

    LetLet usus assumeassume thatthat wewe wantwant toto definedefine aa

    membermember thatthat isis commoncommon toto allall thethe objectsobjectsandand accessedaccessed withoutwithout usingusing aa particularparticular

    objectobject.. ThatThat is,is, thethe membermember belongsbelongs toto thethe

    classclass asas aa wholewhole ratherrather thanthan thethe objectsobjectscreatedcreated fromfrom thethe classclass.. SuchSuch membermember cancan bebe

    defineddefined asas followsfollows..

    staticstatic intint countcount;;

    staticstatic intint max(intmax(int x,x, intint y)y);;

    //Defining and using static memebers

    class Mathoperation

    {

  • 8/7/2019 Java Evolution

    121/258

    {

    static float mul(float x, float y)

    {

    return x*y;

    }

    static float divide(float x, float y)

    {

    return x/y;

    }}

    class Mathapplication

    {

    public static void main(String args[])

    {

    float a=Mathoperation.mul(4.0,5.0);float b=Mathoperation.divide(a,2.0);

    System.out.println(b= +b);

    }

    }

    //Nesting of methods

    class Nesting

    {

  • 8/7/2019 Java Evolution

    122/258

    {

    int m, n;

    Nesting (int x, int y) //constructor method

    {

    m = x;

    n = y;

    }

    int largest()

    {if (m>=n)

    return(m);

    else

    return(n);

    }

    void display(){

    int large=largest(); //calling a method

    System.out.println(Largest value =+large);

    }

    }

    //Program is continue

    l N ti T t

  • 8/7/2019 Java Evolution

    123/258

    class NestingTest

    {

    public static void main(String args[])

    {

    Nesting nest= new Nesting (50, 40);

    nest.display();

    }

    }

    Inheritance: Extending A ClassInheritance: Extending A Class

  • 8/7/2019 Java Evolution

    124/258

    ReusabilityReusability isis yetyet anotheranother aspectaspect ofof OOPOOP

    paradigmparadigm.. JavaJava ClassesClasses cancan bebe reusedreused ininseveralseveral waysways.. ThisThis isis basicallybasically donedone byby

    creatingcreating newnew classes,classes, reusingreusing thethe propertiesproperties

    ofof existingexisting onesones.. TheThe mechanismmechanism ofof derivingderivingaa newnew classclass fromfrom anan oldold oneone isis calledcalled

    InheritanceInheritance.. TheThe oldold classclass knownknown asas thethe basebase

    classclass oror supersuper classclass oror parentparent classclass andand thethenewnew oneone isis calledcalled thethe subclasssubclass oror derivedderived

    classclass oror childchild classclass..

    InheritanceInheritance

  • 8/7/2019 Java Evolution

    125/258

    TheThe inheritanceinheritance allowsallows subclassessubclasses toto inheritinherit

    allall thethe variablesvariables andand methodsmethods ofof theirtheirparentparent classesclasses inheritanceinheritance maymay taketake

    differentdifferent formsforms..

    SingleSingle InheritanceInheritance (Only(Only oneone supersuper class)class)

    MultipleMultiple InheritanceInheritance (several(several supersuper classes)classes)

    HierarchicalHierarchical InheritanceInheritance (One(One supersuper class,class, manymany subclasses)subclasses)

    MultilevelMultilevel InheritanceInheritance (Derived(Derived fromfrom derivedderived class)class)

    InheritanceInheritance

  • 8/7/2019 Java Evolution

    126/258

    Defining a SubclassDefining a Subclass

    AA subclasssubclass isis defineddefined asas followsfollows::

    classclass subclassnamesubclassname extendsextends superclassnamesuperclassname

    {{

    variablesvariables declarationdeclaration;;

    methodsmethods declarationdeclaration;;

    }}

    Note: Java does not directly implement multiple

    inheritance. However, this concept is implemented using

    a secondary inheritance path in the form of interfaces.

    InheritanceInheritanceA

  • 8/7/2019 Java Evolution

    127/258

    A

    B

    Single InheritanceSingle Inheritance

    B C D

    HierarchicalHierarchical InheritanceInheritance

    A

    B

    C

    MultilevelMultilevel inheritanceinheritance

    B

    C

    A

    Multiple InheritanceMultiple Inheritance

    //Application of single Inheritance

    class Room

  • 8/7/2019 Java Evolution

    128/258

    class Room

    {

    int length;int breadth;

    Room(int x, int y) //constructor

    {

    length=x; breadth=y;

    }

    int area()

    {

    return(length*braadth);

    }

    }

    //Program continue

    class BedRoom extends Room

  • 8/7/2019 Java Evolution

    129/258

    class BedRoom extends Room

    {

    int heigth;BedRoom(int x, int y, int z)

    {

    super(x, y)

    height =z;

    }

    int volume()

    {

    return(length*breath*height);

    }

    //Program Continue

  • 8/7/2019 Java Evolution

    130/258

    class InherTest{ public static void main(String args[])

    {

    BedRoom room1=new BedRoom(14, 12, 10);

    int area1=room1.area(); //superclass method

    int volume1=room1.volume(); //base class method

    System.out.println(Area1 = +area1);

    System.out.println(Volume =+volume);

    }

    }

    Subclass ConstructorSubclass Constructor

  • 8/7/2019 Java Evolution

    131/258

    AA subclasssubclass constructorconstructor isis usedused toto constructorconstructor thethe instanceinstance

    variablesvariables ofof bothboth thethe subclasssubclass andand thethe superclasssuperclass.. TheThekeywordkeyword supersuper isis usedused subjectsubject toto thethe followingfollowing conditioncondition..

    SuperSuper maymay onlyonly bebe usedused withinwithin aa subclasssubclass constructorconstructor

    methodmethod

    TheThe callcall toto superclasssuperclass constructorconstructor mustmust appearappear asas thethe

    firstfirst statementstatement withinwithin thethe subclasssubclass constructorconstructor

    TheThe parametersparameters inin thethe supersuper callcall mustmust matchmatch thethe orderorder

    andand typetype ofof thethe instanceinstance variablevariable declareddeclared inin thethe

    superclasssuperclass..

    //Illustration of method overriding

    class Super

  • 8/7/2019 Java Evolution

    132/258

    p

    {

    int x;Super (int x)

    {

    this.x=x;

    }

    void display()

    {

    System.out.println(Super x= +x);

    }

    }

    Class Sub extends Super

    {

  • 8/7/2019 Java Evolution

    133/258

    {

    int y;

    sub (int x, int y){

    super(x);

    this.y=y;

    }

    void display() //method defined again

    {

    System.out.println(Super x= +x);

    System.out.println(Sub y= +y);

    }

    Class OverrideTest

  • 8/7/2019 Java Evolution

    134/258

    {

    public static void main(String args[])

    {

    Sub s1= new Sub(100, 200);

    s1.display();

    }

    }

    Final Variable and MethodFinal Variable and Method

  • 8/7/2019 Java Evolution

    135/258

    AllAll thethe methodmethod andand variablesvariables cancan bebe overriddenoverridden byby

    defaultdefault inin subclassessubclasses.. IfIf wewe wishwish toto preventprevent thethesubclassessubclasses fromfrom overridingoverriding thethe membersmembers ofof thethe

    superclass,superclass, wewe cancan declaredeclare themthem asas finalfinal usingusing thethe

    keywordkeyword finalfinal asas aa modifiermodifier..

    ExampleExample::--

    finalfinal intint SIZE=SIZE=100100;;

    finalfinal voidvoid showstatusshowstatus()()

    {{bodybody ofof functionfunction;;

    }}

    Note:Note:--

  • 8/7/2019 Java Evolution

    136/258

    MakingMaking aa methodmethod finalfinal ensuresensures thatthat thethefunctionalityfunctionality defineddefined inin thisthis methodmethod

    willwill nevernever bebe alteredaltered inin anyany wayway..

    Similarly,Similarly, thethe valuevalue ofof finalfinal variablevariable cancannevernever bebe changedchanged.. FinalFinal variables,variables,

    behavebehave likelike classclass variablesvariables andand theythey dodo

    notnot taketake anyany spacespace onon individualindividualobjectsobjects ofof thethe classclass..

    Final ClassesFinal Classes

    SometimesSometimes wewe maymay likelike toto preventprevent aa classclass beingbeing furtherfurther

  • 8/7/2019 Java Evolution

    137/258

    SometimesSometimes wewe maymay likelike toto preventprevent aa classclass beingbeing furtherfurther

    subclassessubclasses forfor securitysecurity reasonsreasons.. AA classclass thatthat cancan notnot bebe

    subclassedsubclassed isis calledcalled aa finalfinal classclass.. ThisThis isis achievedachieved inin javajava

    usingusing thethe keywordkeyword finalfinal asas followsfollows::

    finalfinalclassclass AclassAclass

    {{bodybody ofofclassclass;;

    }}

    AnyAny attemptattempt toto inheritinherit thesethese classesclasses willwill causecause anan errorerror andand thethecompilercompiler willwill notnot allowallow itit.. DeclaringDeclaring aa classclass finalfinal preventsprevents anyany

    unwantedunwanted extensionsextensions toto thethe classclass.. ItIt alsoalso allowsallows thethe compilercompiler toto

    performperform somesome optimisationsoptimisations whenwhen aa methodmethod of of finalfinal classclass isis

    invokedinvoked..

    Private protected AccessPrivate protected Access

    A field can be declared with two keywordsA field can be declared with two keywords

  • 8/7/2019 Java Evolution

    138/258

    A field can be declared with two keywordsA field can be declared with two keywords

    private and protected together like:private and protected together like:Example:Example:

    private protected int codeNumber;private protected int codeNumber;

    This is gives a visibility level in between the

    protected access and private access. This

    modifier makes the fields visible in all subclassesregardless of what package they are in.

    remember, these field are not accessible by other

    classes in the same package.

    Rules ofThumb for access modifiersRules ofThumb for access modifiers

    GivenGiven belowbelow areare somesome simplesimple rulesrules ofof applyingapplying

  • 8/7/2019 Java Evolution

    139/258

    GivenGiven belowbelow areare somesome simplesimple rulesrules ofof applyingapplying

    appropriateappropriate accessaccess modifiersmodifiers..

    11.. UseUse publicpublic ifif thethe fieldfield isis toto bebe visiblevisible everwhereeverwhere..

    22.. UseUse protectedprotected ifif thethe fieldfield isis toto bebe visiblevisible everywhereeverywhere

    inin thethe currentcurrent packagepackage andand alsoalso subclassessubclasses inin thethe

    otherother packagespackages..33.. UseUse defaultdefault ifif thethe fieldfield isis toto bebe visiblevisible everywhereeverywhere

    inin thethe currentcurrent packagepackage onlyonly..

    44.. UseUse ofof privateprivate protectedprotected ifif thethe fieldfield isis toto bebe visiblevisible

    onlyonly inin subclasses,subclasses, regardlessregardless ofof packagespackages..

    55.. UseUse privateprivate ifif thethe fieldfield isis notnot toto bebe visiblevisible anywhereanywhere

    exceptexcept inin itsits ownown classclass..

    Using abstract ClassesUsing abstract Classes

    AnyAny ClassClass thatthat containscontains oneone oror moremore abstractabstract methodsmethods

  • 8/7/2019 Java Evolution

    140/258

    AnyAny ClassClass thatthat containscontains oneone oror moremore abstractabstract methodsmethods

    mustmust alsoalso bebe declareddeclared abstractabstract.. ToTo declaredeclare aa classclass

    abstract,abstract, youyou simplysimply useuse thethe abstractabstract keywordkeyword inin frontfront ofofthethe classclass keywordkeyword atat thethe beginningbeginning ofof thethe classclass

    declarationdeclaration.. ThereThere cancan bebe nono objectsobjects ofof anan abstractabstract classclass..

    ThatThat is,is, anan abstractabstract classclass cannotcannot bebe directlydirectly instantiatedinstantiated

    withwith thethe newnew operatoroperator.. SuchSuch objectsobjects wouldwould bebe useless,useless,

    becausebecause anan abstractabstract classclass isis notnot fullyfully defineddefined..

    Also,Also, youyou cannotcannot declaredeclare abstractabstract constructors,constructors, oror

    abstractabstract staticstatic methodsmethods.. AnyAny subclasssubclass onon anan abstractabstract

    classclass mustmust eithereither implementimplement allall ofof thethe abstractabstract methodsmethods

    inin thethe superclass,superclass, oror bebe itselfitself declareddeclared abstractabstract..

    //A simple demonstration of abstract.

    abstract class A

    {

  • 8/7/2019 Java Evolution

    141/258

    {

    Abstract void callme();

    //Concrete methods are still allowed in abstract classes

    void callmetoo( )

    {

    System.out.println(Bs implementation of callme.);

    }}

    class AbstractDemo

    {

    public static void main (String args[])

    B b =new B();

    b.callme();

    b.callmetoo():

    }

    }

    //Using abstract methods and classes

    abstract class Figure

  • 8/7/2019 Java Evolution

    142/258

    abstract class Figure

    {

    double dim1;

    double dim2;

    Figure (double a, double b)

    {

    dim1=a;

    dim2=b;

    }//area is now an abstract method

    abstract double area();

    }

    //Program is continue.

    class rectangle extends Figure

  • 8/7/2019 Java Evolution

    143/258

    class rectangle extends Figure

    {

    Rectangle (double a, double b)

    {

    super (a, b);

    }

    double area()

    {

    System.out.println(Inside Area for Rectangle.);return dim1*dim2;

    }

    }

    //Program is continue.

    class Triangle extends Figure

  • 8/7/2019 Java Evolution

    144/258

    g g

    {

    Triangle (double a, double b)

    {

    super (a, b);

    }

    //override area for right triangle

    double area()

    {System.out.println(Inside Area forTriangle.);

    return dim1*dim2/2;

    }

    //Program is continue.

    class AbstractAreas

  • 8/7/2019 Java Evolution

    145/258

    {

    public static void main (String args []){

    //Figure f=newFigure(10,10); //illegal now

    Rectangle r =new Rectangle(9,5);

    Triangle t= newTriangle(10,8);

    Figure figref; //this is ok, no object is created

    figref=r;

    System.out.println(Area is +figref.area());

    figref=t;

    System.out.println(Area is +figref.area());

    }

    }

    Defining InterfacesDefining Interfaces

    AnAn interfaceinterface isis basicallybasically aa kindkind ofof classclass LikeLike

  • 8/7/2019 Java Evolution

    146/258

    AnAn interfaceinterface isis basicallybasically aa kindkind ofof classclass.. LikeLike

    classes,classes, interfacesinterfaces containcontain methodsmethods andandvariablesvariables butbut withwith aa majormajor differencedifference.. TheThe

    differencedifference isis thatthat interfacesinterfaces definedefine onlyonly

    abstractabstract methodsmethods andand finalfinal fieldsfields.. ThisThismeansmeans thatthat interfacesinterfaces dodo notnot specifyspecify anyany

    codecode toto implementimplement thesethese methodsmethods andand datadata

    fieldsfields containcontain onlyonly constantsconstants.. Therefore,Therefore, ititisis thethe responsibilityresponsibility ofof thethe classclass thatthat

    implementsimplements anan interfaceinterface toto definedefine thethe codecode

    forfor implementionimplemention ofof thesethese methodsmethods..

    Syntax for defining InterfaceSyntax for defining Interface

  • 8/7/2019 Java Evolution

    147/258

    interfaceinterface InterfaceNameInterfaceName

    {{

    variablesvariables declarationdeclaration;;

    methodsmethods declarationdeclaration;;

    }}

    HereHere InterfaceInterface isis thethe keykey wordword andand

    InterfaceNameInterfaceName isis anyany validvalid javajava variable(Justvariable(Just

    likelike classclass names)names)..

    defining Interfacedefining Interface

  • 8/7/2019 Java Evolution

    148/258

    NOTENOTE:: ThatThat allall variablesvariables areare

    declareddeclared asas constantsconstants.. MethodsMethods

    declarationdeclaration willwill containcontain onlyonly aa listlist ofof

    methodsmethods withoutwithout anyany bodybodystatementsstatements..

    ExampleExample::--returnreturn--typetype methodnamemethodname11 ((parameter_listparameter_list));;

    HereHere isis anan exampleexample ofof anan interfaceinterface definitiondefinition thatthat

    containscontains twotwo variablesvariables andand oneone methodmethod

  • 8/7/2019 Java Evolution

    149/258

    interfaceinterface itemitem

    {{

    staticstatic finalfinal intint codecode ==10011001;;

    staticstatic finalfinal StringString name=Fanname=Fan;;voidvoid display()display();;

    }}

    Note: That the code for the method is not included in theinterface and the method declaration simply ends with a

    semicolon. The class that implements this interface must

    define the code for the method

    Extending InterfacesExtending InterfacesLikeLike classesclasses interfacesinterfaces cancan alsoalso bebe extendedextended ThatThat

  • 8/7/2019 Java Evolution

    150/258

    LikeLike classes,classes, interfacesinterfaces cancan alsoalso bebe extendedextended.. ThatThat

    is,is, anan interfaceinterface cancan bebe subsub interfacedinterfaced fromfrom otherotherinterfacesinterfaces.. TheThe newnew subsub interfaceinterface willwill inheritinherit allall

    thethe membersmembers ofof thethe subsub interfaceinterface inin thethe mannermanner

    similarsimilar toto subclassessubclasses.. ThisThis isis achievedachieved usingusing thethe

    keywordkeyword extendsextends asas shownshown belowbelow::

    ExampleExample

    interfaceinterface namename22 extendsextends namename11

    {{

    bodybody ofof namename22

    }}

    Extending InterfacesExtending InterfacesExampleExample::

  • 8/7/2019 Java Evolution

    151/258

    ExampleExample::

    interfaceinterface ItemConstantsItemConstants{{

    intint codecode 10011001;;

    StringString Name=FANName=FAN;;

    }}

    interfaceinterface ItemMethodsItemMethods

    {{

    voidvoid display()display();;

    }}

    Example ContinuedExample Continued

  • 8/7/2019 Java Evolution

    152/258

    pp

    Interface item extendsInterface item extends ItemConstantsItemConstants,, ItemMethodsItemMethods

    {{

    ..

    ....

    ..

    }}

    Implementing InterfaceImplementing InterfaceInterfacesInterfaces areare usedused aa superclassessuperclasses whosewhose

  • 8/7/2019 Java Evolution

    153/258

    InterfacesInterfaces areare usedused aa superclassessuperclasses whosewhose

    propertiesproperties areare inheritedinherited byby classesclasses.. ItIt isis thereforethereforenecessarynecessary toto createcreate aa classclass thatthat inheritsinherits thethe givengiven

    interfaceinterface.. ThisThis isis donedone asas followsfollows::

    ExampleExample::

    classclass classnameclassname implementsimplements interfacenameinterfacename

    {{

    bodybody ofof classnameclassname;;

    }}

    HereHere thethe classclass classnameclassname implementsimplements thethe interfaceinterface

    interfancenameinterfancename..AA moremore generalgeneral formform ofof implementationimplementation

    maymay looklook likelike thisthis::

    //Implementing interfaces

    interface Area // interface defined

  • 8/7/2019 Java Evolution

    154/258

    {

    final static float pi =3.14F;float compute (float x, float y);

    }

    class Rectangle implements Area //Interface Implemented

    {

    public float compute (float x, float y)

    {

    return(x*y);

    }

    }

    //Program continue..

    class Circle implements Area

    {

  • 8/7/2019 Java Evolution

    155/258

    {

    public float compute (float x, float y){

    return(pi*x*y);

    }

    }

    class InterfaceTest

    {

    public static void main(String args[])

    {

    Rectangle rect=new Rectangle();

    Circle cir =new Circle();

    Area area; //Interface Object

    //Program continue..

    area rect; //interface Object

    i l ( f l ( ))

  • 8/7/2019 Java Evolution

    156/258

    System.out.println(Area of Rectangle =+area.compute(10, 20));

    // area refers to cir objectarea = cir;

    System.out.println(Area of Rectangle =+area.compute(10, 0));

    }

    }

    The output is as follows:The output is as follows:

    Area of Rectangle =200;Area of Rectangle =200;

    Area of Circle =314;Area of Circle =314;

    //Implementing multiple interfaces

    class student

  • 8/7/2019 Java Evolution

    157/258

    {

    int rollnumber;

    void getNumber(int n)

    {

    rollNumber=n;

    }

    void putNumber()

    {System.out.println(Roll no: + rollnumber);

    }

    }

    //program Continue

    class Test extends Student

    {

  • 8/7/2019 Java Evolution

    158/258

    {

    float part1, part2;void getMarks (flaot m1, float m2)

    {

    part1=m1;

    part2=m2;

    }

    void putMarks()

    { System.out.println(Marks Obtained );

    System.out.println(Part 1= +part1);

    System.out.println(Part 2= +part2);

    }

    }

    //program Continue

    interface Sports

  • 8/7/2019 Java Evolution

    159/258

    {

    float sportwt = 6.0F;

    void putwt();

    }

    class results extends Test implements Sports

    {

    float total;

    public void putwt(){

    System.out.println(Sports Wt = +sportwt);

    }

    //program Continue

    void display()

  • 8/7/2019 Java Evolution

    160/258

    void display()

    {

    total=part1+part2+sportwt;

    putNumber();

    putMarks();

    putwt();

    System.out.println(Total score= +total);}

    }

    //program Continue

    class Hybrid

  • 8/7/2019 Java Evolution

    161/258

    y

    {public static void main (String args[])

    {

    Results student1=new Results();student1.getnumber(1234);

    student1.getMarks(27.5F,33.0F);

    student1.display();}

    }

    //program Continue

  • 8/7/2019 Java Evolution

    162/258

    Output of the ProgramRollno: 1234Rollno: 1234

    Marks ObtainedMarks Obtained

    part1=27.5part1=27.5part2=33part2=33

    Sports wt=6;Sports wt=6;

    total Score=66.5total Score=66.5

    Java APIPackagesJava APIPackagesJavaJava APIAPI providesprovides largelarge numbernumber ofof classesclasses

  • 8/7/2019 Java Evolution

    163/258

    pp gg

    groupedgrouped intointo differentdifferent packagespackages accordingaccording totofunctionalityfunctionality.. MostMost ofof thethe timetime wewe useuse packagespackages

    availableavailable withwith thethe javajava APIAPI..

    Java System Packages and their ClassesJava System Packages and their Classes

    Language support classes. These are classes that java compiler itself

    uses and therefore they are automatically imported. They include

  • 8/7/2019 Java Evolution

    164/258

    Java.langJava.languses and therefore they are automatically imported. They include

    classes for primitive types, strings, math functions, threads and

    exception

    java.utiljava.util

    Language utility classes such as vectors, date etc.

    Java.io

    Input/output support classes. They provide facilities for the input and

    output of data.

    Java.awt

    Set of classes for implementing graphical user interface. They include

    classes for windows, buttons, lists. Menus and so on.

    Java.net

    Classes for networking. They include classes for communicating with

    local computers as well as with internet servers.

    Java.applet

    Classes for creating and implementing applets.

    //The listing below show a package named package1

    containing a single class ClassA

  • 8/7/2019 Java Evolution

    165/258

    package package1;

    Public class ClassA

    {

    public void displayA(){

    System.out.println(Class A);

    }

    }

  • 8/7/2019 Java Evolution

    166/258

    StaticImportStaticImport

    StaticStatic importimport isis anotheranother languagelanguage

  • 8/7/2019 Java Evolution

    167/258

    StaticStatic importimport isis anotheranother languagelanguage

    featurefeature.. ThisThis featurefeature eliminateseliminates thetheneedneed ofof qualifyingqualifying aa staticstatic membermember

    withwith thethe classclass namename.. thethe staticstatic importimport

    declarationdeclaration isis similarsimilar toto thatthat ofof importimport..

    WeWe cancan useuse thethe importimport statementstatement toto

    importimport classesclasses fromfrom packagespackages andand useusethemthem withoutwithout qualifyingqualifying thethe packagepackage..

    //Use of static import

    Import static java.lang.Math.*;

    public class mathop

  • 8/7/2019 Java Evolution

    168/258

    public class mathop

    {public static void circle (double r)

    {

    double area=PI*r*r;

    System.out.println(The Area of circle is :+area);}

    public static void main(String args[])

    {

    mathop obj =new mathop();

    obj.circle(2,3);

    }

    }

    Multithreaded ProgrammingMultithreaded ProgrammingMultithreadingMultithreading isis aa conceptualconceptual programmingprogramming

  • 8/7/2019 Java Evolution

    169/258

    paradigmparadigm wherewhere aa program(process)program(process) isis divideddivided

    intointo twotwo oror moremore subprogaramssubprogarams (processes),(processes),

    whichwhich cancan bebe implementedimplemented atat thethe samesame timetime inin

    parallel,parallel, forfor example,example, oneone subprogramsubprogram cancan displaydisplay

    anan animationanimation onon thethe screenscreen whilewhile anotheranother maymaybuildbuild thethe nextnext animationanimation toto bebe displayeddisplayed.. ThisThis isis

    somethingsomething similarsimilar toto dividingdividing aa tasktask intointo subtaskssubtasks

    andand assigningassigning themthem toto differentdifferent peoplepeople forforexecutionexecution independentlyindependently andand simultaneouslysimultaneously..

    ThreadThreadAA th dth d ii i ili il tt th tth t

  • 8/7/2019 Java Evolution

    170/258

    AA threadthread isis similarsimilar toto aa programprogram thatthat

    hashas singlesingle flowflow ofof controlcontrol .. ItIt hashas

    beginning,beginning, aa body,body, andand anan end,end, andand

    executesexecutes commandscommands sequentiallysequentially.. InInfact,fact, allall mainmain programsprograms inin ourour

    earlierearlier examplesexamples cancan bebe calledcalled

    singlesingle--threadedthreaded programsprograms..

    Creating ThreadCreating Thread

    CreatingCreating threadsthreads inin javajava isis simplesimple

  • 8/7/2019 Java Evolution

    171/258

    CreatingCreating threadsthreads inin javajava isis simplesimple..

    ThreadsThreads areare implementedimplemented inin thethe formformofof objectsobjects thatthat containcontain aa methodmethod calledcalled

    run()run().. TheThe run()run() methodmethod isis thethe heartheart

    andand soulsoul ofof anyany threadthread.. ItIt makesmakes upup thethe

    entireentire bodybody ofof threadthread andand isis thethe onlyonly

    methodmethod inin whichwhich thethe threadsthreads behaviorbehaviorcancan bebe implementedimplemented.. AA typicaltypical run()run()

    wouldwould appearappear asas followfollow..

    public void run()

    {

  • 8/7/2019 Java Evolution

    172/258

    .....

    (Statements for implementing thread)

    }

    The run() method should be invoked by an object of the concerned

    thread. This can achieved by creating the thread and initiating itwith the help of another thread method called start().

    1. By Creating Thread classBy Creating Thread class

    Define a class that extends thread class and override its run()

    method with the code required by the thread.2. By Converting class to threadBy Converting class to thread

    interface has only one method, run(), that is to be defined in

    the method with the code to be executed by the thread.

    Extending the Thread ClassExtending the Thread Classwewe cancan makemake ourour class,class, runnablerunnable asas threadthread byby

  • 8/7/2019 Java Evolution

    173/258

    extendingextending thethe classclass javajava..langlang..ThreadThread.. ThisThis givesgives usus

    accessaccess toto allall thethe threadthread methodsmethods directlydirectly.. ItIt

    includesincludes thethe followingfollowing stepssteps..

    11.. DeclareDeclare thethe classclass asas extendingextending thethe ThreadThread

    classclass..

    22.. ImplementImplement thethe run()run() methodmethod thatthat isis responsibleresponsible forfor

    executingexecuting thethe sequencesequence ofof codecode thatthat thethe threadthread willwill

    executeexecute..33.. CreateCreate aa threadthread objectobject andand callcall thethe start()start() methodmethod toto

    initiateinitiate thethe threadthread executionexecution..

    //Creating threads using the thread class

    Class A extends Thread

  • 8/7/2019 Java Evolution

    174/258

    Class A extends Thread

    {public void run()

    {

    for( int i=1; i

  • 8/7/2019 Java Evolution

    175/258

    Class B extends Thread

    {public void run()

    {

    for( int j=1; j

  • 8/7/2019 Java Evolution

    176/258

    Class C extends Thread

    {public void run()

    {

    for( int k=1; k

  • 8/7/2019 Java Evolution

    177/258

    Class ThreadTest

    {

    public static void