[Go to site: main page, start]

0% found this document useful (0 votes)
15 views14 pages

Java Math Functions and Examples

The document provides examples of using mathematical functions and the char data type in Java. It shows how to use Math class methods like max(), sqrt(), pow() for calculations and trigonometric functions like sin(), cos(), tan(). It also demonstrates storing and displaying char values, and typecasting between int and char. The char data type can hold 16-bit Unicode characters and uses 2 bytes in Java to support the Unicode standard.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views14 pages

Java Math Functions and Examples

The document provides examples of using mathematical functions and the char data type in Java. It shows how to use Math class methods like max(), sqrt(), pow() for calculations and trigonometric functions like sin(), cos(), tan(). It also demonstrates storing and displaying char values, and typecasting between int and char. The char data type can hold 16-bit Unicode characters and uses 2 bytes in Java to support the Unicode standard.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Integrative Programming Examples about Mathematical Functions, Characters, and Strings

1. Mathematical Functions
Java Math class provides several methods to work on math calculations like min(), max(), avg(),
sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
1. public class JavaMathExample1
2. {
3. public static void main(String[] args)
4. {
5. double x = 28;
6. double y = 4;
7.
8. // return the maximum of two numbers
9. [Link]("Maximum number of x and y is: " +[Link](x, y));
10.
11. // return the square root of y
12. [Link]("Square root of y is: " + [Link](y));
13.
14. //returns 28 power of 4 i.e. 28*28*28*28
15. [Link]("Power of x and y is: " + [Link](x, y));
16.
17. // return the logarithm of given value
18. [Link]("Logarithm of x is: " + [Link](x));
19. [Link]("Logarithm of y is: " + [Link](y));
20.
21. // return the logarithm of given value when base is 10
22. [Link]("log10 of x is: " + Math.log10(x));
23. [Link]("log10 of y is: " + Math.log10(y));
24.
25. // return the log of x + 1
26. [Link]("log1p of x is: " +Math.log1p(x));
27.
28. // return a power of 2
29. [Link]("exp of a is: " +[Link](x));
30.
31. // return (a power of 2)-1
32. [Link]("expm1 of a is: " +Math.expm1(x));
33. }
34. }
Integrative Programming Examples about Mathematical Functions, Characters, and Strings

Output:

Maximum number of x and y is: 28.0


Square root of y is: 2.0
Power of x and y is: 614656.0
Logarithm of x is: 3.332204510175204
Logarithm of y is: 1.3862943611198906
log10 of x is: 1.4471580313422192
log10 of y is: 0.6020599913279624
log1p of x is: 3.367295829986474
exp of a is: 1.446257064291475E12
expm1 of a is: 1.446257064290475E12
--------------------------------------------------------
1. public class JavaMathExample2
2. {
3. public static void main(String[] args)
4. {
5. double a = 30;
6.
7. // converting values to radian
8. double b = [Link](a);
9.
10. // return the trigonometric sine of a
11. [Link]("Sine value of a is: " +[Link](a));
12.
13. // return the trigonometric cosine value of a
14. [Link]("Cosine value of a is: " +[Link](a));
15.
16. // return the trigonometric tangent value of a
17. [Link]("Tangent value of a is: " +[Link](a));
18.
19. // return the trigonometric arc sine of a
20. [Link]("Sine value of a is: " +[Link](a));
21.
22. // return the trigonometric arc cosine value of a
23. [Link]("Cosine value of a is: " +[Link](a));
24.
25. // return the trigonometric arc tangent value of a
26. [Link]("Tangent value of a is: " +[Link](a));
27.
28. // return the hyperbolic sine of a
Integrative Programming Examples about Mathematical Functions, Characters, and Strings

29. [Link]("Sine value of a is: " +[Link](a));


30.
31. // return the hyperbolic cosine value of a
32. [Link]("Cosine value of a is: " +[Link](a));
33. // return the hyperbolic tangent value of a
34. [Link]("Tangent value of a is: " +[Link](a));
35. }
36. }

Output:

Sine value of a is: -0.9880316240928618


Cosine value of a is: 0.15425144988758405
Tangent value of a is: -6.405331196646276
Sine value of a is: NaN
Cosine value of a is: NaN
Tangent value of a is: 1.5374753309166493
Sine value of a is: 5.343237290762231E12
Cosine value of a is: 5.343237290762231E12
Tangent value of a is: 1.0

------------------------------****************************----------------------------

What is NaN argument ?

A constant holding a Not-a-Number (NaN) value of type double. It is equivalent to


the value returned by [Link](0x7ff8000000000000L).

---------------********************-----------------****************------------

