unit 3: java data types math class and string class

37
Unit 3: Java Data Types Math class and String class

Upload: beverley-webster

Post on 30-Dec-2015

225 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Unit 3: Java Data Types Math class and String class

Unit 3: Java Data TypesMath class and String class

Page 2: Unit 3: Java Data Types Math class and String class

The Math Class

•Java has many mathematical constants and functions available.

•There is a class built into Java called Math that contains all of these functions.

•This will only cover a part of the Math class. Complete information on Math can be found in the Java API documentation.

•Just add this line at the top of your program:▫import java.lang.Math;

Page 3: Unit 3: Java Data Types Math class and String class

Mathematical Constants

•The Math class contains mathematical constants such as pi and e.

•You would be able to access these constants using the names Math.PI and Math.E.

•The variable names are capitalized because they are constants.

•You could use the Math class in arithmetic.▫area = Math.PI * radius * radius;

Page 4: Unit 3: Java Data Types Math class and String class

How!?• When using pi, the name of the class is used

(Math), followed a dot, followed by the name of the variable (PI)

• Although it’s contained in the Math class, we are able to use it without making use of a method to obtain it.

• Furthurmore, we don’t create an instance of the Math class to use it.

• The kind of variable we are using is called a static variable. This differs from other variables we’ve seen so far.

• We’ll look further into static variables later on.

Page 5: Unit 3: Java Data Types Math class and String class

Static Variables•It’s also important to note that the Math class

is used without constructing an instance of it.• It’s variables are available for use without any

Math objects in existence.•A class may serve as a model for the creation

of objects, but it may also serve as a container for useful things.

•The Math class only exists like a container, and the constants are some of the useful things it contains.

Page 6: Unit 3: Java Data Types Math class and String class

Static Methods

•The Math class also contains higher mathematical operators, such as trigonometric functions.

•Just like the mathematical constants, we don’t create an instance of the Math class. It’s just there, in the box of useful things that is Math.

•Such methods are referred to as static methods.

Page 7: Unit 3: Java Data Types Math class and String class

Using Static Methods

•Recall that the previous model of making method calls was this:▫object.method(paramaters);

•With static methods, there is no object to call the method on. All info goes through the class to produce a result. And so, the model is this for static methods:▫returnValue =

ClassName.method(parameters);

Page 8: Unit 3: Java Data Types Math class and String class

Using Static Methods

•The static methods in the Math class return a value, so the variable that the results are stored into has to agree with the type that the Math class gives out.

•The following slide contains schematics for some functions of the Math class.

•Notice that the schematic begins with a declaration of the type of the return value, and the parameters are declared with their types inside the parentheses.

Page 9: Unit 3: Java Data Types Math class and String class

Schematics!•double exp(double x)

▫This returns e raised to the x power•double pow(double x, double y)

▫This returns x raised to the y power•double log(double x)

▫This returns the natural logarithm of x, ln(x)•double sqrt(double x)

▫This returns the square root of x.•double abs(double x)

▫This returns the absolute value of x, |x|

Page 10: Unit 3: Java Data Types Math class and String class

Highly Mathematical!!

•Assuming that the Math class is available for use and the rest of the program is in place, here is a fragment illustrating the use of one of these methods.▫double someValue = 3.2;

double resultValue;resultValue = Math.sqrt(someValue);

Page 11: Unit 3: Java Data Types Math class and String class

Temptations

•It might be tempting to do this…▫resultValue = someValue.sqrt(); //

NOOOOOOO•This is wrong for two reasons…

▫The Math class methods cannot be called on other objects or variables. The thing you want to operate on has to be

passed in as a parameter.▫Also, someValue is a variable, not an object,

and it is not possible to call a method on a variable.

Page 12: Unit 3: Java Data Types Math class and String class

The PI life chose me

•Suppose that we wanted to write this famous equation. The best equation of all time.

•We could rewrite it in code like this:▫area = Math.PI * Math.pow(radius, 2.0);

Page 13: Unit 3: Java Data Types Math class and String class

Black Box

•Keep in mind that these methods are black boxes.

•We know how we should use them, but we don’t know how they internally work.

•You can find out the required types of the parameters and the types of the return variables in the Java API documentation.

•BUT! You will not find the code for the methods there.

Page 14: Unit 3: Java Data Types Math class and String class

Java Data TypesString class

Page 15: Unit 3: Java Data Types Math class and String class

String Cheese

•Strings are a sequence of characters treated as a group.

•They are among the most commonly used data items, along with simple numeric variables.

•We have already encountered string constants.

•Anything enclosed in double quotes is a string, so the following is a string constant:▫“Hello World”

Page 16: Unit 3: Java Data Types Math class and String class

String class

•There is a String class in Java.•It is possible to construct instances of this

class and obtain references to them.•Because strings are so commonly used,

and because the double quotes are so closely associated with them, there is a special syntax for constructing strings.

•Here is an example:▫String myString = “Hello World!”;

Page 17: Unit 3: Java Data Types Math class and String class

String class

•Note that it is not necessary to make use of the keyword ‘new’ in order to create an instance of a string.

•The reference to the string can now be used in the following way, with the expected results:▫System.out.println(myString);

•Once declared, the reference can be re-used like any other variable. Like so:▫myString = “A new string”;

Page 18: Unit 3: Java Data Types Math class and String class

Remember the method models…•Recall that we saw this model for calling

methods on objects:▫object.method(parameters);

•Then we saw this model for static methods:▫returnValue = Class.method(parameters);

Page 19: Unit 3: Java Data Types Math class and String class

