oop - java - pg-desd - sessions 2v1

Upload: gauravlko

Post on 04-Jun-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    1/70

    J2SE Core Java

    PG-DESD

    Aug-2013

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    2/70

    Session 2:

    Learning Objectives

    By the end of this session, you must be able to

    Explain basic programming constructs of Java

    Explain Classes and Objects in Java

    Use instance data and methods

    Use newoperator to create instances

    Explain Constructors - Overloading

    Explain Method overloading

    Write programs on Parameter passing object asparameter

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    3/70

    Identifiers:

    Identifiers are the named words a programmer uses in aprogram

    An identifier can be made up of letters, digits, the underscorecharacter (_), and the dollar sign ($)

    They cannot begin with a digit

    Java is case sensitive, therefore Total and total are

    different identifiers

    Java Programming - Basic Constructs

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    4/70

    Reserved Words

    abstract

    boolean

    break

    bytebyval

    case

    cast

    catch

    char

    classconst

    continue

    default

    do

    double

    elseextends

    false

    final

    finally

    float

    forfuture

    generic

    goto

    if

    implements

    importinner

    instanceof

    int

    interface

    long

    nativenew

    null

    operator

    outer

    package

    privateprotected

    public

    rest

    return

    short

    staticsuper

    switch

    synchronized

    this

    throw

    throwstransient

    true

    try

    var

    void

    volatilewhile

    Often we use special identifiers called reserved words that

    already have a predefined meaning in the language A reserved word cannot be used in any other way

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    5/70

    Variables

    Programming languages uses variables to store data

    To allocate memory space for a variable JVM requires:

    1) To specify the data type of the variable

    2) To associate an identifier with the variable

    3) Optionally, the variable may be assigned an initial value

    All done as part of variable declaration.

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    6/70

    Basic Variable Declaration

    Syntax:

    datatype identifier [=value];

    Datatype must be

    A simple data type

    User defined datatype (Class type)

    Value is an optional initial value.

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    7/70

    We can declare several variables at the same time:type identifier [=value][, identifier [=value] ];

    Examples:

    int a, b, c;

    int d = 3, e, f = 5;

    byte g = 22;

    double pi = 3.14159;

    char ch = 'x';

    Basic Variable Declaration

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    8/70

    Constants

    A constant is an identifier that is similar to a variable exceptthat it holds one value for its entire existence

    The compiler will issue an error if you try to change a constant

    In Java, we use the finalmodifier to declare a constant

    Example: finalint MIN_HEIGHT = 69;

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    9/70

    Data Types - Primitive

    Java defines eight simple (primitive) types:

    1. byte 8-bit integer type2. short 16-bit integer type

    3. int 32-bit integer type

    4. long 64-bit integer type

    5. float 32-bit floating-point type

    6. double 64-bit floating-point type7. char symbols in a character set (16-bit Unicode)

    8. boolean logical values true and false

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    10/70

    10

    Introduction - Data Types

    Data type Bytes Min Value Max Value Literal Values

    byte 1 -27 271 123

    short 2 -215 2151 1234

    int 4 -231

    231

    1 12345, 086, 0x675

    long 8 -263 2631 123456

    float 4 - - 1.0

    double 8 - - 123.86

    char 2 0 2161 a, \n

    boolean - - - true, false

    General rule:

    Min value = 2(bits 1)

    Max value = 2(bits-1)1

    (where 1 byte = 8 bits)

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    11/70

    11

    Types of operators

    Assignment Operators

    Arithmetic Operators

    Unary Operators

    Equality Operators Relational Operators

    Conditional Operators

    instaceof Operator

    Bitwise Operators

    Shift Operators

    Operators - Types

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    12/70

    12

    Assignment Operator

    Arithmetic Operators

    Operator Description Example

    = Assignment int i = 10;

    int j = i;

    Operators Assignment Operators/Arithmetic Operators

    Operator Description Example

    + Addition int i = 8 + 9; byte b = (byte) 5+4;

    - Subtraction int i = 9 4;

    * Multiplication int i = 8 * 6;

    / Division int i = 10 / 2;

    % Remainder int i = 10 % 3;

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    13/70

    13

    Unary Operators

    Operator Description Example

    + Unary plus int i = +1;

    - Unary minus int i = -1;

    ++ Increment int j = i++;

    -- Decrement int j = i--;! Logical Not boolean j = !true;

    Operators Unary Operators/Equality Operators

    Operator Description Example

    == Equality If (i==1)

    != Non equality If (i != 4)

    Equality Operators

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    14/70

    14

    Relational Operators

    Operator Description Example

    > Greater than if ( x > 4)

    < Less than if ( x < 4)

    >= Greater than or equal to if ( x >= 4)

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    15/70

    15

    instanceof Operator

    Operator Description Example

    instanceof Instance of If (john instance of person)

    Operators instanceof Operator/Bitwise Operators/shift operators

    Operator Description Example& Bitwise and 001 & 111 = 1

    | Bitwise or 001 | 110 = 111

    ^ Bitwise ex-or 001 ^ 110 = 111

    ~ Reverse ~0 = 1

    Bitwise Operators

    Shift Operators

    Operator Description Example

    >> Right shift 4 >> 1 = 0100 >> 1 = 0010 = 2

    Unsigned Right shift 4 >>> 1 =0100 >>> 1 =0010 = 2

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    16/70

    Arithmetic Example

    classArithmeticDemo {

    public static void main (String[] args){

    // result is now 3

    int result = 1 + 2;

    System.out.println(result);

    // result is now 2

    result = result - 1;

    System.out.println(result);

    // result is now 4

    result = result * 2;

    System.out.println(result);

    // result is now 2

    result = result / 2;

    System.out.println(result);

    // result is now 10result = result + 8;

    // result is now 3

    result = result % 7;

    System.out.println(result);

    }

    }

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    17/70

    class BitDemo{

    public static void main(String[] args) {

    int bitmask = 0x000F;

    int val = 0x2222;

    System.out.println(val & bitmask);

    }

    }

    Logical Example

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    18/70

    class ConditionalDemo1{

    public static void main(String[] args){

    int value1 = 1;

    int value2 = 2;

    if((value1 == 1) && (value2 == 2))

    System.out.println("value1 is 1 AND value2 is 2");if((value1 == 1) || (value2 == 1))

    System.out.println("value1 is 1 OR value2 is 1");

    }

    }

    class ConditionalDemo2 {

    public static void main(String[] args){

    int value1 = 1;

    int value2 = 2;

    int result;boolean someCondition = true;

    result = someCondition ? value1 : value2;

    System.out.println(result);

    }

    }

    Examples

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    19/70

    class PrePostDemo{

    public static void main(String[] args){int i = 3;

    i++;

    // prints 4

    System.out.println(i);

    ++i;

    // prints 5System.out.println(i);

    // prints 6

    System.out.println(++i);

    // prints 6

    System.out.println(i++);

    // prints 7System.out.println(i);

    }

    }

    Increment/ Decrement Example

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    20/70

    Operator Precedence

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    21/70

    Selection Statements

    Java selection statements allow us to control the flow of programs

    execution based upon conditions known only during run-time.

    Java provides four selection statements:

    1) if

    2) if-else

    3) if-else-if

    4) switch

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    22/70

    22

    Flow Control if-else if-else

    Syntax Example

    if () {

    // logic for true condition-1 goeshere

    } else if () {

    // logic for true condition-2 goes

    here

    } else {

    // if no condition is met, controlcomes here

    }

    int a = 10;

    if (a < 10 ) {System.out.println(Less than 10);

    } else if (a > 10) {

    System.out.pritln(Greater than 10);

    } else {

    System.out.println(Equal to 10);

    }

    Result: Equal to 10s

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    23/70

    23

    Flow Control switch

    Syntax Example

    switch () {

    case :

    // stmt-1break;

    case :

    //stmt-2

    break;

    default:

    //stmt-3

    int a = 10;

    switch (a) {

    case 1:System.out.println(1);

    break;

    case 10:

    System.out.println(10);

    break;

    default:

    System.out.println(None);

    Result: 10

    switch

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    24/70

    class IfElseDemo{

    public static void main(String[] args)

    {

    int testScore=78;

    char grade;

    if(testScore>=90)grade='A';

    else if (testScore>=70)

    grade='B';

    else if(testScore>=50)

    grade='C';

    elsegrade='D';

    System.out.println("Grade="+grade);

    }

    }

    Selection Statements ifelse-if

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    25/70

    import java.io.*;

    class SwitchDemo{

    public static void main(String[] args) throws Exception

    {

    /*BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

    int color=Integer.parseInt(br.readLine());*/

    int color=3;

    switch(color)

    {

    case 1: System.out.println("RED"); break;

    case 2: System.out.println("BLUE"); break;

    case 3: System.out.println("YELLOW");break;default: System.out.println(Invalid Color");

    }

    }

    }

    Selection Statements switch

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    26/70

    class SwitchDemo2{

    public static void main(String[] args) {

    int month = 2;

    int year = 2000;

    int numDays = 0;

    switch (month) {case 1: case 3: case 5:

    case 7: case 8: case 10:

    case 12:

    numDays = 31;break;

    case 4: case 6:

    case 9: case 11:

    numDays = 30; break

    case 2:

    if (year % 4 == 0)

    numDays = 29;

    else

    numDays = 28 break;

    default:System.out.println("Invalid month.");

    break;

    }

    System.out.println("N umber of Days =+ numDays);

    }

    }

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    27/70

    Iteration Statements

    Java iteration statements enable repeated execution of part of a

    program until a certain termination condition becomes true.

    Java provides three iteration statements:

    1) do - while

    2) while

    3) for

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    28/70

    28

    Flow Control do-while / while

    do-whileSyntax Example

    do {

    // stmt-1

    } while ();

    int i = 0;

    do {

    System.out.println(In do); i++;

    } while ( i < 10);

    Result: Prints In do 11 times

    whileSyntax Example

    while () {

    //stmt

    }

    int i = 0;

    while ( i < 10 ) {

    System.out.println(In while); i++;

    }

    Result: In while 10 times

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    29/70

    29

    Flow Control for loop

    for

    Syntax Example

    for ( initialize; condition; expression)

    {// stmt

    }

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

    {System.out.println(In for);

    }

    Result: Prints In do 10 times

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    30/70

    class WhileDemo{

    public static void main(String[] args)

    {

    int count=1;

    while(count

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    31/70

    class DoWhileDemo

    {

    public static void main(String[] args)

    {

    int count=1;

    do

    {

    System.out.println("Count="+count);

    count++;

    } while(count

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    32/70

    class ForDemo1

    {public static void main(String[] args)

    {

    for(int i=0;i

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    33/70

    Jump Statements

    Java jump statements enable transfer of control to other parts ofprogram.

    Java provides three jump statements:

    1) break

    2) continue

    3) return

    In addition, Java supports exception handling that can also alterthe control flow of a program.

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    34/70

    class BreakDemo{

    public static void main(String[] args) {

    int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076,2000, 8, 622, 127 };

    int searchfor = 12;

    int i;

    boolean foundIt = false;

    for (i = 0; i < arrayOfInts.length; i++) {

    if (arrayOfInts[i] == searchfor) {

    foundIt = true;

    break;}

    }

    if (foundIt) {

    System.out.println("Found " + searchfor + " at index " + i);

    } else

    {System.out.println(searchfor + " not in the array");

    }

    }

    }

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    35/70

    class ContinueDemo{

    public static void main(String[] args) {

    String searchMe = "peter piper picked a " + "peck of pickled peppers";

    int max = searchMe.length();

    int numPs = 0;

    for (int i = 0; i < max; i++) {

    // interested only in p'sif (searchMe.charAt(i) != 'p')

    continue;

    // process p's

    numPs++;

    }System.out.println("Found " + numPs + " p's in the string.");

    }

    }

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    36/70

    Coding Guidelines

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    37/70

    What is an Object?

    Real world entities or things which have:

    1) State

    2) Behavior

    3) Identity

    Example: your dog, your car etc.,

    State name, color, breed of a dog Behavior sitting, barking, waging tail, running

    Indentity your dog

    A software object is a bundle of variables (state) and methods

    (operations).

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    38/70

    What is a Class?

    Class is basis for the Java language.

    Each concept we wish to describe in Java must be included in a class.

    Class is a group of set of values and set of operations

    A class is a template for objects

    A class is a blueprint / prototype that defines the variables and methodscommon to all objects of a certain kind.

    Example: your dog is a object of the class Dog.

    An object holds values for the variables defined in the class.

    A class defines a new data type, whose values are objects

    An object is an instance of a class

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    39/70

    The Class hierarchy

    Classes are arranged in a hierarchy

    The root, or topmost, class is Object

    Every class but Object has at least one superclass

    A class may have subclasses

    Each class inheritsall the fields and methods of its superclasses

    Cl D fi i i

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    40/70

    Class Definition

    A class consists of :

    Name, Several variable declarations (instance variables) Several method declarations

    These are called members of the class

    A Class also consists constructors and blocks

    General form of a class:class classname {

    type instance-variable-1;type instance-variable-n;

    type method-name-1(parameter-list) { }type method-name-2(parameter-list) { }type method-name-m(parameter-list) { }

    }

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    41/70

    Declaring and creating objects

    Declare a reference

    Example:

    Person p;String s;

    Creating an instance/object

    Person p = new Person();

    String s = new String (India);

    The new keyword is used to allocate

    memory at run-time

    s

    India

    E l P

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    42/70

    Example Program

    E l P Wh t h i th

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    43/70

    Example Program: What happens in the memory

    E l P A bj t

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    44/70

    Example Program Anonymous object

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    45/70

    Object Destruction

    A program accumulates memory through its execution.

    Two mechanisms to free memory that is no longer needed by theprogram:

    1) Manual in C/C++

    2) Automatic in Java

    In Java, when an object is no longer accessible through anyvariable, it is eventually removed from the memory by the garbagecollector.

    Garbage collector is parts of the Java Run-Time Environment.

    Constructor

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    46/70

    Constructor

    A constructor used to initialize the state of an object.

    It is invoked at the time of object creation It constructs the values (data) for the object

    Features:

    1) It is syntactically similar to a method

    2) It has the same name as the name of its class

    3) It is written without return type;

    The default return type is the class

    When the class has no constructor, the default constructorautomatically supplied the compiler.

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    47/70

    Example: Constructor

    class Box {

    double width;double height;

    double depth;

    Box() {

    System.out.println("Constructing Box");

    width = 10; height = 10; depth = 10;

    }

    double volume() {

    return width * height * depth;

    }}

    Default Constructor

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    48/70

    Default Constructor

    Parameterized Constructor

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    49/70

    Parameterized Constructor

    Constructor Overloading

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    50/70

    Constructor Overloading

    Constructor Copying values

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    51/70

    ConstructorCopying values

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    52/70

    Method Overloading

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    53/70

    Method Overloading A class with multiple methods by the same name but different parameters Implements polymorphism in java (static) Three ways: Number of arguments Types of arguments Order and Type of argument

    Method Overloading

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    54/70

    Method Overloading

    M th d l di i t ibl b h i t t

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    55/70

    Method overloading is not possible by changing return types.

    Is Overloading main() method possible ?

    Overloading main() method

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    56/70

    public class Simple /*Whenever your class is public and contains main()

    method, file name must be same as your class name.*/{

    public static void main(String[] args){

    System.out.println("Hello World!");main(10);// main() call

    }public static void main(int a) // main() method overloading{

    System.out.println(a);}

    }

    Overloading main() method

    Method Overloading

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    57/70

    Method Overloading

    Method Overloading

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    58/70

    Method Overloading

    Parameter Passing

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    59/70

    gOnly pass-by value or call by value is available in Java. There is no callby reference. Primitive data types and objects can be passed as values

    P t P i

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    60/70

    Parameter Passing

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    61/70

    Assignment Lab:

    Get yourself acquainted with java environment.

    Build a class Emp, which contains details about the

    Employee and compile and run its instances.

    -Create instances ( minimum 3)

    - Constructors

    - Methods

    - Overloaded methods and constructors

    - Copy objects one to other

    Assignments on CCR

    Assignment Reading:

    Study the book Java Complete Reference

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    62/70

    this facility

    static member, static method and static

    block

    JDK and its Usage

    Garbage Collection

    Next.

    Java Modifiers

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    63/70

    63

    Java Modifiers

    Modifier Class Class

    Variables

    Methods Method

    Variablespublic

    private

    protected

    default

    final

    abstract

    strictfp

    transient

    synchronized

    native

    volatile

    static

    Modifiers Class

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    64/70

    64

    Modifiers Class

    public Class can be accessed from any other class present in any package

    default Class can be accessed only from within the same package. Classes outside the

    package in which the class is defined cannot access this class

    final This class cannot be sub-classed, one cannot extend this class

    abstract Class cannot be instantiated, need to sub-classs/extend.

    strictfp Conforms that all methods in the class will conform to IEEE standard rules for

    floating points

    Modifiers Class Attributes

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    65/70

    65

    Modifiers Class Attributes

    public Attribute can be accessed from any other class present in any package private

    Attribute can be accessed from only within the class protected

    Attribute can be accessed from all classes in the same package and sub-classes.

    default Attribute can be accessed only from within the same package.

    final This value of the attribute cannot be changed, can assign only 1 value

    transient The attribute value cannot be serialized

    volatile Thread always reconciles its own copy of attribute with master.

    static Only one value of the attribute per class

    Modifiers Methods

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    66/70

    66

    Modifiers Methods

    public Method can be accessed from any other class present in any package

    private Method can be accessed from only within the class

    protected Method can be accessed from all classes in the same package and sub-classes.

    default Method can be accessed only from within the same package.

    final The method cannot be overridden

    abstract Only provides the method declaration

    strictfp Method conforms to IEEE standard rules for floating points

    synchronized Only one thread can access the method at a time

    native Method is implemented in platform dependent language

    static Cannot access only static members.

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    67/70

    Access Levels

    Modifier Class Package Subclass World

    public Y Y Y Yprotected Y Y Y N

    no modifier Y Y N N

    private Y N N N

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    68/70

    Assignment Lab:

    Get yourself acquainted with java environment.

    Build a class Emp, which contains details about the

    Employee and compile and run its instances.

    -Create instances ( minimum 3)

    - Constructors

    - Methods

    - Overloaded methods and constructors

    - Copy objects one to other

    Assignment Reading:

    Study the book Java FAQ

    Assignment Tutorial:

    Compare and contrast C++ and Java

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    69/70

    Questions?

    Thank You,

    Sreenivas Sadhu

  • 8/13/2019 OOP - Java - PG-DeSD - Sessions 2v1

    70/70