You are on page 1of 31

1

CS 241: OBJECT
ORIENTED
PROGRAMMING
Dr. Ibrahim Eldesoky
Ibrahim_desoky@hotmail.com
2

Concept : Garbage Collection


• Objects are allocated on the heap (a part of memory space
reserved for our programs to run).
• When an object is no longer referenced by a variable, it
can no longer be accessed by the program.
• In this case, it is useless, and it is called garbage.

• Java performs automatic garbage collection periodically.


So the memory space occupied by the useless objects will
be available.
• You don't have to do anything to make garbage collection
work, and in general you will not be aware of it.
3

String Class VS StringBuffer class

• Java provides two classes to support strings:


• 1- String class – the instances of String class are immutable, which
means that once you instantiate an instance of a string like
• String str1 = "hello";
• The object in memory cannot be altered. Instead you will have to
create a new instance, copy the old String and append whatever else
as in this example:
• String str1 = "hello";
• str1 = str1 + " world!";
• What is really happening hear is that we are NOT updating the existing
str1 object... we are reallocating new memory all together, copying the
"hello" data and appending " world!" to the end, then settings the str1
reference to point to this new memory . So it really looks more like this
under
• String str1 = "hello";
• String str2 = str1 + " world!";
• str1 = str2;
4

String Class VS StringBuffer class


• String Class has some unique privileges not shared by
ordinary classes.
• A string can be created using string literals.
• Operators +,==,!= are applicable to strings.
• The characters in a string are indexed by 0 to n-1, where n is the
length of the string.

• 2- StringBuffer class – the instances of StringBuffer class are


mutable, i.e., the content of a StringBuffer object can be
changed after its creation.
• Performance wise, StringBuffer is faster when performing
concatenations. This is because when you concatenate a
String, you are creating a new object (internally) every time
since String is immutable.
5

StringBuffer class
• You have to use new operator to instantiate a StringBuffer object
as follows:
• StringBuffer s1= new StringBuffer();
Construct an instance of the StringBuffer class that is empty but
has an initial capacity (size) of characters = 16 characters
(default).

• int n = 100;
• StringBuffer s1= new StringBuffer(n);
Construct an instance of the StringBuffer class that is empty but
has an initial capacity (size) of characters equal to the value of n
(100 in this example).

• StringBuffer s1= new StringBuffer (“abc”);


Construct an instance of the StringBuffer class that is initialized
by the string literal “abc”
6

Append() and insert() methods


• StringBuffer append(String s)
Returns the current object with the String parameter s appended to the
end.

StringBuffer sb = new StringBuffer (“hello”);


sb.append (“HI”)  returns s as “helloHI”

• StringBuffer insert(int index, char c)


StringBuffer insert(int index, String s)
Inserts the character c (or String s) into the current StringBuffer object at
index index. The characters (after index) are shifted to right.

StringBuffer sb = new StringBuffer (“abcd”);


sb.insert(0,”AB”)  returns sb as “ABabcd”

sb.insert(1,”CD”)  returns sb as “ACDBabcd”

sb.insert(8,”EFG”)  returns sb as ACDBabcdEFG”


7

StringBuffer delete (int i, int j)


• Returns this StringBuffer object after deleting the sequence of characters
starting from index i to index j-1

• Example:
• StringBuffer sb = new StringBuffer (“aBCdefg”);
• sb.delete (1,3)  returns sb as “adefg”

• There is also: StringBuffer deleteCharAt(int i)


• Returns this StringBuffer object after deleting the character at index i.

• StringBuffer sb = new StringBuffer (“aBCdefg”);


• sb.deleteCharAt(1);  returns sb as “aCdefg”

• Length(), charAt() , substring() , indexof(String s) methods are also


defined for StringBuffer class.
8
• + operator is not applicable to StringBuffer

• The relational operators == != will compare between the references to


the StringBuffer objects.

• String s1= “abc”;


• String s2= “abc”;
• Boolean flag1 = (s1==s2);  True

• StringBuffer sb1 = new StringBuffer (“abc”);


