2.DataTypes ControlStatements Operators

download 2.DataTypes ControlStatements Operators

of 42

Transcript of 2.DataTypes ControlStatements Operators

  • 8/7/2019 2.DataTypes ControlStatements Operators

    1/42

    RENAISSANCE SOFTLABS (P) LTDRENAISSANCE SOFTLABS (P) LTD

  • 8/7/2019 2.DataTypes ControlStatements Operators

    2/42

    Data Types

  • 8/7/2019 2.DataTypes ControlStatements Operators

    3/42

    Built-in Data Types

    Java primitives (whole numbers)Java primitives (whole numbers)

    bytebyte

    shortshort

    intintlonglong

    Java primitives (real numbers)Java primitives (real numbers)

    floatfloat

    doubledouble

  • 8/7/2019 2.DataTypes ControlStatements Operators

    4/42

    Built-in Data Types

    Java primitives (text)Java primitives (text)

    char (character, use single quotes: b)char (character, use single quotes: b)

    String *String *

    Java primitives (True/False)Java primitives (True/False)

    booleanboolean

    * String is not a primitive* String is not a primitive

  • 8/7/2019 2.DataTypes ControlStatements Operators

    5/42

    Variable Declarations

    Simple formSimple form

    ; ;

    ExampleExample

    int total;int total;

    Optional initialization at declarationOptional initialization at declaration

    = ; = ;

    ExampleExample

    int total = 0;int total = 0;

  • 8/7/2019 2.DataTypes ControlStatements Operators

    6/42

    Examples

    int counter;int counter;

    int numStudents = 583;int numStudents = 583;

    float gpa;float gpa;

    double batAvg = .406;double batAvg = .406;

    char gender;char gender;

    char gender = f;char gender = f;

    boolean isSafe;boolean isSafe;

    boolean isEmpty = true;boolean isEmpty = true;

    String personName;String personName;

    String streetName = North Avenue;String streetName = North Avenue;

  • 8/7/2019 2.DataTypes ControlStatements Operators

    7/42

    Primitive Type Facts

    Type Size Min Default

    boolean false

    Max

    1bit false* true*

    char '\u0000' (null)2

    byte (byte) 01 -128 127short (short) 02 -32,768 32,767

    int 04 -2,147,483,648 2,147,483,647

    long 0L8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807

    float 0.0F4 Approx 3.4E+38 with 7 significant digits

    double 0.0D8 Approx 1.7E+308 with 15 significant digits

    void

    * Not truly min and max. Note: Size is in Bytes

  • 8/7/2019 2.DataTypes ControlStatements Operators

    8/42

    Condition

    als & Iteration

  • 8/7/2019 2.DataTypes ControlStatements Operators

    9/42

    Decision Statements

    if statementif statement omitting else branch:omitting else branch:

    if (condition)if (condition)

    statement1;statement1;

    if statementif statement omitting else branch:omitting else branch:

    iif (condition)f (condition) {{

    statements;statements;}} // if// if

  • 8/7/2019 2.DataTypes ControlStatements Operators

    10/42

    Decision Statements

    if statementif statement -- single statement bodies:single statement bodies:

    if (condition)if (condition)

    statement1;statement1;

    elseelse

    statement2;statement2;

    if statementif statement -- multiple statement blocks:multiple statement blocks:

    if (condition)if (condition) {{

    statements;statements;

    }}

    elseelse {{statements;statements;

    }} // if// if

  • 8/7/2019 2.DataTypes ControlStatements Operators

    11/42

    Multiple Selections via switch

    1.1. Use if construct for single selection.Use if construct for single selection.

    2.2. Use if/else construct for double selection.Use if/else construct for double selection.

    3.3. Use switch construct for multiple selection.Use switch construct for multiple selection.

    Notes about switch:Notes about switch:

    Useful when making a selection amongUseful when making a selection among

    multiple values of the same variable.multiple values of the same variable.

    Not useful when selecting among valuesNot useful when selecting among values

    of different variables.of different variables.

  • 8/7/2019 2.DataTypes ControlStatements Operators

    12/42

    Switch syntax

    switch ()switch ()

    {{

    case :case :

    // whatever code you want// whatever code you want

    break;break; // usually need this// usually need thiscase :case :

    // whatever code you want// whatever code you want

    break;break; // usually need this// usually need this

    default:default:

    // whatever code you want// whatever code you want

    break;break; // optional// optional

    }}

  • 8/7/2019 2.DataTypes ControlStatements Operators

    13/42

    Multiple Selections via switch

    Note the "optional" default case at the end of the switch statement.

    It is technically optionalIt is technically optional onlyonlyin terms of syntax.in terms of syntax.

    switch (number) {

    case 1:

    System.out.println ("One");

    break;case 2:

    System.out.println ("Two");

    break;

    case 3:

    System.out.println ("Three");

    break;

    default:System.out.println("Not 1, 2, or 3");

    break; // Needed???

    } // switch

    For safety and good programming practice, always include a 'default' case.

    This might

    work without

    the default

    case, but

    would be

    poor

    technique

  • 8/7/2019 2.DataTypes ControlStatements Operators

    14/42

    How many days?

    if (month == 4 || month == 6 ||if (month == 4 || month == 6 ||

    month == 9 || month == 11)month == 9 || month == 11)

    numdays = 30;numdays = 30;

    else if (month = 2)else if (month = 2){{

    numdays = 28;numdays = 28;

    if (leap)if (leap)

    numdays = 29;numdays = 29;

    }}

    elseelse

    numdays = 31;numdays = 31;

  • 8/7/2019 2.DataTypes ControlStatements Operators

    15/42

    Switch

    switch (month)switch (month)

    {{

    case 4:case 4:

    case 6:case 6:

    case 9:case 9:

    case 11:case 11:numdays = 30;numdays = 30;

    break;break;

    case 2:case 2:

    numdays = 28;numdays = 28;

    if(leap)if(leap)numdays = 29;numdays = 29;

    break;break;

    default:default: /* Good idea? *//* Good idea? */

    numdays = 31;numdays = 31;

    }}

  • 8/7/2019 2.DataTypes ControlStatements Operators

    16/42

    Java example:

    while (condition){

    }

    Java Iteration Constructs: "While Loops"

    Note: Check is made before entering loop thus it is possible that loop may not

    execute

  • 8/7/2019 2.DataTypes ControlStatements Operators

    17/42

    Java example:

    do

    {statement 1;

    ...

    statement N;

    } while (condition);

    Java Iteration Constructs: "Do While Loops"

    Test Last Loop: Body of loop is guaranteed to be executed at least once.

    Useful when termination condition is developed inside loop.

  • 8/7/2019 2.DataTypes ControlStatements Operators

    18/42

    Java Iteration Constructs: For Loop

    Java example:

    int count;

    for (count = 1; count

  • 8/7/2019 2.DataTypes ControlStatements Operators

    19/42

    Secret!A for Loop can always be converted to a while loop

    i = 0i = 0;;

    while (while (i < 10i < 10)){{

    System.out.println(i);System.out.println(i);

    i++;i++;

    }}

    for(for(i = 0i = 0;; i < 10i < 10;; i++i++))

    {{System.out.println(i);System.out.println(i);

    }}

    This will help you understand the sequence of operations

    of a forloop

  • 8/7/2019 2.DataTypes ControlStatements Operators

    20/42

    OperatorsOperators

  • 8/7/2019 2.DataTypes ControlStatements Operators

    21/42

    Operators based on the number ofOperators based on the number ofoperators:operators:

    Unary OperatorsUnary Operators

    Binary OperatorsBinary Operators

    Ternary OperatorsTernary Operators

  • 8/7/2019 2.DataTypes ControlStatements Operators

    22/42

    Arithmetic Operators

    Sign Unary OperatorsSign Unary Operators

    ++

    --

    Increment and Decrement OperatorsIncrement and Decrement Operators

    ++++

    ----

    Basic Arithmetic OperatorsBasic Arithmetic Operators

    ++

    --

    **

    //

    %%

  • 8/7/2019 2.DataTypes ControlStatements Operators

    23/42

    Relational Operators

    Greater than (>)Greater than (>)

    Less than (=)

    Less than or equal to (

  • 8/7/2019 2.DataTypes ControlStatements Operators

    24/42

    Logical Operators

    Bitwise OperatorsBitwise Operators

    ShortShort--circuit operatorscircuit operators

  • 8/7/2019 2.DataTypes ControlStatements Operators

    25/42

    Bitwise Logical Operators

    AND (&)AND (&)

    OR

    (|)OR

    (|)

    XOR (^)XOR (^)

    Bitwise Inversion (~)`Bitwise Inversion (~)`

  • 8/7/2019 2.DataTypes ControlStatements Operators

    26/42

    Short-Circuit Logical Operators

    ShortShort--circuit Logical AND (&&)circuit Logical AND (&&)

    ShortShort--circuit Logical O

    ROR

    (||)circuit Logical OR

    OR

    (||)

    Boolean InversionBoolean Inversion--NOT (!)NOT (!)

  • 8/7/2019 2.DataTypes ControlStatements Operators

    27/42

    Assignment Operators

    ==

    +=+=

    --==

    *=*= /=/=

    %=%=

    &=&=

    |=|= ^=^=

  • 8/7/2019 2.DataTypes ControlStatements Operators

    28/42

    Advanced Operators

    Shortcut ifShortcut if--else statement (?else statement (?:):)

    Dot operator (.)Dot operator (.)

    Cast operator ()Cast operator ()

    newnew

    instanceofinstanceof

  • 8/7/2019 2.DataTypes ControlStatements Operators

    29/42

    Equality

    Equality of primitives (==)Equality of primitives (==)

    Equality of references (==)

    Equality of references (==)

    Equality of object (equals)Equality of object (equals)

  • 8/7/2019 2.DataTypes ControlStatements Operators

    30/42

    Arrays

  • 8/7/2019 2.DataTypes ControlStatements Operators

    31/42

    A problem with simple variables

    One variable holds one valueOne variable holds one value

    The value may change over time, but at anyThe value may change over time, but at anygiven time, a variable holds a single valuegiven time, a variable holds a single value

    If you want to keep track of many values, youIf you want to keep track of many values, youneed many variablesneed many variables

    All of these variables need to have namesAll of these variables need to have names

    What if you need to keep track of hundreds orWhat if you need to keep track of hundreds orthousands of values?thousands of values?

  • 8/7/2019 2.DataTypes ControlStatements Operators

    32/42

    Multiple values

    AnAn arrayarray lets you associate one name with a fixed (butlets you associate one name with a fixed (but

    possibly large) number of valuespossibly large) number of values

    All values must have the same typeAll values must have the same type

    The values are distinguished by a numericalThe values are distinguished by a numerical indexindex between 0between 0

    and array size minus 1and array size minus 1

    12 43 6 83 14 -57 109 12 0 6

    0 1 2 3 4 5 6 7 8 9

    myArray

  • 8/7/2019 2.DataTypes ControlStatements Operators

    33/42

    Indexing into arrays

    To reference a single array element, useTo reference a single array element, use

    arrayarray--namename [[indexindex]]

    Indexed elements can be used just like simple variablesIndexed elements can be used just like simple variables

    You can access their valuesYou can access their values

    You can modify their valuesYou can modify their valuesAn array index is sometimes called aAn array index is sometimes called a subscriptsubscript

    12 43 6 83 14 -57 109 12 0 6

    0 1 2 3 4 5 6 7 8 9

    myArray

    myArray[0] myArray[5] myArray[9]

  • 8/7/2019 2.DataTypes ControlStatements Operators

    34/42

    Using array elements

    Examples:Examples:x = myArray[1];x = myArray[1]; // sets x to 43// sets x to 43

    myArray[4] = 99;myArray[4] = 99; // replaces 14 with 99// replaces 14 with 99

    m = 5;m = 5;

    y = myArray[m];y = myArray[m]; // sets y to// sets y to --5757

    z = myArray[myArray[9]];z = myArray[myArray[9]];// sets z to 109// sets z to 109

    12 43 6 83 14 -57 109 12 0 6

    0 1 2 3 4 5 6 7 8 9

    myArray

  • 8/7/2019 2.DataTypes ControlStatements Operators

    35/42

    Array values

    An array may holdAn array may hold anyanytype of valuetype of value

    All values in an array must be theAll values in an array must be the samesame typetype

    For example, you can have:For example, you can have:

    An array ofAn array ofintegersintegersAn array ofAn array ofStringsStringsAn array ofAn array ofPersonPersonAn array of arrays ofAn array of arrays ofStringsStringsAn array ofAn array ofObjectObject

  • 8/7/2019 2.DataTypes ControlStatements Operators

    36/42

    Two ways to declare arrays

    You can declare more than one variable in the same declaration:You can declare more than one variable in the same declaration:int a[ ], b, c[ ], d;int a[ ], b, c[ ], d; // notice position of brackets// notice position of brackets

    aa andand cc areare intint arraysarrays

    bb andand dd are justare just intintss

    Another syntax:Another syntax:int [ ] a, b, c, d;int [ ] a, b, c, d; // notice position of brackets// notice position of brackets

    aa,, bb,, cc andand dd areare intint arraysarrays

    When the brackets come before the first variable, they apply toWhen the brackets come before the first variable, they apply toallallvariables in the listvariables in the list

  • 8/7/2019 2.DataTypes ControlStatements Operators

    37/42

    Different ways of Creating the array

    int myarray [ ]= {1,2,3};int myarray [ ]= {1,2,3}; Only ValuesOnly Values

    int myarray [ ]= new int[3];int myarray [ ]= new int[3]; Only size of arrayOnly size of array

    myarray[0]=1;myarray[0]=1;

    myarray[1]=2;myarray[1]=2;myarray[2]=3;myarray[2]=3;

    int myarray [ ]= new int[] {1,2,3};int myarray [ ]= new int[] {1,2,3}; No size, only valuesNo size, only values

  • 8/7/2019 2.DataTypes ControlStatements Operators

    38/42

    How to retrieve the values

    To retrieve the values from an arrayTo retrieve the values from an array

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

    {{

    System.out.println(Value is: + myarray[i]);System.out.println(Value is: + myarray[i]);}}

    HereHere lengthlength

    indicates the size of an arrayindicates the size of an array

  • 8/7/2019 2.DataTypes ControlStatements Operators

    39/42

    Arrays of objects

    Suppose you declare and define an arraySuppose you declare and define an array

    of objects:of objects:

    Person[ ] people = new Person[20];Person[ ] people = new Person[20];

    There is nothing wrong with this array, butThere is nothing wrong with this array, but

    it has 20it has 20 referencesreferences to Persons in itto Persons in it

    all of these references are initiallyall of these references are initially nullnull

    you haveyou have not yetnot y

    etdefined 20 Personsdefined 20 Persons

    For example,For example, people[12].namepeople[12].name will givewill give

    you ayou a nullPointerExceptionnullPointerException

  • 8/7/2019 2.DataTypes ControlStatements Operators

    40/42

    Arrays of arrays

    The elements of an array can be arraysThe elements of an array can be arrays

    Once again, there is a special syntaxOnce again, there is a special syntax

    Declaration:Declaration: int[ ][ ] table;int[ ][ ] table; (or(orint table[ ][ ];int table[ ][ ];))

    Definition:Definition: table = new int[10][15];table = new int[10][15];

    Combined:Combined: int[ ][ ] table = new int[10][15];int[ ][ ] table = new int[10][15];The first index (The first index (1010) is usually called the) is usually called the rowrow index; the secondindex; the second

    index (index (1515) is the) is the columncolumn indexindex

    An array like this is called aAn array like this is called a twotwo--dimensional arraydimensional array

  • 8/7/2019 2.DataTypes ControlStatements Operators

    41/42

    Different ways of creating array of arrays

    int[ ][ ] table = { {1, 2}, {3, 6}, {7, 8} };int[ ][ ] table = { {1, 2}, {3, 6}, {7, 8} };

    int[ ][ ] table = new int[3][2];int[ ][ ] table = new int[3][2];

    Int[ ][ ] table = new int[ ][ ] { {1, 2}, {3, 6}, {7, 8} };Int[ ][ ] table = new int[ ][ ] { {1, 2}, {3, 6}, {7, 8} };

    1 2

    3 6

    7 8

    0 1

    0

    1

    2

    For example,For example, table[1][1]table[1][1] containscontains 66

    table[2][1]table[2][1] containscontains 88,, andand

    table[1][2]table[1][2] is array out of boundsis array out of bounds

    To retrieve the values:To retrieve the values:

    for (int i = 0; i < 3; i++)for (int i = 0; i < 3; i++)

    {{ for (int j = 0; j < 2; j++)for (int j = 0; j < 2; j++)

    {{System.out.println ( table[i][j] );System.out.println ( table[i][j] );

    }}

    }}

  • 8/7/2019 2.DataTypes ControlStatements Operators

    42/42

    Size of these arrays

    int[ ][ ] table = new int[3][2];int[ ][ ] table = new int[3][2];

    The length of this array is the number ofThe length of this array is the number ofrows:rows:

    table.lengthtable.length isis 33

    Each row contains an arrayEach row contains an array

    To get the number ofTo get the number ofcolumns,columns, pick a row and ask forpick a row and ask forits length:its length:

    table[0].lengthtable[0].length isis 22

    But remember, rows may not all be the sameBut remember, rows may not all be the same

    lengthlength

    1 2

    3 67 8

    0 1

    0

    12