You are on page 1of 70

O B J E C T O R I E N T E D

P R O G R A M M I N G
Course 3
Loredana STANCIU
loredana.stanciu@aut.upt.ro
Room B613
THE NUMBERS CLASSES
Primitive types to define variables:
int i = 2;
float j;
double d;
Wrapper classes for each of the primitive data types
Wrap the primitive type in an object
Often, the wrapping is done by the compiler
The compiler boxes a primitive type in its wrapper class
(unboxes the object into a primitive type)
Integer x, y;
x = 12;
y = 15;
System.out.println(x+y);
THE NUMBERS CLASSES
All of the numeric wrapper classes are
subclasses of the abstract class Number
THE NUMBERS CLASSES
Why to use a Number object rather than a
primitive?
As an argument of a method that expects an object
To use constants defined by the class, such as
MIN_VALUE and MAX_VALUE, that provide the
upper and lower bounds of the data type.
To use class methods for various conversions
METHODS IMPLEMENTED BY ALL SUBCLASSES
OF NUMBER
Converts the value of this Number object to the
primitive data type returned.
byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
METHODS IMPLEMENTED BY ALL SUBCLASSES
OF NUMBER
Compares this Number object to the argument.
int compareTo(Byte anotherByte)
int compareTo(Double anotherDouble)
int compareTo(Float anotherFloat)
int compareTo(Integer anotherInteger)
int compareTo(Long anotherLong)
int compareTo(Short anotherShort)
METHODS IMPLEMENTED BY ALL SUBCLASSES
OF NUMBER
boolean equals(Object obj)
Determines whether this number object is
equal to the argument.
The methods return true if the argument is not
null and is an object of the same type and
with the same numeric value.
CONVERSION METHODS, INTEGER CLASS
static int parseInt(String s)
Returns an integer (decimal only).
String toString()
Returns a String object representing the
value of this Integer.
static String toString(int i)
Returns a String object representing the
specified integer.
CONVERSION METHODS, INTEGER CLASS
static Integer valueOf(int i)
Returns an Integer object holding the value
of the specified primitive.
static Integer valueOf(String s)
Returns an Integer object holding the value
of the specified string representation.
FORMATTING NUMERIC PRINT OUTPUT
The java.io package includes a
PrintStream class:
the System.out object
represents the standard output (the screen)
Can be used to invoke every printing method
described in PrintStream
FORMATTING NUMERIC PRINT OUTPUT
The java.io package includes a
PrintStream class
System.out.println(String s)
System.out.format(String format,
Object... args)
System.out.printf(String format,
Object... args)
System.out.format(Locale l, String
format, Object... args)
FORMATTING NUMERIC PRINT OUTPUT
The conversion characters
http://java.sun.com/javase/6/docs/api/java/util/F
ormatter.html
Conversion Argument category Description
c, C character The result is a Unicode character
s string The result is a string
d integral The result is formatted as a decimal integer
e, E floating point The result is formatted as a decimal number in
computerized scientific notation
f floating point The result is formatted as a decimal number
g, G floating point The result is formatted using computerized scientific
notation or decimal format, depending on the precision
and the value after rounding
n line separator The result is the platform-specific line separator
FORMATTING NUMERIC PRINT OUTPUT
System.out.format("The value of
the float variable is %f, " + "
" the value of the integer " +
" variable is %d, and the " +
"string is %s", floatVar,
intVar, stringVar);
http://java.sun.com/javase/6/docs/api/java
/util/Formatter.html
FORMATTING NUMERIC PRINT OUTPUT
int i = 461012;
System.out.format("The value of
i is: %d%n", i);
The output: The value of i is: 461012
float floatVar = 3.14;
System.out.format(Locale.FRANCE,
"The value of the float variable
is %f%n", floatVar);
The output: The value of the float
variable is: 3,14
FORMATTING NUMERIC PRINT OUTPUT
To use a Local constant the java.util
package should be imported into your
program
Extra information regarding the subject:
http://download.oracle.com/javase/1.5.0/docs/a
pi/java/util/Locale.html
FORMATTING NUMERIC PRINT OUTPUT
long n = 461012;
System.out.format("%d%n", n); 461012
System.out.format("%08d%n", n); 00461012
System.out.format("%+8d%n", n); +461012
System.out.format("%,8d%n", n); 461,012
System.out.format("%+,8d%n", n); +461,012
FORMATTING NUMERIC PRINT OUTPUT
double pi = Math.PI;
System.out.format("%f%n", pi); 3.141593
System.out.format("%.3f%n", pi); 3.142
System.out.format("%10.3f%n", pi); 3.142
System.out.format("%-10.3f%n", pi); 3.142
System.out.format(Locale.FRANCE, 3,1416
"%-10.4f%n%n", pi);
import java.util.*;
ADVANCED MATHEMATICAL COMPUTATION
import java.lang.Math.*;
int abs(float f)
int round(float f)
int min(int arg1, int arg2)
int max(int arg1, int arg2)
double exp(double d)
double log(double d)
double pow(double base, double exponent)
double sqrt(double d)
ADVANCED MATHEMATICAL COMPUTATION
double sin(double d)
double cos(double d)
double tan(double d)
double asin(double d)
double acos(double d)
double atan(double d)
double toDegrees(double d)
double toRadians(double d)
ADVANCED MATHEMATICAL COMPUTATION
Random Numbers
random() method returns a pseudo-randomly selected
number between 0.0 and 1.0 (exclusively)
int number = (int)(Math.random() * 10);
Two defined constants
E the base of natural logarithms
PI the ratio of the circumference of a circle to its diameter
SUMMARY OF NUMBERS
Wrapper classes Byte, Double, Float,
Integer, Long, or Short to wrap a number of
primitive type in an object
The Number classes include constants and useful
class methods
To format a string containing numbers for output, you
can use the printf() or format() methods in
the PrintStream class
The Math class contains a variety of class methods
for performing mathematical functions
PROBLEM
Compute the following expression:
= 3

+2 +1
The value of should be randomly generated
as a number less than 100. and are
floating point numbers.
Print on the screen, formatted in Romanian
style, the values of and using 8 digits out of
which 2 are used to represent the floating point
part
SOLUTION
import java.util.*;
class Solution{
public static void main(String[] arg){
double x = (double)(Math.random() *
100);
double y = 3*Math.pow(x,2) + 2*x +1;
System.out.format(Local.FRANCE,For x =
%8.2f,y = %8.2f,x,y);
}
}
Output: For x= 81,59 y= 20136,18
CHARACTERS
char primitive type Character wrapper class
The Character class is immutable, so that once it is
created, a Character object cannot be changed.
Creating an Character object:
Character ch = new Character('a');
autoboxingor unboxing
Character test(Character c) {...}
char c = test('x');
java.lang.Character
CHARACTERS
Usefull methods
boolean isLetter(char ch)
boolean isDigit(char ch)
boolean isWhiteSpace(char ch)
boolean isUpperCase(char ch)
boolean isLowerCase(char ch)
char toUpperCase(char ch)
char toLowerCase(char ch)
toString(char ch)
CHARACTERS
Escape sequences (preceded by a \)
Escape
Sequance
Description
\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a formfeed in the text at this point.
\ Insert a single quote character in the text at this point.
\ Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.
CHARACTERS
When do you need an escape sequences?
If you want to print the following message:
She said "Hello!" to me.
You should write
System.out.println("She said
\"Hello!\" to me.");
PROBLEM
Consider an array of characters containing a
sentence. Knowing that the words are
separated by space, count how many words are
there. Also count the names (starting with a
capital letter). For simplicity, we consider all the
characters being letters.
SOLUTION
public class SolutionChar{
public static void main(String[] arg){
int count=0, countName=0;
char[] array = {'A','n','a','
','i','s',' ','h','e','r','e'};
for(int i=0;i<array.length;i++)
if((Character.isSpace(array[i])) ||
(i==array.length-1)) count++;
else if
(Character.isUpperCase(array[i]))
countName++;
System.out.printf("There are %d words
and %d Names %n", count, countName);
}} Output: There are 3 words and 1 Names
STRINGS
A sequence of characters objects in the
Java programming language
How to create a string?
String greeting = "Hello world!";
String s = new String(greeting);
char[] c={'h','e','l','l','o','.'};
String S = new String(c);
STRINGS
The String class is immutable
The methods used on strings creates other
strings
accessor methods methods used to obtain
information about an object
String palindrome = "Dot saw I
was Tod";
int len = palindrome.length();
STRINGS
Reverse a palindrome
char[] tempCharArray = new char[len];
char[] charArray = new char[len];
for (int i = 0; i < len; i++) {
tempCharArray[i] = palindrome.charAt(i); }
for (int j = 0; j < len; j++) {
charArray[j] = tempCharArray[len - 1 - j];
}
String reversePalindrome = new
String(charArray);
System.out.println(reversePalindrome);
Output: doT saw I was toD
STRINGS
Concatenate strings
string1.concat(string2);
"My name is ".concat("Ana");
"Hello," + " world" + "!"
to span lines in source files
String s="Now is the time +
" of roses.";
CONVERTING BETWEEN NUMBERS AND
STRINGS
Converting Strings to Numbers
Number.valueOf()
float a = (Float.valueOf(args[0]) ).floatValue();
float b = (Float.valueOf(args[1]) ).floatValue();
Number.parsePrimitive()
float a = Float.parseFloat(args[0]);
float b = Float.parseFloat(args[1]);
CONVERTING BETWEEN NUMBERS AND
STRINGS
Converting Numbers to Strings
int i;
String s1 = "" + i;
String s2 = String.valueOf(i);
int i;
double d;
String s3 = Integer.toString(i);
String s4 = Double.toString(d);
CONVERTING BETWEEN NUMBERS AND
STRINGS
public class ToStringDemo {
public static void main(String[] args) {
double d = 858.48;
String s = Double.toString(d);
int dot = s.indexOf('.');
System.out.println(dot + " digits before
decimal point.");
System.out.println( (s.length() - dot -
1) + " digits after decimal point.");
}
}
MANIPULATING CHARACTERS IN A STRING
String aPal = "Niagara. O roar
again!";
char aChar = aPal.charAt(9);
MANIPULATING CHARACTERS IN A STRING
String aPal = "Niagara. O roar
again!";
String r =aPal.substring(11,15);
MANIPULATING CHARACTERS IN A STRING
Get the character from a certain index
String charAt(int index)
Get the substring between two indexes
String substring(int beginIndex,
int endIndex)
Get the substring from a certain index until the
end of string
String substring(int beginIndex)
SEARCHING FOR CHARACTERS AND
SUBSTRINGS IN A STRING
Splits a string using a separator into an array
of strings
String[] split(String regex)
Removes leading and trailing white space
String trim()
String toLowerCase()
String toUpperCase()
SEARCHING FOR CHARACTERS AND
SUBSTRINGS IN A STRING
int indexOf(int ch)
int lastIndexOf(int ch)
int indexOf(int ch, int fromIndex)
int lastIndexOf(int ch, int fromIndex)
int indexOf(String str)
int lastIndexOf(String str)
int indexOf(String str, int fromIndex)
int lastIndexOf(String str, int
fromIndex)
boolean contains(CharSequence s)
SEARCHING FOR CHARACTERS AND
SUBSTRINGS IN A STRING
public class Filename {
private String fullPath;
private char pathSeparator, extensionSeparator;
public Filename(String str, char sep, char ext) {
fullPath = str;
pathSeparator = sep;
extensionSeparator = ext; }
public String extension() {
int dot =
fullPath.lastIndexOf(extensionSeparator);
return fullPath.substring(dot + 1); }

SEARCHING FOR CHARACTERS AND


SUBSTRINGS IN A STRING

public String filename() {
int dot =
fullPath.lastIndexOf(extensionSeparator);
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(sep + 1, dot); }
public String path() {
int sep = fullPath.lastIndexOf(pathSeparator);
return fullPath.substring(0, sep);
}
}
SEARCHING FOR CHARACTERS AND
SUBSTRINGS IN A STRING
Extension = html
Filename = index
String fpath = "/home/mem/index.html";
Filename myHomePage = new Filename(fpath, '/', '.');
REPLACING CHARACTERS AND SUBSTRINGS
INTO A STRING
String replace(char oldChar, char
newChar)
String replaceAll(String regex, String
replacement)
String replaceFirst(String regex,
String replacement)
COMPARING STRINGS AND PORTIONS OF
STRINGS
boolean endsWith(String suffix)
boolean startsWith(String prefix)
int compareTo(String anotherString)
int compareToIgnoreCase(String str)
boolean equals(Object anObject)
boolean equalsIgnoreCase(String
anotherString)
PROBLEM
Search into a string a substring, both received
as arguments when running the program.
Return the beginning position.
Consider a string containing, separated through
;, the name, the price and the quantity of a
product. Extract them and perform the
necessary type transformations.
SOLUTION P1
public class SolutionStr1{
public static void main(String[] arg){
if(arg.length>=2){
String s1=arg[0];
String s2=arg[1];
int i;
if((i=s1.indexOf(s2))==-1)
System.out.printf("\"%s\" is not included
in \"%s\" %n", s2, s1);
else
System.out.printf("\"%s\" is included in
\"%s\" starting position %d%n", s2, s1,
i);
}
else System.out.println("Not enough arguments");
}}
SOLUTION P2
public class SolutionStr2{
public static void main(String[] arg){
String s1="bread;3.5;52";
String[] array=s1.split(";");
String name=array[0];
double price=Double.valueOf(array[1]);
int quantity =
Integer.valueOf(array[2]);

System.out.printf("Product: %s, %f,


%d", name, price, quantity);
}}
THE JAVA I/O SYSTEM
Applications need to process some input and
produce some output based on that input
In Java, java.io package
allows the input and output of a program
primarily focused on input and output to files,
network streams, internal memory buffer
import java.io.*;
THE JAVA I/O SYSTEM
I/O operations based on streams
flows of data you can either read from, or write to
typically connected to a data source, or data
destination
has no concept of an index of the read or written
data
cannot typically move forth and back in a stream
are typically byte based
Input streams
Output streams
THE JAVA I/O SYSTEM
Standard I/O
System.in
is an InputStream object
typically connected to keyboard input of console
programs
System.out
is a PrintStream object
outputs the data you write to it to the console
System.err
is a PrintStream object
it is normally only used to output error texts
THE JAVA I/O SYSTEM
Input and Output - Source and Destination
The terms "input" and "output" can sometimes be a bit
confusing
Java's IO package concerns with:
the reading of raw data from a source
the writing of raw data to a destination
The typical sources and destinations of data:
Files
Pipes
Network Connections
In-memory Buffers (e.g. arrays)
System.in, System.out, System.error
THE JAVA I/O SYSTEM
A program that needs to read data an input
stream or reader
A program that needs to write data an output
stream or writer
An InputStream or Reader is linked to a
source of data.
An OutputStream or Writer is linked to a
destination of data.
THE JAVA I/O SYSTEM
Java IO Purposes and Features
File Access
Network Access
Internal Memory Buffer Access
Inter-Thread Communication (Pipes)
Buffering
Filtering
Parsing
Reading and Writing Text (Readers / Writers)
Reading and Writing Primitive Data (long, int etc.)
Reading and Writing Objects
THE JAVA I/O SYSTEM
Some Java IO classes
Byte based Character based
Input Output Input Output
Basic InputStream OutputStream Reader
InputStreamReader
Writer
OutputStreamWriter
Files FileInputStream
RandomAccessFile
FileOutputStream
RandomAccessFile
FileReader FileWriter
Pipes PipedInputStream PipedOutputStream PipedReader PipedWriter
Buffering BufferedInputStream BufferedOutputStream BufferedReader BufferedWriter
Strings StringReader StringWriter
Formatted
data
PrintStream PrintWriter
THE JAVA I/O SYSTEM
The InputStream class:
the base class of all input streams in the Java IO API
used for reading byte based data, one byte at a time
The FileInputStream class read the contents of
a file as a stream of bytes
InputStream input = new
FileInputStream("c:\\data\\input-text.txt");
int data = input.read();
while(data != -1)
{doSomethingWithData(data);
data = input.read();}
input.close();
THE JAVA I/O SYSTEM
The OutputStream class:
the base class of all output streams in the Java IO API
used to write byte based data, one byte at a time
The FileOutputStream class writes the
contents of a file as a stream of bytes
OutputStream output = new
FileOutputStream("c:\\data\\output-
text.txt");
output.write(Hello World.getBytes());
output.close();
THE JAVA I/O SYSTEM
The Reader is the baseclass of all Reader's in the
Java IO API (character based) BufferedReader
Reader reader = new FileReader();
int data = reader.read();
while(data != -1){
char dataChar = (char) data;
data = reader.read(); }
Can be combined with an InputStream wrapped
into InputStreamReader
Reader reader = new
InputStreamReader(inputStream);
THE JAVA I/O SYSTEM
The InputStreamReader class is intended to wrap
an InputStream, thereby turning the byte based
input stream into a character based Reader.
InputStream inputStream = new
FileInputStream("c:\\data\\input.txt");
Reader reader = new
InputStreamReader(inputStream);
int data = reader.read();
while(data != -1){
char theChar = (char) data;
data = reader.read(); }
reader.close();
THE JAVA I/O SYSTEM
The Writer is the baseclass of all Writer's in the Java
IO API (character based) BufferedWriter,
PrintWriter
Writer writer = new
FileWriter(("c:\\data\\output-text.txt");
writer.write(Hello World);
Writer.close();
Can be combined with an OutputStream wrapped
into OutputStreamWriter
Writer write = new
OutputStreamWriter(outputStream);
THE JAVA I/O SYSTEM
Reading text lines
BufferedReader readLine()
Reads from an input stream until the line end
Returns a reference to a String without the line
end or null
IOException is throwed if no reading done
The constructor needs an object of
InputStreamReader
FileInputStream if reading from a file
System.in if reading from the console
THE JAVA I/O SYSTEM
BufferedReader r_in = new BufferedReader(new
InputStreamReader(new
FileInputStream(file_name)));
BufferedReader r_in = new BufferedReader(new
InputStreamReader (System.in));
line = r_in.readLine();
while(line != null)
{Do something
line = r_in.readLine();}
r_in.close();
THE JAVA I/O SYSTEM
The PrintStream class:
Enables the writing of formatted data to an
underlying OutputStream
Contains the print()/println() to print a
string
Contains the powerful format() and printf()
methods
The constructor needs an object of
FileOutputStream (write a file as a
stream of bytes)
THE JAVA I/O SYSTEM
PrintStream w_out = new PrintStream (new
FileOutputStream(file_name));
w_out.println();
w_out.print(true);
w_out.print((int) 123);
w_out.print((float) 123.456);
w_out.printf(Locale.UK, "Text + data: %1$",
123);
w_out.close();
THE JAVA I/O SYSTEM
Streams and Readers / Writers need to be
closed properly
r_in.close( );
w_out.close( );
public static void main (String[ ] arg)
throws IOException {

}
THE JAVA I/O SYSTEM SCANNER
Can parse primitive types and strings using
regular expressions
Breaks its input into tokens using a delimiter
pattern, which by default matches whitespace
Has various next methods to convert the tokens
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
THE JAVA I/O SYSTEM SCANNER
Scanner sc = new Scanner(new
File("myNumbers"));
while (sc.hasNextLong())
{ long aLong = sc.nextLong(); }
System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();
System.out.println("Your username is " +
username);
THE JAVA I/O SYSTEM SCANNER
Problems:
a scanning operation may block waiting for input.
is not safe for multithreaded use without external
synchronization.
doesnt work well reading strings and numbers with
the same scanner
Import java.util.Scanner
REFERENCES
The Java Tutorials. Learning the Java Language.
http://java.sun.com/docs/books/tutorial/java/data
/index.html
Java IO Tutorial. http://tutorials.jenkov.com/java-
io/index.html
Java Scanner
http://docs.oracle.com/javase/1.5.0/docs/api/java
/util/Scanner.html

You might also like