0% found this document useful (0 votes)
56 views

Arrays& Library Classes - Address Calculation

The document discusses arrays and string/math library functions in Java programs. It begins by defining an array as a container that holds a fixed number of values of a single type. It notes the need for arrays is to group related information. Advantages include defining multiple variables in one statement and accessing elements using indexes. The document then provides examples of selection, bubble, and insertion sort algorithms. It also explains linear and binary search techniques with examples. Finally, it provides sample programs to sort an array using bubble and selection sort, find max/min/sum of array elements, and store/display multiple data types in arrays.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Arrays& Library Classes - Address Calculation

The document discusses arrays and string/math library functions in Java programs. It begins by defining an array as a container that holds a fixed number of values of a single type. It notes the need for arrays is to group related information. Advantages include defining multiple variables in one statement and accessing elements using indexes. The document then provides examples of selection, bubble, and insertion sort algorithms. It also explains linear and binary search techniques with examples. Finally, it provides sample programs to sort an array using bubble and selection sort, find max/min/sum of array elements, and store/display multiple data types in arrays.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Arrays, April 7

String &
Library
Functions
2020
Array programs and the use of String and Math Library functions in
programs. By Dulu Dutta
ARRAYS
Q1. What is an Array? What is the need of an array? What are the advantages of using Arrays?
Give the general form of an array.

Answer: An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is fixed.

An array of ten elements


Each item in an array is called an element, and each element is accessed by its numerical index.
As shown in the above illustration, numbering begins with 0. The 9th element, for example,
would therefore be accessed at index 8.
Need: An array is a way of grouping related information, as it is a structure that can hold
multiple values of the same type.
Advantages:
1. In single statement we can define as many variables as we want.
2. Any variables can be accessed using its index number.
3. Program become short and therefore, easy to compile and debug.
4. Each element of any array can be accessed or printed using loop.
The general form of a one dimensional array declaration is:
Type [] variable-name;
variable –name = new elementType[arraySize]
Q2. What is index of an element? Which element is arr[9] of the array?

Answer: When elements are stored in an array, individual elements are selected by an index
which is usually a non-negative scalar integer. Indices are also called subscripts.

The 10th element is arr[9] of the array.

Q3: Describe Selection Sort and Bubble Sort algorithm.

Answer:
Bubble Sort: Bubble Sorting is an algorithm in which we are comparing first two values and put
the larger one at higher index. Then we take next two values compare these values and place larger
value at higher index. This process do iteratively until the largest value is not reached at last index.
2|Pag e
Then start again from zero index up to n-1 index. The algorithm follows the same steps iteratively
until elements are not sorted.
Selection Sort: In selection sorting algorithm, find the minimum value in the array then swap it
first position. In next step leave the first value and find the minimum value within remaining
values. Then swap it with the value of minimum index position. Sort the remaining values by using
same steps. Selection sort is probably the most intuitive sorting algorithm to invent.

Insertion sort : - It is a simple sorting method in which the sorted array is built by taking one
entry at a time. It is very efficient on small lists but not as effective on larger ones. It is popular
because of its simplicity.

Example:

public class InsertionSort


{
public void main(int array[])
{
int i;
int n = array.length;
System.out.println("Values Before the sort:\n");
for(i = 0; i < n; i++)
System.out.print( array[i]+" ");
System.out.println();
for (i = 1; i < n; i++)
{
int j = i;
int b = array[i];
while ((j > 0) && (array[j-1] > b))
{
array[j] = array[j-1];
j--;
}
array[j] = b;
}
System.out.print("Values after the sort:\n");
for(i = 0; i <n; i++)
System.out.print(array[i]+" ");
}
}

Q4: Describe Linear Search and Binary Search technique with an example.

