Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Unit 3: Java Data Types Math class and String class."— Presentation transcript:

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

2 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;

3 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;

4 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.

5 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.

6 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.

7 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);

8 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.

9 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|

10 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);

11 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.

12 The PI life chose me

13 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.

14 Java Data Types String class

15 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”

16 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!”;

17 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”;

18 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);

19 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();

20 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.

21 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);

22 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.

23 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”; HELLO 01234

24 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);

25 Substring String mySubstring; mySubstring = myString.substring(0, 4); System.out.println(anotherString); Output: ▫ Hell

26 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.

27 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.

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

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

30 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);

31 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.

32 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.

33 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;

34 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

35 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);

36 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.

37 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


Download ppt "Unit 3: Java Data Types Math class and String class."

Similar presentations


Ads by Google