0% found this document useful (0 votes)
32 views100 pages

Unit Iii1

This document discusses various aspects of Strings in Java. It defines a String as a sequence of characters and explains that Strings in Java are immutable. It describes how to create Strings using string literals and the String class. The document also discusses the various String methods available in Java like length(), concat(), charAt(), indexOf(), replace(), toLowerCase() etc. that can be used to perform common string operations.

Uploaded by

hasan zahid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views100 pages

Unit Iii1

This document discusses various aspects of Strings in Java. It defines a String as a sequence of characters and explains that Strings in Java are immutable. It describes how to create Strings using string literals and the String class. The document also discusses the various String methods available in Java like length(), concat(), charAt(), indexOf(), replace(), toLowerCase() etc. that can be used to perform common string operations.

Uploaded by

hasan zahid
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 100

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-ShareAlike 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
char Array[ ] = new char [5];
– Using a character array char[] ch={'j','a','v','a'};
– Using String Class.  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.StringBuffer 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 s1="Welcome";
– String s2="Welcome“;
s2 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 startIndex, int numChars);
String s = new String(char ch[10],5,5);
5. Creates a string using other string object
15
Java String Example

public class StringExample{


public static void main(String args[]){

String s1="java";//creating string by java string literal


char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example“);//creating java string by new
keyword
System.out.println(s1); Output
System.out.println(s2); java
System.out.println(s3); 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()); => 5
String ss=“Welcome”;
System.out.println(ss.length()); => 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 s1=“to”; String s2=“gether”;
s1.concats(s2) => "together"
Character Extraction
charAt()- Used to extract a single character at
an index.
Syntax:-
char charAt(int where)
where” is the index of the character that you
want to obtain.
String s=“Java”;
ch c=s.charAt(2); => v
Character Extraction
getChars()- Used to extract more than one
chracter

Syntax:-
public void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)

– srcBegin - index of the first character in the string to copy.


– srcEnd - index after the last character in the string to copy.
– dst - the destination array.
– dstBegin - the start offset in the destination array.
Eg:
String s=“Welcome to Java”
char c[6];
s.getChars(3,6,c,0); => ?
Character Extraction
byte[] getbytes() – converts all chars to byte
array

char[] toCharArray() – converts all chars to char


array
String Compare
• equals() - Compares the invoking string to the
specified object.
public boolean equals(Object anObject)
– E.g..,
String s1=“abc”; String s2=“xyz”;
Boolean b;
b= s1.equals (s2);== false

• equalsIgnoreCase()- Compares this String to another


String, ignoring case considerations.
public boolean equalsIgnoreCase(String
anotherString)
– String s1=“JAVA”; String s2=“java”
– Boolean b;
– b=s1.equalsIgnoreCase(S2);  true
String Compare
• compareTo() - 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 compareTo(String anotherString)


public int compareToIgnoreCase(String str)
String Compare
• startsWith() – Tests if this string starts with the specified
prefix.
public boolean startsWith(String prefix)
“Figure”.startsWith(“Fig”); => true

• endsWith() - Tests if this string ends with the specified suffix.


public boolean endsWith(String suffix)
“Figure”.endsWith(“re”); => true
• Searching Strings
indexOf – Searches for the first occurrence of a character or
substring. Returns -1 if the character does not occur.

public int indexOf(int ch)- Returns the index


within this string of the first occurrence of the specified
character.

public int indexOf(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.indexOf(‘a’); =>?
str.indexOf(“day”); =>?
public int indexOf(int ch, int fromIndex)
- Returns the index within this string of the first occurrence of th
specified character, starting the search at the specified index.

public int indexOf(String str, int fromIndex)


- 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.indexOf(‘a’, 6); ======= ?
str.indexOf(“was”, 2); ======== ?
lastIndexOf() –Searches for the last occurrence of a
character or substring.

The methods are similar to indexOf().

int lastIndexOf(int ch) ;


int lastIndexOf(String str) ;
int lastindexOf(int ch, int startIndex)
int lastindexOf(String str, int startIndex);
Any other String Operations needed?
Other String Operations
substring()
replace()
trim()
valueOf()
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 beginIndex)

Eg: "unhappy".substring(2) => "happy"