String methods

•Since String is a class, it has methods associated with it.

•One such method is length(), which allows you to find out how many characters a string object contains.▫int stringLength;

stringLength = myString.length();

Page 20: Unit 3: Java Data Types Math class and String class

String methods

•This shows that methods called on objects can also return values.

•In this case, length() depends entirely on the associated string object when the method is called.

•No parameters are needed inside the parentheses.

•This is an example of a method that returns the contents of some instance variable maintained inside the object.

Page 21: Unit 3: Java Data Types Math class and String class

String methods

•Of course, method calls on objects that return values may also take parameters.

•This will be explored further on later.•So now, the model becomes this:

▫returnValue = object.method(parameters);

Page 22: Unit 3: Java Data Types Math class and String class

Immutability• It’s not immediately apparent, but the String

class has a special characteristic.• If you examine all of the methods of the class,

you’ll note there are no methods that modifies the string.

• Though you can obtain information about a string object, can obtain its contents, and assign a new string to an existing reference, you cannot change the string itself.

• This is immutability, the inability to alter an object’s state after it has been initialized.

Page 23: Unit 3: Java Data Types Math class and String class

Character indexing

•In Java, the individual characters in a string can be identified numerically by their position, starting at the left beginning with 0.

•This is illustrated below:▫String myString = “Hello”;

H E L L O

0 1 2 3 4

Page 24: Unit 3: Java Data Types Math class and String class

Substring• The String class has a method that returns a

selected portion of the string. It takes two integer parameters.

• The first parameter (start) tells the starting position of the substring of interest in the string.

• The second parameter (past_end) tells the position immediately past the last character of interest.

• Model:▫otherString = someString.substring(start,

past_end);

Page 25: Unit 3: Java Data Types Math class and String class

Substring

•String mySubstring;mySubstring = myString.substring(0, 4);System.out.println(anotherString);

•Output:▫Hell

Page 26: Unit 3: Java Data Types Math class and String class

Substring

•Notice that using substring doesn’t trim the original string. It remains unchanged.

•An entirely new string is created from a part of the original string (that is, it is copied), and stored in its own string reference.

Page 27: Unit 3: Java Data Types Math class and String class

Concatenation

•It is also possible to put strings together, in a process called concatenation.

•In fact, we’ve already seen this.•When doing output, it was possible to do

something like this:▫System.out.println(“Hello” + “ “ + “World”);▫Output: Hello World

•It turns out we can use the ‘+’ sign to serve as a symbol for concatenation.

Page 28: Unit 3: Java Data Types Math class and String class

Concatenation• String myString1, myString2, myString3,

myString4;myString2 = “Hello”;myString3 = “ “;myString4 = “World”;myString1 = myString2 + myString3 + myString4;System.out.println(myString1);

Page 29: Unit 3: Java Data Types Math class and String class

Concatenation with numbers

•It is also possible to mix strings with numerical values.▫System.out.println(“The result is: “ + 27);

Page 30: Unit 3: Java Data Types Math class and String class

Concatenation with numbers

•Of course, it is also possible to do this and get the same results:▫int result = 27;

String myString = “The result is: “;String anotherString = myString + result;System.out.println(anotherString);

Page 31: Unit 3: Java Data Types Math class and String class

Concatenation with numbers

•When shown as a parameter to the println() method, the “+” sign appears to be a punctuation mark, like a comma.

•However, it is an operator, but with a special characteristic.

•When used only on numeric types, it does addition.

•When used only on strings, it does concatenation.

Page 32: Unit 3: Java Data Types Math class and String class

Concatenation with numbers

•When used on a mixture of numbers and strings, in converts the numeric types to strings and does concatenation.

•The fact that the same operator does different things depending on what its operands are is referred to as overloading.

•This topic will come up again later on.

Page 33: Unit 3: Java Data Types Math class and String class

Concatenation with numbers

•Because the “+” works in this way you can convert numeric values to strings in general.

•A pair of double quotes with nothing between them (not even a space) is referred to as the empty string.

•If you concatenate this with any numeric variable, the result is a string containing only the sequence of symbols that represented the value.▫String myString = “” + 42;

Page 34: Unit 3: Java Data Types Math class and String class

ConCATenation with numbers• double myDouble = 3.75;

String myString1 = “” + myDouble;String myString2 = myString1.substring(2, 3);System.out.println(“The digit in the 10ths place is: “ + myString2);

•Output:▫The digit in the 10ths place is: 7

Page 35: Unit 3: Java Data Types Math class and String class

Converting numbers to strings

•As mentioned earlier, there are classes with the names Integer and Double.

•Like the Math class, these classes contain useful methods.

•These classes provide another way of converting numbers.▫import java.lang.Double; //At the top of

the code▫myString = Double.toString(myDouble);▫myString2 = Integer.toString(myInteger);

Page 36: Unit 3: Java Data Types Math class and String class

Converting strings to numbers• Integer and Double classes also contain methods

that turn the contents of a string to a number.▫ import java.lang.Integer;▫…▫String myString = “375”;

int myInteger = Integer.parseInt(myString);• Similar classes for numeric types other than

double and int exist.• They all contain similar conversion methods, and

other methods.• Details can be found in the Java API

documentation.

Page 37: Unit 3: Java Data Types Math class and String class

Lab

•Questions 19-38 on the assignment sheet.▫19-30: Show the output, just like in the last

set of questions.▫31: Short answer▫32: One line of code using the Math class.▫33-37: Several lines of code, making up a

complete program▫38: Integer parsing