You are on page 1of 88

CSE-2102

Object Oriented Programming

Dr. Muhammad Ibrahim


Assistant Professor
Dept. of Computer Science and Engineering
University of Dhaka
Topics
● Basics of OOP
● Basics of Java: comments, branching, iteration, block of
code, variable scope, literals
● Data and expression types
● Pitfalls of assignment statement
○ Type conversion
○ Type casting

2
Dr. Muhammad Ibrahim
Abstraction in OOP
● The core philosophy of OOP is to visualize the problem in
terms of abstraction.
● While functional programming also encourages this
concept (using structure in C/C++, for example), OOP
provides a rich set of features to ease the implementation
of this abstraction.

3
Dr. Muhammad Ibrahim
Three Concepts of OOP
● Encapsulation
○ The mechanism that binds data and code together.
○ it keeps data safe from outside interference.
● Inheritance
○ This mechanism allows for reusing codes and data.
● Polymorphism
○ This mechanism allows the programmers to use the same
name for multiple (but related) entities.

4
Dr. Muhammad Ibrahim
Very Basics of Java
● Comments
● Basics of main function
● Console I/O
● Branching statement
● Loops
● Block of code
● Some lexical matters

5
Dr. Muhammad Ibrahim
Comments
● Mostly same as C/C++

//a one line comment

/* multiple

line

comment.

*/
6
Dr. Muhammad Ibrahim
Basics of main Function
public static void main

● All Java application programs start from main function.


○ Like C/C++.
○ Applets (now obsolete) and some other schemes, however, don’t have main.
● “public” is called the access specifier
○ Has the same meaning as C++.
○ Public because main function should be called outside the class in which it is
defined.
● It is a static method because it should be executed before creation of any class.
○ Inside a static method, a non-static method (of the same class) cannot be
called without using an object.
○ Static methods can be called without using objects.
7
Dr. Muhammad Ibrahim
Basics of main Function (Contd.)
● There is an important difference between main function of
Java and that of C/C++
○ In C/C++, main is a standalone function in the sense that it
has no relationship with a class.
○ In Java, however, main is always inside a class.

8
Dr. Muhammad Ibrahim
Console Input and Output
Point to note: Console inputs and outputs are not very common in real-life Java
programs as these programs involve graphical user interfaces (GUI).

System.out.println("My first Java program.");

● Newline appended at the end of the string.


● System is a predefined class (details later).
○ It is by-default included in a program.
● out is a stream (object) connected to the output stream (details later).

9
Dr. Muhammad Ibrahim
Console Input and Output
Power of System.out.println function:

int i=10;
System.out.println("Value of i: " + i);

char ch;
c = (char)System.in.read();
● Reads characters, but returns as integers.
● Line buffered, so ENTER must be pressed.
● Also, this function may throw IOException (will be discussed later).

Another way to take console input:

Scanner sc = new Scanner(System.in);


int num = sc.nextInt();

Many other ways are there !


10
Dr. Muhammad Ibrahim
Conditional Statements
● if-else
● switch

11
Dr. Muhammad Ibrahim
Iteration
● for
● while
● do-while

12
Dr. Muhammad Ibrahim
Block of Code
Same as C/C++

13
Dr. Muhammad Ibrahim
Lexical Matters
● Whitespace, identifier, literal, comment
○ All have mostly the same rules as C++.

14
Dr. Muhammad Ibrahim
So we have already covered the very basics of Java!

15
Dr. Muhammad Ibrahim
Data Types
Java is a strongly typed language. Part of Java’s safety and robustness emerge
from this property.

● Every variable and expression has a strictly defined type.


● In an assignment operation, no type-conversion or type-coercion of conflicting
types takes place automatically.
○ For allowable types, however, automatic conversions do take place.
■ E.g.: assignment of an integer to a long is allowed.
■ But a double value cannot be assigned to a byte type - we need casting before this
assignment.

16
Dr. Muhammad Ibrahim
Data Types
Primitive types/Simple Types

1. Integers: byte (8 bit), short (16 bit), int (32 bit), long (64 bit).

2. Floating-point: float (32 bit), double (64 bit).

3. Character: char (16 bit).

4. Boolean: boolean.

5. Latest: “untyped” variable, type assigned during initialization.


var i = 10; var j = 3.4;

17
Dr. Muhammad Ibrahim
Data Types
A few points to note:

● Java doesn’t have unsigned type.


