+ All Categories
Home > Documents > 3 1 Classes

3 1 Classes

Date post: 31-May-2018
Category:
Upload: suresh1130
View: 214 times
Download: 0 times
Share this document with a friend

of 62

Transcript
  • 8/14/2019 3 1 Classes

    1/62

    1Java

    The Class Explored

    Part I

  • 8/14/2019 3 1 Classes

    2/62

    2Java

    Class Constants10

    Class members9

    Instance members8Destruction7

    Instanceof6

    This5

    Null4

    References3

    Constructor2

    public and private access specifiers1

    Contents

  • 8/14/2019 3 1 Classes

    3/62

    3Java

    Command Line Arguments16for-each loop statement15

    Initializing arrays14

    Arrays13

    Immutability12

    String11

    contents

  • 8/14/2019 3 1 Classes

    4/62

    4Java

    Know

    public and private access specifiers

    What a constructor is

    What references, null, this and instanceofare

    How objects are destroyed

    The difference between instance and classmember variables

  • 8/14/2019 3 1 Classes

    5/62

    5Java

    The String class

    How to work with Arrays

    The new for-each loop statement

    How to get arguments from the

    command line

    Know

  • 8/14/2019 3 1 Classes

    6/62

    6Java

    Be Able To

    Use public and private access specifiers

    Write constructors

    Write programs using the String class andarrays

  • 8/14/2019 3 1 Classes

    7/62

    7Java

    Public and Private access

    Specifiers

    Name

    Registration number

    Name of the degree

    Current Semester

    Identified by

  • 8/14/2019 3 1 Classes

    8/62

    8Java

    public class Student{

    private String name;

    private int regNo;

    private StringdegreeName;

    private intcurrentSemester;

    public String getName()

    public voidsetName(String nm)

    public int getRegNo()public void setRegNo(int r)

    public String getDegreeName()public voidsetDegreeName(String dnm)

    public int getCurrentSemester()public voidsetCurrentSemester(int i)

  • 8/14/2019 3 1 Classes

    9/62

    9Java

    setRegNo(int r) Student object

    regno 12345

  • 8/14/2019 3 1 Classes

    10/62

    10Java

    Constructor

    When we create an object using new

    keyword a constructor is called.

    There can be more than one constructor for a

    class.

  • 8/14/2019 3 1 Classes

    11/62

    11Java

    public class Student{

    private String name;

    private int regNo;

    private String degreeName;

    private int currentSemester;

    /*Constructors 1 for student who have decided the degreethey are going to enroll into */

    public Student(String nm, String d){

    setName(nm);

    regNo=generateRegno();setDegreeName(d);

    setCurrentSemester(1);}

    A constructor has

    the same name as

    the class and has

    no return value.

  • 8/14/2019 3 1 Classes

    12/62

    12Java

    /*Constructors 2 for student who have notdecided the degree they are going to enrollinto */

    public Student(String nm){

    setName(nm);

    regNo=generateRegno();

    setCurrentSemester(1);}

    private int generateRegno(){

    int nextNo=0;

    //logic to generate reg no.

    return nextNo;}

    // place for setter methodsFolder 1

  • 8/14/2019 3 1 Classes

    13/62

    13Java

    public class StudentTest{

    public static void main(String args[]){

    //Creating object using constructor 1

    Student student1=

    new Student(John, M.C.A.);

    //Creating object using constructor 2

    Student student2=new Student(Mary);

    }

    }

  • 8/14/2019 3 1 Classes

    14/62

    14Java

    new Student();

    class Student{Student(){..}

    }

    Compiler

    looks for

    But since we dont have this

    constructor the compiler flags an

    error.

    Can we create student object

    similar to college object?

    Student student1= newStudent();

  • 8/14/2019 3 1 Classes

    15/62

    15Java

    But what happened in case

    of the College class ?

    When there are no constructors

    explicitly written in a class, the java

    compiler inserts a constructor which

    does not have any arguments. But

    if we explicitly include one or moreconstructors, then the compiler

    does not insert any constructor.

  • 8/14/2019 3 1 Classes

    16/62

    public class College{

    private String name;

    public void display(String str){

    System.out.println(Welcome to !);

    System.out.println(name);

    }

    public static void main(String args[]){

    College collegeObject= new College();

    collegeObject.name=XYZ College;

    collegeObject.display(XYZ College);}

    }

    publicCollege(){super();

    }

    Compiler inserts

    Folder 2

  • 8/14/2019 3 1 Classes

    17/62

    17Java

    References

    Student student2=new Student(Mary);

    name:MaryregNo:2

    currentSemester:1degreeName:null

    student2

    HEAPPointingto address

    of theactualstudent2object in

    memory

    STACK

  • 8/14/2019 3 1 Classes

    18/62

    18Java

    Student student1= new Student(Mary);

    Student student2=student1;student1.setName(Merry Mary);

    System.out.println(student2.getName());

    This code snippet prints

    Merry Mary. Why ?

  • 8/14/2019 3 1 Classes

    19/62

    19Java

    name:MaryMerry MaryregNo:2

    currentSemester:1degreeName:null

    student1

    student2

  • 8/14/2019 3 1 Classes

    20/62

    20Java

    null

    Default value of an object reference is null.

    class Test{Student student;

    void test(){student.display();}

    null

    An error occurs at runtime

    class Test{

    void test(){Student student;student.display();

    }

    An error occurs atcompile time

  • 8/14/2019 3 1 Classes

    21/62

    21Java

    this

    public class Student{

    String name;

    Student(String name){

    name=name;

    regNo=generateRegno();

    currentSemester=1; }}

    this.name=name;

  • 8/14/2019 3 1 Classes

    22/62

    22Java

    public class Student{

    String name;

    public Student(Stringname, String d){

    this(name);

    setDegreeName(d);

    }

    public Student(Stringname){

    setName(name);

    regNo=generateRegno();

    setCurrentSemester(1);

    }

    }

    calls

  • 8/14/2019 3 1 Classes

    23/62

    23Java

    instanceof

    Usage:

    object-refinstanceofclass-name

    returns a boolean value.

    Example:Student s1= new Student(Mary);

    System.out.println(s1 instanceof Student);

    System.out.println(s1 instanceof College);

    true

    Compilation error

  • 8/14/2019 3 1 Classes

    24/62

    24Java

    null instanceof Student

    returns false.

  • 8/14/2019 3 1 Classes

    25/62

    25Java

    Destruction

    Objects are automatically Garbage collected. Object is garbage collected

    -- if the object reference is set to null and no

    other object reference refers to thatobject

    OR

    -- if the object goes out of scope and itsreference is not assigned to any othervariable outside its scope.

  • 8/14/2019 3 1 Classes

    26/62

    26Java

    heap

    Student student1= new Student(Mary);

    Student studentref=student1;

    student1=null;

    student

    student1studentref

    Will the student object created in the first

    line be garbage collected?

    null

    How many objects are created?

  • 8/14/2019 3 1 Classes

    27/62

    27Java

    Instance members

    public class Student{

    private String name;

    public void setName(String name){...

    }

    Instance

    member

    variable

    Instance memberfunction

  • 8/14/2019 3 1 Classes

    28/62

    28Java

    Class members

    public class Student{

    private int gRegNo;

    public Student(String nm){

    regNo=generateRegno();

    setCurrentSemester(1);}

    private int generateRegno(){

    gRegNo++;

    return gRegNo; }}

  • 8/14/2019 3 1 Classes

    29/62

    29Java

    student1

    Student

    name:MarygRegNo:1regNo:1

    Student

    name:JohngRegNo:1regNo:1

    student2

    Again 1! Should be 2

    Student student1= new Student(Mary);

    Student student2= new Student(John);

  • 8/14/2019 3 1 Classes

    30/62

    30Java

    public class Student{

    private static int gRegNo;

    Student(String nm){

    regNo=generateRegno();

    ...}

    private int generateRegno(){

    gRegNo++;

    return gRegNo; }

    public static int getGRegNo(){

    return gRegNo;}

    ...}Folder 3

  • 8/14/2019 3 1 Classes

    31/62

    31Java

    public class StudentTest(){

    public static void main(String args[]){

    Student student1= new Student(Mary);

    Student student2= new Student(John);

    System.out.println( Student.getGRegNo());

    System.out.println( student1.getGRegNo());

    }

  • 8/14/2019 3 1 Classes

    32/62

    32Java

    student1

    Student

    name:MaryregNo:1

    Student

    name:JohnregNo:2

    student2

    Student student1= new Student(Mary);

    Student student2= new Student(John);

    It is correct now.

    gRegNo:2

  • 8/14/2019 3 1 Classes

    33/62

  • 8/14/2019 3 1 Classes

    34/62

    34Java

    Class Constants

    public class Student{public static final intMAX_STUDENTS=3000;..}

  • 8/14/2019 3 1 Classes

    35/62

    35Java

    String

    Constructors:String()String(String)

    Examples of creating String object:String s=abc;

    String s= new String();

    String s= new String(Hello);String s1= new String(s);

  • 8/14/2019 3 1 Classes

    36/62

    36Java

    Methods of String class:

    int length() :

    String s= new String(Hello);

    System.out.println(s.length());

    //prints 5

    char charAt(int index)

    String s="Have a nice day";

    System.out.println(s.charAt(0));

    // prints H

  • 8/14/2019 3 1 Classes

    37/62

    37Java

    String s1=abc,s2=def;

    String s3=s1+s2; // returns abcdef

    String s4=s1+1; // returns abc1

    String concat(String str)

    String s1=java.concat(c)

    //returns javac

  • 8/14/2019 3 1 Classes

    38/62

    38Java

    boolean equals(Object object)

    boolean equalsIgnoreCase(String anotherString)

    Example:

    String s1=abc;

    String s2=sbc;String s3=ABC;

    s1.equals(s2) ;//returns falses1.equalsIgnoreCase(s3) );//returnstrue

  • 8/14/2019 3 1 Classes

    39/62

    39Java

    Wait a minute. Why do we require

    equals() method to compare Strings

    ? Can we not compare using ==.

    == is alright with primitive

    datatypes. But with

    references, == will actually

    compare the addresses whilewhat we are want here is to

    check equality of value of

    strings.

  • 8/14/2019 3 1 Classes

    40/62

    40Java

    public Stringsubstring(int beginIndex)

    public Stringsubstring(int beginIndex,int endIndex)

    Example:icecream".substring(3)

    returns cream

    icecream".substring(0,3)

    returns ice

  • 8/14/2019 3 1 Classes

    41/62

    41Java

    Comparing two strings:

    public intcompareTo(String anotherString)

    public intcompareToIgnoreCase(String str)

    Example:

    String s1="ABC";String s2="acc";

    s2.compareTo(s1)

    returns 32

    s2.compareToIgnoreCase(s1)

    returns 1

  • 8/14/2019 3 1 Classes

    42/62

    42Java

    String toLowerCase()

    String toUpperCase()

    String replace(char oldChar,char newChar)StringreplaceAll(String reg,String replacement)

    boolean startsWith(String prefix)public boolean endsWith(String suffix)

  • 8/14/2019 3 1 Classes

    43/62

    43Java

    Immutability

    String s1="ABC";

    String s2=ABC;

    ABCs1

    s2

    String pool

  • 8/14/2019 3 1 Classes

    44/62

    44Java

    Strings are Immutable Objects.

    String s1="ABC";s1=DEF

    ABC

    DEF

    s1

    String pool

    This string object

    remains intact. This is

    not changed.

    New String object is

    created

  • 8/14/2019 3 1 Classes

    45/62

    45Java

    String pool

    ABC

    DEF

    s1

    s2

    Compare this with object references (slide 15)

    Assigning string references:

    String s1="ABC";String s2=s1;

    s2=DEF;

    System.out.println(s1);// prints ABC

  • 8/14/2019 3 1 Classes

    46/62

    46Java

    Constructor:

    String(String newStr)

    String s1="ABC";

    String s2=new String(ABC);

    ABC

    ABC

    s1

    s2

    String pool

  • 8/14/2019 3 1 Classes

    47/62

    47Java

    String s1="ABC";

    String s2=s1;

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

    s2="DEF";

    System.out.println(s1==s2);String s4="ABC";

    System.out.println(s1==s4);

    String s3=new String(s1);System.out.println(s1==s3);

    What is printed

    in each case?

  • 8/14/2019 3 1 Classes

    48/62

    48Java

    Arrays

    int sum=0,mul=0;int num[]= new int[5];

    for(int i=0;i

  • 8/14/2019 3 1 Classes

    49/62

    49Java

    int num[]= new int[5];

    00000

    numnum[0]num[1]

    num[2]num[3]num[4]

    automatically initialized to 0

  • 8/14/2019 3 1 Classes

    50/62

    50Java

    public class ArrayTest{

    static int num[];public static void main(Stringargs[]){System.out.println(num);

    System.out.println(num[0]);}}

    error at runtime

    prints null

    Folder 4

    E l f f

  • 8/14/2019 3 1 Classes

    51/62

    51Java

    Example for an array of

    references

    We will implement Stack data structure that can

    contain Strings

    We need to have an array of String objectsinside the Stack class.

  • 8/14/2019 3 1 Classes

    52/62

    public class Stack{

    private String stackData[];private int top;private final int MAX_CAPACITY;

    public Stack(){this(10);}public Stack(int capacity){

    stackData=new String[capacity];

    top=-1;MAX_CAPACITY=capacity;}

    Creates Stack instance

    Creates an arrayrepresenting stack

    last insertion index

    Folder 5

  • 8/14/2019 3 1 Classes

    53/62

    53Java

    public Stringpush(String data)

    {

    if(!isFull()){stackData[++top]=data;

    return stackData[top];}else return "Stack Full ! ";

    }If the stack is not full it inserts the data on the top ofthe list.

  • 8/14/2019 3 1 Classes

    54/62

    54Java

    public Objectpop() {if(isEmpty()){

    return "Stack Empty ! ";}else {

    String obj=stackData[top];

    stackData[top]=null;top--;return obj;}

    }If the stack is not empty it pops out the data from the

    top of the list.

  • 8/14/2019 3 1 Classes

    55/62

    55Java

    public booleanisEmpty(){if(top==-1) return true;else return false; }

    public booleanisFull(){if(top==MAX_CAPACITY-1)return true;else return false; }

    public static void main(String args[]) {

    Stack s=new Stack(3);System.out.println("push Object :

    "+s.push("Prema"));

    System.out.println("push Object :

    "+s.push("Padma"));System.out.println("push Object :

    "+s.push("Prasad" ));

    System.out.println("remove top "+s.pop());}

  • 8/14/2019 3 1 Classes

    56/62

    56Java

    Change the program to handlethe problem gracefully.

    Execute and findout what happens

    when you push 4th

    element into the

    stack?

  • 8/14/2019 3 1 Classes

    57/62

    57Java

    Initializing arrays

    int [] a= {1,2,4,8,26};

    int [] a=new int[] {1,2,4,8,26};

    int a[]= new int[0];

    anonymous array

    Creates an array of length 0

  • 8/14/2019 3 1 Classes

    58/62

    58Java

    for-each loop statement

    This is a new feature in 1.5 .

    Convenient way to iterate through arrays ( and

    collection)

    Syntax:

    for(datatype variable: array)statement

  • 8/14/2019 3 1 Classes

    59/62

    59Java

    Example 1:

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

    for(int j:a)

    System.out.println(j);

    Example 2:Student s[]= new Student [2];

    s[0]= new Student(Mary);

    s[1]= new Student(John);for(Student s1:s)

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

  • 8/14/2019 3 1 Classes

    60/62

    60Java

    Command Line Arguments

    2 command line arguments sent to StudentTest class

  • 8/14/2019 3 1 Classes

    61/62

    61Java

    public class StudentTest{

    public static void main(Stringargs[]){

    //Creating object using constructor 1

    Student student1=

    new Student(args[0], args[1]);

    }

    }Mary M.C.A.

    Folder 6

  • 8/14/2019 3 1 Classes

    62/62

    So what will happen if you

    run StudentTest withoutsupplying command line

    arguments ?


Recommended