Answer:
3|Pag e
Linear Search: Linear Search refers to the searching technique in which each element of an array
is compared with the search item, one by one, until the search item is found or all elements have
been compared. This method, which traverses the array sequentially to locate the given item, is
called Linear Search or Sequential Search.
public class linsearch
{ int a[ ]={5, 1, 12, -5, 16, 2, 12, 14};
public void linse (int n)
{ int i, flag=0;
for(i=0; i<a.length; i++)
{
if(n==a[i])
{
flag = 1;
break;
}
}
if(flag==1)
System.out.print("Element Present in position"+ (i+1));
else
System.out.print("Element not present.");
}}
Binary Search: A fast way to search a sorted array is to use a binary search. The idea is to look
at the element in the middle. If the key is equal to that, the search is finished. If the key is less
than the middle element, do a binary search on the first half. If it's greater, do a binary search of
the second half.

The advantage of a binary search over a linear search is astounding for large numbers. For an
array of a million elements, binary search, will find the target element with a worst case of only
20 comparisons. Linear search, O(N), on average will take 500,000 comparisons to find the
element. This performance comes at a price - the array must be sorted first.

Example:

public class binsearch


{
int a[]={5, 10, 15, 20, 25, 30, 35, 40, 45, 50};
public void search(int n)
{
int flag = 0, low=0, upper, mid=0;
upper= 9;
while(low<=upper)
{

4|Pag e
mid= (low+upper)/2;
if(n>a[mid])
low = mid + 1;
else if(n<a[mid])
upper = mid - 1;
else
{
flag = 1;
break;
}}
if(flag ==1)
System.out.println("Element present at position: " + (mid+1));
else
System.out.println("Element not present");
}}
The length property: The length property is used to find the length of an array.

arrayName.length
where, length is a property provided by java for all arrays.
Example:
for( int i=0; i<myArray.length; i++)
{System.out.print(myArray[i]);}
Array Programs:

Q1. Write a program to sort an array using Bubble Sort.

public class bubblesrt //class declaration

{ public void sort(int a[]) // function with passing the array as argument
{ int l=a.length, temp;
for (int i=0; i<l;i++)
{ for(int j=0; j<l-i-1;j++)
{
if(a[j]>a[j+1]) // comparing first two values
{ temp= a[j]; // swapping the higher value to higher index
a[j]=a[j+1];
a[j+1]=temp; }}
}
System.out.print("Value after sorting");
for(int i=0;i<l;i++) // printing the array elements
System.out.print(a[i]+ ",");
}}
Q2. Write a program to sort an array using Selection Sort.

5|Pag e
class selection{
int a[ ]={5, 1, 12, -5, 16, 2, 12, 14}; // array declaration and initialization
public void selsort() //function
{ int i, j, small, temp, pos=0;
for(i=0; i<a.length; i++)
{small =a[i]; //assigning first element to variable small
pos = i;
for(j=i+1;j<a.length;j++)
{
if(a[j]< small)
//comparing variable small with other elements of the array
{
small= a[j];
pos =j;
}}
temp= a[i]; //swapping
a[i] = a[pos];
a[pos] = temp;
}
System.out.println("Array in ascending order is:");
for(i=0;i<a.length;i++) // printing the array elements
System.out.print(a[i]+ "\t");
}}
Q3. Write a program to find the maximum value, minimum value and sum of the elements of an
array.

public class select


{ int a[] ={2, 5, 4, 1, 3}; // array declaration and initialization
int l=a.length;
int max=a[0], min=a[0], sum=0; //variable declaration
public void determine() //function
{ for (int i=0; i<l;i++)
{
if(max<a[i])
max=a[i]; //comparing and assigning the maximum value to variable max
}
for (int i=0; i<l-1;i++)
{
if(min>a[i])
min=a[i]; //comparing and assigning the minimum value to variable min
}
for (int i=0; i<l;i++)
sum=sum+a[i]; // sum of the elements

6|Pag e
System.out.println("Maximum Value is:" + max); //output
System.out.println("Minimum Value is:"+ min); //output
System.out.println("Sum is:"+ sum); //output
}}

Q4: Write a program to store name, address and marks in 3 different arrays and display it.