● Primitive types are not object-oriented features.
○ Java provides object-oriented features such as “Integer” (which will be discussed later).
● So why not make all primitive types object-oriented?
○ Because it will reduce the efficiency as objects take more CPU cycles than primitive types.
● As opposed to C/C++ where a string is an array of characters, in Java a string
is an object, and is declared with the keyword String.
○ Using objects enables us to use a rich set of built-in functions on strings (will be discussed
later in details).
○ However, using explicit character array is still allowed.

18
Dr. Muhammad Ibrahim
Data Types
● In C/C++ the size of a particular type depends on the platform. In Java,
however, the size is fixed (32 bit for an integer) irrespective of the platform.
● In C/C++, a char is 8-bit long that contains the ASCII value of a character.
Java, on the other hand, uses Unicode representation of characters - so a
char in Java has 16 bits - this is to accommodate all different languages’
symbols.
○ Note: the ASCII values of English letters are still the same in Unicode, so ’A’ still has 65 as
Unicode, for example. Unicode is a bit inefficient for the languages where it were not required
e.g. English, but for the sake of global portability this price is paid.

19
Dr. Muhammad Ibrahim
Variables
● Declaration
● Initialization
● Assignment

20
Dr. Muhammad Ibrahim
Variables
● Inside block of code: same as C/C++.
○ A difference between C/C++ and Java: the following code segment is valid in C/C++ but not in
Java:
{
int i=1;
{
int i=2;
}
}
● Inside a function: same as C/C++.
○ Global variable: allowed if it is inside a class.
● Inside a class: like C/C++
○ Accessible inside a class. Regarding access mode outside the class, this depends on the
access mode of the variable (private or public etc.).
○ More on this will be discussed later.
21
Dr. Muhammad Ibrahim
A Note on “code” Outside Methods (but inside class)
Allowed: Initializations, expression

Not allowed: loops, branching statements, method calls.

Question: When are such statements called?

Ans.:

22
Dr. Muhammad Ibrahim
A Note on Code Outside Methods (but inside class)
Allowed: Initializations, expression, block of codes.

Not allowed: loops, branching statements, method calls.


However, these are allowed inside the (static) block of code.

Question: When are such statements called?

Ans.:
1) For non-static fields, at the time of object creation of the class, before the
constructor call.
2) For static fields, once for the class definition (not for each object creation).
Just when main function begins execution (before any statement).
23
Dr. Muhammad Ibrahim
Type Conversion and Casting
As stated earlier, in an assignment operation, no type-conversion or type-coercion
of conflicting types takes place automatically.

For allowable types, however, automatic conversions do take place. E.g.


assignment of an integer to a long is allowed. But a double value cannot be
assigned to a byte type - we need to cast before this assignment.

24
Dr. Muhammad Ibrahim
Automatic Conversions
Two conditions in assignment operation:

1. Two types must be compatible. Numeric types (integer and floating point
numbers) are compatible to each other, whereas numeric types are not compatible
with char and boolean. Also, char and boolean are not compatible.

2. The destination size must be bigger than/equal to the source.

25
Dr. Muhammad Ibrahim
Coercion (Type Cast)
● In C/C++, type casting is done by default.
● In Java, however, it must be explicitly cast.
○ For example, the following code segment is valid in C/C++:
double d=12.3467;
int i = d;
○ But in Java explicit type cast is required as follows:
double d=12.3467;
int i = (int)d;
○ That’s why Java is strongly typed language - you (i.e., the programmer) are totally aware of
exactly what’s being stored in an assignment operation.
○ From int to byte, the number that is stored is the modulo by the range of the byte.
○ For floating to integer, the fractional part of the number is truncated.

26
Dr. Muhammad Ibrahim
Next Topics
Automatic type promotion
Basics of array
Basics of string
Pointer
Operators
Branching statements
Iterations
Classes
27
Automatic Type Promotion
In addition to assignment operation, in an expression, type casting may occur.
byte a=100, b=100;
int i = a*b;
Here the term a*b exceeds the range of byte.

To overcome this problem, Java automatically converts bytes, short and char to int, and
integers to long.

The above may cause unexpected error, however. Consider the following code that
raises a compile time error:

byte b=10;
b=b+2;//trying to assign an integer to byte! Error!
28
Dr. Muhammad Ibrahim
Automatic Type Promotion
Type Promotion Rules

1. In the beginning, all byte, short and char are converted to int.

2. If any one operand is long, the whole expression is made long.

3. If any one operand is float, the whole expression is made float.

4. If any one operand is double, the whole expression is made double.