➢ Java code explaining abs(), acos(), toRadians() method in Math class.


// Java program explaining Math class methods
// abs(), acos(), toRadians()

import [Link].*;
public class NewClass
{

public static void main(String[] args)


{
// Declaring the variables
int Vali = -1;
float Valf = .5f;

// Printing the values


Integrative Programming Examples about Mathematical Functions, Characters, and Strings

[Link]("Initial value of int : "+Vali);


[Link]("Initial value of int : "+Valf);

// Use of .abs() method to get the absoluteValue


int Absi = [Link](Vali);
float Absf = [Link](Valf);

[Link]("Absolute value of int : "+Absi);


[Link]("Absolute value of int : "+Absf);
[Link]("");

// Use of acos() method


// Value greater than 1, so passing NaN
double Acosi = [Link](60);
[Link]("acos value of Acosi : "+Acosi);
double x = [Link];

// Use of toRadian() method


x = [Link](x);
double Acosj = [Link](x);
[Link]("acos value of Acosj : "+Acosj);

}
}

Output:
Initial value of int : -1
Initial value of int : 0.5
Absolute value of int : 1
Absolute value of int : 0.5
acos value of Acosi : NaN
acos value of Acosj : 1.5159376794536454

2. Character Data Type in Java


The Java char keyword is a primitive data type. It is used to declare the character-
type variables and methods. It is capable of holding the unsigned 16-bit Unicode
characters.

o The char range lies between 0 to 65,535 (inclusive).

o Its default value is '\u0000'.

o Its default size is 2 byte.

o It is used to store characters.


Integrative Programming Examples about Mathematical Functions, Characters, and Strings

➢ Why char uses 2 bytes in java?

It is because Java uses Unicode system not ASCII code system.

➢ What is \u0000?

The \u0000 is the lowest range of the Unicode system.

--------------------**********************------------------------------

Example 1
Let's see a simple example of displaying characters.

1. public class CharExample1 {


2.
3. public static void main(String[] args) {
4.
5. char char1='a';
6. char char2='A';
7.
8.
9. [Link]("char1: "+char1);
10. [Link]("char2: "+char2);
11. }
12. }

Output:

char1: a
char2: A
Integrative Programming Examples about Mathematical Functions, Characters, and Strings

Example 2
//You don’t have to know the Unicode of each character; these are just as examples to show
you how Java could deal with these Unicode

In this example, we provide integer value to char variable. Here, compiler implicitly
typecast integer to char and display the corresponding ASCII value.

1. public class CharExample2 {


2.
3. public static void main(String[] args) {
4.
5. char char1=65;
6. char char2=97;
7.
8. [Link]("char1: "+char1);
9. [Link]("char2: "+char2);
10.
11. }
12. }

Output:

char1: A
char2: a

Example 3
In this example, we typecast the integer value to char explicitly.

1. public class CharExample3 {


2.
3. public static void main(String[] args) {
4.
5. int num1=97;
6. char char1=(char)num1;
7.
8. int num2=65;
9. char char2=(char)num2;
10.
11. [Link]("char1: "+char1);
Integrative Programming Examples about Mathematical Functions, Characters, and Strings

12. [Link]("char2: "+char2);


13.
14. }
15.
16. }

Output:

char1: a
char2: A

Example 4
In this example, we increment the provided char value by 1.

1. public class CharExample5 {


2.
3. public static void main(String[] args) {
4.
5. char char1='A';
6. char1=(char)(char1+1);
7.
8. [Link]("char: "+char1);
9.
10. }
11. }

Output:

char: B

Example 5
//We can understand this example after we know how array works in Java

Let's see an example to break the string in the form of characters.

1. import [Link];
2.
3. public class CharExample6 {
4.
Integrative Programming Examples about Mathematical Functions, Characters, and Strings

5. public static void main(String[] args) {


6.
7. String str="javatpoint";
8. char[] ch=[Link]();
9.
10. [Link]("String: "+str);
11. [Link]("char: "+[Link](ch));
12.
13. }
14.
15. }

Output:

String: javatpoint
char: [j, a, v, a, t, p, o, i, n, t]

3. String in Java

In Java, a string is a sequence of characters. For example, "hello" is a string


containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.

We use double quotes to represent a string in Java. For example,

// create a string
String type = "Java programming";

Here, we have created a string variable named type. The variable is initialized with
the string Java Programming.

Note: Strings in Java are not primitive types (like int , char , etc). Instead, all strings
are objects of a predefined class named String .
And, all string variables are objects of the String class.
Integrative Programming Examples about Mathematical Functions, Characters, and Strings