import java.io.*;
public class nameaddoercentage
{ String[] name=new String [5]; // declaring String array
String[] address=new String[5]; // declaring String array
int[] num=new int[5]; // declaring integer array
int sum=0;
BufferedReader a= new BufferedReader(new InputStreamReader(System.in));
public void display()throws IOException
{
for(int i=0;i<5;i++)
{
System.out.println("Enter Name:"); //console base input
name[i]= a.readLine();
System.out.println("Enter address:");
address[i]= a.readLine();
System.out.println("Enter Amount:");
num[i]=Integer.parseInt(a.readLine());
}
for(int i=0;i<5;i++)
{
System.out.println("Name is:"+ name[i]); //output
System.out.println("Address is:"+address[i]);
System.out.println("Number is:"+num[i]);
}}}
Q5: The marks obtained by 5 students in a subject are tabulated as follows:-
Name Marks
-- --
-- --
-- --
Write a program to input the names and marks of the students in the subject.
Calculate and display
i) The subject average marks (Subjects average marks = subject total / 5)
ii) The highest marks in the subject
(The maximum marks in the subject are 100)

import java.io.*;
7|Pag e
public class subaverage
{ String[] name=new String [5]; // declaring String array
double[] marks=new double[5]; // declaring integer array
double sum=0, average=0; //variable declaration
double max;
BufferedReader a= new BufferedReader(new InputStreamReader(System.in));
public void display()throws IOException
{
for(int i=0;i<5;i++) //console base input
{
System.out.println("Enter Name:");
name[i]= a.readLine();
System.out.println("Enter Marks");
marks[i]=Double.parseDouble(a.readLine());
sum+=marks[i]; //sum of the elements of marks[] array
}
max=marks[0];
for(int i=0;i<5;i++)
{
if(max<marks[i]) // finding the maximum value
max=marks[i];
}
System.out.println("Highest marks is:"+max); //output
System.out.println("The subject average marks:"+sum/5); //output
}}
Q6: Write a program to print the names and percentage in tabular form.

class arraynamenum {
public static void main()
{
String[] name={"Harry", "Supandi", "Ramesh","Kabya","Ishaan"};
// declares an array of Strings
int[] percentage={10,12,45,20,21}; // declares an array of integers

for(int i=0;i<name.length;i++)
{
System.out.println(name[i]+"--------"+percentage[i]); //output
}
} }
Q7: Write a program to bubble sort the following set of values in ascending order
9, 34, 20, 4, 98, 2, 76, 6, 90, 8
Output: 2

8|Pag e
4
6
8
9
20
34
76
90
98

public class bubblesrt //class declaration

{
int a[] = {9, 34, 20, 4, 98, 2, 76, 6, 90, 8 };
public void sort() // function with passing the array as argument
{ int l=a.length, temp;
for (int i=0; i<l;i++)
{ for(int j=0; j<l-i-1;j++)
{
if(a[j]>a[j+1]) // comparing first two values
{ temp= a[j]; // swapping the higher value to higher index
a[j]=a[j+1];
a[j+1]=temp; }}
}
System.out.print("Value after sorting");
for(int i=0;i<l;i++) // printing the array elements
System.out.println(a[i]);
}}

Q8: Write a program to store 6 elements in an array P and 4 elements in an array Q and produce
a third array R, containing all the elements of P and Q. Display the resultant array.
Example:
INPUT INPUT OUTPUT
P [] Q[] R[]
4 19 4
6 23 6
1 7 1
2 8 2
3 3
10 10
19
23
7
8
9|Pag e
import java.io.*;
public class arraymerge
{
int[] P=new int [6]; // Array declaration
int[] Q=new int [4];
int[] R=new int [10];
BufferedReader a= new BufferedReader(new InputStreamReader(System.in));
public void merge()throws IOException
{ int i, j;
for(i=0;i<6;i++)
{
System.out.println("Enter element:"+ (i+1)+ "of array P:");
P[i]= Integer.parseInt(a.readLine()); //Input for array P
}
for(j=0;j<4;j++)
{
System.out.println("Enter element:"+ (j+1)+ "of array Q:");
Q[j]= Integer.parseInt(a.readLine()); //Input for array Q
}
for(i=0;i<6;i++)
{
R[i]=P[i]; //Copying array P[] to R[]
}
for(j=0;j<4;j++)
{
R[j+6]=Q[j]; ////Copying array Q[] to R[]
}
System.out.println("Elements of the merged array are:");
for(i=0;i<10;i++)
System.out.println(R[i]); // Output
}}

