Professional Documents
Culture Documents
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); }