Example: Create a String in Java

class Main {
public static void main(String[] args) {

// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";

// print strings
[Link](first); // print Java
[Link](second); // print Python
[Link](third); // print JavaScript
}
}

In the above example, we have created three strings named first, second, and third.
Here, we are directly creating strings like primitive types.
However, there is another way of creating Java strings (using the new keyword).
Java String Operations
Java String provides various methods to perform different operations on strings. We
will look into some of the commonly used string operations.

1. Get Length of a String

To find the length of a string, we use the length() method of the String. For example,

class Main {
public static void main(String[] args) {

// create a string
String greet = "Hello! World";
[Link]("String: " + greet);
// get the length of greet
int length = [Link]();
[Link]("Length: " + length);
}
}
Integrative Programming Examples about Mathematical Functions, Characters, and Strings

Output

String: Hello! World


Length: 12

In the above example, the length() method calculates the total number of characters
in the string and returns it.

2. Join two Strings

We can join two strings in Java using the concat() method. For example,

class Main {
public static void main(String[] args) {

// create first string


String first = "Java ";
[Link]("First String: " + first);

// create second
String second = "Programming";
[Link]("Second String: " + second);

// join two strings


String joinedString = [Link](second);
[Link]("Joined String: " + joinedString);
}
}

Output

First String: Java


Second String: Programming
Joined String: Java Programming

In the above example, we have created two strings named first and second . Notice the
statement,

String joinedString = [Link](second);


Integrative Programming Examples about Mathematical Functions, Characters, and Strings

Here, we the concat() method joins first and second and assigns it to the joinedString variable.

We can also join two strings using the + operator in Java.

3. Compare two Strings

In Java, we can make comparisons between two strings using the equals() method.
For example,

class Main {
public static void main(String[] args) {

// create 3 strings
String first = "java programming";
String second = "java programming";
String third = "python programming";

// compare first and second strings


boolean result1 = [Link](second);
[Link]("Strings first and second are equal: " + result1);

// compare first and third strings


boolean result2 = [Link](third);
[Link]("Strings first and third are equal: " + result2);
}
}

Output

Strings first and second are equal: true


Strings first and third are equal: false

In the above example, we have created 3 strings named first, second, and third. Here, we
are using the equal() method to check if one string is equal to another.
The equals() method checks the content of strings while comparing them.

Note: We can also compare two strings using the == operator in Java. However, this
approach is different than the equals() method.
Integrative Programming Examples about Mathematical Functions, Characters, and Strings

➢ Watch this video to get more ideas about compareTo() method

[Link]

Escape character in Java Strings


The escape character is used to escape some of the characters present inside a string.

Suppose we need to include double quotes inside a string.

// include double quote


String example = "This is the "String" class";

Since strings are represented by double quotes, the compiler will treat "This is the
" as the string. Hence, the above code will cause an error.
To solve this issue, we use the escape character \ in Java. For example,

// use the escape character


String example = "This is the \"String\" class.";

Now escape characters tell the compiler to escape double quotes and read the whole
text.
Java Strings are Immutable
In Java, strings are immutable. This means, once we create a string, we cannot change
that string.
To understand it more deeply, consider an example:

// create a string
String example = "Hello! ";

Here, we have created a string variable named example . The variable holds the
string "Hello! " .

Now suppose we want to change the string.

// add another string "World"


// to the previous tring example
Integrative Programming Examples about Mathematical Functions, Characters, and Strings

example = [Link](" World");

Here, we are using the concat() method to add another string World to the previous string.
It looks like we are able to change the value of the previous string. However, this is
not true .
Let's see what has happened here,

1. JVM takes the first string "Hello! "

2. creates a new string by adding "World" to the first string


3. assign the new string "Hello! World" to the example variable
4. the first string "Hello! " remains unchanged

Creating strings using the new keyword


So far, we have created strings like primitive types in Java.

Since strings in Java are objects, we can create strings using the new keyword as well.
For example,

// create a string using the new keyword


String name = new String("Java String");

In the above example, we have created a string name using the new keyword.
Here, when we create a string object, the String() constructor is invoked.

Example: Create Java Strings using the new keyword

class Main {
public static void main(String[] args) {

// create a string using new


String name = new String("Java String");

[Link](name); // print Java String


}
}
Integrative Programming Examples about Mathematical Functions, Characters, and Strings

If we create the string using new keyword, we will not be able to use = = to
compare between two strings

class Main {
public static void main(String[] args) {

// create a string using new


String a = new String("car");
String b = new String("car");

if (a == b)
[Link]("True");
else
[Link]("False");

}
}