public String substring(int beginIndex, int endIndex)


Eg: "smiles".substring(1, 5) => "mile“
String Operations
• replace()- Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.

public String replace(char oldChar, char newChar)

Eg:-
String s= "mesquite in your cellar"
s.replace('e', 'o') => ?
String Operations
• toLowerCase(): Converts all of the characters in a String to
lower case.
• toUpperCase(): Converts all of the characters in this String to
upper case.

public String toLowerCase()


public String toUpperCase()

Eg: “JAVA”.toLowerCase();=> ?
“mcet”.toUpperCase();=> ?
String Operations
• trim() - Returns a copy of the string, with leading and trailing
whitespace omitted.
public String trim()

String s = “ Hi Mom! “.trim();


S = “Hi Mom!”

• valueOf() – Returns the string representation of the char array


argument.
public static String valueOf(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 String valueOf(char c)
public static String valueOf(boolean b)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(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 s1="java string split method by javatpoint";
String[] words=s1.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.isUpperCase(String.charAt(index))
Tutorial Problem
4.Write a java program to read two string S1,S2.
and check S2 is available in S1 or not.
Hints:
S1 =“Welcome to Java”
S2=“com ”
What is String Buffer?
StringBuffer
• A StringBuffer is like a String, but can be modified.

• The length and content of the StringBuffer sequence


be changed through certain utility methods.

• StringBuffer is a synchronized and allows us to mutate


the string.

• This is more useful when using in a multithreaded


environment.
StringBuffer
• StringBuffer defines three constructors:
1.StringBuffer() --
Creates an empty string buffer with initial capacity of 16
StringBuffer s=new StringBuffer();

2.StringBuffer(int size) ---


create an empty string buffer with specified capacity of length
StringBuffer s= new StringBuffer(10);

3.StringBuffer(String str) ---


create an empty string buffer with specified string.
StringBuffer s= new StringBuffer(“java”);
StringBuffer Operations
Append
• The principal operations on a StringBuffer are the append and
insert methods, which are overloaded so as to accept data of
any type.

StringBuffer 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[]){
StringBuffer buffer = new StringBuffer(“Hi”);
buffer.append(“Bye”);
System.out.println(buffer);
}
}

• Output
HiBye
StringBuffer Operations
Insert

• The insert method adds the characters at a specified point.

StringBuffer insert(int index, String str)

Index specifies at which point the string will be inserted into the
invoking StringBuffer object.
StringBuffer Operations
• delete() - Removes the characters in a substring of this
StringBuffer. The substring begins at the specified start and
extends to the character at index end - 1 or to the end of the
StringBuffer if no such character exists. If start is equal to end,
no changes are made.
public StringBuffer delete(int start, int end)
Public StringBuffer deleteCharAt(int index)
StringBuffer Operations
• reverse() - The character sequence contained in this string buffer is
replaced by the reverse of the sequence.

public StringBuffer reverse()

Class test
{
public static void main(String ss[])
{
StringBuffer b=new StringBuffer(“Java”);
System.out.println(b.reverse());
}
} avaJ
StringBuffer 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[])
{
StringBuffer s=new StringBuffer("Java is my favorite language");
System.out.println("Lenth =" +s.length());
System.out.println("Capacity = "+s.capacity());
}
}
StringBuffer Operations
similar to String

• substring() - Returns a new String that contains a subsequence of


characters currently contained in this StringBuffer. The substring
begins at the specified index and extends to the end of the
StringBuffer.
public String substring(int start)

• length() - Returns the length of this string buffer.

public int length()


StringBuffer Operations

• charAt() - The specified character of the sequence currently


represented by the string buffer, as indicated by the index argument,
is returned.
public char charAt(int index)
• getChars() - Characters are copied from this string buffer into the destination
character array dst. The first character to be copied is at index srcBegin; the last
character to be copied is at index srcEnd-1.

public void getChars(int srcBegin, int srcEnd, char[] dst,


int dstBegin)

• setLength() - Sets the length of the StringBuffer.

public void setLength(int newLength)


Examples: StringBuffer
sb.length(); 5

sb.capacity(); 21 (16 characters room is added


if no size is specified)

