Professional Documents
Culture Documents
CS 241: OBJECT
ORIENTED
PROGRAMMING
Dr. Ibrahim Eldesoky
Ibrahim_desoky@hotmail.com
2
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).
• Example:
• StringBuffer sb = new StringBuffer (“aBCdefg”);
• sb.delete (1,3) returns sb as “adefg”
• Note: All other relational operators are not applicable to all object
variables.
9
• More Examples:
System.out
Class Scanner
- Source = Keyboard
- ...
+ nextDouble() : double
+ nextInt() : int
+ nextString(): String
+ ...
16
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:
• 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.*
Reading a file
• To create a file object:
• You can use the Scanner methods to read the data from
the file: nextLine(); nextInt(); nextDouble(); ….
20
boolean hasNext();
boolean hasNextFloat();
boolean hasNextInt();
boolean hasNextLong();
boolean hasNextShort();
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{
Wrapper Classes
Integer class
Static Modifier
• The modifier static can be used in declaring fields or
methods.
• Example :
static int i;
Static int addNumbers (int x, int y);
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;
• double r=10;
• Double area;
• Area = Math.PI * r*r;
• Or:
• Area = Math.PI * Math.pow(r,2);
30
• Consider
final String POEM_TITLE = “Appearance of Brown";
• 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