ADDRESS CALCULATION IN ARRAYS


1. Single-dimensional array

Address of a given element, A[X] can be calculated as: -


Address of A[X] = B + (X – L) * W
Where, B = Base Address
10 | P a g e
W = Byte Size (memory required to hold one element of the array)
X = Subscript of the given element
L = Lower limit (Bound) of the array (0 by default, if not mentioned)
2. Double-dimensional array

A) Row – Major formula

Address of a given element, A[X] [Y]can be calculated as: -


Address of A[X][Y]= B + [(X – Lr) * C + (Y – Lc)] * W
Where, B = Base Address
W = Byte Size (memory required to hold one element of the array)
X = Row subscript of the given element
Y = Column subscript of the given element
Lr = Lower limit (Bound) of the row (0 by default, if not mentioned)
Lc = Lower limit (Bound) of the column (0 by default, if not mentioned)
C = Total number of columns in the array
B) Column – Major formula

Address of a given element, A[X] [Y]can be calculated as: -


Address of A[X][Y]= B + [(Y – Lc) * R + (X – Lr)] * W
Where, B = Base Address
W = Byte Size (memory required to hold one element of the array)
X = Row subscript of the given element
Y = Column subscript of the given element
Lr = Lower limit (Bound) of the row (0 by default, if not mentioned)
Lc = Lower limit (Bound) of the column (0 by default, if not mentioned)
R = Total number of rows in the array
EXAMPLES
1. Given the base address of an array A[1200…1400] as 1000 and size of each element as 2
bytes, find the address of A[1350].
Solution: B = 1000, L = 1200, W = 2, X = 1350
Address of A[X] = B + (X – L) * W

11 | P a g e
= 1000 + (1350 – 1200) * 2
= 1000 + 150*2
= 1000 + 300
= 1300

2. A two-dimensional array T is created in the row-major format with 10 rows and 12 columns.
Each element occupies 4 bytes of storage space. The base address of the array is 2000. Find the
address of element T[5][6].
Solution: B = 2000, Lr = 0, Lc = 0, W = 4, C = 12, X = 5, Y = 6
Address of A[X][Y] = B + [(X – Lr) * C + (Y – Lc)] * W
= 2000 + [(5 – 0) * 12 + (6 – 0)] * 4
= 2000 + (5*12 + 6)*4
= 2000 + 66 * 4
= 2000 + 264
= 2264
3. A two-dimensional array T is created in the column-major format with 10 rows and 12
columns. Each element occupies 4 bytes of storage space. The base address of the array is 2000.
Find the address of element T[5][6].
Solution: B = 2000, Lr = 0, Lc = 0, W = 4, R= 10, X = 5, Y = 6
Address of A[X][Y] = B + [(Y – Lc) * R + (X – Lr)] * W
= 2000 + [(6 – 0) * 10 + (5 – 0)] * 4
= 2000 + (6*10 + 5)*4
= 2000 + 65 *4
= 2000 + 260
= 2260

4. An array X[-10…..10, -12…..10] requires two bytes for each element. The base address of the
array is 1200. Find out the location of X[6][4] if the array is arranged in the row-major format.
Solution: Number of rows (R) = (Ur – Lr) + 1 = 10 - (-10) + 1 = 21
Number of columns (C) = (Uc – Lc) +1 = 10 – (-12) + 1 = 23
B = 1200, Lr = -10, Lc = -12, W = 2, C = 23, X = 6, Y = 4