sb.charAt(1); e
sb.setCharAt(1,’i’); Hillo
sb.setLength(2); Hi
sb.append(“l”).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 ensureCapacity() method in StringBuffer.
StringBuilder
• StringBuilder is the same as the StringBuffer
class
• The StringBuilder class is not synchronized and
hence in a single threaded environment, the
overhead is less than using a StringBuffer.
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,
– doubleValue( ) returns the value as a double.
– floatValue( ) returns the value as a float.
java.lang
Number
• byte byteValue( )
• double doubleValue( )
• float floatValue( )
• int intValue( )
• long longValue( )
• short shortValue( )
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 NumberFormatException
• Double(double num)
• Double(String str) throws NumberFormatException
java.lang
The Methods Defined by Float
• byte byteValue( )
• int compare(float num1, float num2)
• int compareTo(Float f ),int equals(Float f)
• double doubleValue( )
• float floatValue( )
• float max(float val, float val2) –JDK8
• float min(float val, float val2)-JDK8
• float sum(float val, float val2)- JDK8
Double class also have similar methods
java.lang
class DoubleDemo {
public static void main(String args[]) {
Double d1 = new Double(3.14159);
Double d2 = new Double("314159E-5");
System.out.println(d1 + " = " + d2 + " -> " +
d1.equals(d2));
}
}
• o/p
– 3.14159 = 3.14159 –> true
isInfinite( ) and isNaN( )
• isInfinite( ) returns true if the value being tested is infinitely large or
small in magnitude.
• isNaN( ) returns true if the value being tested is not a number.

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


Double d1 = new Double(1/0.);
Double d2 = new Double(0/0.);
System.out.println(d1 + ": " + d1.isInfinite() + ", " + d1.isNaN());
System.out.println(d2 + ": " + d2.isInfinite() + ", " + d2.isNaN());
}
}