• StringBuffer sb2 = new StringBuffer (“abc”);
• Boolean flag2 = (sb1==sb2);  False

• Note: All other relational operators are not applicable to all object
variables.
9

• More Examples:

• String s1= “abc”; //correct


• StringBuffer s2= “abc”;  Syntax error

• StringBuffer s2= new stringBuffer (“abc”);


• Boolean flag1 = (s1==s2);  Syntax error

• StringBuffer sb1 = new StringBuffer (“abcd”);


• StringBuffer sb2 = new StringBuffer (“ef”);
• Sb1 = sb1+“hi”  Syntax error
// it has to be: sb1.append(“hi”)
• Sb1=sb1+sb2  Syntax error
//It has to be : sb1.append(sb2)
10

Program Input Output in Java

• Java provides many classes to perform the program


input and output.
• Program I/O: refers to any I/O performed by the
program.
• Program I/O can come from or be sent to the monitor
screen, data files, network sockets, or the keyboard.
• File I/O: refers specifically to I/O performed on files.
11

Program Input Output in Java

• Java designers constructed program I/O to be based


on three principles:
1. The input and output are based on streams that have a
physical device at one end, such as a disk file, and data
streams into or out of the program in a flow of characters or
bytes. Classes are used to manage how the data comes into
or leaves a program.
2. I/O should be portable and should obtain consistent results even
though the platforms may differ.
3. Java provides many classes that each perform a few tasks
instead of large classes that do many things.
12

Standard Streams (Keyboard, monitor)

• There are pre-defined standard streams objects:


1. System.in : - it is associated with Keyboard
• References an InputStream object
• Attribute: keyboard
• Behaviors: reading

2. System.out: - it is associated with monitor


• References an PrintStream object
• Attribute: monitor
• Behaviors: printing (Ex. Print() and println() methods)
• Remember : System.out.print(…..), to invoke the print
method.
13

System.out

Variable System.out gives


System.out : PrintStream access to an output stream
of type PrintStream
- destination =
- ... The printing destination attribute
for this PrintStream object is the
+ println(String s) : void console window
+ print(String s) : void
+ ... The behaviors of a PrintStream
object support a high-level view
of printing
14

Class Scanner

• We don’t use the reading methods of System.in because


they are too low level methods.
So how can we read from the keyboard?
We are going to use a Class called “Scanner”, it is defined in
the java.util. package.
• Class Scanner:
• Supports extraction of an input as numbers, characters, and strings
from a text.

• you need to define the source of the text (keyboard or file).


• Our source will be System.in to read from the keyboard.
15

To Access the standard input stream

Scanner stdin = new Scanner(System.in);

A new operation constructs a new object of type


scanner. The location of this object in the memory will
be stored in stdin variable.

• The graphical representation to the constructed object


stdin : Scanner

- Source = Keyboard
- ...

+ nextDouble() : double
+ nextInt() : int
+ nextString(): String
+ ...
16

• Now you are ready to use the following methods to read


from the keyboard:

double stdin.nextDouble();
float stdin.nextFloat();
int stdin.nextInt();
long stdin.nextLong();
short stdin.nextShort();
byte stdin.nextByte();
boolean stdin.nextBoolean();
String stdin.nextLine(); // to read string
17

Example:

To read an integer from the keyboard:

• int i;
• Scanner stdin = new Scanner(System.in);

• i= stdin.nextInt();
18

Reading a file

• Class File
• Provides a system-independent way of representing the file of
interest
• You have to import Java.io.*

• Constructor: File (String s)


• Creates a File with name s
• Name can be either an absolute pathname or a pathname relative
to the current working folder
19

Reading a file
• To create a file object:

File file = new File (“c:/ java / words.txt”);


Or ,
File file = new File (“words.txt”);

• To Create a scanner associated with the file of interest:

Scanner fileIn = new Scanner(file);

• You can use the Scanner methods to read the data from
the file: nextLine(); nextInt(); nextDouble(); ….
20

• Scanner class provides some “has” methods report whether


there is a next value of the desired form:

boolean hasNext();

