java unit1

Upload: arunchinnathambi

Post on 25-Feb-2018

264 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/25/2019 Java Unit1

    1/97

    Java An Introduction Programming language developed by Sun Microsystems in 1991.

    Originally called Oak by James Gosling

    Originally created for consumer electronics ( !" !#$" Mobile

    P%one" etc.&

    'nternet and eb )as *ust emerging" so Sun turned it into a

    language of 'nternet Programming.

    Pure Ob*ect oriented language

    Java is a )%ole platform" )it% a %uge library" containing lots of

    reusable code" and an e+ecution environment t%at provides

    services suc% as

    security

    portability across operating systems

    automatic garbage collection.

    1

  • 7/25/2019 Java Unit1

    2/97

    Need for Java Many di,erent types of controllers )it% di,erent set of #P- are

    used in electronic devices.

    %e problem )it% # and # is t%at designed to be compiled for a

    speci/c target.

    0n attempt to solve t%ese problems" Gosling and ot%ers began

    )ork on a portable" platformindependent language t%at on avariety of #P-s under di,ering environments.

    Second force )as t%e introduction of orld )ide )eb demand a

    language t%at could useful in creating portable application.

    2

  • 7/25/2019 Java Unit1

    3/97

    Java White Paper Buzzwords Simple

    Ob*ect Oriented tec%ni2ue for programming t%at focuses on t%edata (3 ob*ects& and on t%e interfaces to t%at ob*ect.

    Portable

    0rc%itecture 4eutral 5y generating bytecode instructions" make ite+ecutable on many processors" given t%e presence of t%e Javaruntime system.

    'nterpreted Java interpreter can e+ecute Java bytecodes directlyon any mac%ine.

    4et)orkSavvy Java %as an e+tensive library of routines for coping)it% #P6'P protocols like 7P and 8P.

    7ig% Performance J' #ompiler monitor t%e code and optimi:e t%e

    code for speed. $obust ;mp%asis on early c%ecking for possible problems" laterdynamic (runtime& c%ecking" and eliminating situations t%at areerrorprone.

    Multit%readed

    Secure intended to be used in net)orked6distributedenvironments. 3

  • 7/25/2019 Java Unit1

    4/97

    Java Milestones

    4

    =ear Milestones

    199> Sun decided to develop a soft)are t%at could be used forconsumer electronics. 0 pro*ect called Green Pro*ectcreated and %ead by James Gosling.

    1991;+plored Possibility of using #" )it% some updatesannounced a ne) language named ?Oak@

    199A

  • 7/25/2019 Java Unit1

    5/97

    Java Applications

    Java is used to develop t)o types of application programE

    Standalone applications

    eb applications (applets&

    5

  • 7/25/2019 Java Unit1

    6/97

    Java EnvironentJ

  • 7/25/2019 Java Unit1

    7/97

    !aple "elloworld application6 Simple 7ello)orld Java application 6

    class test

    K

    public static void main(StringL args&

    K

    System.out.println(?7ello)orld Java@&N

    66 save it as test.*ava

    #ompile E *avac test.*ava

    ;+ecute E *ava test

    7ello)orld Java

    7

  • 7/25/2019 Java Unit1

    8/97

    Process of Buildin# and $unnin# Java Applications

    8

  • 7/25/2019 Java Unit1

    9/97

    !aple Java E%ecution

    9

  • 7/25/2019 Java Unit1

    10/97

    Java is &opiled and Interpreted

    10

  • 7/25/2019 Java Unit1

    11/97

    "ow different fro copiled lan#ua#es'

    11

  • 7/25/2019 Java Unit1

    12/97

    Platfor Independenc(

    12

  • 7/25/2019 Java Unit1

    13/97

    Introduction to J)M J!M is t%e interpreter used to convert t%e byte code to mac%ine

    code on t%e y and e+ecute it.

    5yte code is optimi:ed instruction set )%ic% independent of

    mac%ine.JVM Architecture

    13

  • 7/25/2019 Java Unit1

    14/97

    J)M

    Advantages ;nable *ava program run in protected environment

    rite once" run any)%ere (one si:e /ts all&

    5ro)ser can cac%e t%e do)nloaded code and reuse it later

    14

  • 7/25/2019 Java Unit1

    15/97

    !pot the errors1. 8i+ t%e errors

    #lass

  • 7/25/2019 Java Unit1

    16/97

    !pot the errorsA. 'dentify and /+ t%e errors in t%e follo)ing codeE

    public class elcome

    K

    public void main(string argsL&K

    System.out.println(elcome to JavaT&N

    &

    16

  • 7/25/2019 Java Unit1

    17/97

    Input Processin#

    import *ava.util

    public class 'nput

  • 7/25/2019 Java Unit1

    18/97

    $eadin# Input-sing #onsole class Java.io

    import *ava.util

    public class 'nput

  • 7/25/2019 Java Unit1

    19/97

    19

  • 7/25/2019 Java Unit1

    20/97

    20

  • 7/25/2019 Java Unit1

    21/97

    21

  • 7/25/2019 Java Unit1

    22/97

    22

  • 7/25/2019 Java Unit1

    23/97

    23

    * l ti l f J fil

  • 7/25/2019 Java Unit1

    24/97

    *eclaration rules for a Java file 0 source code /le can %ave only one public class.

    'f t%e source /le contains a public class" t%e /lename must matc%

    t%e public class name. 0 /le can %ave only one package statement" but multiple imports.

    %e package statement (if any& must be t%e /rst (noncomment&

    line in a source /le.

    %e import statements (if any& must come after t%e package and

    before t%e class declaration.

    'f t%ere is no package statement" import statements must be t%e

    /rst (noncomment& statements in t%e source /le. package and import statements apply to all classes in t%e /le.

    0 /le can %ave more t%an one nonpublic class.

    8iles )it% no public classes %ave no naming restrictions.

    24

    &l A difi

  • 7/25/2019 Java Unit1

    25/97

    &lass Access odifiers %ere are t%ree access modi/ersE public" protected" and private.

    %ere are four access levelsE public" protected" default" and private.

    #lasses can %ave only public or default access. 0 class )it% default access can be seen only by classes )it%in t%e

    same package.

    0 class )it% public access can be seen by all classes from all

    packages.

    #lass visibility revolves around )%et%er code in one class can

    #reate an instance of anot%er class

    ;+tend (or subclass&" anot%er class 0ccess met%ods and variables of anot%er class

    25

    Ja a Tokens

  • 7/25/2019 Java Unit1

    26/97

    Java Tokens

    Smallest individual units in a program are kno)n as tokens. %e

    compiler recogni:es t%em for building up e+pressions and

    statements.

    0 Java program is a collection of tokens" comments and )%ite spaces.

    Java language includes /ve types of tokens. %ey areE

    1. 'denti/ers

    A. #omments

    V. Fey)ords

    V. Uiterals

    B. OperatorsC. Separators

    26

    Identifiers

  • 7/25/2019 Java Unit1

    27/97

    Identifiers'denti/ers are programmer designed tokens. %ey are used for

    naming classes" met%ods" variables" ob*ects" labels" packages and

    interfaces in a program. Java identi/ers follo) t%e follo)ing rulesE 'denti/ers must start )it% a letter" a currency c%aracter (W&" or a

    connecting c%aracter suc% as t%e underscore ( X &.

    'denti/ers cannot start )it% a numberT

    0fter t%e /rst c%aracter" identi/ers can contain any combination of

    letters" currency c%aracters" connecting c%aracters" or numbers.

    'n practice" t%ere is no limit to t%e number of c%aracters an

    identi/er can contain. =ou cant use a Java key)ord as an identi/er.

    'denti/ers in Java are casesensitiveN foo and 8OO are t)o di,erent

    identi/ers.

    27

    +e#al and Ille#al identifiers

  • 7/25/2019 Java Unit1

    28/97

    +e#al and Ille#al identifiers

    Legal Identifers

    Illegal identifers

    28

    Nain# &onventions

  • 7/25/2019 Java Unit1

    29/97

    Nain# &onventions 4ames of all public met%ods and instance variables start )it% a

    leading lo)ercase letter. ;+ampleE average" sum

    %en more t%an one )ord are used in a name" t%e second andsubse2uent )ords are marked )it% a leading uppercase letters.

    ;+ampleE dayemperature" /rst

  • 7/25/2019 Java Unit1

    30/97

    &oents#omments %elp programmers to communicate and understand t%e

    program. %ey are not programming statements and t%us are ignored

    by t%e compiler. 'n Java" comments areEUine #omment Statement preceded by t)o slas%es (66&

    5lock #omment Statement enclosed bet)een 6 and 6

    Java

  • 7/25/2019 Java Unit1

    31/97

    Java ,e(words

    31

    Java *efault Access Modifier

  • 7/25/2019 Java Unit1

    32/97

    Java *efault Access Modifier

  • 7/25/2019 Java Unit1

    33/97

    Ei#ht Priitives-

    33

    ;ig%t primitives of *ava areE

    8our of t%em are integer typesN t)o are oatingpoint number typesN one ist%e c%aracter type c%arN and one is a 5oolean type for trut% values.

    *ata .(pes-

  • 7/25/2019 Java Unit1

    34/97

    *ata .(pes-Integer types :

    Float types :

    34

    Character Type

  • 7/25/2019 Java Unit1

    35/97

    Character Type

    'n order to store c%aracter constants in memory. Java provides ac%aracter data type called c%ar. %e c%ar type assumes a si:e of A bytes but"basically" it can %old only a single c%aracter.

    Boolean Type

    5oolean type is used )%en )e )ant to test a particular condition duringt%e e+ecution of t%e program. %ere are only t)o values t%at a boolean typecan takeE true or alse. $emember" bot% t%ese )ords %ave been declared askeywords. 5oolean type is denoted by t%e key)ord boolean and uses onlyone it of storage.

    T!"# C$%V#&'I$%

  • 7/25/2019 Java Unit1

    36/97

    36

    36

    T!"# C$%V#&'I$%

    Type

    Conversion

    Casting

    Operations

    Arithmetic

    Operations

    Ep!icit

    Conversion"mp!icit

    Conversion

    #onvert a data of one type to anot%er before it is used in arit%meticoperations or to store a value of one type into a variable of anot%er type.;+ampleE

    byte b1 3 C>Nbyte bA 3 D>N

    byte bV 3 b1 bAN;rrorE

    ?cannot implicitly covert type int to type byte@int bV 3 b1 bAN 66 4o ;rror

    'n #Z" type conversions take place in t)o )ays1. 'mplicit conversions

    A. ;+plicit conversions

    I(plicit Conversions

  • 7/25/2019 Java Unit1

    37/97

    37

    37

    I(plicit Conversions

    %e conversion can al)ays be performed )it%out any loss of data. 8ornumeric types" t%is implies t%at t%e destination type can fully represent t%erange of t%e source type. 8or e+ample" a s%ort can be converted implicitly to

    an int" because t%e s%ort range is a subset of t%e int range. %erefore"

    s%ort b 3 ICNint a 3 bN

    Java does t%e conversion automatically. 0n implicit conversion is also kno)n

    as automatic type conversion.

    %e process of assigning a smaller type to a larger one is kno)n as)idening or promotion.

    Some ;+amples of implicit conversion areE

    byte +1 3 ICNs%ort +A 3 +1Nint +V 3 +ANlong +B 3 +VNoat +C 3 +BNdecimal +D 3 +BN

    Java &onversion hierarch( chart

  • 7/25/2019 Java Unit1

    38/97

    38

    38

    (

    short

    int

    !ong

    #!oat

    $o%&!e

    &yte

    char

    8 ' &it types

    16 ' &it types

    32 ' &it types

    64 ' &it types

    E%plicit &onversions

  • 7/25/2019 Java Unit1

    39/97

    39

    39

    E%plicit &onversions

    The process o# assigning a !arger type to a sma!!er one is (no)n as norro)ing* The

    norro)ing may res%!t in !oss o# in#ormation*

    There are many conversions that cannot &e imp!icit!y ma$e &et)een types* "# )eattempt s%ch conversions+ the compi!er )i!! give an error message*

    ,or eamp!e+ the #o!!o)ing conversions cannot &e ma$e imp!icit!y-

    int to short

    int to !ong!ong to int

    #!oat to int

    $ecima! to any n%meric type

    any n%meric type to char

    .o)ever+ )e can ep!icit!y carry o%t s%ch conversions %sing the /cast operator* The

    process is (no)n as casting an$ is $one as #o!!o)s-

    t(pe varia/le0 1 2t(pe3 varia/le4

    )aria/les

  • 7/25/2019 Java Unit1

    40/97

    )aria/les!ariables is an identi/er t%at denotes t%e storage location used to store a

    data value.

    !ariable declaration denotes t%ree t%ingsE

    ype of t%e value t%e variable going to store.

    5ased on t%e place of declaration t%e initial value assigned.

    4ame of t%e variable to refer t%e value.

    5ased on t%e type t%e si:e of memory allocation is determined.Rules for variable declaration:

    Variable name must contain numbers, alphabets, and underscore symbol.

    They must not begin with a digit.

    Uppercase and lowercase are distinct. This means that the variable Total isnot the same as total or TOTA.

    !t should not be a "eyword.

    #hite space is not allowed.

    Variable names can be of any length. A variable must be declared before it40

    )aria/le

  • 7/25/2019 Java Unit1

    41/97

    )aria/le%en a variable is assigned a value t%at is too large (in si:e& to bestored" it causes overo). Java does not report )arnings or errors onovero).

    ;+ample E

    int value 3 A1BIB[VDBI 1N 66 value )ill actually be A1BIB[VDB[( causes overo)&

    41

    Java varia/le t(pes

  • 7/25/2019 Java Unit1

    42/97

    Java varia/le t(pes%ree types of variable used in *avaE

    Uocal variables ( declared inside function or construct&

    'nstance variable ( 4on static variable declared inside t%e class and

    accessed using ob*ect& Static variable (declared )it% static modi/er and accessed using

    class name&.

    ;+ampleE

    class !ariableN

    static int b3A>N

    public static void main(StringL ar&

    KString c3?7ello@N

    !ariable

  • 7/25/2019 Java Unit1

    43/97

    Assi#nent !tateents 5 E%pression

    43

    variable can get t%e value using assignment statement or assignmente+pression.

    !alue is assigned using assignment operator

    ;+ample E

    int a 3 1>N

    0n e+pression represents a computation involving values" variables"and operators t%at" taking t%em toget%er" evaluates to a value.

    ;+ampleE

    int +3 C (V 6 A& V AN

    4oteE Java is strongly typed language i.e." variable on t%e left must becompatible )it% t%e data type of t%e value on t%e rig%t.

    &onstants

  • 7/25/2019 Java Unit1

    44/97

    &onstants4amed constants or constant represent permanent data t%at neverc%anges its value" once gets initiali:ed.

    ;+ampleE/nal double pi3 V.1BN

    8inal indicate t%at you can assign to t%e variable once.

    44

    6perators in Java

  • 7/25/2019 Java Unit1

    45/97

    6perators in Java

    0rit%metic operators

    $elational operators

    Uogical operators

    0ssignment operators

    'ncrement and

  • 7/25/2019 Java Unit1

    46/97

    p

    46

    &elational $perators

    Logical$perators

    Bitwise 6perator

  • 7/25/2019 Java Unit1

    47/97

    Bitwise 6perator

    47

    Assign(ent $perator

  • 7/25/2019 Java Unit1

    48/97

    48 48

    0ssignment operators are used to assign t%e value of an e+pression to avariable. #Z %as a set of \s%ort%and] assignment operators )%ic% are used int%e form

    v op) e+p

    v is t%e variablee+p is t%e e+pressionop is t%e binary operator

    v op) e+p is e2uivalent to v 3 v op(e+p&N;+E

    + 3 y 1N is e2uivalent to + 3 + (y 1&

    Advantages*

    . %at appears on t%e left %and side need not be repeated andt%erefore it becomes easier to )rite.

    . %e statement is more concise and easier to read.

    . %e use of s%ort%and operators results in a more e^cient code.

    ncre(en an ecre(en pera or

  • 7/25/2019 Java Unit1

    49/97

    49 49

    %e operators are and

    means 'ncrement Operator means N is e2uivalent to

    a L i 3 1>N i 3 i 1N

    Conditional $perator't i l k t

  • 7/25/2019 Java Unit1

    50/97

    50 50

    't is also kno)n as ernary operator

    Synta+Ee,p-./ e,p-0* e,p-1

    'pecial $perators

    Instanceo $perator

    %e instanceof is an ob*ect reference operator and returns true if t%eob*ect on t%e left %and side is an instance of t%e class given on t%e rig%t %and side. %is operator allo)s us to determine )%et%er t%e ob*ect belongsto a particular class or not.

    ;+ampleE

    person instanceof student

    +ot $perator%e dot operator (.& is used to access t%e instance variables and met%ods

    of class ob*ects.

    ;+ampleE

    person1.age 66$eference to t%e variable age

    person1.salary( & 66$eference to t%e met%od salary( &

    *ecision Ma7in# !tateents

  • 7/25/2019 Java Unit1

    51/97

    #)o types of

  • 7/25/2019 Java Unit1

    52/97

    2 ( 3#onsists of a 5oolean condition follo)ed by one or statement.

    $ynta%:

    if(5ooleanXe+pression&

    K

    66Statements )ill e+ecute if t%e 5oolean e+pression is true

    ;+ampleE Problem statement

    #alculate t%e area of t%e circle in case of radius is positive integer

    class 0reaK

    public static void main(StringL ar&

    K

    Scanner s3ne) Scanner(System.in&N

    int rad3s.ne+t'nt(&N

    if(rad>&K

    System.out.println( ? t%e area is ? (V.1B rad rad&&N

    52

    .wo wa( if stateent

  • 7/25/2019 Java Unit1

    53/97

    (%en t%ere are multiple conditions need to be evaluated t%en )e can use ifelse construct. 'f t%e condition is true one set of statement e+ecutesot%er)ise alternate set get e+ecuted.

    Synta+E

    if (booleane+pression& K

    statement(s&fort%etruecaseN

    else K

    statement(s&fort%efalsecaseN

    53

    Nested if structure

  • 7/25/2019 Java Unit1

    54/97

    4ested if structure come into play )%en t%ere are too many alternateconditions to be evaluated.

    Synta+Eif (booleane+pression&

    K

    if (booleane+pression&

    K

    statement(s&fort%etruecaseN

    else

    K

    statement(s&fort%efalsecaseN

    54

    4 ti i l t t t

  • 7/25/2019 Java Unit1

    55/97

    4esting i2elsestatementi(5ooleane+pression&K

    rueblock statement(S&

    i(5ooleane+pression&Krueblock Statement(s&

    elseK

    8alseblock Statement(s&

    elseK

    8alseblock statement(s&

    else i Ladder*

  • 7/25/2019 Java Unit1

    56/97

    i(conditionX1&StatementX1N

    else i(conditionXA&

    StatementXANelse i(conditionXV&

    StatementXVN..

    . else i(conditionXn&

    StatementXnNelse

  • 7/25/2019 Java Unit1

    57/97

    1.8orgetting 4ecessary 5races

    A. rong Semicolon at t%e if Uine

    57

    &oon errors in !election stateent

  • 7/25/2019 Java Unit1

    58/97

    V. $edundant esting of 5oolean !alues

    B.

  • 7/25/2019 Java Unit1

    59/97

    1. #ode to c%eck )%et%er t%e number entered by user is even or odd number.

    A. 5ody Mass 'nde+ (5M'& is a measure of %ealt% on )eig%t. 't can be calculated bytaking your )eig%t in kilograms and dividing by t%e s2uare of your %eig%t inmeters. %e interpretation of 5M' for people 1D years or older is as follo)sE

    V. #omputing ta+es E %e -nited States federal personal income ta+ is calculatedbased on /ling status and ta+able income. %ere are four /ling statusesE single/lers" married /ling *ointly" married /ling separately" and %ead of %ouse%old. %eta+ rates vary every year. able V.A s%o)s t%e rates for A>>9. 'f you are" say" single)it% a ta+able income of W1>">>>" t%e /rst W["VC> is ta+ed at 1>` and t%e ot%erW1"DC> is ta+ed at 1C`. So" your ta+ is W1">[A.C

    59

    !cenarios

  • 7/25/2019 Java Unit1

    60/97

    Uottery E Suppose you )ant to develop a program to play lottery. %eprogram randomly generates a lottery of a t)odigit number" prompts t%euser to enter a t)odigit number" and determines )%et%er t%e user )insaccording to t%e follo)ing ruleE

    1. 'f t%e user input matc%es t%e lottery in e+act order" t%e a)ard is W1>">>>.

    A. 'f all t%e digits in t%e user input matc% all t%e digits in t%e lottery" t%ea)ard is WV">>>.

    V. 'f one digit in t%e user input matc%es a digit in t%e lottery" t%e a)ard isW1">>>.

    60

    !witch case

  • 7/25/2019 Java Unit1

    61/97

    0 s)itc% statement allo)s a variable to be tested for e2uality against a list of

    values. ;ac% value is called a case" and t%e variable being s)itc%ed on is

    c%ecked for eac% case. 'f statement makes a problem di^cult" )%en too

    many c%oices are t%ere to evaluate in suc% circumstances s)itc% is t%e

    alternative.

    Synta+E

    s)itc%(e+pression&

    K

    case value E

    66Statements

    breakN66optional

    case value E

    66Statements

    breakN66optional

    defaultE66Optional

    66Statements

    61

    T3# '4ITC3 'TAT#M#%T

  • 7/25/2019 Java Unit1

    62/97

    switch(e+pression&K

    casevalueX1E

    blockX1NreakN

    casevalueXAEblockXANreakN

    casevalueXVE

    blockXVNreakN

    deaultE

    defaultXblockreakN

    StatementX+N

    $ules for switch

  • 7/25/2019 Java Unit1

    63/97

    %e s)itc%e+pression must yield a value of c%ar" byte" s%ort" or int type

    and must al)ays be enclosed in parent%eses.

    %e value1" and value4 must %ave t%e same data type as t%e value of t%e

    s)itc%e+pression. 4ote t%at value1" and value4 are constant e+pressions"

    meaning t%at t%ey cannot contain variables" suc% as 1 +.

    %en t%e value in a case statement matc%es t%e value of t%e s)itc%

    e+pression" t%e statements starting from t%is case are e+ecuted until eit%er

    a break statement or t%e end of t%e s)itc% statement is reac%ed.

    %e key)ord break is optional. %e break statement immediately ends t%e

    s)itc% statement.

    %e default case" )%ic% is optional" can be used to perform actions )%ennone of t%e speci/ed cases matc%es t%e s)itc%e+pression.

    %e case statements are c%ecked in se2uential order" but t%e order of t%e

    cases (including t%e default case& does not matter. 7o)ever" it is good

    programming style to follo) t%e logical se2uence of t%e cases and place63

    !cenario

  • 7/25/2019 Java Unit1

    64/97

    Scissorrockpaper gameE %e program randomly generates a number >" 1" orA representing scissor" rock" and paper. %e program prompts t%e user toenter a number >" 1" or A and displays a message indicating )%et%er t%e useror t%e computer )ins" loses" or dra)s.

    'n a ?main@ met%od" generate a random integer bet)een 1 and 1V torepresent t%e possible values in a suit of playing cards.

    -se a ?s)itc%@ statement t%at applies cases to your random integer.

    'f t%e random number is 1" print out ?0ce@ to t%e console.

    'f t%e random number is 11" print out ?Jack@ to t%e console.

    'f t%e random number is 1A" print out ?ueen@ to t%e console.

    'f t%e random number is 1V" print out ?Fing@ to t%e console.%e default case s%ould simply print t%e random integer to t%e console.

    64

    &onditional E%pression

  • 7/25/2019 Java Unit1

    65/97

    %en )e )ant to assign a value to a variable based on certain condition tobe evaluated" t%e )e can use conditional e+pression.

    'ynta,*

    Y3 booleane+pression R e+pression1 E e+pressionAN#,a(ple *

    o /nd t%e biggest of t)o numbersE

    class 5ig

    K

    public static void main(StringL ar&

    K

    int a3'nteger.parse'nt(arL>&N

    int b3'nteger.parse'nt(arL1&N

    if(ab&

    System.out.println ( ? a is big ?&N

    else

    System.out.println ( ? b is big ?&N

    $eplaced byE

    65

    66replaced entire ifstatement

    int res 3 ( a b & R a E b N

    E%ercises

  • 7/25/2019 Java Unit1

    66/97

    .5 &ewrite the ollowing state(ent using a conditional e,pression*

    if (temperature 9>&

    pay 3 pay 1.CN

    elsepay 3 pay 1.1N

    05 4rite a progra( that pro(pts the user to enter the (onth andyear and displays the nu(er o days in the (onth5 6or e,a(ple7 ithe user entered (onth 0 and year 08887 the progra( should displaythat 6eruary 0888 has 09 days5 I the user entered (onth 1 andyear 088:7 the progra( should display that March 088: has 1. days5

    15 4rite a progra( that pro(pts the user to enter an integer andchecks whether the nu(er is divisile y oth : and ;7 or neither o

    the(7 or se a switch state(ent to rewrite the ollowing i state(ent anddraw the ?ow chart or the switch state(ent*

  • 7/25/2019 Java Unit1

    67/97

    if (a 33 1&

    + 3 CN

    else if (a 33 A&

    + 3 1>Nelse if (a 33 V&

    + 3 1DN

    else if (a 33 B&

    + 3 VBN

    ;5 4rite a switch state(ent that assigns a 'tring variale day%a(ewith 'unday7 Monday7 Tuesday7 4ednesday7 Thursday7 6riday7'aturday7 i day is 87 .7 07 17 =7:7 ;7 accordingly5

    @5 &ewrite the ollowing i state(ent using the conditional operator*if (count ` 1> 33 >&

    System.out.print(count QHnQ&N

    else

    System.out.print(count Q Q&N

    67

    +oops

  • 7/25/2019 Java Unit1

    68/97

    Uoop is control structure t%at e+ecutes t%e se2uence statement multiple

    times based on condition. Java supports t%ree di,erent set of iteration

    statements suc% asE

    %ile loop

  • 7/25/2019 Java Unit1

    69/97

    5ased on conditional e+pression inside t%e loop" t%e set of statements gete+ecuted multiple times

    'ynta,*

    initiali:ationN

    )%ile(testXcondition&

    K

    5ody of t%e Uoop

    #,a(ple*

    #ounting of numbers 1 to 1>>

    &&code

    int sum, count'()

    while*count+((-

    sum/'count)

    count//)

    0

    $.O.1*count-)69

    +o4hile loopd %il l i i ti f t% %il l % d %il l t t%

  • 7/25/2019 Java Unit1

    70/97

    do)%ile loop is a variation of t%e )%ile loop. %e do)%ile loop e+ecutes t%eloop body /rst" t%en c%ecks t%e loop continuationcondition to determine)%et%er to continue or terminate t%e loop.

    Syntax :

    do K

    66 Uoop bodyN

    Statement(s&N

    )%ile (loopcontinuationcondition&N

    Tip: Use the do-hile loop if you ha!e state"ents inside the loop

    that "ust #e executed at least once$i"port %a!a$util$Scanner&

    pu#lic class TestDo'hile (

    pu#lic static !oid "ain)String*+ args, (

    int data su" . /&

    Scanner input . ne Scanner)Syste"$in,&Syste"$out$print)0Enter an int !alue )the progra" exits if the inputis /,: 0,&

    data . input$nextInt),&

    su" 1. data&

    Syste"$out$println)0The su" is 0 1 su",&70

    6or Loop0 for loop is a repetition control structure t%at allo s ou to e^cientl rite a

  • 7/25/2019 Java Unit1

    71/97

    0 for loop is a repetition control structure t%at allo)s you to e^ciently )rite aloop t%at needs to e+ecute a speci/c number of times.

    'ynta,*

    for (initiali:ationNtestXconditionNincrement&

    K

    5ody of t%e Uoop

    #,a(ple*

    public class est

    K

    public static void main(String argsL&

    K

    for(int + 31>N + A>N + 3 +1&

    K

    System.out.print(Qvalue of + E Q + &N

    System.out.print(QHnQ&N

    71

    #nhanced or loop'ynta,*

  • 7/25/2019 Java Unit1

    72/97

    'ynta,*

    for(declaration E e+pression&

    K 66Statements

    +eclaration*

    %e ne)ly declared block variable" )%ic% is of a type compatible )it% t%eelements of t%e array you are accessing. %e variable )ill be available )it%int%e for block and its value )ould be t%e same as t%e current array element.

    #,pression*

    %is evaluates to t%e array you need to loop t%roug%. %e e+pression can be

    an array variable or met%od call t%at returns an array.#,a(ple*

    public class est

    K public static void main(String argsL&

    K

    for( String s E args&K

    System.out.println(s&N

    72

    Additional 8eatures of the for +oop&ase 0-

    p 1 09

    &ase -for 2 1 0:::9 F:9 1 039

    &

  • 7/25/2019 Java Unit1

    73/97

    73 73

    p 9

    for 2n 1 :9 n;0n1:9n;01?:9n;19 n1n=0>1@03

    @@@@@@@@@@

    @@@@@@@@@@

    &ase C-

    su 1 :9

    for 2 i 10> i;4: 55 su ;0::9 i==3

    @@@@@@@@@@@

    @@@@@@@@@@@

    &ase D-

    for 2% 1 2=n349 %F:9% 1 %43

    &ase ?-

    @@@@@@@@@

    @@@@@@@@@ 1 ?9

    for 29 G1 0::93

    !(steHoutHprintln239

    1 = ?9

    @@@@@@@@@@@@@@@@

    &ase

  • 7/25/2019 Java Unit1

    74/97

    74

    continueNgotoN

    pulic class BreakContinue4ithLael

    pulic static void (ain'tring argsDEF

    intDE nu(ers) new intDE.887.G70.718H$>T#&*orint i ) 8 inu(ers5length iKKF

    ii 0 )) 8F

    'yste(5out5println$dd nu(er* K i K 7 continue ro( $>T#&laelF

    continue $>T#& H I%%#&*

    orint < ) 8

  • 7/25/2019 Java Unit1

    75/97

    3$ 'rite a code to re!erse the nu"#er using hile loop$

    4$ 5reatest Co""on di!isor: 6et the to input integers #e n3 and

    n4$ 7ou 8no that nu"#er 3 is a co""on di!isor #ut it "ay not #e

    the greatest co""on di!isor$ So you can chec8 hether 8 )for8 4 9

    and so on, is a co""on di!isor for n3 and n4 until 8 is greater

    than n3 or n4$ Store the co""on di!isor in a !aria#le na"ed gcd$

    Initially gcd is 3$ 'hene!er a ne co""on di!isor is found it

    #eco"es the ne gcd$

    9$ ;redicating the Future Tuition: Suppose that the tuition for a

    uni!ersity is e!ery year$

    In ho "any years ill the tuition #e dou#led?

    75

    $eview Kuestions@ l th f ll i d I t B 3// l t l f l

  • 7/25/2019 Java Unit1

    76/97

    @nalyAe the folloing code$ Is count B 3// alays true alays falseor so"eti"es true or so"eti"es false at ;oint @ ;oint and ;ointC?

    int count ' ()

    while *count + ((-

    && 1oint A

    $ystem.out.println*2#elcome to 3ava45n2-)

    count//)

    && 1oint 6

    0 && 1oint 7

    o "any ti"es is the folloing loop #ody repeated? 'hat is theprintout of the loop?

    76

    'hat are the dierences #eteen a hile loop and a do-hile loop?Con!ert the folloing hile loop into a do-hile loop$

  • 7/25/2019 Java Unit1

    77/97

    int sum 3 >N

    int number 3 input.ne+t'nt(&N

    )%ile (number T3 >& K

    sum 3 numberNnumber 3 input.ne+t'nt(&N

    Do the folloing to loops result in the sa"e !alue in su"?

    Can you alays con!ert a hile loop into a for loop? Con!ert the

    folloing hile loop into a for loop5int i 3 1" sum 3 >N

    )%ile (sum 1>>>>& K

    sum 3 sum iN

    iN

    77

  • 7/25/2019 Java Unit1

    78/97

    Suppose the input is 4 9 /$ 'hat is the output of the folloingcode?

    import *ava.util.ScannerNpublic class est K

    public static void main(StringL args& K

    Scanner input 3 ne) Scanner(System.in&N

    int number" ma+N

    number 3 input.ne+t'nt(&Nma+ 3 numberN

    )%ile (number T3 >& K

    number 3 input.ne+t'nt(&N

    if (number ma+&

    ma+ 3 numberN

    System.out.println(Qma+ is Q ma+&N

    System.out.println(Qnumber Q number&N

    78

    'hat is the 8eyord #rea8 for? 'hat is the 8eyord continue for?'ill the folloing progra" ter"inate? If so gi!e the output$

  • 7/25/2019 Java Unit1

    79/97

    The for loop on the left is con!erted into the hile loop on the right$'hat is

    rong? Correct it$

    79

    @fter the #rea8 state"ent is executed in the folloing loop hichstate"ent is executed? Sho the output$

  • 7/25/2019 Java Unit1

    80/97

    for (int i 3 1N i BN i& K

    for (int * 3 1N * BN *& K

    if (i * A&

    breakNSystem.out.println(i *&N

    System.out.println(i&N

    @fter the continue state"ent is executed in the folloing loophich state"ent is executed? Sho the output$

    for (int i 3 1N i BN i& K

    for (int * 3 1N * BN *& K

    if (i * A&continueN

    System.out.println(i *&N

    System.out.println(i&N

    80

    Identify and Gx the errors in the folloing code:public class est K

  • 7/25/2019 Java Unit1

    81/97

    public void main(StringL args&

    K

    for (int i 3 >N i 1>N i&N

    sum 3 iNif (i *&N

    System.out.println(i&

    else

    System.out.println(*&N

    )%ile (* 1>&NK

    *N

    N

    K

    *N )%ile (* 1>&

    81

    'hat is rong ith the folloing code?

  • 7/25/2019 Java Unit1

    82/97

    82

    'rite a progra" that displays all the nu"#ers fro" 3// to 3///ten per line that are di!isi#le #y and H$

    Use a hile loop to Gnd the s"allest integer n such that n4 isgreater than 34///$

    'rite a progra" that reads an integer and displays all its s"allest

    factors in increasing order$ For exa"ple if the input integer is 34/the output should #e as follos: 4 4 4 9 $

    rite a program t%at displays all t%e numbers from 1>> to 1>>>

  • 7/25/2019 Java Unit1

    83/97

    rite a program t%at displays all t%e numbers from 1>> to 1>>>"ten per line" t%at are divisible by C and D.

    -se a )%ile loop to /nd t%e smallest integer n suc% t%at nA isgreater t%an 1A">>>.

    83

    Array 0n array is a data structure )%ic% de/nes an ordered collection of a

  • 7/25/2019 Java Unit1

    84/97

    0n array is a data structure )%ic% de/nes an ordered collection of a/+ed number of %omogeneous data elements

    %e si:e of an array is /+ed and cannot increase to accommodatemore elements

    'n Java" array are ob*ects and can be of primitive data types orreference types

    0ll elements in t%e array must be of t%e same data type

    Creating an Array1.

  • 7/25/2019 Java Unit1

    85/97

    arrayname 3 ne) type Lsi:eN

    ;+amplesE

    number 3 ne) int LCNaverage 3 ne) oat L1>N

    15 +eclaration and Creation in one step

    Synta+E

    type L arrayname 3 ne) type Lsi:eN;+amplesE

    int L number 3 ne) int LCN

    =5 InitialiNation o Arrays

    Synta+E type L arrayname 3 Klist of valuesN

    ;+ampleE

    int L number 3 KVA"BC"VB"CD"VBN

    int L number 3 ne) int LV K1>"A>"V>N

    85

    $ne +i(ensional Array* 0 list of liketyped ele(ents. 8irst create an array variable of t%e desired type

  • 7/25/2019 Java Unit1

    86/97

    8irst create an array variable of t%e desired type. new is a special operator t%at allocates memory. 0ssigning values are based on t%e array variable inde+ ranges from 8 to

    n.N

    o display t%e values in output is also based on inde+.

    class 0rraysK

    public static void main(String argsL&K

    int mont%XdaysLNmont%Xdays 3 ne) intL1ANmont%XdaysL> 3 V1N mont%XdaysLD 3 V1Nmont%XdaysL1 3 A[N mont%XdaysLI 3 V1Nmont%XdaysLA 3 V1N mont%XdaysL[ 3 V>Nmont%XdaysLV 3 V>N mont%XdaysL9 3 V1Nmont%XdaysLB 3 V1N mont%XdaysL1> 3 V>Nmont%XdaysLC 3 V>N mont%XdaysL11 3 V1NSystem.out.println(?0pril %as ? mont%XdaysLV ?days@&N

    $O"* April has 18 days

    class 4umberSortingK

  • 7/25/2019 Java Unit1

    87/97

    public static void main(String argsL&K

    int numberL 3 KCC"B>"[>"DC"I1N

    int n 3 number.lengt%NSystem.out.println(QGiven UistQ&Nfor(int i 3 >NinNi&K

    System.out.println(Q Q numberLi&N

    System.out.print(QHnQ&Nfor(int i 3 >Ni nN i&K

    for(* 3 1N* nN *&K

    if (numberLi number L*&

    Kint temp 3 numberLiNnumberLi 3 numbdfL*NnumberL* 3 tempN

    System.out.println(QSorted listEQ&N

  • 7/25/2019 Java Unit1

    88/97

    for(int i 3 >Ni nNi&K

    System.out.println(Q Q numberLi&N

    System.out.println(Q Q&N

    The PoreachQ loop* 0 po)erful looping construct t%at allo)s repeating for eac% element in an

    array )it%out %aving to con/rm )it% inde+ values.

    'ynta,* orvariale * collectionFstate(ent

    #,* int aDE ) .87087187=87:8Hor int * aF

    'yste(5out5printlnF

    J til A

  • 7/25/2019 Java Unit1

    89/97

    Java5util5Arrays*

    %e

  • 7/25/2019 Java Unit1

    90/97

    ;+Eint L a 3 K1"A"VNint L bN

    b 3 aN

    Two +i(ensional Array

    ">">"K1"1"1N

    class MultiableK

    /nal static int $OS 3 CN

  • 7/25/2019 Java Unit1

    91/97

    /nal static int $OS CN/nal static int #OU-M4S 3 CN

    public static void main(String argsL&

    Kint productLL 3 ne) intL$OSL#OU-M4SNint ro)"columnN

    System.out.println(QMultiplication ableQ&NSystem.out.println(Q Q&N

    int i"*Nfor(i31Ni$OSNi&K

    for(*31N*#OU-M4SN*&K

    productLiL* 3 i *NSystem.out.print(Q Q productLiL*&N

    System.out.println(Q Q&N

    Variale R 'iNe Arrays

    !ariable Si:e array is called Array o Array or %ested Array or

  • 7/25/2019 Java Unit1

    92/97

    92 92

    !ariable Si:e array is called Array o Arrayor %ested ArrayorJagged Array

    ;+E

    int L L + 3 ne) int LV L N 66%ree ro)s array

    + L> 3 ne) int LA 668irst $o)s %as t)o elements+ L1 3 ne) int LB 66Second $o)s %as four elements+ LA 3 ne) int LV 66%ird $o)s %as t%ree elements

    0

    1

    2

    0 1

    1 3

    2 2

    public class My0rraycAK

    public static void main(String argsL &

  • 7/25/2019 Java Unit1

    93/97

    93

    public static void main(String argsL &K

    Scanner s3ne) Scanner(System.in&NintLL *ag3ne) intLVLN

    *agL>3ne) intLBN*agL13ne) intLVN*agLA3ne) intLCNSystem.out.println(Q;nter t%e array elementsQ&Nfor(int i3>Ni*ag.lengt%Ni&K

    for(int *3>N**agLi.lengt%N*&*agLiL*3s.ne+t'nt(&N

    for(int i3>Ni*ag.lengt%Ni&K

    for(int *3>N**agLi.lengt%N*&K

    System.out.print(*agLiL* QHt Q&NSystem.out.println(&N

    !ariable lengt% argumentsJava allo)s us to pass a variable number of arguments of t%e same

  • 7/25/2019 Java Unit1

    94/97

    J p gtype to a met%od. %e parameter in t%e met%od is declared asfollo)sE

    type4ame... parameter4ames

    $ulesE

    0 function s%ould contain only one variable lengt% parameter

    %e variable lengt% parameter must be last in t%e list

    Preceded by any number usual parameters.

    94

    class v0rgK

  • 7/25/2019 Java Unit1

    95/97

    public static void printMa+(int... numbers &

    K

    for (int i 3 >N i numbers.lengt%N i&

    K

    System.out.println( numbersLi &N

    public static void main(StringL ar&K

    printMa+(1"A"V"B"C&N

    printMa+(1"A"B&N

    95

    Pat% #lassPat% P07 and #U0SSP07 are operating system level environment

  • 7/25/2019 Java Unit1

    96/97

    variables.

    P07 is used to de/ne )%ere t%e system can /nd t%e e+ecutables(.e+e& /les ;+ample pat%3 cEHprogram /lesH*avaH*dk.I.>X>CHbin

    #U0SSP07 is used to specify t%e location of .class /les

    96

    J0$Steps to create *ar 8ileE

  • 7/25/2019 Java Unit1

    97/97

    create a *ava code save t%e /le

    compile t%e *ava /les to create .class /les

    create a (aniestmanifest is t%e description contains t%e main class %eader

    ;+ampleE Main#lassE classname

    save it in .mft e+tension

    create