29
Dr. Muhammad Ibrahim
Array
● Array in Java works a bit differently than that of C/C++.
● To declare an array, we write:
int a[10];
● but to allocate space for the array, we need to write:
a = new int[10];
● In C++, new operator is used only for allocating dynamic memory (i.e.,
memory from heap space as opposed to stack memory).
○ In contrast, in Java all arrays are dynamically allocated.

30
Dr. Muhammad Ibrahim
Array (Contd.)
● The initial values are automatically made 0 or equivalent, in particular, 0 for
numeric values, null for reference type variables (remember that Java has no
explicit pointers), and false for boolean values.
● Array access rules are the same as C/C++.
● Multidimensional arrays are just like that of C/C++.

31
Dr. Muhammad Ibrahim
String
In Java, unlike C/C++, a string is not a sequence of character literals. A string in Java is in fact an object,
not a primitive data type.

We’ll discuss strings in details later in this course, but for the time being below I show how to use a string
literal:
String str = "A text";
System.out.println(str);

Unlike C/C++, a string is not terminated by a null character. Rather, the null character is just like any other
character.
String s = new String("a\0b");
System.out.println("s: " + s + ", len:" + s.length());
Output: s: ab, len: 3

Finally, C-like character arrays are still allowed (but seldom used):
public char str[] = new char[80];
str[0] = 'a';
str[1] = 'b';
System.out.println("str: " + str); // output: ab 32
Dr. Muhammad Ibrahim
Pointer
● The concept of pointers is fundamental in almost all programming languages.
● In C/C++, programmers can explicitly manipulate pointers.
● In Java, however, programmers cannot explicitly manipulate pointers, but
rather Java compiler manages the pointers.
○ Why you ask? Because one of the main merits of Java is that a Java program does not access
"non-permitted" resources of a host computer.
○ More specifically, we know that a pointer can access any address of the host computer. But a
Java program is not meant to have unlimited access to host computers. If Java were to allow
programmers to use pointers, a Java program could not be said to be non-interfering with the
host computer’s resources.
○ Also, lack of direct pointer arithmetic relieves many programmers.

33
Dr. Muhammad Ibrahim
Operators
● Four groups of operators: arithmetic, bitwise, relational and logical.
● Besides these, there are some special operators.
● Regarding arithmetic operators, the operands can be any data type save
boolean.
○ char is a subset of int type, so char has no issues to be operands.
● Regarding relational operators, unlike C/C++, statements like if(a) and
if (!a) are not valid in Java if a is not a boolean
○ You need to write the full version, i.e., if (a != 0) and if (a==0).
○ However, if a is boolean, then this is fine.
○ In C/C++, true is any nonzero value and false is zero. In Java, in contrast, true and false are
non-numerical values which don’t have any relationship with zero or nonzero.
● An important operator: instanceof
○ if (ob instanceof myclass) … …
34
Dr. Muhammad Ibrahim
More on Branching Statements
● In C/C++, the variable based on which branching is performed can be only a
few (int, char).
● In Java, however, a rich set of types can be used as branching variable: byte,
short, int, char, enumerations (to come later) and (from JDK 7) Strings.
● Recall that if-else is more powerful than switch in that switch can check only
for equality, whereas if-else can check for greater/less relationships etc. as
well.
○ However, switch statements are easy to manage when we need a long if-else ladder.
○ Also, from the perspective of a compiler, a switch statement is faster to execute than an
equivalent if-else.
○ Update: from JDK 17 (late 2021), flexibility of switch statement has been greatly empowered.
■ Check yourself.
35
Dr. Muhammad Ibrahim
Iteration
● Already discussed
● Recall that the following code is valid both in C++ and Java, but not in C:

for (int a : array) { //array is an array of integers

36
Dr. Muhammad Ibrahim
Jump Statements
● Conditional and unconditional break, continue and return.
○ Same as C/C++.
○ Note: too many jump statements harm the readability of your code, so use them wisely.
○ Labeled break and labeled continue are also possible in Java, but seldom used.
● In addition to these jump statements, an additional way to break the normal
execution of a program is to use Java’s exception handling mechanism (which
will be taught later).
○ C++ also has this mechanism in a slightly different form.
● Unlike C/C++, Java doesn’t provide a goto statement as goto dismantles
the structured programming normt by jumping to here and there, thereby
creating the so-called "spaghetti code" problem.

37
Dr. Muhammad Ibrahim
End of Lecture 4.

38
Dr. Muhammad Ibrahim
Next Topics
● Class
● Methods
● Reference variable
● Garbage collection
● Arrays of objects
● Overloading

39
Dr. Muhammad Ibrahim
Class Method definition:
● Recall that Java is ret-type func-name(param-list)
object-oriented. {
● class is used to define object. //body of the function
}
● Members
○ Can be data or code (or both)
○ Private members: accessible only Instantiation of objects (allocating
inside the class where it is declared.
○ Public members: accessible by all
memory):
classes.
class-name object = new class-name();
○ Protected and default: to be
discussed later.
Calling (public) members from outside:

object-name.member
40
Dr. Muhammad Ibrahim
Class
class class-name {
private int i; //private variable
public char ch; //public variable

public void f(){


// code here…
}

public static void main(String args[]){


class-name ob = new class-name();
ob.f();
//ob.i; // Compile time error
}//main
}//class

41
Dr. Muhammad Ibrahim
Class
● Like any other OOP language, a class is at the heart of Java.
● However, unlike C++ where you may or may not use a class, in Java it is
mandatory to use at least one class in a program, and any code you write
must be a part of some class.
○ That is, unlike C++, there is no concept of "non-member function" in Java.
● So in this sense Java is a “strictly” OOP language as opposed to C++.
● A class defines a new data type which can be used to create objects, i.e., to
allocate physical memory.
● Every object of a class has its own memory space.

42
Dr. Muhammad Ibrahim
Class (Contd.)
Some differences from C++:

1. In C++, you can write:


myclass a; //assuming no constructor function is present
a.data = 10;//assuming data is a public int in myclass
But in Java, you must write:
myclass a = new myclass();
a.data = 10;//assuming data is a public int in myclass

2. There is no semicolon after class definition.

3. In C++, we write public to make the data/code public. In Java, this is not the
case. (public or no access specifier - details later)
43
Dr. Muhammad Ibrahim
Class (Contd.)
Notes:

● When we compile a Java program (i.e., .java file), a .class file is created for
each of the classes present in the file.
○ Note that if you create multiple objects of the same class, there will exist a single class file for
that class.

myclass a = new myclass();


myclass b = new myclass();
In the above, two objects of type myclass are created, but there will be a
single myclass.class file in the directory.

44
Dr. Muhammad Ibrahim
Class (Contd.)
● Declaration versus allocation of memory
○ If we write myclass ob ; this is a declaration, more specifically, a reference type variable ob
that can point to an object of type myclass.
○ Then when we write ob = new myclass(); the physical memory is allocated. ob actually
stores the starting byte address of the memory allocated for the object.
○ In C++, you can manipulate a pointer variable -- pointer to a class object. In Java, however,
you cannot manipulate the reference variable (e.g., ob++ in the above example).
● Whenever an object of a class is created, a constructor function is called.
(Discussion to come after a few slides.)
○ If the programmer doesn’t write a constructor, a default constructor is called (whose job is to
initialize the data with default values).
● Why primitive types such as int, char etc. are not implemented as objects?
○ The reason is efficiency - an object creation process incurs some overhead, i.e., spends some
CPU cycle.
45
Dr. Muhammad Ibrahim
Access Control
● Three access modes: public, protected and private.
● In addition to these three, using no modifier means yet another option that the
member is accessible to the members of this package but not outside this
package. (A package is a collection of classes.)
● protected is related to inheritance which will be discussed later.
● public and private modes work like that of C++.

46
Dr. Muhammad Ibrahim
Takeaways from the Discussion on Class
● Class is a construct that has members, i.e., data or code or both.
● It’s members can be private, public, default, or protected
○ If public, they can be accessed outside their respective class in conjunction with an object
○ If private, they cannot be accessed outside their respective class
■ Private members can be indirectly accessed through public interfaces, i.e., functions.
● Class is a definition of a user-defined data type, NOT a memory allocation
mechanism
○ Object declaration allocates physical memory.

47
Assignment of Object Reference Variables
myclass a = new myclass();
myclass b = a;

The above code snippet doesn’t create a new object for b=a statement, but rather
simply copies the address of object a to b so that both a and b point to (in Java
jargon, refer to) the same physical object.

Now making b=null doesn’t destroy the physical object, but rather a still refers to
the physical object.

48
Dr. Muhammad Ibrahim
Output?
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
HelloWorld a = new HelloWorld();
HelloWorld b = a;
System.out.println(a.hashCode() + " " + b.hashCode() + "s: "
+ a.equals(b));
}
}