o/p
• Infinity: true, false
• NaN: false, true
java.lang
Byte, Short, Integer, and Long
• Byte(byte num)
• Byte(String str) throws NumberFormatException
• Short(short num)
• Short(String str) throws NumberFormatException
• Integer(int num)
• Integer(String str) throws NumberFormatException
• Long(long num)
• Long(String str) throws NumberFormatException
• Methods are similar to Float/Double
Converting Numbers to and from Strings
import java.io.*;
class ParseDemo {
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str; int I; int sum=0;
System.out.println("Enter numbers, 0 to quit.");
do {
str = br.readLine();
try {
i = Integer.parseInt(str);
} catch(NumberFormatException 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 IsDemo {
public static void main(String args[]) {
char a[] = {'a', 'b', '5', '?', 'A', ' '};
for(int i=0; i<a.length; i++) {
if(Character.isDigit(a[i])) System.out.println(a[i] + " is a digit.");
if(Character.isLetter(a[i])) System.out.println(a[i] + " is a letter.");
if(Character.isWhitespace(a[i])) System.out.println(a[i] + " is whitespace.");
if(Character.isUpperCase(a[i])) System.out.println(a[i] + " is uppercase.");
if(Character.isLowerCase(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 ProcessBuilder 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.getRuntime( ).
java.lang
exec() is method to execute the program you want to run as well as its input
parameters

class ExecDemo {
public static void main(String args[]) {
Runtime r = Runtime.getRuntime();
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 ExecDemoFini {
public static void main(String args[]) {
Runtime r = Runtime.getRuntime();
Process p = null;
try {
p = r.exec("notepad");
p.waitFor();
} catch (Exception e) {
System.out.println("Error executing notepad.");
}
System.out.println("Notepad returned " + p.exitValue());
}
}
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 totalMemory( ) and


freeMemory( ) 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 sourceStart, Object
target, int targetStart, 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
sourceStart.
• 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 targetStart.
• size is the number of elements that are copied.
ProcessBuilder
• ProcessBuilder 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( ).
• ProcessBuilder offers more control over the
processes. For example, you can set the current
working directory.
• ProcessBuilder defines these constructors:
• ProcessBuilder(List<String> args)
• ProccessBuilder(String ... args)
ProcessBuilder
• To create a process using ProcessBuilder, simply create an instance
of ProcessBuilder, 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 {
ProcessBuilder proc = new ProcessBuilder("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 sourceStart, Object target, int


targetStart, int size)
– Copies an array
• static String clearProperty(String which)
– Deletes the environmental variable specified
• static Console console( )
– Returns the console associated with the JVM.
• static long currentTimeMillis( )
• Returns the current time in terms of milliseconds
• static void exit(int exitCode)
– Halts execution and returns the value of exitCode to the parent process
System
• static void gc( )
– Initiates garbage collection.

• static String getProperty(String which)


– Returns the property associated with which

• static void setErr(PrintStream eStream)
– Sets the standard err stream to eStream.

• static void setIn(InputStream iStream)


– Sets the standard in stream to iStream.

• static void setOut(PrintStream oStream)


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,000");
// time a for loop from 0 to 100,000,000
start = System.currentTimeMillis(); // get starting time
for(long i=0; i < 100000000L; i++) ;
end = System.currentTimeMillis(); // get ending time
System.out.println("Elapsed time: " + (end-start));
}
}

• Timing a for loop from 0 to 100,000,000


• Elapsed time: 10
class ACDemo {
System
static byte a[] = { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74 };
static byte b[] = { 77, 77, 77, 77, 77, 77, 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);

System.out.println("a = " + new String(a));


System.out.println("b = " + new String(b));
}
}
Output a = ABCDEFGHIJ
b = MMMMMMMMMM
System
• The following program displays the path to the
current user directory:
class ShowUserDir {
public static void main(String args[]) {
System.out.println(System.getProperty("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 CloneNotSupportedException


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 Student18 implements Cloneable{
int rollno; String name;
Student18(int r,String n){ rollno=r ; name=n; }
public Object clone()throws CloneNotSupportedException
{ return super.clone(); }
public static void main(String args[]){
try{
Student18 s1=new Student18(101,"amit");
Student18 s2=(Student18)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name); Output:
101 amit
}catch(CloneNotSupportedException 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.
• getClass()
• - Returns the runtime class of an object.
• hashCode()
• - Returns a hash code value for the object.
• notify()
• - Wakes up a single thread that is waiting on this object's monitor.
• notifyAll()
• - Wakes up all threads that are waiting on this object's monitor.
• wait()
• - Causes current thread to wait until another thread invokes the notify()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 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 MathDemo
{ public static void main(String[] args) {
double x = 4876.1874d;
double y = -0.0d;
System.out.println(“Math.abs(" + x + ")=" + Math.abs(x));
System.out.println("Math.abs(" + y + ")=" + Math.abs(y)); }
}
cosine , sine , tangen
• static double acos(double a)
• static double asin(double a)
• static double atan(double a)

This method returns the cosine , sine , 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 MathDemo
{ 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 MathDemo {
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 MathDemo {
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 MathDemo {
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 MathDemo {
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.160000000000004
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 MathDemo {
public static void main(String[] args) {
float x = 1654.9874f;
float y = -9765.134f; System.out.println("Math.round(" + x +
")=" + Math.round(x));
System.out.println("Math.round(" + y + ")=" + Math.round(y));
}} Math.round(1654.9874f)=1655
Math.round(-9765.134f)=-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 MathDemo {
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 MathDemo {
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
toDegree
• static double toDegrees(double angrad)This method
converts an angle measured in radians to an
approximately equivalent angle measured in degrees.
public class MathDemo
{ public static void main(String[] args) {
double x = 45; double y = -180;
x = Math.toDegrees(x);
y = Math.toDegrees(y); System.out.println("Math.tanh("
+ x + ")=" + Math.tanh(x));
System.out.println("Math.tanh(" + y + ")=" +
Math.tanh(y));
}}
toRadians
• static double toRadians(double angdeg)This method
converts an angle measured in degrees to an
approximately equivalent angle measured in radians.
import java.lang.*;
public class MathDemo {
public static void main(String[] args) {
double x = 45; double y = -180;
x = Math.toRadians(x);
y = Math.toRadians(y); System.out.println("Math.tanh(" +
x + ")=" + Math.tanh(x));
System.out.println("Math.tanh(" + y + ")=" + Math.tanh(y));
}}

You might also like