12 | P a g e
Address of A[X][Y] = B + [(X – Lr) * C + (Y – Lc)] * W
= 1200 + [(6-(-10) * 23 + (4-(-12)] * 2
= 1200 + (16*23 + 16) * 2
= 1200 + (368 + 16) * 2
= 1200 + 384 * 2
= 1200 + 768
= 1968

Library Classes
STRING Library Function

Return
Type
Method Description

int compareTo(String anotherString) 1. Returns negative value if the


calling string is less then the
argument string
2. Returns positive value if the
calling string is greater then the
string in the argument.
3. Returns zero if the calling string
and the string in the argument are
equal.
char charAt(int index) Returns the character at the specified
index.

String concat(String str) Returns a string by joining the calling


string with the string passed as
argumrnt.

boolean equals(String anotherString) When the calling string and the within
argument are same, then the function
returns true else returns false

boolean equalsIgnoreCase(String anotherS Compares this String to another String,


tring) ignoring case considerations.

int indexOf(ch) Returns the index within this string of


the first occurrence of the specified
character.

int indexOf(ch, int) Returns the index within this string of


the first occurrence of the specified

13 | P a g e
character starting from the index
number specified as second parameter.

int indexOf(String str) Returns the index within this string of


the first occurrence of the specified
substring.

int indexOf(String str, Returns the index within this string of


int fromIndex) the first occurrence of the specified
substring, starting at the specified
index.

int lastIndexOf(int ch) Returns the index within this string of


the last occurrence of the specified
character.

int length() Returns the length of this string.

String substring(int beginIndex) Returns part of String from the


specified start index position.

String substring(int beginIndex, Returns part of String from the


int endIndex) specified start index position (First
parameter) to end index position
(Second parameter) excluding character
at the end index.

char[] toCharArray() Converts this string to a new character


array.

String toLowerCase() Converts all of the characters in this


String to lower case.

String toUpperCase() Converts all of the characters in this


String to upper case.

String trim() Removes white space from both ends of


this string.

String valueOf(char c) Returns the string representation of


the char argument.

String valueOf(double d) Returns the string representation of


the double argument.

String valueOf(float f) Returns the string representation of


the float argument.

String valueOf(int i) Returns the string representation of


the int argument.

String valueOf(long l) Returns the string representation of


the long argument.

14 | P a g e
Boolean endsWith(String str) Checks for starting from the end of the
string

Boolean startsWith(String str) It checks the given string that begins


with a specified string returns either
true or false.

String replace(char oldChar, char Returns string after replacing the


newChar) character in the first parameter by the
character in second parameter.

Sample Program 1

public class stringexamplelib


{ int i, x;
String a=" My name is raju"; //Declaring String
String b= "from Balipara"; // Declaring String
char c[] = a.toCharArray(); //Converting String to character array
void main()
{ System.out.println("Converting String a to uppercase:");
a= a.toUpperCase(); //Converting each character of the string to upper case
System.out.println(a);
System.out.println("Converting String a to lowercase:");
a= a.toLowerCase(); //Converting each character of the string to lower case
System.out.println(a);
System.out.println("Concatinating a and b:");
System.out.println(a.concat(b)); //Concatinating String
System.out.println("The length of the String a assigned to variable x:");
x= a.length(); //assigning the string leagth including white space to variable x
System.out.println(x);
System.out.println("Printing the character array after converting:");
for (i=0; i<x;i++)
System.out.print(c[i]); //Printing the character array after converting
} }
Output:

Converting String a to uppercase:


MY NAME IS RAJU
Converting String a to lowercase:
my name is raju
Concatinating a and b:

15 | P a g e
my name is rajufrom Balipara
The length of the String a assigned to variable x:
16
Printing the character array after converting:
My name is raju
Sample Program 2

public class stringexamplelib2


{ int i, x;
String a=" My name is Kaif other name is Kaju ";//Declaring String
String b= "from Balipara";// Declaring String
void main()
{ System.out.println("Removing extra space from before and after the string using trim() function:");
a= a.trim();
System.out.println(a);
System.out.println("Function CharAt()returning the character at the specified index(index starts
from 0):");
System.out.println(b.charAt(3));
System.out.println("Function indexOf() returning the index position of the character:");
System.out.println(a.indexOf('i'));
System.out.println("Function indexOf() returning the index position of the character starting from
the index number specified as second parameter:");
System.out.println(a.indexOf('i', 9));
System.out.println("Function indexOf() returning the index position of the string passed as argument
starting from the 0 index :");
System.out.println(a.indexOf("Kaif"));
System.out.println("Function indexOf() returning the index position of the String starting from the
index number specified as second parameter:");
System.out.println(a.indexOf("name",7));
System.out.println("Function lastIndexOf(ch) Returns the index within this string of the last
occurrence of the specified character:");
System.out.println(a.lastIndexOf('K'));
System.out.println("Function substring(int beginIndex) Returns a new string that is a substring of
this string:");
System.out.println(a.substring(6));
16 | P a g e
System.out.println("Function substring(int beginIndex, int endIndex) Returns a new string that is a
substring of this string:");
System.out.println(a.substring(6,25));
System.out.println("Function replace(char oldChar, char newChar) Returns string after replacing the
character in the first parameter by the character in second parameter.:");
System.out.println(a.replace('K', 'R'));
}}
Output:
Removing extra space from before and after the string using trim() function:
My name is Kaif other name is Kaju
Function CharAt()returning the character at the specified index(index starts from 0):
m
Function indexOf() returning the index position of the character:
8
Function indexOf() returning the index position of the character starting from the index number specified
as second parameter:
13
Function indexOf() returning the index position of the string passed as argument starting from the 0 index
:
11
Function indexOf() returning the index position of the String starting from the index number specified as
second parameter:
22
Function lastIndexOf(ch) Returns the index within this string of the last occurrence of the specified
character:
30
Function substring(int beginIndex) Returns a new string that is a substring of this string:
e is Kaif other name is Kaju
Function substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string:
e is Kaif other nam
Function replace(char oldChar, char newChar) Returns string after replacing the character in the first
parameter by the character in second parameter.:
My name is Raif other name is Raju
Sample Program 3

17 | P a g e
public class stringexamplelib3
{ String a="Hello";//Declaring String
String b= "Hello World";// Declaring String
String c="hello";
int x=18;
void main()
{ System.out.println("compareTo(String anotherString) is comparing String a with String b");
System.out.println(a.compareTo(b));
System.out.println("Function equals(String anotherString)returns true when the calling string
and the String within argument are same, else returns false:");
System.out.println(a.equals(c));
System.out.println("Function equalsIgnoreCase(String anotherString) Compares this String to
another String, ignoring case considerations.:");
System.out.println(a.equalsIgnoreCase(c));
System.out.println("Function endsWith(String str) Checks for starting from the end of the string
:");
System.out.println(b.endsWith(a));
System.out.println("Function startsWith(String str), checks the given string that begins with a
specified string returns either true or false.:");
System.out.println(b.startsWith(a));
System.out.println("Function valueOf(int x), returns the string representation of the int
argument.:");
System.out.println(String.valueOf(x));
} }
Output:
compareTo(String anotherString) is comparing String a with String b
-6
Function equals(String anotherString)returns true when the calling string and the String within argument
are same, else returns false:
false
Function equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case
considerations.:
true
Function endsWith(String str) Checks for starting from the end of the string :
false
Function startsWith(String str), checks the given string that begins with a specified string returns either
true or false.:
true
Function valueOf(int x), returns the string representation of the int argument.:
18

NOTE: In the sample programs the use of String library functions in a program are demonstrated and the
output is given.

18 | P a g e
Math Library Function

Math Constants
Two common constants are defined in the Math class.
double Math.E() Value of e, 2.718282..., base of the natural logarithms.
double Math.PI() Value of pi, 3.14159265 ....
Math Methods
Trigonometric Methods

double Math.sin(ar) Returns the sine of ar.


double Math.cos(ar) Returns the cosine of ar.
double Math.tan(ar) Returns the tangent of ar.

Exponential Methods
The two basic functions for logarithms and power are available. These both use the base e
(Math.E) as is the usual case in mathematics.

double Math.pow(d1, d2) Returns d1d2.


double Math.log(d) Returns the logarithm of d to base e.

Misc Methods
double Math.sqrt(d) Returns the square root of d.
t Math.abs(x) Returns absolute value of x with same type as the parameter: int,
long, float, or double.
t Math.max(x, y) Returns maximum of x and y with same type as the parameter:
int, long, float, or double.
t Math.min(x, y) Returns minimum of x and y with same type as the parameter: int,
long, float, or double.
Integer Related Methods
The following methods translate floating point values to integer values, altho these values may
still be stored in a double.
double Math.floor(d) Returns the closest integer-valued double which is equal to or less
than d.
double Math.ceil(d) Returns the closest integer-valued double which is equal to or
greater than d.
double Math.rint(d) Returns the closest integer-valued double to d.

19 | P a g e
Random Numbers
double Math.random() Returns a number x in the range, 0.0 <= x < 1.0.

public class MathLibraryExample {

public static void main(String[] args) {

int i = 7;
int j = -9;
double x = 72.3;
double y = 0.34;

System.out.println("i is " + i);


System.out.println("j is " + j);
System.out.println("x is " + x);
System.out.println("y is " + y);

// The absolute value of a number is equal to


// the number if the number is positive or
// zero and equal to the negative of the number
// if the number is negative.

System.out.println("|" + i + "| is " + Math.abs(i));


System.out.println("|" + j + "| is " + Math.abs(j));
System.out.println("|" + x + "| is " + Math.abs(x));
System.out.println("|" + y + "| is " + Math.abs(y));

// The "ceiling" of a number is the


// smallest integer greater than or equal to
// the number. Every integer is its own
// ceiling.
System.out.println("The ceiling of " + i + " is " + Math.ceil(i));
System.out.println("The ceiling of " + j + " is " + Math.ceil(j));
System.out.println("The ceiling of " + x + " is " + Math.ceil(x));
System.out.println("The ceiling of " + y + " is " + Math.ceil(y));

// The "floor" of a number is the largest


// integer less than or equal to the number.
// Every integer is its own floor.
System.out.println("The floor of " + i + " is " + Math.floor(i));
System.out.println("The floor of " + j + " is " + Math.floor(j));
System.out.println("The floor of " + x + " is " + Math.floor(x));
System.out.println("The floor of " + y + " is " + Math.floor(y));

// Comparison operators

// min() returns the smaller of the two arguments you pass it


System.out.println("min(" + i + "," + j + ") is " + Math.min(i,j));
System.out.println("min(" + x + "," + y + ") is " + Math.min(x,y));

20 | P a g e
System.out.println("min(" + i + "," + x + ") is " + Math.min(i,x));
System.out.println("min(" + y + "," + j + ") is " + Math.min(y,j));

// There's a corresponding max() method


// that returns the larger of two numbers
System.out.println("max(" + i + "," + j + ") is " + Math.max(i,j));
System.out.println("max(" + x + "," + y + ") is " + Math.max(x,y));
System.out.println("max(" + i + "," + x + ") is " + Math.max(i,x));
System.out.println("max(" + y + "," + j + ") is " + Math.max(y,j));

// Trigonometric methods
// All arguments are given in radians

// Convert a 45 degree angle to radians


double angle = 45.0 * 2.0 * Math.PI/360.0;
System.out.println("cos(" + angle + ") is " + Math.cos(angle));
System.out.println("sin(" + angle + ") is " + Math.sin(angle));

// log(a) returns the natural


// logarithm (base e) of a.
System.out.println("log(1.0) is " + Math.log(1.0));
System.out.println("log(10.0) is " + Math.log(10.0));
System.out.println("log(Math.E) is " + Math.log(Math.E));

// pow(x, y) returns the x raised


// to the yth power.
System.out.println("pow(2.0, 2.0) is " + Math.pow(2.0,2.0));
System.out.println("pow(10.0, 3.5) is " + Math.pow(10.0,3.5));
System.out.println("pow(8, -1) is " + Math.pow(8,-1));

// sqrt(x) returns the square root of x.


for (i=0; i < 10; i++) {
System.out.println(
"The square root of " + i + " is " + Math.sqrt(i));
}

// Finally there's one Random method


// that returns a pseudo-random number
// between 0.0 and 1.0;

System.out.println("Here's one random number: " + Math.random());


System.out.println("Here's another random number: " + Math.random());

Note: In the example above the different data types are used in the Math Library Function and
their output is discussed. You can copy and paste the program and you can check the output. If

21 | P a g e
you study this program and output carefully, any question or output of program segments
(normally given in section A of the question paper) related to Math class can be answered.

Memorize the Math Library functions and the return type.

22 | P a g e

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy