Lecture - 3.5-Array - Type Conversion - Math Class
Lecture - 3.5-Array - Type Conversion - Math Class
5
Array, Type conversion and Math Class in Java
Today’s Topics
• Array in JAVA
• Type conversion
• Math Class
2
3
Array
• Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type.
• An array is used to store a collection of data, but it is often more useful to think of an array as
a collection of variables of the same type.
• Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
4
Declaration of an Array
• datatype [ ] arrayName;
int [ ] arr;
5
Array Example:1 - Two ways
6
Array Example:2 : take input from user
import java.util.Scanner;
1. Declare an array with N size. N will be the input from user. Store N integers in the
Array and print the elements.
8
9
Type conversion
Assigning a value of one type to a variable of another type
float a = 4.99;
int a1 = (int) a;
10
Example
double d = 100.04;
int i = (int)d;//explicit type casting required
11
12
Math Class
import java.lang.Math;
13
Commonly Used Methods of the Math class
Basic Math Functions
• Math.abs(x) Trigonometric Math Functions
• Math.ceil(x) • Math.PI
• Math.floor(x) • Math.E
• Math.min(x,y)
• Math.max(x,y)
• Math.round(x)
• Math.random() –
To get a random value between 0 and e.g. 100, multiply the
value
returned by Math.random() with the maximum number (e.g.
100).
Exponential and Logarithmic Math Functions
• Math.pow(x,y)
• Math.sqrt(x)
• Math.exp(x)
• Math.log(x)
• Math.log10(x)
1. Find absolute, floor, ceil , round and square root values of a number.
2. Find the maximum and minimum values from three numbers using MATH Class.
4. Calculate 2^0 to 2^n Using Math Class. ‘n’ will be input from user.
5. Calculate the area of a circle. pow() method and the value of PI should be used from
Math class
16
Thank you!
17