boolean hasNextFloat();
boolean hasNextInt();
boolean hasNextLong();
boolean hasNextShort();

• Also, there is close() method to close the stream after you


finish reading the file.
21

Reading a file - Example


import java.util.*;
import java.io.*;
public class FileRead{
public static void main (String[] args) throws IOException
{

File file = new File(“C://email.txt”);


Scanner fileIn = new Scanner (file);

while (fileIn.hasNext()) {
String currentLine = fileIn.nextLine();
System.out.println (currentLine);
} // end while

fileIn.close();
}
} // end main and class
22

IOException
• Notice the definition of the method main:
public static void main (String[] args) throws IOException{

• The inclusion of the throws expression is a warning to users of the


method, that it may generate an unhandled exception.

• Exception: is an abnormal event that occurs during program


execution
• Ex: attempt to manipulate a nonexistent file.

• If an exception occurs and there is no handler for it, the program


terminates.
• Java requires the throws expression for any method that does not
handle I/O exceptions that it may generate.
23

Wrapper Classes

• For each primitive data type, there exists a wrapper class.


• Wrapper Classes:
• Byte Short Integer Long Float Double Character Boolean.

• They represent the primitive variables within a class wrapper

• A wrapper class contains the same type of data as its corresponding


primitive data type, but it represents the information as an object (an
instance of that wrapper class).

• A wrapper class is useful:


• when we need an object instead of a primitive data type.
• Wrapper classes contain useful methods.
24

Integer class

• You can instantiate an Integer object using either of the


following two sentences:
• Integer i1=5;
• Integer i1= new Integer (5);

• The following code segment is valid:


• int i=2;
• Integer z=5;
• z=i+z;
• System.out.println (“z= ”+z); // z= 7
25

int parseInt (String s)

• parseInt is a static method (class method) in the wrapper class


Integer which converts a string into an int value (assuming that
the string holds the digits of that integer).

• String astring= “10 ”


• int num = Integer.parseInt(astring);  Syntax error
• int num = Integer.parseInt(astring.trim()); // correct

• int num = Integer.parseInt(10);  Syntax error. why?

• int num = Integer.parseInt (“ab”);  Syntax error. why?

• StringBuffer sb =new StringBuffer (“10”);

• int num = Integer.parseInt(sb);  Syntax error.why?


26

Static Modifier
• The modifier static can be used in declaring fields or
methods.

• Example :
static int i;
Static int addNumbers (int x, int y);

• A static field/method is a class-field/method and there is


only one copy of it. All instances of that class share
that single copy.

• To access the static method/field you have to use the


class name as follows:
Class name . method name
27

String toString ()
• An instance method returns string representation of this
integer.

Integer i=5;
String s3= i.toString();  assigns “5” to s3

int i=5;
String s3= i.toString();
 Syntax error (as i is not object)
28

Math Class
• It is part of the java.lang package
• It defines two class (static) constants for representing e and
PI:
• static double E;
• Static double PI;

• Also, it contains a collection of class (static) methods for


computing square root, trigonometric fns,…… like:
• static int abs (int num);
• static double cos (double angle);
• static double exp (double power);
• static double pow (double num, double power);
• static double random();
• static double sqrt (double num);
29

Math Class - Example

• The compute the area of a circle

• double r=10;
• Double area;
• Area = Math.PI * r*r;
• Or:
• Area = Math.PI * Math.pow(r,2);
30

final object variables

• Consider
final String POEM_TITLE = “Appearance of Brown";

final String WARNING = “Weather ball is black";


• What is the representation?

POEM_TITLE "Appearance of Brown"

WARNING "Weather ball is black"

The locks indicate the memory locations holds


constants

• Means that the reference cannot be changed. That is, the constant must always refer to the
same memory location.
• Although an object constant must always refer to the same memory location, it does not
mean necessarily that the value stored at that location cannot be modified through its
member methods
31

• Consider

final String s1 = “hello";


S1= “abc”;  It gives syntax error. Why?

final StringBuffer s1 =new StringBuffer (“hello“);


S1.insert(1, “abc”);  It works. Why?

You might also like