Documente Academic
Documente Profesional
Documente Cultură
Class
Part II
1
Java
Contents
1 Arguments passing
2 Passing primitive type
3 What is happening?
4 Passing reference type
5 Changing the member variable value of an object reference that is passed
6 Changing array contents in a method
7 Var-args
8 Accessing var-args
9 Overloading
10 Overloading with var-args
2
Java
Contents
11 Initializers
12 Static Initializer
13 Non-Static Initializer
14 Inner class
15 Types of Inner Class
16 Non static inner class
17 Creating InnerClass instance
18 Result of execution
19 Static Inner Class
20 Test your understanding
3
Java
know
• Argument passing
• var-arg
• Method overloading
• Initializers
• Inner classes and static inner classes
4
Java
Be Able To
5
Java
Arguments passing
• Arguments passing in java is always ‘pass by
value’.
6
Java
Passing primitive type
Folder 1
7
Java
public static void main(String args[]){
int r1=10, r2=20;
swap(r1,r2);
System.out.println(“r1=”+ r1);
System.out.println(“r2=”+r2);
}
}
8
Java
What is happening?
Stack
reg1=20,reg2=10
swap(r1,r2)
r1=10, r2=20 Changes made in swap
main() is not reflected in main()
9
Java
Passing reference type
public class StudentTest{
public static void swap(Student
p,Student q){
Student temp;
temp=p;
p=q;
q=temp;
Folder 2
}
10
Java
public static void main(String a[]){
Student s1=new Student(“John”);
Student s2=new Student(“Mary”);
swap(s1,s2);
System.out.println(“s1=”+
s1.getName());
System.out.println(“s2=”+ s2.getName()
} The program prints :
} s1=John
s2=Mary
11
Java
stack
q
p
swap(s1,s2) heap
s2 Mary..
s1 John..
main()
p heap
John
change(s1)
Mary
s1
main()
s
heap
sort(s1)
0
s1
1 Mary..
main()
John..
17
Java
What is the result when you execute the following?
class StudentTest{
public static void main(String args[]){
Student s1[]=new Student[2];
s1[0]=new Student("Mary");
s1[1]=new Student("John");
change(s1);
for(int i=0;i<s1.length;i++){
System.out.println("Name: " +
s1[i].getName());
}
}
public static void change(Student s[]){
Student temp[]=new Student[1];
temp[0]= new Student("Meena"); Folder 5
s=temp; } } 18
Java
Var-args
• This is a new feature in 1.5 .
• Allows you to specify that a method can take multiple
arguments of same type. The number arguments
may be 0, one or more.
• void go(int… x)
• void go(char c, int… x)
• void go(Animal… a)
• In a method only the last argument can be of variable
length.
19
Java
Accessing var-args
public class Person{
public Person(String name, String…
nicknames)
{
if(nicknames.length!=0){
for(String nm:nicknames)
System.out.println(nm);
System.out.println(nicknames[0]);
} }} Folder 6
20
Java
Can you write main() method
as
public static void
main(String... args)
instead of args[] ?
21
Java
What is the difference between an array and
var-args? (Are both
static void vararg1(int[] i) &
static void vararg2(int… i))
same ?)
Folder 7
22
Java
Overloading
public class CollegeUtility {
public static void
sortStudent(Student s[]){
..} So
many
public static void
sort
sortCollege(College c[]){
method
..} names !
no
List2: From list1, find all the
methods that exactly match
the argument type of
calling method.
yes
25
Java
no
no
Matching method found
List3: Find all the methods from
List1 where arguments of
calling methods are
automatically convertible yes
into arguments of called
methods.
no
26
Java
no
no
List4: Find among the
methods in List 3 methods
which are more specific
yes
List4 contains 1 element Matching method found
no
Error
27
Java
Examples
//exact match
public class StudentTest{
public static void display(int regno){
System.out.println(“Registration No.
"+regno);
}
public static void display(String name){
System.out.println(“Name. "+name);
}
public static void main(String str[]){
Student s1=new Student(“Mary”);
display(s1.getName());
display(s1.getRegNo());
Folder 8
}} 28
Java
//automatic conversion
public class StudentTest{
public static void display(long regno){
System.out.println(“Registration No.
"+regno);
}
public static void display(String name){
System.out.println(“Name. "+name);
}
public static void main(String str[]){
Student s1=new Student(“Mary”);
display(s1.getRegNo());
}}
Folder 9
29
Java
//more specific public static void
public class Fee { main(String[] args)
{
int id;
Fee f1= new
double amtPaid; Fee();
void pay(int id,double amt){ f1.pay(123,400);
this.id=id; }
amtPaid=amt; }
} Look at the conversion
sequence to find out which
void pay(int id,float amt) { argument is more specific.
this.id=id; Slide 34 of Nuts and Bolts
Folder 10
amtPaid=amt; }
//ambiguous
public class StudentManager{
public static void
changeSemester(int id, long sem){
…
}
public static void
changeSemester(long id, int seam){
… Automatic
conversion
}
public static void main(String str[]){
changeSemester(1,2);
}
}
31
Java
Overloading with var-args
class AddVarargs {
static void go(int x, int y)
{ System.out.println("int,int");
}
static void go(byte... x)
{ System.out.println("byte... ");
}
public static void main(String[] args){
byte b = 5;
go(b,b);
}}
Folder 11
32
Java
static void vararg(int[] i){}
static void vararg(int... x){}
cannot be overloaded.
33
Java
Initializers
• Initializers are blocks of code that are used to
initialize member variables.
a) Static Initializers
b) Non-Static Initializers
34
Java
But I can declare and initialize variables
in same line like this:
class X{
int var=1; }
Why will I require a block of code ?
35
Java
Let us say that you initialize
your variables after reading
their values from a file.
Reading from a file requires a
sequence of operations at the
minimum - opening a file,
reading and then closing a file
– this means a block of java
statements. This cannot be
done in one statement like
yours. So we do this in
initializers !
36
Java
I can put that code in
the constructor !
37
Java
Static Initializer
public class CollegeConstants{
public static final int YEAR_OF_INCEPTION;
public static final String COLLEGE_NAME ;
Static block
static{
/*
Open the file and set the required
YEAR_OF_INCEPTION, COLLEGE_NAME
*/
}
38
Java
Non-Static Initializer
public class OldStudent {
{
private int regNo;
private String name; Non-Static block
{
/*
Open the file and set the required reg_no, name
of each student
*/
}
}
39
Java
To understand what gets called
when, we shall execute the code
give below.
public class W{
public W(){
System.out.println("W constructor"); }
}
public class Z{
W w= new W();
{
System.out.println("instance block");
} Folder 12
40
Java
static{
System.out.println("static block");
}
public Z(){
System.out.println("Z constructor");
}
public static void main(String st[]){
new Z();
}
}
41
Java
Output:
static block
W constructor
instance block
Z constructor
42
Java
Inner class
• An inner class is a class defined inside the scope of
another class.
• It is also called Nested class.
• The class inside which the inner class is defined is
called outer class.
• Inner class can access all members of the outer class
including private members.
• Based on where the inner class is defined, the inner
class can be classified into two types.
43
Java
Types of Inner Class
• Member class
• Non Static Inner Class or simply inner
class
Note that in some books they don’t
• Static Inner Class
consider static inner classes as
inner classes. They are just
• Local Inner Class considered as nested classes.
47
Java
headNode
public class SinglyLinkedList{
private Node headNode;null
private int noOfNodes=0;
Inner class
class Node {
else {
current=headNode; headNode
headNode=tempNode;
headNode.nextNode = current;} private member of Node class
return
(String)headNode.currentObject;
}
headnode
null
current
tempNode null 49
Java
public String insertLast(Object addobj) {
create
Node create=new Node();
create.currentObject=addobj;
noOfNodes++;
if(headNode==null) First node headNode
headNode=create;
Iterate till the end of
else { the list and get the
Node tempNode = headNode; last node.
while(tempNode.nextNode!=null) {
tempNode = tempNode.nextNode;
}
headNode
tempNode.nextNode=create;}
tempNode
return (String)create.currentObject; create
} 50
Java
public String findNode(int index){Inappropriate index
if(index>noOfNodes) return null;
headNode
Node tempNode = headNode; For index=1
int i=0;
while(i++!=index) 0 1 2
tempNode=tempNode.nextNode;
tempNode returned
return tempNode;}
s=s+"\n"+((String)(n.currentObject.toString()
));
return s;
}
}//end of class
53
Java
class SampleTest {
public static void main(String args[]) {
SinglyLinkedList s = new SinglyLinkedList();
SinglyLinkedList.Node n;
//Insertion
s.insertFirst("Rama");
s.insertLast("Sita");
s.insertFirst("Hanuman");
s.insertLast("Ravana"); How would you create
an instance of Node
// printing class inside this class?
System.out.println("\nPrinting list
\n"+s.toString());
//Deletion
54
int temp=3; Java
if(n==null)
System.out.println("Invalid ID");
else
System.out.println("Deleting " +n);
//Search
temp=2;
if((n=s.findNode(temp))==null)
System.out.println(" Invalid ID ");
else
System.out.println("Found "+ n);
// printing
System.out.println("\nPrinting list
\n"+s.toString());
}
}
55
Java
Result of execution
Printing list
Hanuman
Rama
Sita
Ravana
Deleting Ravana
Found Sita
Printing list
Hanuman
Rama
Sita
56
Java
In lab find out what .class
files are generated when
you compile the LinkedList
class ?
57
Java
Static Inner Class
• A static inner class is a class that’s a static member of
the outer class which can access only static members of
the outer class(including private members). It is also
called top-level class.
• Structure:
public class OuterClass{
public static class InnerClass{} }
• Creating instance:
• Outside the outer class:
OuterClass.InnerClass sinner
=new OuterClass.InnerClass();
• Inside the outer class:
InnerClass inner=new InnerClass();
58
Java
Why static inner class
cannot access instance
members of the outer
class?
59
Java
class Sort{
private static void insertionSort(
int[] a,int s, int temp) {
Sorted array
No. of elements currently in the array New element to be added
int j = s; to ‘a’ in sorted position
while (j > 0 && a[j-1] > temp)
{
a[j] = a[j - 1]; slide elements down to
make room
j--;
}
a[j] = temp;
Sorted array
}
private static int binarySearch(int numbers[],
int key ){
int low,high;
Folder 14
Search element int div=numbers.length;
60
low=0; Java
high=numbers.length-1;
while(true){
div=(low+high)/2;
if(key>numbers[div])
low=div+1;
else if (key<numbers[div])
high=div-1;
else
return div;
Thanks !
68
Java