49
So Far We’ve Learnt…
● When Java was invented and why?
● Very basic constructs of Java
○ Data types and assignment
○ Branch statement
○ Iteration
○ Methods
○ Class
■ How to define
■ How to access its members
■ private/public members
■ Memory allocation
● Benefit of the encapsulation mechanism of OOP over non-OOP
○ The stack example: how a real-life scenario can be translated into a program
50
Methods
● Unlike C/C++, functions in Java are usually called methods.
● Methods follow the same rules as C/C++ regarding return types and
parameters.
● Recall that there is no provision for creating non-member functions in Java.

51
Dr. Muhammad Ibrahim
Constructor Methods
● In programming, initialization of variables is often needed.
● Almost each object needs some sort of initialization when created.
○ A bank account may need to set some initial fund
○ A library may need to set the number of available books
● Now, whenever we create an object, we could initialize its data, perhaps by
calling a function (e.g., init()).
● However, a constructor function offers a handy way to achieve this.
○ A special member function that is automatically called by the compiler immediately after an
object is created.
○ So we just need to put our code of initialization inside this function

52
Dr. Muhammad Ibrahim
Constructor Method
public class constructors {
int num;
String str;

public constructors() {
System.out.println("Inside constructor ... ");
num = -1;
str = "No string yet.";
}

public static void main (String args[]){


constructors ob = new constructors();
}
}

53
Dr. Muhammad Ibrahim
Constructor
● Constructor method takes the same name as the class.
● If the programmer does not write a constructor, Java compiler puts a default
constructor.
● Constructors may take parameters but does not have a return type.
○ If you do put a return type, it will be treated as a normal method, not as a constructor.
public class constructors {
int num;
public static void main (String
String str;
args[]){
constructors ob = new constructors();
public constructors(){
ob.constructors(5);
System.out.println("Inside my constructor");
}
}
}
public int constructors(int n) {
System.out.println("Inside method ... ");
num = n;
System.out.println("num inside method: " + Output: ?
num);
str = "No string yet.";
return n;
} 54
Dr. Muhammad Ibrahim
Constructor
● Constructor method takes the same name as the class.
● If the programmer does not write a constructor, Java compiler puts a default
constructor.
● Constructors may take parameters but does not have a return type.
○ If you do put a return type, it will be treated as a normal method, not as a constructor.
public class constructors {
int num;
public static void main (String
String str;
args[]){
constructors ob = new constructors();
public constructors(){
ob.constructors(5);
System.out.println("Inside my constructor");
}
}
}
public int constructors(int n) {
System.out.println("Inside method ... ");
num = n;
System.out.println("num inside method: " + Output
num); Inside my constructor
str = "No string yet.";
Inside method ...
return n;
} num inside constructor: 5 55
Dr. Muhammad Ibrahim
Constructors: Java Vs. C++
Parameterized constructors, return types etc. follow the same rules.

The default constructor of Java sets the default values to variables, i.e., 0 to
numeric, null to character and false to boolean.

In C++, this is not the case, i.e., you might see garbage values if you print a
variable without assigning an explicit value.

In addition, C++ has another similar function called destructor whereas Java does
not.

56
Dr. Muhammad Ibrahim
“Destructor” Function?
● When it comes to an object going out of scope, is there
any counterpart to constructor function? Dangling pointer in C/C++
● In C++, a destructor function can be defined that is
invoked whenever an object is going out of scope, i.e., it
can no longer be cited.
○ Benefits as well as side effects (mainly due to pointers).
● In Java, however, no such function is there.
○ Ques.: How then are Java program’s resources released?
○ Ans.: Using Java’s own garbage collection mechanism (to come
after a few slides).

https://en.wikipedia.org/wiki/Dangling_pointer
57
Dr. Muhammad Ibrahim
Passing Objects to Functions
● Just like other data types, objects can be passed to functions as parameters.
● Background (from your knowledge of C)
○ Call-by-value: e.g. passing built-in data types
○ Call-by-reference: eg. (1) passing arrays, (2) passing pointers.

58
Dr. Muhammad Ibrahim
Example
public class myclass { public class yourclass {
public void pass_args(yourclass ob){ public int num;
ob.num++;
System.out.println("Hashcode inside method: " + ob.hashCode());
yourclass(){
} num = 10;
public yourclass return_ob(){ }
yourclass ob = new yourclass(); }
ob.num = 100;
return ob;
}
public static void main(String args[]){
myclass mob = new myclass();
yourclass yob = new yourclass();
System.out.println("Hashcode inside main method: " + yob.hashCode());

System.out.println("num in yourclass: " + yob.num);


mob.pass_args(yob);
System.out.println("num in yourclass: " + yob.num);

yourclass yob2 = mob.return_ob();


System.out.println("returned: " + yob2.num);
}
}

