You are on page 1of 62

The Class Explored

Part I

1
Java
Contents

1 public and private access specifiers


2 Constructor
3 References
4 Null
5 This
6 Instanceof
7 Destruction
8 Instance members
9 Class members
10 Class Constants

2
Java
contents
11 String
12 Immutability
13 Arrays
14 Initializing arrays
15 ‘for-each’ loop statement
16 Command Line Arguments

3
Java
Know

• public and private access specifiers


• What a constructor is
• What references, null, this and instanceof
are
• How objects are destroyed
• The difference between instance and class
member variables

4
Java
Know

• The String class


• How to work with Arrays
• The new ‘for-each’ loop statement
• How to get arguments from the
command line

5
Java
Be Able To

• Use public and private access specifiers


• Write constructors
• Write programs using the String class and
arrays

6
Java
Public and Private access
Specifiers
Name
Registration number Identified by
Name of the degree
Current Semester

7
Java
public class Student{ public String getName()

private String name; public void


setName(String nm)
private int regNo; public int getRegNo()
public void setRegNo(int r)

private String public String getDegreeName()


degreeName; public void
setDegreeName(String dnm)
public int getCurrentSemester()
private int
public void
currentSemester;
setCurrentSemester(int i)

8
Java
setRegNo(int r) Student object
regno 12345

9
Java
Constructor

• When we create an object using ‘new’


keyword a constructor is called.

• There can be more than one constructor for a


class.

10
Java
public class Student{
private String name; A constructor has
the same name as
private int regNo;
the class and has
private String degreeName; no return value.
private int currentSemester;
/*Constructors 1 for student who have decided the degree
they are going to enroll into */
public Student(String nm, String d){
setName(nm);
regNo=generateRegno();
setDegreeName(d);
setCurrentSemester(1);}

11
Java
/*Constructors 2 for student who have not
decided the degree they are going to enroll
into */
public Student(String nm){
setName(nm);
regNo=generateRegno();
setCurrentSemester(1);}
private int generateRegno(){
int nextNo=0;
//logic to generate reg no.
return nextNo;}
Folder 1
// place for setter methods 12
Java
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”);
}
}

13
Java
Can we create student object
similar to college object?–
Student student1= new
Student();

new Student();
Compiler
class Student{
looks for Student(){..}
}
But since we don’t have this
constructor the compiler flags an
error.
14
Java
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 more
constructors, then the compiler
does not insert any constructor.

15
Java
public class College{ public
Compiler inserts College(){
private String name;
super();
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”);}
Folder 2
}
References
Student student2=new Student(“Mary”);

HEAP
Pointing
to address
STACK of the
name:Mary
actual
regNo:2
student2 currentSemester:1
object in degreeName:null
memory
student2

17
Java
Student student1= new Student(“Mary”);
Student student2=student1;
student1.setName(“Merry Mary”);
System.out.println(student2.getName());

This code snippet prints


‘Merry Mary’. Why ?

18
Java
student2
name:Mary
Merry Mary
student1 regNo:2
currentSemester:1
degreeName:null

19
Java
null
• Default value of an object reference is null.
class Test{
Student student; null
void test(){
student.display() An error occurs at runtime
;
}
class Test{
void test(){ An error occurs at
Student student;
student.display()
compile time
;
} 20
Java
this
public class Student{
String name;

Student(String name){
name=name; this.name=name;
regNo=generateRegno();
currentSemester=1; }}
21
Java
public class Student{ public Student(String
String name; name){

… setName(name);

public Student(String regNo=generateRegno();


name, String d){ setCurrentSemester(1);
calls
this(name); }
setDegreeName(d); …
} }
22
Java
instanceof
• Usage:
object-ref instanceof class-name
returns a boolean value.
Example: true
Student s1= new Student(“Mary”);

System.out.println(s1 instanceof Student);

System.out.println(s1 instanceof College);


Compilation error

23
Java
null instanceof Student
returns false.

24
Java
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 that
object
OR
-- if the object goes out of scope and its
reference is not assigned to any other
variable outside its scope.

25
Java
Student student1= new Student(“Mary”);
Student studentref=student1;
student1=null;
How many objects are created?

studentref null
heap
student1

student
Will the student object created in the first
line be garbage collected?

26
Java
Instance members

public class Student{ Instance


member
private String name; variable
public void setName(String name){
...
}
Instance member
function

27
Java
Class members
public class Student{
private int gRegNo;
public Student(String nm){
regNo=generateRegno();
setCurrentSemester(1);}
private int generateRegno(){
gRegNo++;
return gRegNo; }}

28
Java
Student student1= new Student(“Mary”);
Student student2= new Student(“John”);

student1

student2 Student
Student name:Mary
name:John gRegNo:1
gRegNo:1 regNo:1
regNo:1

Again 1! Should be 2

29
Java
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
...} 30
Java
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());
}

