UNIT 3 This work is created by N

UNIT 3 This work is created by N. Senthil madasamy, Dr. A. Noble Mary Juliet, Dr. M. Senthilkumar and is licensed under a Creative Commons Attribution-Share. Alike 4. 0 International License

What is String? 3

What is String? • A string is a sequence of characters • The easiest way to represent a sequence of characters in JAVA – Using a character array – Using String Class. char Array[ ] = new char [5]; char[] ch={'j', 'a', 'v', 'a'}; String s="java"; 4

Java String • Strings in java are immutable. • What is immutable? Once created they cannot be altered any alterations will lead to creation of new string object.

How many of you agree java contains only immutable String Class?

Sting Classes • Strings are implemented as two classes in Java – java. lang. String provides an unchangeable String object – java. lang. String. Buffer provides a String object that can be amended

java. lang. String • How to create String object? – By string literal – By new keyword

String Literal • Java String literal is created by using double quotes. For Example: – String s="welcome"; • Each time you create a string literal, – the JVM checks the string constant pool first. – If the string already exists in the pool, a reference to the pooled instance is returned.

String Literal • If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example: – String s 1="Welcome"; – String s 2="Welcome“; s 2 will not create new instance

java. lang. String Why java uses concept of string literal? • To make Java more memory efficient

String Using new keyword • String s=new String("Welcome"); • In such case, JVM will create – a new string object in normal(non pool) heap memory and – the literal "Welcome" will be placed in the string constant pool. – The variable s will refer to the object in heap(non pool).

String Constructors • What are the string constructors may require for your program? 14