59
Dr. Muhammad Ibrahim
End of Lecture 5.

60
Reference Variable’s Benefit Over Pointer Variable
● When you use a reference parameter, the compiler automatically passes the
address of the variable used as the argument; there is thus no need to type
‘&’ as required in C/C++.
● Furthermore, inside the function there is no need to use * to update the value
since the compiler knows it.
● Important: the reference variable, unlike the pointer variable in C/C++, cannot
be changed.
○ In the previous example, n++ inside the function would NOT mean the next location to n, but
rather would mean the value of n is increased by 1.
● Reference is thus a more convenient and handy way than the pointer to
implement call-by-reference concept.
61
Dr. Muhammad Ibrahim
Passing Objects to Functions: Java Vs. C++
● In Java, objects are passed using the called-by-reference scheme.
○ No bitwise copy of members, rather just a reference of the object is passed.
○ So changes in the object’s data inside the called function does change the object’s data of the
calling function.
○ Since there is a single copy of the members of the object being passed as parameters,
changes made inside the called function will be visible in the calling function.
● In C++, in contrast, objects are passed using the called-by-value scheme.
○ Bitwise copy of members.
○ So changes in the object’s data inside the called function doesn’t change the object’s data of
the calling function.
○ To implement call-by-reference in C++, address of an object (in the form of explicit pointer) can
be passed which requires the parameter to be a pointer to that object. A special reference type
variable is also allowed.

62
Dr. Muhammad Ibrahim
Returning Objects from Function: Java Vs. C++
● In Java, when an object is returned by a function, a reference to the object is
returned.
● In C++, in contrast, when an object is returned by a function, a temporary
object is automatically created that holds the return value.
○ This (temporary) object is returned to the calling function.
○ After returning, this object is destroyed.
■ So possible side effects need to be considered if destructor function is defined.
○ Constructor function, however, is not called (like the case of call-by-value).
○ Important: many compilers, however, avoid creating the above-mentioned temporary object.

63
Dr. Muhammad Ibrahim
In a Nutshell: Using Objects as Parameters and Return Types

● A major difference between C++ and Java is as follows. In C++, when we


pass an object to a function as a parameter, the call-by-value scheme is used,
i.e., a bitwise (physical) copy of the object is created. In Java, in contrast, the
call-by-reference scheme is applied in the sense that object variables are
reference variable by-default (recall that copying a reference to another
reference means that copying the address of the object), i.e., a reference to
the object is created, so no new object is created.
○ Note, however, that in Java when we use primitive data types, it is passed using the
call-by-value concept.
● Regarding returning an object from a method, the above discussion also
applies here.
64
Dr. Muhammad Ibrahim
this Reference
● A special reference called “this” which is automatically passed to any method
when it is called. ob.f1();
● It is a reference to the object that generates the method call.
● A common use of “this” is to remove ambiguity:

void myclass (int num){


this.num = num; //assume that num is a variable of myclass.
}

Output of the following code?


boolean check (myclass ob){
if (ob == this) return true; return false;
}
System.out.println(mob.check(mob));//mob is a myclass type object
myclass mob2 = new myclass(4), mob3 = new myclass(4);
System.out.println(mob2.check(mob3));
65
Dr. Muhammad Ibrahim
Garbage Collection
● In C/C++, if we dynamically allocate memory (using malloc() or new), we
need to free it using free() function or delete operator.
● In Java this is done automatically by the Java runtime system.
○ When no reference of an object exist, it is automatically deallocated.
■ So no way for the dangling pointer to be created!
○ Garbage collector runs periodically, without informing the programmers.

66
Dr. Muhammad Ibrahim
“finalize” Method
● In C++ we have the notion of a destructor function which is called automatically
when an object is going out-of-scope.
● In Java although we don’t need to deallocate memory, we may need to perform
some bookkeeping tasks such as closing a file.
● A “finalize” method is called just before the object is about to be deallocated by the
garbage collector.
○ The programmer doesn’t know when the finalize method is called. So if we want to release some
resources at a specific time, we need to do it manually, i.e., writing a normal method - not the finalize
method.
■ Here lies a difference between C++’s destructor and Java’s finalize - a destructor is called when
an object goes out-of-scope, so we know at what point of code it is called (and so you can work
out the output). But a finalize method is not necessarily called when an object goes
out-of-scope, but rather the programmer doesn’t know when it will be called (by the garbage
collector).
○ So is C++ more powerful than Java in this regard? Not necessarily, as we dive into details of Java
we’ll see that the need of a destructor function is not felt at all in Java.
67
Dr. Muhammad Ibrahim
Arrays of Objects
● Since the objects are (user-defined) data types, like other variables you can
create array of objects.
● Syntax is the same as others arrays.
myclass ob[] = new myclass[4];
ob[0] = new myclass();
ob[1] = new myclass();
myclass nob = new myclass();
myclass ob2[] = {new myclass(4), new myclass(3)};
// myclass ob3[] = {4, 5}; // ERROR in Java, but OK in C++
System.out.println(nob.getClass());
System.out.println(ob.getClass() + " " + ob.hashCode());
System.out.println(ob[0].hashCode() + ", " + ob[1].hashCode());
System.out.println(ob[0].getClass());