31
Java
Student student1= new Student(“Mary”);
Student student2= new Student(“John”);

student1
gRegNo:2
Student
student2 name:Mary
Student
regNo:1
name:John
regNo:2

It is correct now.
32
Java
A static method can
access only static
members. Why?
Hint: A static member can
be called even if the
instances are not created.

Can constructors be static ?

33
Java
Class Constants

public class Student{


public static final int
MAX_STUDENTS=3000;
..
}

34
Java
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);

35
Java
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
36
Java
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”

37
Java
boolean equals(Object object)
boolean equalsIgnoreCase(String anotherString)

Example:
String s1=“abc”;
String s2=“sbc”;String s3=“ABC”;
s1.equals(s2) ;//returns false
s1.equalsIgnoreCase(s3) );//returns
true
38
Java
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 while
what we are want here is to
check equality of value of
strings.
39
Java
public String
substring(int beginIndex)
public String
substring(int beginIndex,
int endIndex)
Example:
“icecream".substring(3)
returns “cream“
“icecream".substring(0,3)
returns “ice”

40
Java
Comparing two strings:
public int
compareTo(String anotherString)
public int
compareToIgnoreCase(String str)
Example:
String s1="ABC";String s2="acc";
s2.compareTo(s1)
returns 32
s2.compareToIgnoreCase(s1)
returns 1 41
Java
String toLowerCase()
String toUpperCase()

String replace(char oldChar,


char newChar)
String
replaceAll(String reg,String replacement
)

boolean startsWith(String prefix)


public boolean endsWith(String suffix)

42
Java
Immutability

String s1="ABC";
String s2=“ABC”;

s1 ABC String pool

s2
43
Java
Strings are Immutable Objects.
String s1="ABC";
s1=“DEF” This string object
remains intact. This is
not changed.

s1 ABC
String pool
New String object is DEF
created

44
Java
Assigning string references:
String s1="ABC";
String s2=s1;
s2=“DEF”;
System.out.println(s1);// prints ABC

s1 ABC
String pool
s2 DEF

Compare this with object references (slide 15)


45
Java
Constructor:
String(String newStr)

String s1="ABC";
String s2=new String(“ABC”);

s1 ABC String pool

s2 ABC

46
Java
What is printed
String s1="ABC"; in each case?
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);

47
Java
Arrays

int sum=0,mul=0; Allocating 5 spaces for int


int num[]= new int[5];
Declaring array of type int
for(int i=0;i<num.length;i++){
sum=sum+num[i];
mul=mul*num[i];
}

Returns the size of the array


Accessing array elements

48
Java
int num[]= new int[5];

num[0] 0 num
num[1] 0
num[2] 0
0
num[3] 0
num[4]

automatically initialized to 0

49
Java
public class ArrayTest{
static int num[];
public static void main(String
args[]){
System.out.println(num); prints null
System.out.println(num[0]);
}
}

error at runtime
Folder 4
50
Java
Example for an array of
references
• We will implement Stack data structure that can
contain Strings
• We need to have an array of String objects
inside the Stack class.

51
Java
Creates an array
representing stack
public class Stack{
private String stackData[];
private int top; last insertion index
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
Folder 5
public String push(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 of
the list.

53
Java
public Object pop() {
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.
54
Java
public boolean isEmpty(){
if(top==-1) return true;
else return false; }
public boolean isFull(){
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());} 55
Java
Execute and find
out what happens
when you push 4th
element into the
stack?

Change the program to handle


the problem gracefully.

56
Java
Initializing arrays
• int [] a= {1,2,4,8,26};
• int [] a=new int[] {1,2,4,8,26};

anonymous array
int a[]= new int[0];

Creates an array of length 0

57
Java
‘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

58
Java
• 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()); 59
Java
Command Line Arguments

2 command line arguments sent to StudentTest class


60
Java
public class StudentTest{
public static void main(String
args[]){
//Creating object using constructor 1
Student student1=
new Student(args[0], args[1]);
}
}
Mary M.C.A.
Folder 6
61
Java
So what will happen if you
run StudentTest without
supplying command line
arguments ?

62
Java

You might also like