You are on page 1of 31

CSC 201

Lecture - 10
Agenda
• Parameter passing in Java.
• Sample programs.
• Introduction to Object-Oriented
Programming.
• Next Lab session.
Parameter Passing in Java
They are the ways in which parameters are
transferred between functions/methods when
one method calls another.
Ex: We can call a method mysort(parameters)
from our main() method in Java.
Please refer to lecture – 9 for example.
• We can pass pass parameters by two
mechanisms in general
Pass – By – Value/Pass – By – Copy
Pass – By - Reference
Pass-By-Value
• A copy of the argument is made and then passed to the receiving method.
Public static void MyMethod(int num)
{
System.out.println(“In MyMethod, the value of num is:”+num);
num = 3;
System.out.println(“num is:”+num);
} Callee
Public static void main(String[] args)
{
int number = 1;
MyMethod(number);
System.out.println(“Number is:”+number);
}
What is an argument? Caller
Pass By Value
• Pass-By-Value: A copy of the argument is
made and then passed to the receiving
method.
If the callee method modifies the value of
the argument inside of its method body,
the caller will never see the results of
these modifications.
Pass By Reference
• Later, when we cover Objects.
Scope
Java rules for scope in case of local variables:
1) A variable’s scope extends from the line it is declared
until the end of the block it is contained in.
2) A formal parameter’s scope is the entire method. What
is a formal parameter? They are the variables declared
in the parameter list of a method. In our case ‘int num’
in the method MyMethod().
3) A variable declared in the ‘for’ loop control has a scope
that extends to the end of ‘for’ loop
A local variable is the one which is accessible only within
the function or block where it is declared.
Passing Strings as parameters in
Java
For primitive type arguments in Java, the changes
made in the methods are not reflected in the
caller program/method.
Thus parameters are passed by value.
With non-primitive types, the changes made in the
methods are reflected in the caller
program/method. Exception: Strings.

With reference to Strings, let us see an example


first.
Passing strings as parameters
example
Public static void main(String[] args)
{
String mystr = “csc”;
StringMethod(mystr);
System.out.println(“mystr is:”+mystr);
}
Public static void StringMethod(String str)
{
str = “hi”;
System.out.println(“Str is:”+str);
}
STRINGS ARE IMMUTABLE!
• The reason that the changes made in the
methods are not reflected in the caller
program/method for strings is because
strings are immutable.
• It means Strings cannot be changed!
• String is a class, each string that is
created is a String class object.
• Strings are never actually changed,
instead a new string is created.
Example
Public static void main(String[] args)
{
String name = “Pavani”;
name.replace(‘a’,’x’);
System.out.println(name);
}
What is the output???
Public static void main(String[] args)
{
String name="pavani";
String new_name = name.replace('a','x');
System.out.println(name);
System.out.println(new_name);
}
Now we assign the name.replace to another string.
• So, if you pass a string as a parameter
even though it is supposed to act like an
array (i.e the changes made in the
methods must be reflected in the caller
program), they act like passing of the
primitive types! They are immutable!
Object-Oriented Programming
• What is an Object?
Look around you, you see many
objects in your daily life. Ex: In our
classroom ‘board’, ‘chair’, ‘pen’ are all
objects.
• Real-world objects share two
characteristics : state and behavior.
• Identifying the state and behavior is our
start to think in OOP terms.
State and Behavior
PEN (is an Object)
State Behavior

cap Write
Ink_amount Close
Fill_ink
Another Example
Car (is an Object)

State Behavior

Color SpeedUp
Speed Brake_apply
gear Gear_change
Another Example
Table-Lamp (is an Object)

State Behavior

On Turn On
Off Turn Off
Software Object
• Like real world objects, Software objects
are conceptually similar. They consist of
state and behavior.
• An object stores its state in fields
(variables in some programming
languages) and behavior through methods
(functions in some programming
languages).
• A set of possible variables and methods
for our object ‘pen’ might be:
Variables: boolean cap;
double ink_amount;

Methods : write();
fill_ink();
Data Types in Java
• Java is a strongly typed language. It
means that every variable used has a type
that is known at compile time.
• Importance of type: It helps limit the
values that a variable can hold, limit the
operations on those variables.
• Strong typing helps detect errors at
compile time.
Data Types in Java
• In Java types are divided into two
categories: primitive types and reference
types.
• Primitive types: int, float, char etc.
• Reference types: class type, interface type
and array type.
Memory representation-Arrays
• When you declare an array, memory does
not get allocated. It just simply allocates
memory to contain a reference to the
array!
• int[] myarr; 100
myarr
234
Memory allocation - Arrays
• When array size is ‘5’, int[] myarr = new
int[5] Myarr[0] 100

Myarr[1] 101

Myarr[2] 102

Myarr[3] 103

Myarr[4] 104
Reference Types
• A data type is a set of values and set of
operations defined on those values.
• The java class provides a mechanism for
defining our own data types. In a class we
specify the data type values and
implement data type operations.
Designing Our Data Type
Example:

Public class car Creating a class

Car(int speed, int gear)


Constructor

void changeSpeed(int speedIncrement)


void changeGear(int newGear)
Instance Methods
Classes in Java
A class can be defined as a blueprint / template or
prototype for objects.
Constructor: It is a special method with the same
name as the class and no return type. If you want
to initialize variables based on certain conditions
when your class is created we use constructors.
Instance Methods: Can take arguments and return
the values. They are not static methods!
How to use data types in our code?
• We should be able to declare variables, create objects to
hold data type values and invoke methods and
manipulate these values.
• Declaring variables: We can declare the variable of a
reference type as we did for a primitive data type.
Ex: car car_variable;
• Creating Objects: In Java, each data type value is stored
in an object. When client invokes a constructor, the Java
system creates or instantiates an individual object.
Keyword ‘new’ is used.
Ex: car car_variable = new car(20,2);
Example
Class car
{
int speed;
int color;
int gear;
void changeSpeed() { …. }
void changeGear() { ………….}
}
Class main
{
public static void main(String[] args)
{
// We create instances of the class car here
}
}
class car
{
String color;
int speed;
int gear;

car(int const_speed, int const_gear)


{
speed = const_speed;
gear = const_gear;

}
car()
{
color = "RED";
speed = 80;

public void speedUp(int speedIncrement)


{
speed = speed + speedIncrement;
}

void printCarDetails()
{
System.out.println("New Speed is:"+speed+" NewGear is:"+gear);
}
}

public class Main {

public static void main(String[] args) {


// TODO code application logic here

car toyota_instance = new car(10,2);


car BMW_instance = new car();

toyota_instance.speedUp(30);
BMW_instance.speedUp(20);
System.out.println("My toyota car details are:");
toyota_instance.printCarDetails();
System.out.println("BMW car details are:");
BMW_instance.printCarDetails();
}
}
• In Java, each data type value is stored in
an Object.
• You can create any number of objects of a
particular class.
• In my previous example, I had 2 car
objects.
Static Methods & Instance Methods
• Static methods should be invoked with the
class name. Ex: Math.abs().
• Instance methods is invoked with Object
name.
• Instance methods are used to implement
data type operations.
• Instance methods manipulate object value
where as static methods compute return
value.

You might also like