Note: Java object’s physical address is not usually visible (however, advanced libraries may do it).
Hashcodes are just “symbolic identifiers” for objects used by JVM to allocate physical memory.
68
Dr. Muhammad Ibrahim
Digression: try these yourselves
● == operator //checks references (i.e., hashcodes) of the two objects
● instanceof operator
● equals() method //checks the contents of the two objects
● compareTo() method
● compareToIgnoreCase() method
● compare() method
● hashCode() method
● getClass() method
● toString() method //default implementation returns classname@hashcode_ in_Hex.

… with both your defined objects and string objects


69
Array of Objects (contd.)
myclass twob[][] = {
{new myclass(3), new myclass(), new myclass()},
{new myclass(2)}
};
System.out.println(twob + ", # rows: " + twob.length);
System.out.println("# cols in 1st row: " + twob[0].length +
", # cols in 2nd row: " + twob[1].length);

70
“new” Operator
● Alternative to malloc() function of C, in Java we have new operator.
● Safer (less chance of syntax error) and more convenient way for dynamic
memory management.
● Advantages of new over malloc()
○ No sizeof is required.
○ No type-casting is required.
■ In C, no casting is required for malloc(), but in C++ it does.
○ Possible to initialize during memory allocation.
● Note: why dynamic memory (using new)?
○ Much more memory allocation than static allocation is possible
○ 10000000 sized integer array was not found to be possible in my experiment, but with dynamic
memory it was found to be fine!

71
Dr. Muhammad Ibrahim
Overloading
● In OOP, polymorphism is mainly achieved using function overloading.
● Overloading mechanism in Java works just like that of C++.
○ Overloading of normal methods
○ Overloading of constructors

72
Dr. Muhammad Ibrahim
Recursion
Recursion in Java follows the same rules as in C/C++.

73
Dr. Muhammad Ibrahim
Topics
The keyword “static”

The keyword “final”

More on strings

Command-line arguments

Nested class

Variable length arguments


The Keyword “static”
● In Java every method must be inside some class.
○ So an object must be used to call a method outside the class where it is defined.
● However, sometimes we want to call a method without creating an object of
the class to which the function belongs.
● In these cases, we write the keyword static in front of the function.
● Both the functions and variables can be declared static.
○ If we want to use a static method in a class where it is declared, we just use it by calling its
name.
○ If we want to use it outside its class, we need to write classname.methodname format - but
without creating an object.

75
Dr. Muhammad Ibrahim
The Keyword “static”
● The variables that are declared as static are actually global variables, i.e., all
objects of this class share a single memory space.
● Restrictions that apply on static methods are as follows:
○ can call only static methods.
■ Non-static methods must be called using an object.
○ can only access static data.
■ Non-static data must be accessed using an object.
○ cannot use “this” or “super”

76
Dr. Muhammad Ibrahim
The Keyword “static”
● There is a mechanism to initialize static variables which is using a static block
of code.
● This block is executed just after all the static statements (i.e., that involve
static variables) are executed.
● The example of the following slide demonstrates this scenario.