The output will be False, even though both strings equal "car".

Common questions

Powered by AI

Java's Math class facilitates trigonometric computations through several methods such as Math.sin(), Math.cos(), and Math.tan(), among others. These functions expect the angle to be provided in radians, converting degrees using Math.toRadians() is often necessary . Potential errors include incorrect angle measurements if not properly converted and domain violations in inverse trigonometric functions. For instance, Math.asin() and Math.acos() expect arguments between -1 and 1, otherwise they return NaN . Programmatically handling such cases ensures correct and reliable trigonometric calculations.

Strings in Java can be created using string literals or the new keyword. String literals, such as String first = "Java";, are stored in the string pool, allowing Java to optimize memory use by reusing instances. This practice improves performance and minimizes memory consumption . Creating strings with the new keyword, such as new String("Java String"), results in separate object instances even if identical, avoiding pooling. This approach is less efficient as it uses more memory and does not allow object reusability . Thus, literals are generally preferred unless unique instances are necessary.

Java provides two primary methods for comparing strings: equals() and the '==' operator. The equals() method compares the content of strings, returning true if the strings have identical characters in the same order. It is case-sensitive, meaning 'java' and 'Java' are considered different . On the other hand, the '==' operator checks if two string references point to the same object in memory rather than comparing actual content. This means even if two strings contain the same characters, they return false if they are different objects, as demonstrated when strings are created using the new keyword . Thus, equals() is generally preferred for content comparison, whereas '==' is used for reference checks.

Java's Math.sqrt() method computes the square root of a specified double value. It outputs a numeric result for non-negative inputs, and returns NaN for negative inputs due to the constraints of real number square roots . Considerations include ensuring input validations to avoid unexpected NaN results in program flows that require real numbers. Correct handling involves checking inputs for negativity and implementing appropriate fallbacks or logic branches to manage NaN outputs, ensuring stable and accurate mathematical computations particularly in finance and engineering applications.

Java treats strings as immutable, meaning once a string is created, it cannot be altered. For example, concatenating two strings with the concat() method creates a new string by combining the original strings and assigns it to a new variable, without altering the original strings . This immutability has several practical effects: it enhances security and performance, as strings can be cached for efficiency, prevents accidental changes, and allows for safe use in concurrent programming. However, it also implies increased memory overhead due to creation of new string instances during manipulations.

Java uses Unicode instead of ASCII to accommodate a broader set of characters that include international languages and symbols. ASCII is limited to 128 characters, while Unicode supports over 65,000 characters. This use of Unicode is why the char data type in Java uses 2 bytes, allowing it to store a larger range of characters as opposed to the 8-bit limitations of ASCII . The main impact is increased flexibility in character representation at the cost of higher memory use due to larger byte size, supporting globalized applications.

Java's Math class provides functions like Math.log(), Math.log10(), and Math.log1p() to handle different logarithmic bases and values. Math.log() computes the natural logarithm (base e), useful in exponential decay models. Math.log10() calculates the base 10 logarithm, applicable in scientific and engineering fields for signaling changes on a multiplicative scale. Math.log1p() is the natural logarithm of (1+x) and is precise for small values of x . These functions offer precision and performance benefits in calculating exponential growth, decay, and comparing scaled quantities across disciplines.

Typecasting integers to characters in Java involves converting the integer values representing Unicode numbers to their corresponding character representation. This can be done either implicitly or explicitly. For implicit casting, an integer is directly assigned to a char variable, as shown when the integer 65 is assigned to a char resulting in 'A' . Explicit casting, demonstrated with (char)num1, forces the conversion of an integer to a char type . This results in compact and effective ways to handle character manipulation, such as transforming numerical keyboard input into textual output.

'NaN' stands for Not-a-Number and is a constant that represents a value that is undefined or unrepresentable, typically in floating-point calculations. In Java, operations like the square root of a negative number or the arc cosine of a value outside the range of -1 to 1 result in NaN . For example, Math.acos(60) results in NaN because the arc cosine function does not accept arguments outside -1 to 1 as its range. It's crucial to handle NaN in programs to avoid incorrect computations and logic errors.

The Java Math class provides the method Math.pow(x, y) to calculate the power of x raised to y. For instance, Math.pow(28, 4) computes 28 to the power of 4, which equals 614656.0 . This function is essential for handling mathematical computations in programming that require exponential calculations. It simplifies the process of manually iterating multiplications and ensures accurate results with floating-point arithmetic. The implication of using this function is that it handles very large numbers efficiently but requires careful handling of data types to avoid overflow and precision errors, especially with significant exponents.

You might also like