String Constructors 1. Creates an empty string String s = new String(); 2. Creates a string with “value” String s = new String(“value”); 3. Creates a String with character array String s = new String(char ch[10]); 4. Creates a string using subrange of a character array String(char ch[], int start. Index, int num. Chars); String s = new String(char ch[10], 5, 5); 5. Creates a string using other string object String s = new String(String s 1); 15
![Java String Example public class String. Example{ public static void main(String args[]){ String s Java String Example public class String. Example{ public static void main(String args[]){ String s](http://slidetodoc.com/presentation_image_h2/338171b0f4fd3c0bc793c8a502ad80b8/image-14.jpg)
Java String Example public class String. Example{ public static void main(String args[]){ String s 1="java"; //creating string by java string literal char ch[]={'s', 't', 'r', 'i', 'n', 'g', 's'}; String s 2=new String(ch); //converting char array to string String s 3=new String("example“); //creating java string by new keyword System. out. println(s 1); Output System. out. println(s 2); java System. out. println(s 3); Strings example }}

String Methods? • What are the string methods you need for solve any string operations ?

• Java String class provides a lot of methods to perform operations on string such as • Length • Concatenation • Conversion • Character Extraction • String Compare • Searching Strings • Changing Case • Others

Length • The length of a string is the number of characters that it contains. • Syntax: int length(); Eg: System. out. println(“Hello”. length()); String ss=“Welcome”; System. out. println(ss. length()); => 5 => 7

Concatenation • The + operator is used to concatenate two or more strings. Eg: String myname = “Harry” String str = “My name is” + myname+ “. ”; • For string concatenation the Java compiler converts an operand to a String whenever the other operand of the + is a String object.

concat() - Concatenates the specified string to the end of this string. If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, containing the invoking string with the contents of the str appended to it. public String concat(String str) String s 1=“to”; String s 2=“gether”; s 1. concats(s 2) => "together"

Character Extraction char. At()- Used to extract a single character at an index. Syntax: char. At(int where) where” is the index of the character that you want to obtain. String s=“Java”; ch c=s. char. At(2); => v

Character Extraction get. Chars()- Used to extract more than one chracter Syntax: public void get. Chars(int src. Begin, int src. End, char[] dst, int dst. Begin) – src. Begin - index of the first character in the string to copy. – src. End - index after the last character in the string to copy. – dst - the destination array. – dst. Begin - the start offset in the destination array. Eg: String s=“Welcome to Java” char c[6]; s. get. Chars(3, 6, c, 0); => ?
![Character Extraction byte[] getbytes() – converts all chars to byte array char[] to. Char. Character Extraction byte[] getbytes() – converts all chars to byte array char[] to. Char.](http://slidetodoc.com/presentation_image_h2/338171b0f4fd3c0bc793c8a502ad80b8/image-22.jpg)
Character Extraction byte[] getbytes() – converts all chars to byte array char[] to. Char. Array() – converts all chars to char array

String Compare • equals() - Compares the invoking string to the specified object. public boolean equals(Object an. Object) – E. g. . , String s 1=“abc”; String s 2=“xyz”; Boolean b; b= s 1. equals (s 2); == false • equals. Ignore. Case()- Compares this String to another String, ignoring case considerations. public boolean equals. Ignore. Case(String another. String) – String s 1=“JAVA”; String s 2=“java” – Boolean b; – b=s 1. equals. Ignore. Case(S 2); true

String Compare • compare. To() - Compares two strings lexicographically. – The result is a negative integer if this String object lexicographically precedes the argument string. – The result is a positive integer if this String object lexicographically follows the argument string. – The result is zero if the strings are equal. public int compare. To(String another. String) public int compare. To. Ignore. Case(String str)

String Compare • starts. With() – Tests if this string starts with the specified prefix. public boolean starts. With(String prefix) “Figure”. starts. With(“Fig”); => true • ends. With() - Tests if this string ends with the specified suffix. public boolean ends. With(String suffix) “Figure”. ends. With(“re”); => true

• Searching Strings index. Of – Searches for the first occurrence of a character or substring. Returns -1 if the character does not occur. public int index. Of(int ch)- Returns the index within this string of the first occurrence of the specified character. public int index. Of(String str) - Returns the index within this string of the first occurrence of the specified substring. Eg: String str = “How was your day today? ”; str. index. Of(‘a’); =>? str. index. Of(“day”); =>?

public int index. Of(int ch, int from. Index) - Returns the index within this string of the first occurrence of th specified character, starting the search at the specified index. public int index. Of(String str, int from. Index) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. String str = “How was your day today? ”; str. index. Of(‘a’, 6); ======= ? str. index. Of(“was”, 2); ==== ?

last. Index. Of() –Searches for the last occurrence of a character or substring. The methods are similar to index. Of(). int last. Index. Of(int ch) ; int last. Index. Of(String str) ; int lastindex. Of(int ch, int start. Index) int lastindex. Of(String str, int start. Index);

Any other String Operations needed?

Other String Operations substring() replace() trim() value. Of() Split()

Other String Operations substring() - Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string. public String substring(int begin. Index) Eg: "unhappy". substring(2) => "happy" public String substring(int begin. Index, int end. Index) Eg: "smiles". substring(1, 5) => "mile“

String Operations • replace()- Returns a new string resulting from replacing all occurrences of old. Char in this string with new. Char. public String replace(char old. Char, char new. Char) Eg: String s= "mesquite in your cellar" s. replace('e', 'o') => ?

String Operations • to. Lower. Case(): Converts all of the characters in a String to lower case. • to. Upper. Case(): Converts all of the characters in this String to upper case. public String to. Lower. Case() public String to. Upper. Case() Eg: “JAVA”. to. Lower. Case(); => ? “mcet”. to. Upper. Case(); => ?

String Operations • trim() - Returns a copy of the string, with leading and trailing whitespace omitted. public String trim() String s = “ Hi Mom! S = “Hi Mom!” “. trim(); • value. Of() – Returns the string representation of the char array argument. public static String value. Of(char[] data)

String Operations • The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string. Other forms are: public static public static String String value. Of(char c) value. Of(boolean b) value. Of(int i) value. Of(long l) value. Of(float f) value. Of(double d)

String Operations • split()- splits this string against given regular expression and returns a char array. • Synatax – public String split(String regex) – public String split(String regex, int limit) Eg: String s 1="java string split method by javatpoint"; String[] words=s 1. split("\s"); //splits the string based on whitespace System. out. println(words[0]) ?

Tutorial Problem 1. Write a java program to count no of vowels presented in given string Eg: “Welcome to Java” o/p => a=2 e=2 i=0 o=2 u=0

Tutorial Problem 2. Write a java program to check whether the given string is palindrome or not • Hint: MALAYALAM is Palindrome 3. Write a program that computes your initials from your full name and displays them. • Hint : S. Raj Kumar=> SRK • Character. is. Upper. Case(String. char. At(index))

Tutorial Problem 4. Write a java program to read two string S 1, S 2. and check S 2 is available in S 1 or not. Hints: S 1 =“Welcome to Java” S 2=“com ”

What is String Buffer?

String. Buffer • A String. Buffer is like a String, but can be modified. • The length and content of the String. Buffer sequence be changed through certain utility methods. • String. Buffer is a synchronized and allows us to mutat the string. • This is more useful when using in a multithreaded environment.

String. Buffer • String. Buffer defines three constructors: 1. String. Buffer() -- Creates an empty string buffer with initial capacity of 16 String. Buffer s=new String. Buffer(); 2. String. Buffer(int size) --- create an empty string buffer with specified capacity of length String. Buffer s= new String. Buffer(10); 3. String. Buffer(String str) --- create an empty string buffer with specified string. String. Buffer s= new String. Buffer(“java”);

String. Buffer Operations Append • The principal operations on a String. Buffer are the append and insert methods, which are overloaded so as to accept data of any type. String. Buffer append(String str) • The append method always adds these characters at the end of the buffer.
![Example public class mybuffers{ public static void main(String args[]){ String. Buffer buffer = new Example public class mybuffers{ public static void main(String args[]){ String. Buffer buffer = new](http://slidetodoc.com/presentation_image_h2/338171b0f4fd3c0bc793c8a502ad80b8/image-44.jpg)
Example public class mybuffers{ public static void main(String args[]){ String. Buffer buffer = new String. Buffer(“Hi”); buffer. append(“Bye”); System. out. println(buffer); } } • Output Hi. Bye

String. Buffer Operations Insert • The insert method adds the characters at a specified point. String. Buffer insert(int index, String str) Index specifies at which point the string will be inserted into the invoking String. Buffer object.

String. Buffer Operations • delete() - Removes the characters in a substring of this String. Buffer. The substring begins at the specified start and extends to the character at index end - 1 or to the end of the String. Buffer if no such character exists. If start is equal to end, no changes are made. public String. Buffer delete(int start, int end) Public String. Buffer delete. Char. At(int index)

String. Buffer Operations • reverse() - The character sequence contained in this string buffer is replaced by the reverse of the sequence. public String. Buffer reverse() Class test { public static void main(String ss[]) { String. Buffer b=new String. Buffer(“Java”); System. out. println(b. reverse()); } } ava. J

String. Buffer Operations • capacity() - Returns the current capacity of the String buffer. The capacity is the amount of storage available for newly inserted characters. public int capacity() class test { public static void main(String ss[]) { String. Buffer s=new String. Buffer("Java is my favorite language"); System. out. println("Lenth =" +s. length()); System. out. println("Capacity = "+s. capacity()); } }

String. Buffer Operations similar to String • substring() - Returns a new String that contains a subsequence of characters currently contained in this String. Buffer. The substring begins at the specified index and extends to the end of the String. Buffer. public String substring(int start) • length() - Returns the length of this string buffer. public int length()

String. Buffer Operations • char. At() - The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned. public char. At(int index) • get. Chars() - Characters are copied from this string buffer into the destination character array dst. The first character to be copied is at index src. Begin; the last character to be copied is at index src. End-1. public void get. Chars(int src. Begin, int src. End, char[] dst, int dst. Begin) • set. Length() - Sets the length of the String. Buffer. public void set. Length(int new. Length)

Examples: String. Buffer sb. length(); 5 sb. capacity(); 21 (16 characters room is added if no size is specified) sb. char. At(1); e sb. set. Char. At(1, ’i’); Hillo sb. set. Length(2); Hi sb. append(“l”) Hill sb. insert(0, “Big “); Big Hill sb. replace(3, 11, “”); Big sb. reverse(); gib

Tutorial Question • Differentiate String & String Builder • What is ensure. Capacity() method in String. Buffer.

String. Builder • String. Builder is the same as the String. Buffer class • The String. Builder class is not synchronized and hence in a single threaded environment, the overhead is less than using a String. Buffer.

java. lang • It contains classes and interfaces that are fundamental to virtually all of Java programming. • It is Java’s most widely used package. • java. lang is automatically imported into all programs.

java. lang

java. lang Number • The abstract class Number defines a superclass that is implemented by the classes that wrap • the numeric types byte, short, int, long, float, and double. • Number has abstract methods that return the value of the object in each of the different number formats. • For example, – double. Value( ) returns the value as a double. – float. Value( ) returns the value as a float.

java. lang Number • byte. Value( ) • double. Value( ) • float. Value( ) • int. Value( ) • long. Value( ) • short. Value( )

java. lang Double and Float • Double and Float are wrappers for floating-point values of type double and float, respectively. • The constructors for Float & Double are shown here: • Float(double num) • Float(float num) • Float(String str) throws Number. Format. Exception • Double(double num) • Double(String str) throws Number. Format. Exception

java. lang The Methods Defined by Float • byte. Value( ) • int compare(float num 1, float num 2) • int compare. To(Float f ), int equals(Float f) • double. Value( ) • float max(float val, float val 2) –JDK 8 • float min(float val, float val 2)-JDK 8 • float sum(float val, float val 2)- JDK 8 Double class also have similar methods
![java. lang class Double. Demo { public static void main(String args[]) { Double d java. lang class Double. Demo { public static void main(String args[]) { Double d](http://slidetodoc.com/presentation_image_h2/338171b0f4fd3c0bc793c8a502ad80b8/image-60.jpg)
java. lang class Double. Demo { public static void main(String args[]) { Double d 1 = new Double(3. 14159); Double d 2 = new Double("314159 E-5"); System. out. println(d 1 + " = " + d 2 + " -> " + d 1. equals(d 2)); } } • o/p – 3. 14159 = 3. 14159 –> true

is. Infinite( ) and is. Na. N( ) • is. Infinite( ) returns true if the value being tested is infinitely large or small in magnitude. • is. Na. N( ) returns true if the value being tested is not a number. class Inf. Na. N {public static void main(String args[]) { Double d 1 = new Double(1/0. ); Double d 2 = new Double(0/0. ); System. out. println(d 1 + ": " + d 1. is. Infinite() + ", " + d 1. is. Na. N()); System. out. println(d 2 + ": " + d 2. is. Infinite() + ", " + d 2. is. Na. N()); } } o/p • Infinity: true, false • Na. N: false, true

java. lang Byte, Short, Integer, and Long • Byte(byte num) • Byte(String str) throws Number. Format. Exception • Short(short num) • Short(String str) throws Number. Format. Exception • Integer(int num) • Integer(String str) throws Number. Format. Exception • Long(long num) • Long(String str) throws Number. Format. Exception • Methods are similar to Float/Double

Converting Numbers to and from Strings import java. io. *; class Parse. Demo { public static void main(String args[]) throws IOException { Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader(System. in)); String str; int I; int sum=0; System. out. println("Enter numbers, 0 to quit. "); do { str = br. read. Line(); try { i = Integer. parse. Int(str); } catch(Number. Format. Exception e) { System. out. println("Invalid format"); i = 0; } sum += i; System. out. println("Current sum is: " + sum); } while(i != 0); }

Character Java. lang • Character is a simple wrapper around a char. • The constructor for Character is – Character(char ch) class Is. Demo { public static void main(String args[]) { char a[] = {'a', 'b', '5', '? ', 'A', ' '}; for(int i=0; i<a. length; i++) { if(Character. is. Digit(a[i])) System. out. println(a[i] + " is a digit. "); if(Character. is. Letter(a[i])) System. out. println(a[i] + " is a letter. "); if(Character. is. Whitespace(a[i])) System. out. println(a[i] + " is whitespace. "); if(Character. is. Upper. Case(a[i])) System. out. println(a[i] + " is uppercase. "); if(Character. is. Lower. Case(a[i])) System. out. println(a[i] + " is lowercase. "); } } }

java. lang Void • The Void class has one field, TYPE, which holds a reference to the Class object for type void. • Can’t create instances of this class.

java. lang • Process • The abstract Process class encapsulates a process—that is, an executing program. • It is used primarily as a superclass for the type of objects created by exec( ) in the Runtime class, or by start( ) in the Process. Builder class.

java. lang • Process methods

java. lang • Runtime • The Runtime class encapsulates the run-time environment. • We can get a reference to the current Runtime object by calling the static method Runtime. get. Runtime( ).

java. lang exec() is method to execute the program you want to run as well as its input parameters class Exec. Demo { public static void main(String args[]) { Runtime r = Runtime. get. Runtime(); Process p = null; try { p = r. exec("notepad"); //you can Specify the path of Exe files } catch (Exception e) { System. out. println("Error executing notepad. "); } } } This program will open notepad and terminate its execution , even notepad still open.
![java. lang class Exec. Demo. Fini { public static void main(String args[]) { Runtime java. lang class Exec. Demo. Fini { public static void main(String args[]) { Runtime](http://slidetodoc.com/presentation_image_h2/338171b0f4fd3c0bc793c8a502ad80b8/image-70.jpg)
java. lang class Exec. Demo. Fini { public static void main(String args[]) { Runtime r = Runtime. get. Runtime(); Process p = null; try { p = r. exec("notepad"); p. wait. For(); } catch (Exception e) { System. out. println("Error executing notepad. "); } System. out. println("Notepad returned " + p. exit. Value()); } } This program will open notepad and wait for termination of notepad.

java. lang Memory Management • Java provides automatic garbage collection, • sometimes we wants to know how large the object heap is and how much of it is left. • We can use this information, for example, to check our code for efficiency or to approximate how many more objects of a certain type can be instantiated. • To obtain these values, use the total. Memory( ) and free. Memory( ) methods. • Example

java. lang System • The System class holds a collection of static methods and variables. • The standard input, output, and error output of the Java run time are stored in the in, out, and err variables

java. lang System methods • Copies an array. • static void arraycopy(Object source, int source. Start, Object target, int target. Start, int size) • The array to be copied is passed in source, and the index at which point the copy will begin within source is passed in source. Start. • The array that will receive the copy is passed in target, and the index at which point the copy will begin within target is passed in target. Start. • size is the number of elements that are copied.

Process. Builder • Process. Builder provides another way to start and manage processes (that is, programs). • All processes are represented by the Process class, and a process can be started by Runtime. exec( ). • Process. Builder offers more control over the processes. For example, you can set the current working directory. • Process. Builder defines these constructors: • Process. Builder(List<String> args) • Proccess. Builder(String. . . args)

Process. Builder • To create a process using Process. Builder, simply create an instance of Process. Builder, specifying the name of the program and any needed arguments. To begin execution of the program, call start( ) on that instance. • Here is an example that executes the Windows text editor notepad class PBDemo { public static void main(String args[]) { try { Process. Builder proc = new Process. Builder("notepad. exe", "testfile"); proc. start(); } catch (Exception e) { System. out. println("Error executing notepad. "); } } }

System • The System class holds a collection of static methods and variables. • The standard input, output, and error output of the Java run time are stored in the in, out, and err variables. • static void arraycopy(Object source, int source. Start, Object target, int target. Start, int size) – Copies an array • static String clear. Property(String which) – Deletes the environmental variable specified • static Console console( ) – Returns the console associated with the JVM. • static long current. Time. Millis( ) • Returns the current time in terms of milliseconds • static void exit(int exit. Code) – Halts execution and returns the value of exit. Code to the parent process

System • static void gc( ) – Initiates garbage collection. • static String get. Property(String which) – Returns the property associated with which • • static void set. Err(Print. Stream e. Stream) – Sets the standard err stream to e. Stream. • static void set. In(Input. Stream i. Stream) – Sets the standard in stream to i. Stream. • static void set. Out(Print. Stream o. Stream) – Sets the standard out stream to o. Stream.
![System Timing program execution. class Elapsed { public static void main(String args[]) { long System Timing program execution. class Elapsed { public static void main(String args[]) { long](http://slidetodoc.com/presentation_image_h2/338171b0f4fd3c0bc793c8a502ad80b8/image-78.jpg)
System Timing program execution. class Elapsed { public static void main(String args[]) { long start, end; System. out. println("Timing a for loop from 0 to 100, 000"); // time a for loop from 0 to 100, 000 start = System. current. Time. Millis(); // get starting time for(long i=0; i < 10000 L; i++) ; end = System. current. Time. Millis(); // get ending time System. out. println("Elapsed time: " + (end-start)); } } • Timing a for loop from 0 to 100, 000 • Elapsed time: 10 • nano. Time( ) rather than current. Time. Millis nanoseconds
![System class ACDemo { static byte a[] = { 65, 66, 67, 68, 69, System class ACDemo { static byte a[] = { 65, 66, 67, 68, 69,](http://slidetodoc.com/presentation_image_h2/338171b0f4fd3c0bc793c8a502ad80b8/image-79.jpg)
System class ACDemo { static byte a[] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 }; static byte b[] = { 77, 77, 77, 77 }; public static void main(String args[]) { System. out. println("a = " + new String(a)); System. out. println("b = " + new String(b)); System. arraycopy(a, 0, b, 0, a. length); } } Output System. out. println("a = " + new String(a)); System. out. println("b = " + new String(b)); a = ABCDEFGHIJ b = MMMMM

System • The following program displays the path to the current user directory: class Show. User. Dir { public static void main(String args[]) { System. out. println(System. get. Property("user. dir")); } }

Object • Using clone( ) and the Cloneable Interface • The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object. • The java. lang. Cloneable interface must be implemented by the class whose object clone we want to create. • • The clone() method is defined in the Object class. Syntax of the clone() method is as follows: • protected Object clone() throws Clone. Not. Supported. Exception

Object • Why use clone() method ? • The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.

Object Class Student 18 implements Cloneable{ int rollno; String name; Student 18(int r, String n){ rollno=r ; name=n; } public Object clone()throws Clone. Not. Supported. Exception { return super. clone(); } public static void main(String args[]){ try{ Student 18 s 1=new Student 18(101, "amit"); Student 18 s 2=(Student 18)s 1. clone(); System. out. println(s 1. rollno+" "+s 1. name); Output: System. out. println(s 2. rollno+" "+s 2. name); 101 amit }catch(Clone. Not. Supported. Exception c){} 101 amit } }

• • • • Cloning clone() – Creates a new object and returns a copy of this object. equals() - Indicates whether some other object is "equal to" this one. finalize() - Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. get. Class() - Returns the runtime class of an object. hash. Code() - Returns a hash code value for the object. notify() - Wakes up a single thread that is waiting on this object's monitor. notify. All() - Wakes up all threads that are waiting on this object's monitor. wait() - Causes current thread to wait until another thread invokes the notify() method or the notify. All() method for this object 86

87

88

Math Function • The java. lang. Math class contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

• abs static double abs(double a) / static float abs(float a)/ static long abs(long a) • This method returns the absolute value of a given data type value import java. lang. Math; public class Math. Demo { public static void main(String[] args) { double x = 4876. 1874 d; double y = -0. 0 d; System. out. println(“Math. abs(" + x + ")=" + Math. abs(x)); System. out. println("Math. abs(" + y + ")=" + Math. abs(y)); } }

cosine , tangen • static double acos(double a) • static double asin(double a) • static double atan(double a) This method returns the cosine , tangen value

ceil • static double ceil(double a)This method returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. import java. lang. *; public class Math. Demo { public static void main(String[] args) { double x = 125. 9; double y = 0. 4873; System. out. println("Math. ceil(" + x + ")=" + Math. ceil(x)); System. out. println("Math. ceil(" + y + ")=" + Math. ceil(y)); } Math. ceil(125. 9)=126. 0 } Math. ceil(0. 4873)=1. 0

floor • The java. lang. Math. floor(double a) returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer import java. lang. *; public class Math. Demo { public static void main(String[] args) { double x = 60984. 1; double y = -497. 99; System. out. println("Math. floor(" + x + ")=" + Math. floor(x)); System. out. println("Math. floor(" + y + ")=" + Math. floor(y)); System. out. println("Math. floor(0)=" + Math. floor(0)); } Math. floor(60984. 1)=60984. 0 } Math. floor(-497. 99)=-498. 0 Math. floor(0)=0. 0

exp • static double exp(double a)This method returns Euler's number e raised to the power of a double value. import java. lang. *; public class Math. Demo { public static void main(String[] args) { double x = 5; double y = 0. 5; System. out. println("Math. exp(" + x + ")=" + Math. exp(x)); System. out. println("Math. exp(" + y + ")=" + Math. exp(y)); } } Math. exp(5)=148. 4131591025766 Math. exp(0. 5)=1. 6487212707001282

Max &Min • • static double max(double a, double b) static float max(float a, float b) static int max(int a, int b) static long max(long a, long b) static double min(double a, double b) static float min(float a, float b) static int min(int a, int b) static long min(long a, long b)

Max & Min-Examp; e import java. lang. *; public class Math. Demo { public static void main(String[] args) { int x = 9875; int y = 154; System. out. println("Math. min(" + x + ", " + y + ")=" + Math. min(x, y)); } System. out. println("Math. max(" + x + ", " + y + ")=" + Math. max(x, y)); } } Math. min(9875, 154)=154 Math. maxn(9875, 154)=9875

pow • static double pow(double a, double b)This method returns the value of the first argument raised to the power of the second argument. import java. lang. *; public class Math. Demo { public static void main(String[] args) { double x = 2. 0; double y = 5. 4; // print x raised by y and then y raised by x System. out. println("Math. pow(" + x + ", " + y + ")=" + Math. pow(x, y)); System. out. println("Math. pow(" + y + ", " + x + ")=" + Math. pow(y, x)); } } Math. pow(2. 0, 5. 4)=42. 22425314473263 Math. pow(5. 4, 2. 0)=29. 160000004

round • static long round(double a)This method returns the closest long to the argument. static int round(float a)This method returns the closest int to the argument. import java. lang. *; public class Math. Demo { public static void main(String[] args) { float x = 1654. 9874 f; float y = -9765. 134 f; System. out. println("Math. round(" + x + ")=" + Math. round(x)); System. out. println("Math. round(" + y + ")=" + Math. round(y)); Math. round(1654. 9874 f)=1655 }} Math. round(-9765. 134 f)=-9765

random • static double random()This method returns a double value with a positive sign, greater than or equal to 0. 0 and less than 1. 0. import java. lang. *; public class Math. Demo { public static void main(String[] args) { double x = Math. random(); System. out. println("Random number : " + x); }} Random number : 0. 11501691809557013

sqrt • static double sqrt(double a)This method returns the correctly rounded positive square root of a double value. import java. lang. *; public class Math. Demo { public static void main(String[] args) { double x = 9; double y = 25; System. out. println("Math. sqrt(" + x + ")=" + Math. sqrt(x)); System. out. println("Math. sqrt(" + y + ")=" + Math. sqrt(y)); Math. sqrt(9)=3. 0 }} Math. sqrt(25)=5. 0

to. Degree • static double to. Degrees(double angrad)This method converts an angle measured in radians to an approximately equivalent angle measured in degrees. public class Math. Demo { public static void main(String[] args) { double x = 45; double y = -180; x = Math. to. Degrees(x); y = Math. to. Degrees(y); System. out. println("Math. tanh(" + x + ")=" + Math. tanh(x)); System. out. println("Math. tanh(" + y + ")=" + Math. tanh(y)); }}

to. Radians • static double to. Radians(double angdeg)This method converts an angle measured in degrees to an approximately equivalent angle measured in radians. import java. lang. *; public class Math. Demo { public static void main(String[] args) { double x = 45; double y = -180; x = Math. to. Radians(x); y = Math. to. Radians(y); System. out. println("Math. tanh(" + x + ")=" + Math. tanh(x)); System. out. println("Math. tanh(" + y + ")=" + Math. tanh(y)); }}
- Slides: 100