77
Dr. Muhammad Ibrahim
The Keyword “static”
// Demonstrate static variables, methods, and blocks.
class static_usage {
static int a = 10;
static int b;
static void func(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Initializing static block");
b = a + 2;
}
public static void main(String args[]) {
func(100);
}
}
78
Dr. Muhammad Ibrahim
The Keyword “static”
class HelloWorld {
static int a; Output?
static int b;
static {
System.out.println("a: " + a + ", b: " + b);
}
{
b++;
System.out.println("b in block: " + b);
}
public HelloWorld(){
System.out.println("constructor");
}
public static void main(String[] args) {
System.out.println("Hello, World!");
var ob = new HelloWorld();
var ob2 = new HelloWorld();
} 79
}
The Keyword “static” Output:
class HelloWorld { a: 0, b: 0
static int a; Hello, World!
static int b; b in block: 1
static { constructor
System.out.println("a: " + a + ", b: " + b); b in block: 2
} constructor
{
============
b++;
Lessons learnt
System.out.println("b in block: " + b);
First, static codes (once per
}
public HelloWorld(){
class)
System.out.println("constructor"); Then, non-method codes
} (once per object, so object
public static void main(String[] args) { creation required)
System.out.println("Hello, World!"); Then, constructor (once per
var ob = new HelloWorld(); object, so object creation
var ob2 = new HelloWorld(); required)
} 80
}
The Keyword “final”
● A variable can be declared as final, and this means that the value of the
variable is unchangeable.
● We must initialize a final variable in the declaration statement (or in the
non-method block), or we must initialize it in a constructor of a class.
○ The point here is, final data must be initialized before/at the time of object creation.
● Methods can also be declared as final, but this meaning is drastically different
which is related to inheritance (to be discussed later).

81
Dr. Muhammad Ibrahim
More on Strings
● Every string in Java is an object of class String.
○ Even string constant in System.out.println("A text"); is also an object.
● A string in Java is immutable, i.e., not changeable.
○ Two related classes called StringBuffer and StringBuilder, however, allow strings to be
changed.
■ When to use which? These libraries mostly differ in time and memory requirements.

A few operations:
● String creation: String str = "A string";
● Concatenation: str = str1 + " more text" + str2;
● str.equals(str2), str.length(), str.charAt(index ).
● Arrays of strings: String str_arr[] = "ab", "cd", "ef";
82
Dr. Muhammad Ibrahim
More on Strings
class HelloWorld { Output?
int a;
public HelloWorld(int n){
a = n;
}
public static void main(String[] args) {
System.out.println("Hello, World!");
var ob1 = new HelloWorld(2);
var ob2 = new HelloWorld(2);
System.out.println(ob1.hashCode() + ", " + ob2.hashCode());
String s1 = "S1a";
String s2 = "S1a";
System.out.println(s1.hashCode() + ", " + s2.hashCode());
System.out.println(s1 == s2);
s2 = s2 + " ";
System.out.println(s1.hashCode() + ", " + s2.hashCode());
System.out.println(s1 == s2);
} 83
}
More on Strings
class HelloWorld { Output:
int a; Hello, World!
public HelloWorld(int n){
295530567, 2003749087
a = n;
}
81379, 81379
public static void main(String[] args) { true
System.out.println("Hello, World!"); 81379, 2522781
var ob1 = new HelloWorld(2); false
var ob2 = new HelloWorld(2);
System.out.println(ob1.hashCode() + ", " + ob2.hashCode());
String s1 = "S1a";
String s2 = "S1a";
System.out.println(s1.hashCode() + ", " + s2.hashCode());
System.out.println(s1 == s2);
s2 = s2 + " ";
System.out.println(s1.hashCode() + ", " + s2.hashCode());
System.out.println(s1 == s2);
} 84
}
Command Line Arguments
Just like C/C++.

85
Dr. Muhammad Ibrahim
Nested Class and Inner Class (Self-Study)
● Declared inside a class.
● Can access even private members of the surrounding class.
● But the surrounding class don’t have direct access to the members of the nested
class, i.e., the enclosing class must use an object of the nested class to access
its members.
● It is considered to be a member of the surrounding class.
● Usually non-static, but static nested class is also allowed (which is seldom used).
○ Inner class is a non-static nested class.
● Inner class objects can only be created inside the surrounding class, not outside
it.
● Inner class can be created inside a deep block of the surrounding class.
● Application of inner/nested classes: in some specific scenarios.
86
Dr. Muhammad Ibrahim
Varargs: Variable Length Arguments (Self-Study)
● int ... v indicates that v is an array of integers that can take arbitrary
number of integers as parameters.
○ varargs must be the last argument.
○ There can be only one varargs per function.
○ int doIt(int a, int b, double c, int ... vals)
○ int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!
● Methods that use varargs can be overloaded.
○ However, ambiguity may arise because of overloading varargs.
● Final word on varargs: if not absolutely necessary, some programmers avoid
the use of varargs mainly because of the possible ambiguity.

87
Dr. Muhammad Ibrahim
End of Lecture 6.

Reading materials up to this point: Chapters 1 - 7 of the textbook.

Dr. Muhammad Ibrahim

You might also like