02 Core Java IntroTo Language

Embed Size (px)

Citation preview

  • 8/3/2019 02 Core Java IntroTo Language

    1/60

    An Introduction

    Java Technology

  • 8/3/2019 02 Core Java IntroTo Language

    2/60

    Confidential Mr. Anuj

    Agenda

    Fundamentals

    Operators

    Flow Controls

  • 8/3/2019 02 Core Java IntroTo Language

    3/60

    Confidential Mr. Anuj 3

    Java Source File Structure

    Java Keywords

    Identifiers

    Literals

    Variables and Data Types

    Variable Declaration and Initialization

    Operators

    Primitive Casting

    Flow Controls

    Outline

  • 8/3/2019 02 Core Java IntroTo Language

    4/60

    Confidential Mr. Anuj 4

    At the end of this section, you should be able to: Recognize and create correctly constructed source code

    Recognize and create correctly constructed declarations

    Distinguish between legal and illegal identifiers

    Describe all the primitive data types and the ranges ofthe integral data types

    Recognize correctly formatted data types

    Learn to properly declare and initialize variables

    Understand the contents of the argument list of anapplications main() method

    Objectives

  • 8/3/2019 02 Core Java IntroTo Language

    5/60

    Confidential Mr. Anuj 5

    Objectives (continued)

    Operators: Learn to use: Unary operators

    Arithmetic operators

    String operators

    Relational operators

    Conditional operators

    Logical operators

    Assignment operators

    Be familiar with object, shift and bitwise operators

    Identify the order of evaluation and change its precedence

    Learn how to cast primitive data types

  • 8/3/2019 02 Core Java IntroTo Language

    6/60

    Confidential Mr. Anuj 6

    Objectives (continued)

    Flow Controls: Learn syntax and correct use of:

    if-else() statement

    switch() statement

    while() statement

    do-while() statement

    for() statement

    break, continue and label statements

    Introduce the concept of return statement

  • 8/3/2019 02 Core Java IntroTo Language

    7/60Confidential Mr. Anuj 7

    /** Created on Jul 14, 2005** First Java Program*/

    package com.jds.sample;import java.util.*;

    /*** @author JDS*/

    public class JavaMain {

    public static voidmain(String[] args) {// print a messageSystem.out.println("Welcome to Java!");

    }}

    class Extra {/** class body*/

    }

    1. Package declaration

    Used to organize a collection ofrelated classes.

    2. Import statement

    Used to reference classes anddeclared in other packages.

    3. Class declaration

    A Java source file can have several

    classes but only one public class is

    allowed.

    declaration order

    Java Source File Structure

  • 8/3/2019 02 Core Java IntroTo Language

    8/60Confidential Mr. Anuj 8

    1. Single Line Comment

    // insert comments here

    2. Block Comment

    /*

    * insert comments here

    */

    3. Documentation Comment

    /**

    * insert documentation

    */

    /** Created on Jul 14, 2005** First Java Program*/

    package com.jds.sample;import java.util.*;

    /*** @author JDS*/

    public class JavaMain {

    public static voidmain(String[] args) {// print a messageSystem.out.println("Welcome to Java!");

    }}

    class Extra {/** class body*/

    }

    Java Source File Structure

    Comments

    Tabs and spaces are ignored bythe compiler. Used to improvereadability of code.

    Whitespaces

  • 8/3/2019 02 Core Java IntroTo Language

    9/60Confidential Mr. Anuj 9

    /** Created on Jul 14, 2005** First Java Program*/

    package com.jds.sample;import java.util.*;

    /*** @author JDS*/

    public class JavaMain {

    public static voidmain(String[] args) {// print a messageSystem.out.println("Welcome to Java!");

    }}

    class Extra {/** class body*/

    }

    Every java program includes at

    least one class definition. Theclass is the fundamentalcomponent of all Java programs.

    A class definition contains all thevariables and methods that makethe program work. This is

    contained in the class bodyindicated by the opening andclosing braces.

    Java Source File Structure

    Class

  • 8/3/2019 02 Core Java IntroTo Language

    10/60Confidential Mr. Anuj 10

    /** Created on Jul 14, 2005** First Java Program*/

    package com.jds.sample;import java.util.*;

    /*** @author JDS*/

    public class JavaMain {

    public static voidmain(String[] args) {// print a messageSystem.out.println("Welcome to Java!");

    }}

    class Extra {/** class body*/

    }

    Java Source File Structure

    Braces are used for groupingstatements or block of codes.

    The left brace ({) indicatesthe beginning of a class body,

    which contains any variablesand methods the class needs.

    The left brace also indicatesthe beginning of a methodbody.

    For every left brace that

    opens a class or method youneed a corresponding rightbrace (}) to close the class ormethod.

    A right brace always closesits nearest left brace.

    Braces

  • 8/3/2019 02 Core Java IntroTo Language

    11/60Confidential Mr. Anuj 11

    /** Created on Jul 14, 2005** First Java Program*/

    package com.jds.sample;import java.util.*;

    /*** @author JDS*/

    public class JavaMain {

    public static voidmain(String[] args) {// print a messageSystem.out.println("Welcome to Java!");

    }

    }

    class Extra {/** class body*/

    }

    Java Source File Structure

    This line begins the main()

    method. This is the line at whichthe program will begin executing.

    main() method

    Declares a parameter namedargs, which is an array of String.

    It represents command-linearguments.

    String args[]

  • 8/3/2019 02 Core Java IntroTo Language

    12/60Confidential Mr. Anuj 12

    /** Created on Jul 14, 2005** First Java Program*/

    package com.jds.sample;import java.util.*;

    /*** @author JDS*/

    public class JavaMain {

    public static voidmain(String[] args) {// print a messageSystem.out.println("Welcome to Java!");

    }

    }

    class Extra {/** class body*/

    }

    Java Source File Structure

    A complete unit of work in aJava program.

    A statement is alwaysterminated with a semicolon andmay span multiple lines in yoursource code.

    Java statement

    Semicolon (;) is the terminating

    character for any java statement.

    Terminating characterThis line outputs the stringWelcome to Java! followed by

    a new line on the screen.

    System.out.println()

  • 8/3/2019 02 Core Java IntroTo Language

    13/60Confidential Mr. Anuj 13

    true

    strictfp

    null

    implements

    extends

    char

    transient

    static

    new

    if

    else

    catch

    throws

    short

    native

    double

    case

    throw

    return

    long

    for

    do

    byte

    while

    this

    public

    interface

    float

    default

    break

    volatile

    synchronized

    protected

    int

    finally

    continue

    boolean

    void

    switch

    private

    instanceof

    final

    assert

    try

    super

    package

    import

    false

    class

    abstract

    Java Keywords

    gotoconst

  • 8/3/2019 02 Core Java IntroTo Language

    14/60

    Confidential Mr. Anuj 14

    printMeis not the same as PrintMe

    Identifiers

    An identifieris the name given by aprogrammer to a variable, statementlabel, method, class, and interface

    An identifier must begin with a letter,$ or _

    Subsequent characters must beletters, numbers, $ or _

    An identifier must not be a Javakeyword

    Identifiers are case-sensitive

    Incorrect Correct

    3strikes strikes3Write&Print Write_Print

    switch Switch

  • 8/3/2019 02 Core Java IntroTo Language

    15/60

    Confidential Mr. Anuj 15

    A literalis a representation of a value of a particular type

    Literals

    Type Examples & Values

    boolean true false

    character a \uFFFF' \777

    integer 123 123L O123 Ox123

    floating-point 123.5 123.5D 123.5F 123.5e+6

    object test null

    escape sequences \n \t \b \f \r \ \ \\

  • 8/3/2019 02 Core Java IntroTo Language

    16/60

    Confidential Mr. Anuj 16

    Variable and Data Types

    A variableis a named storage location used to representdata that can be changed while the program is running

    A data typedetermines the values that a variable cancontain and the operations that can be performed on it

    Categories of data types:

    1. Primitive data types

    2. Reference data types

  • 8/3/2019 02 Core Java IntroTo Language

    17/60

    Confidential Mr. Anuj 1717

    What is strongly typed means?

    Java is what is known as a strongly typedlanguage.

    That means that Java is a language that will only accept specific values

    within specific variables or parameters.

    Some languages, such as JavaScript, are weakly typed languages. This

    means that you can readily store whatever you want into a variable.

  • 8/3/2019 02 Core Java IntroTo Language

    18/60

    Confidential Mr. Anuj 1818

    Here is an example of the difference between strongly typedand weakly typed languages:

    JavaScript (weakly typed)

    1: var x; // Declare a variable

    2: x = 1; // Legal

    3: x = "Test"; // Legal

    4: x = true; // Legal

    Java (strongly typed)

    1: int x; // Declare a variable of type int

    2: x = 1; // Legal

    3: x = "Test" // Compiler Error

    4: x = true; // Compiler Error

  • 8/3/2019 02 Core Java IntroTo Language

    19/60

    Confidential Mr. Anuj 19

    Primitive Data Types

    Type Bits Lowest Value Highest Value

    boolean (n/a) false true

    char 16 '\u0000' [0] '\uffff' [216-1]

    byte 8 -128 [-27] +127 [27-1]

    short 16 -32,768 [-215] +32,767 [215-1]

    int 32 -2,147,483,648 [-231] +2,147,483,647 [231-1]

    long 64 -9,223,372,036,854,775,808 [-263] +9,223,372,036,854,775,807 [263-1]

    float 32 1.40129846432481707e-45 3.40282346638528860e+38

    double 64 4.94065645841246544e-324 1.79769313486231570e+308

    Primitive data types represent atomicvalues and are built-in to Java

    Java has 8 primitive data types

  • 8/3/2019 02 Core Java IntroTo Language

    20/60

    Confidential Mr. Anuj 20

    Reference Data Types

    Reference data types represent objects

    A referenceserves as a handle to the object, it isa way to get to the object

    Java has 2 reference data types

    1. Class

    2. Interface

  • 8/3/2019 02 Core Java IntroTo Language

    21/60

    Confidential Mr. Anuj 21

    Declaring a variable with primitive data type

    int age = 21;

    Declaring a variable with reference data type

    Date now = new Date();

    String name =

    Jason

    ;

    Variable Declaration & Initialization

    identifier

    name

    primitive

    type

    initial

    value

    identifiername

    referencetype

    initialvalue

  • 8/3/2019 02 Core Java IntroTo Language

    22/60

    Confidential Mr. Anuj 22

    Primitive Type Declaration

    Identifiername

    type

    int age;

    stack

    age = 17;

    valueIdentifiername

    age

    MEMORY

    declaration

    initialization/assignment

    allot space to memory

    017

  • 8/3/2019 02 Core Java IntroTo Language

    23/60

    Confidential Mr. Anuj 23

    The heap

    Car object

    Values

    Reference Type Declaration

    type

    Car myCar;

    myCar = new Car(Bumble Bee);

    Identifiername

    Bumble Bee

    memory address

    location

    allot space to memory

    reference

    myCar

    Identifiername

  • 8/3/2019 02 Core Java IntroTo Language

    24/60

    Confidential Mr. Anuj 2424

    Class Account

    int num;

    char type;

    double balance;

    num = 101;

    type = S

    balance = $1000.00 ;

    Account obj1

    num = 241;

    type = C

    balance = $4890.00 ;

    Account obj2

    Memory

    0x 0fed02e

    0x 0fc024b

  • 8/3/2019 02 Core Java IntroTo Language

    25/60

    Confidential Mr. Anuj 25

    Member VariablesDeclared inside the classbut outside of all methods.Accessible by all methodsof the class.

    Local Variables Availableonly within the methodwhere they were declared.

    Method parameters havelocal scope.

    Scope of Variable

    public class HelloWorld {//accessible throughout the class

    String name;

    public void otherMethod(){

    float salary = 15000.00f;

    //cant access age variable from here}

    public static void main(String args[ ]) {

    //cant access salary variable from here

    int age=17;

    //cant access ctr variable from herefor (int ctr=0 ; ctr

  • 8/3/2019 02 Core Java IntroTo Language

    26/60

    Confidential Mr. Anuj 26

    Fundamentals

    Operators

    Flow Controls

    Agenda

  • 8/3/2019 02 Core Java IntroTo Language

    27/60

    Confidential Mr. Anuj 27

    Unary operators

    Arithmetic operators

    String operator

    Relational operators

    Conditional operator Logical operator

    Assignment operators

    Object operators

    Shift operators

    Bitwise operators

    Evaluation order

    Primitive Casting

    Operators and Assignments

  • 8/3/2019 02 Core Java IntroTo Language

    28/60

    Confidential Mr. Anuj 28

    Unary Operators

    Unary operators use only one

    operand

    ++ Increment by 1, can be prefix or postfix

    -- Decrement by 1, can be prefix or postfix

    + Positive sign

    - Negative sign

    int num=10;

    System.out.println("incrementing/decrementing...");

    System.out.println(++num);

    System.out.println(--num);System.out.println(num++);

    System.out.println(num--);

    System.out.println("setting signs...");

    System.out.println(+num);

    System.out.println(-num);

    incrementing/decrementing...

    11

    10

    10

    11setting signs...

    10

    -10

    Sample code: Sample output:

  • 8/3/2019 02 Core Java IntroTo Language

    29/60

    Confidential Mr. Anuj 29

    Arithmetic Operators

    Arithmetic operators are used for basic

    mathematical operations

    + Add

    - Subtract

    * Multiply

    / Divide

    % Modulo, remainder

    int num1=15, num2=10;

    System.out.println("calculating...");

    System.out.println(num1 + num2);

    System.out.println(num1 - num2);System.out.println(num1 * num2);

    System.out.println(num1 / num2);

    System.out.println(num1 % num2);

    calculating...

    25

    5

    150

    15

    Sample code: Sample output:

  • 8/3/2019 02 Core Java IntroTo Language

    30/60

    Confidential Mr. Anuj 30

    String Operator

    String operator (+) is used to concatenate operands If one operand is String, the other operands are converted to String

    String fname = "Josephine", lname = Luv", mi = "T";

    String fullName = lname +", " + fname +" " + mi + ".";

    String nickName = "Jessy";

    int age=21;

    System.out.println("My full name is: "+ fullName);

    System.out.println("You can call me "+ nickName +"!");

    System.out.println("I'm "+ age +" years old.");

    My full name is: Luv, Josephine T.

    You can call me Jessy!

    I'm 21 years old.

    Sample code:

    Sample output:

  • 8/3/2019 02 Core Java IntroTo Language

    31/60

    Confidential Mr. Anuj 31

    Relational Operators

    Relational operators are used to compare values boolean values cannot be compared with non-boolean values Only object references are checked for equality, and not their states Objects cannot be compared with null null is not the same as

    < Less than

    Greater than

    >= Greater than or equal to

    == Equals

    != Not equals

  • 8/3/2019 02 Core Java IntroTo Language

    32/60

    Confidential Mr. Anuj 32

    Relational Operators

    String name1 = "Marlon"; int weight1=140, height1=74;

    String name2 = "Katie"; int weight2=124, height2=78;

    boolean isLight = weight1 < weight2, isLightEq = weight1 height2, isTallEq = height1 >= height2;

    System.out.println("Is " + name1 + " taller than " + name2 + "? " + isTall);

    System.out.println("Is " + name1 + " taller or same height as " + name2 + "? " + isTallEq);

    boolean isWeighEq = weight1 == weight2, isTallNotEq = height1 != height2;

    System.out.println("Is " + name1 + " same weight as " + name2 + "? " + isWeighEq);

    System.out.println("Is " + name1 + " not as tall as " + name2 + "? " + isTallNotEq);

    System.out.println("So who is heavier?");

    System.out.println("And who is taller?");

    Is Marlon lighter than Katie? false

    Is Marlon lighter or same weight as Katie? false

    Is Marlon taller than Katie? false

    Is Marlon taller or same height as Katie? false

    Is Marlon same weight as Katie? false

    Is Marlon not as tall as Katie? true

    So who is heavier?

    And who is taller?

    Sample code:

    Sample output:

  • 8/3/2019 02 Core Java IntroTo Language

    33/60

    Confidential Mr. Anuj 33

    The ternary operator (?:) provides a handy way to code simple if-else()

    statements in a single expression, it is also known as the conditional operator If condition is true, then exp1 is returned as the result of operation

    If condition is false, then exp2 is returned as the result of operation

    Can be nested to accommodate chain of conditions

    Conditional operator

    condition ? exp1 : exp2;

    int yyyy=1981, mm=10, dd=22;

    String mmm = mm==1?"Jan":mm==2?"Feb":mm==3?"Mar":mm==4?"Apr":mm==5?"May":mm==6?"Jun":

    mm==7?"Jul":mm==8?"Aug":mm==9?"Sep":mm==10?"Oct":mm==11?"Nov":mm==12?"Dec":"Unknown";

    System.out.println("I was born on " + mmm + " " + dd + ", " + yyyy);

    I was born on Oct 22, 1981

    Sample code:

    Sample output:

    Syntax:

  • 8/3/2019 02 Core Java IntroTo Language

    34/60

    Confidential Mr. Anuj 34

    Logical Operators

    Logical operators are used to compareboolean expressions

    ! inverts a boolean value & | evaluate both operands && || evaluate operands conditionally

    ! NOT

    & AND

    | OR

    ^ XOR

    && Short-circuit AND

    || Short-circuit OR

    Op1 Op2 !Op1 Op1 & Op2 Op1 | Op2 Op1 ^ Op2 Op1 && Op2 Op1 || Op2

    false false true false false false false false

    false true true false true true false true

    true false false false true true false true

    true true false true true false true true

    Truth Table

  • 8/3/2019 02 Core Java IntroTo Language

    35/60

    Confidential Mr. Anuj 35

    Similar to the Boolean operators, but with an added ability to

    short-circuit part of the process, using a couple of mathematicalrules:

    If the left operand of an && operation is false, the result isautomatically false, and the right operand is not evaluated

    If the left operand of an || operation is true, the result isautomatically true, and the right operand is not evaluated

    Boolean Complement ( ! ):

    The NOT function inverts the value of boolean

    Short-circuit Logical Operators (&&,|| and !)

    boolean a = (5>8) && (8>5);false;

    boolean b = (8>5) || (5>8);true;

    boolean c = !b;false;

  • 8/3/2019 02 Core Java IntroTo Language

    36/60

    Confidential Mr. Anuj 36

    Logical Operators

    int yrsService=8;

    double perfRate=86;

    double salary=23000;

    char position='S';

    // P-probationary R-regular, S-supervisor, M-manager, E-executive, T-top executive

    boolean forRegular, forSupervisor, forManager, forExecutive, forTopExecutive;

    forRegular = yrsService>1 & perfRate>80 & position=='P'& salary5 & perfRate>85 & position=='R'& salary7 & perfRate>85 & position=='S'& salary10 & perfRate>80 & position=='M'& salary10 & perfRate>80 & position=='E'& salary

  • 8/3/2019 02 Core Java IntroTo Language

    37/60

    Confidential Mr. Anuj 37

    Assignment Operators

    Assignment operators areused to set the value of avariable

    = Assign

    += Add and assign

    -= Subtract and assign

    *= Multiply and assign

    /= Divide and assign

    %= Modulo and assign

    &= AND and assign

    |= OR and assign

    ^= XOR and assign

    double unitPrice=120, qty=2, salesAmount;double discRate=15, discAmount, vatRate=10, vatAmount;

    // compute gross sales

    salesAmount = unitPrice * qty;

    System.out.println("Gross Sales: " + salesAmount);

    // compute tax

    vatRate /= 100;vatAmount = salesAmount * vatRate;

    salesAmount += vatAmount;

    System.out.println("Tax: " + vatAmount);

    // compute discount

    discRate /= 100;

    discAmount = salesAmount * discRate;

    salesAmount -= discAmount;

    System.out.println("Discount: " + discAmount);

    System.out.println("Please pay: " + salesAmount);

    Gross Sales: 240.0

    Tax: 24.0

    Discount: 39.6

    Please pay: 224.4

    Sample code:

    Sample output:

  • 8/3/2019 02 Core Java IntroTo Language

    38/60

    Confidential Mr. Anuj 38

    Casting

    Castingis converting from one data type to another

    Implicit castingis an implied casting operations

    Explicit castingis a required casting operations

    Primitive castingis converting a primitive data type to another

    Widening conversionis casting a narrower data type to a broader

    data type Narrowing conversionis casting a broader data type to a narrower

    data type

    Reference castingis converting a reference data type to another

    Upcastingis conversion up the inheritance hierarchy

    Downcastingis conversion down the inheritance hierarchy Casting between primitive and reference type is not allowed

    In Java, casting is implemented using () operator

  • 8/3/2019 02 Core Java IntroTo Language

    39/60

    Confidential Mr. Anuj 39

    Primitive Casting Flow

    byte short int long float double

    char

    widening conversion

    narrowing conversion

  • 8/3/2019 02 Core Java IntroTo Language

    40/60

    Confidential Mr. Anuj 40

    Primitive Casting Rule

    arithmetic implicit widening conversion

    relational implicit widening conversion

    shift implicit widening conversion

    bitwise implicit widening conversion

    assignment implicit widening conversion (if target is broader )

    parameter passing implicit widening conversion (if formal parameter is broader)

    logical none

    ternary ?: noneboolean none

    (all others) explicit casting (narrowing or widening conversion)

  • 8/3/2019 02 Core Java IntroTo Language

    41/60

    Confidential Mr. Anuj 41

    Implementing Primitive Casting

    public static voidmain(String args[]) {short age = 20;char sex = M;byte iq = 80;int height = 64;long distance =300;float price = 99.99f;

    double money = 500.00;

    age = sex; // will this compile?sex = iq; // will this compile?iq = (byte) height; // will this compile?distance = height; // will this compile?

    price = money; // will this compile?sex = (char) money; // will this compile?

    }

  • 8/3/2019 02 Core Java IntroTo Language

    42/60

    Confidential Mr. Anuj 42

    Evaluation order of operators in Java is as follows:

    Unary (++ -- + - ~ ())

    Arithmetic (* / % + -)

    Shift (> >>>) Comparison (< >= instanceof == !=)

    Bitwise (& ^ |)

    Short-circuit (&& || !)

    Conditional (?:) Assignment (= += -= *= /=)

    Summary of Operators

  • 8/3/2019 02 Core Java IntroTo Language

    43/60

    Confidential Mr. Anuj 43

    Fundamentals Operators

    Flow Controls

    Agenda

  • 8/3/2019 02 Core Java IntroTo Language

    44/60

    Confidential Mr. Anuj 44

    Flow Controls

    if-else() statement

    switch() statement

    while() statement

    do-while() statement

    for() statement

    break statement

    continue statement

    Statement label

  • 8/3/2019 02 Core Java IntroTo Language

    45/60

    Confidential Mr. Anuj 45

    Types of Flow Control

    1. Sequential Perform statements in the order

    they are written

    1. Selection Perform statements based on

    condition

    1. Iteration Perform statements repeatedly

    based on condition

  • 8/3/2019 02 Core Java IntroTo Language

    46/60

    Confidential Mr. Anuj 46

    if-else() Construct

    if-else() performs statements based on two conditions Condition should result to a boolean expression If condition is true, the statements following if are executed If condition is false, the statements following else are executed

    Can be nested to allow more conditions

    if (condition) { // braces optional

    // statement required

    }

    else { // else clause is optional

    // statement required

    }

    int age=10;

    if (age < 10) {

    System.out.println("You're just a kid.");

    } else if (age < 20){System.out.println("You're a teenager.");

    } else {

    System.out.println("You're probably old...");

    }

    Syntax:

    Example:

    You're a teenager.Output:

  • 8/3/2019 02 Core Java IntroTo Language

    47/60

    Confidential Mr. Anuj 47

    switch() construct

    switch() performs statements based on multiple conditions exp can only be char byte short int, val should be a unique constant of exp

    case statements falls through the next case unless a break is encountered default is executed if none of the other cases match the exp

    switch (exp) {

    caseval:

    // statements here

    caseval:

    // statements here

    default:

    // statements here

    }

    char sex='M';

    switch (sex){

    case'M':

    System.out.println("I'm a male.");break;case'F':

    System.out.println("I'm a female.");break;

    default:

    System.out.println("I am what I am!");

    }

    Syntax:

    Example:

    I'm a male.Output:

  • 8/3/2019 02 Core Java IntroTo Language

    48/60

    Confidential Mr. Anuj 48

    while() loop

    while() performs statements repeatedly whilecondition

    remains truewhile (condition) { // braces optional

    // statements here

    }

    int ctr=10;

    while (ctr > 0) {System.out.println("Timer: " + ctr--);

    }

    Syntax:

    Example:

    Timer: 10

    Timer: 9

    Timer: 8

    Timer: 7Timer: 6

    Timer: 5

    Timer: 4

    Timer: 3

    Timer: 2

    Timer: 1

    Output:

  • 8/3/2019 02 Core Java IntroTo Language

    49/60

    Confidential Mr. Anuj 49

    do-while() loop

    do-while() performs statements repeatedly (at least once) while

    conditionremains truedo

    // statements here

    while (condition);

    int ctr=0;

    do

    System.out.println("Timer: " + ctr++);

    while (ctr < 10);

    // next statement

    Syntax:

    Example:

    Timer: 0

    Timer: 1

    Timer: 2

    Timer: 3Timer: 4

    Timer: 5

    Timer: 6

    Timer: 7

    Timer: 8

    Timer: 9

    Output:

  • 8/3/2019 02 Core Java IntroTo Language

    50/60

    Confidential Mr. Anuj 50

    for() loop

    for() performs statements repeatedly based on a condition

    Init is a list of either declarations or expressions, evaluated firstand only once Conditionis evaluated beforeeach iteration

    Expis a list of expressions, evaluated aftereach iteration

    All entries inside () are optional, for(;;) is an infinite loop

    for (init; condition; exp) { // braces optional

    // statements here

    }

    for (int age=18; age

  • 8/3/2019 02 Core Java IntroTo Language

    51/60

    Confidential Mr. Anuj 51

    break

    break exits loops and switch() statements

    break;

    boolean isEating=true;

    int moreFood=5;

    while (isEating) {

    if (moreFood

  • 8/3/2019 02 Core Java IntroTo Language

    52/60

    Confidential Mr. Anuj 52

    continue

    continue is used inside loops to start a new iteration

    continue;

    for (int time=7; time

  • 8/3/2019 02 Core Java IntroTo Language

    53/60

    Confidential Mr. Anuj 53

    Statement Label A label is an identifier placed before a statement, it ends with : break labelNameis used to exit any labelled statement

    continue labelName is used inside loops to start a new iteration of the labeled loop

    labelName:

    break labelName;

    continue labelName;

    int[] scores = {3,9,10,0,8,10,7,1,9,8};

    outer:

    for (int i=0; i

  • 8/3/2019 02 Core Java IntroTo Language

    54/60

    Confidential Mr. Anuj 54

    Example 1:

    public int sum(int x, int y) {return x + y;

    }

    Example 2:

    public int sum(int x, int y) {

    x = x + y;

    if (x < 100){return x;

    }else{

    return x + 5;

    }

    }

    Example 2:public void getSum(int x) {

    System.out.println(x);

    return;

    }

    return branchingstatement is used toexit from the currentmethod.

    Two forms:

    return ; return;

    return

  • 8/3/2019 02 Core Java IntroTo Language

    55/60

    Confidential Mr. Anuj 55

    Key Points

    A Java source file can include package, import and class

    declarations in that order The main() method is the start of execution of a Java

    application

    Each Java statement is terminated by a semicolon ;

    Identifiers are case-sensitive Java keywords cannot be used as identifiers

    Each variable must be declared with a data type

    There are 8 primitive data types: boolean, char, byte,

    short, int, long, float and double There are 3 reference data types: class, array and

    interface

  • 8/3/2019 02 Core Java IntroTo Language

    56/60

    Confidential Mr. Anuj 56

    Key Points (continued)

    Use unary, arithmetic operators for basic mathematical

    operations

    Use string operator to concatenate strings

    Use relational operators to compare objects

    Use conditional operator as alternative to if-else()

    statement

    Use logical operators to compare boolean values

    Use assignment operators to assign values to variables

    Get familiar with object, shift and bitwise operators Java evaluates operators in order of precedence

    Castingis converting one data type to another

    Ke Points

  • 8/3/2019 02 Core Java IntroTo Language

    57/60

    Confidential Mr. Anuj 57

    Key Points

    if() and switch() are used for branching statements

    while(), do-while() and for() are used for iterating

    statements

    break, continue and labelare used to branch inside

    loops

  • 8/3/2019 02 Core Java IntroTo Language

    58/60

    Confidential Mr. Anuj 58

    http://www.java.sun.com

    http://www.java.com

    http://www.java.net

    http://javaboutique.internet.com

    http://javaboutique.webdeveloper.com

    http://www.javaworld.com http://www.developer.com

    http://javalobby.org

    http://freewarejava.com

    http://onjava.com

    http://javaranch.com http://www.cafeaulait.org

    http://www.java.about.com

    http://www.javacoffeebreak.com

    Java Online Resources

    http://www.java.sun.com/http://www.java.com/http://www.java.net/http://javaboutique.internet.com/http://javaboutique.webdeveloper.com/http://www.javaworld.com/http://www.developer.com/http://javalobby.org/http://freewarejava.com/http://onjava.com/http://onjava.com/http://onjava.com/http://freewarejava.com/http://freewarejava.com/http://javalobby.org/http://javalobby.org/http://www.developer.com/http://www.developer.com/http://www.javaworld.com/http://www.javaworld.com/http://javaboutique.webdeveloper.com/http://javaboutique.webdeveloper.com/http://javaboutique.internet.com/http://javaboutique.internet.com/http://www.java.net/http://www.java.com/http://www.java.com/http://www.java.sun.com/http://www.java.sun.com/
  • 8/3/2019 02 Core Java IntroTo Language

    59/60

    Confidential Mr. Anuj 59

    Tutorials:

    http://java.sun.com/docs/books/tutorial http://www.ibiblio.org/javafaq/javatutorial.html

    http://www.javacoffeebreak.com/tutorials/index.html http://www.cafeaulait.org/course/ http://oopweb.com/Java/Documents/IntroToProgrammingUsingJav

    a/VolumeFrames.html

    FAQs: http://java.sun.com/products/jdk/faq.html

    http://www.ibiblio.org/javafaq/javafaq.html http://www.apl.jhu.edu/~hall/java/Beginners-Corner.html http://www.norvig.com/java-iaq.html http://www.jguru.com/faq/subtopics.jsp?topic=JavaLanguage http://www.javacoffeebreak.com/faq/

    Java Online Resources

    Q i d C

  • 8/3/2019 02 Core Java IntroTo Language

    60/60

    Questions and Comments