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

Java Theory Till Iteration

Uploaded by

poojadimpal9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Java Theory Till Iteration

Uploaded by

poojadimpal9
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Java – Introduction to Object Oriented Programming [OOP]

Object Oriented Programming Definition –


OOP is an approach that provides a way of modularizing programs by creating
partitioned memory area for both data and functions that can be used as a
template (Class) for creating copies of such modules on demand (Objects) To
better Understand this definition lets try to see what procedural programming is –
Procedural Oriented Programming –
In procedural programming major focus is on functions rather than data and
hence we have programs divided into modules or functions.
Functions are group of program statements with same name used to perform
common task (e.g. function named add() might perform addition of 2 or n
numbers).
In this type however, data is usually global and focus on how to access data is not
taken into account. Also this type of programming is at times not suitable for real
world scenarios (we will see and example).
Some features of POP –
• List of instructions are given for a computer to follow.
• Group of similar tasks are organized as functions.
• Most functions shared global data.
• Data is publicly available.
• More focus on functions and least on data.
• It follows top-bottom approach
Object Oriented Programming –
In Object Oriented Programming, focus is given on data and how to access that
data and the real world scenarios share more resemblance. Programs are
organized in terms of Objects which have the data and functions that access that
data. These objects are derived out of Classes (consider them as custom templates
that we users can define and there are inbuit classes and objects too).
Some features of OOP –
• Emphasis on Data rather than the procedure.
• Programs are divided in to Objects.
• Data structures are designed such that they characterize the Objects.
• Functions that operate on the data of an object are tied together in that
same data structure.
• Data is hidden and cannot be directly accesses
• Its follows bottom-top approach
Diagrammatical Representation of POP vs.
OOP

Application of OOPs:
➢ Object oriented database
➢ Parallel programming
➢ Networking
➢ Computer aided design system
➢ Decision support system

Concepts/Elements of Object Oriented Programming

❖ Classes & Objects


❖ Data Abstraction and Encapsulation
❖ Inheritance
❖ Polymorphism
❖ Message Passing

Generation of Programming Languages


There are five generations of Programming languages. They are:
First Generation Languages :
These are low-level languages like machine language. This is also called Binary
Language.
Second Generation Languages:
These are low-level languages which are based on mnemonic codes ,used in
kernels and hardware drives. Example Assembly language
Third Generation Languages:
These are high-level languages based on English grammar.
Examples are C, C++, Java, Visual Basic.
Fourth Generation Languages:
These are languages that consist of statements that are similar to statements in
the human language. These are used mainly in database programming and
scripting.
Example of these languages include Perl, Python, Ruby, SQL Fifth Generation
Languages :
These are the programming languages that have visual tools to develop a
program. Examples of fifth generation language include Mercury, OPS5, and
Prolog.

The first two generations are called low level languages. The next three
generations are called high level languages.

Source Code: A program written in high-level language is called as source code.


Object Code: It is the instruction written in machine language.
Translators: These are the programs or software used to convert the source code
into machine code.
Different type of translators
The different types of translator are as follows:
Compiler
Compiler is a translator which is used to convert programs in high-level language
to low-level language. It translates the entire program at once and also reports the
errors in source program encountered during the translation.

Interpreter
Interpreter is a translator which is used to convert programs in high-level language
to low-level language. Interpreter translates line by line and reports the error once
it encountered during the translation process. It gives better error diagnostics
than a compiler.

Assembler
Assembler is a translator which is used to translate the assembly language code
into machine language code.

Concepts of Objects and Classes


Object: Object is an identifiable unique entity with some characteristics and behavior. An object is an instance of class.
Every object has its unique identity, some definite state and behavior.
State of an object:It is represented as values or attributes of its characteristics at a given point of time. Ex: A switch is an
object can either be in ‘ON’ or ‘OFF’ state at a given point of time.
Behaviour of an object:The behavior of an object is represented through the function of an object. Ex: A human being
can walk, talk, laugh work etc.
Class:It is a collection of similar type of objects which shares common characteristics and behavior. A class is blue print
or prototype of objects. They define variable and functions common to all objects. Class is also known as object factory.
Object Oriented Programming(OOP): OOP is a programming language which is based on objects which exists in real
world. Object always have some characteristics and behavior.
Principles/Elements/Concepts of OOP :
Data Abstraction:Abstraction refers to act of representing essential features without including the background details
or explanations. Eg: We can do transaction through ATM machine without knowing its internal process.
Data Encapsulation:The wrapping of data and functions into a single unit called class is known as Encapsulation. It is the
way of implementing data abstraction that keeps both data and functions safe from being missed. It provides security to
data members.
Inheritance: It is the property by which one class acquires the properties of another class. By this concept classes can be
divided into two types:

i) Super Class:The class from which the properties are getting inherited is known as Super Class. It is also
known as Parent Class or Base Class. ii) Sub Class: The class which inherits the properties of other class is
known as Sub Class. It is also known as Child Class or Derived Class.
Ex: Heredity is the example of Inheritance in which child get characteristics of their parent.

Polymorphism:If a function behaves differently for different objects then it is known as polymorphism. Function
overloading is an example of polymorphism.
Ex: void shape (), void shape(int , int) , void shape(int), void shape(int, float)

Application of OOPs:

i) Object oriented database


ii) Parallel programming
iii) Networking
iv) Computer aided design
system

Introduction To Java
Java is a popular third generation programming language which can be used to create various types of computer
applications. It is a high level language based on OOP concepts. It was originally named as OAK and was developed at
Sun Microsystem in 1991. Features Of Java:

1. Java is an object oriented programming language.


2. Java is a case sensitive language.
3. Java programs are both compile and interpreted.

4. It supports WORA feature, multimedia.

Byte Code:The java compiler translates the source code to an intermediate code called Byte Code. It is independent of
operating system. Java interpreter called JVM(Java Virtual Machine)reads this byte code and convert it into machine
code for different platforms i.e. OS. Due to Byte code java is platform independent language.

Ordinary Compilation: Ordinary compiler converts the source code into machine executable code i.e. binary.
Compiler:It is a software which converts source code to machine code at once and it will show all the errors if any. Its
speed is fast.
Interpreter:It is software which converts source code to machine code line by line. Control will reach to the next line
after removing the errors (if any) of the previous line. Its speed is slow
Access Specifier:Access specifier is a tool to determine whether a method or data member can be accessed by another
method or not. There are three types of access specifier are provide by java:

i) public:If data members are declared as public they can be access inside the class, outside the class, in sub
classes i.e. any where in the program.
ii) private: if data members are declared as private they can be accessed inside the class only not outside.
iii) protected: If data members are declared as protected, they can accessed inside all the classes of the
same package or any sub classes in other package.

VALUES AND DATA TYPES


Token: The smallest individual unit used in a java program is known as tokens. Token is classified as follows: Token

Keywords:These are the reserved words that convey a special meaning to the java compiler. Keywords must be written
in small letters because java is case sensitive language. Any change in keywords causes a syntax error. Ex: byte, int, if,
break, else etc. Java has 50 keywords.
true, false,null are reserved words but not keywords

Identifier:A symbolic name used for various data items is known as identifier. It is a fundamental building block of a
program and is used to give name to different parts of a program like name for variables, class, object, array, functions
etc.
Rules for naming an identifier:

i. A variable or identifier may have any number of characters.


ii. It may contain alphabets, digits, underscore and dollar.
iii. An identifier cannot start with a digit.
iv. It must not be keyword.
v. There should not be space or dot between any letters of a variable.
vi. Uppercase and lowercase are distinct.
Literals or Constant: A data item which does not change its value during the execution of a program, is known as literal
or constant.
Types of literals:

1. Integer literal:The numeric values which are represented without decimal points are called integer literals. They
are numbers having +ve or –ve sign. Ex: 142, -898, 20 etc. It is following types:
I.Decimal literals (Base 10)
II.Octal literals (Base 8)
III.Hexadecimal literals (Base 16)
2. Real literals: These are also called floating point literals. They represent numbers with decimal point literals. It
must have at least one digit before the decimal point and one after the decimal point. Ex: 24.6, 0.0056, 1.6 E -19
3. Character literals: A character literal contains a single character at a time enclosed within single quotes. It may
be alphabet, digit or any special character. Ex: ‘a’, ‘8’, ‘@’ etc.
4. String literal: A set of one or more than one character enclosed within double quotes is known as string literal.
Ex: “XYZ”, “rjp17”, “public” etc.
5. Boolean literal: The Boolean literals stores only true or false.
6. Null literals: Null literal can store always one value i.e. null.
Separator: Separator is also called punctuator. There are 9 separators used in java like ( ) { } [ ] : ; ,
Operator: Operator is the symbol used to perform specific operation on the operands. There are following types of
operators:

1. Unary Operator : An arithmetic operator which applied on a single operand is called operator. It is different
types:
Unary(+) Operator: Ex. +a=10,a=-8, +a=-8
Unary (-) Operator: Ex: a=10, -a=-10,a=-8, -a=8
Unary (++) Operator:It is used to increment the value of operand by 1.
Unary (--) Operator: It is used to decrement the value of operand by 1.
Prefix: “change then use”. Eg:- int a=4,b=9,r; r= ++a ; r and a both will be 5
Postfix: “Use the change” Eg:- int a=4,b=9,r; r= a-- ; r will be 4 and a will be 5

2. Binary Operator:The operator which requires minimum two operands is called binaryoperator.
I. Arithmetic operator: The operator which is applied to perform arithmetic operation or mathematical
calculation is called arithmetic operator. The result of arithmetic is numeric. Ex. +, -, *, /, % + sign is also used
with string Ex: “5” + “b”=”5b”
II. Relational operator: A relational operator compares two operands and determines the relationship between
them. The result of relational operator is in Boolean value i.e. true or false. Ex: <, <=, >, >=, ==, ! =
III. Logical operator: Logical operator is used to connect existing relational operator. There are three logical
operators are use in java which are AND (&&), OR (||) and NOT (!).
IV. Assignment operator: Assignment operator is used to assign the value of expression on the right side to
variable on the left side. Ex: a=8
V. Shorthand assignment operator: This assignment operator allows performing arithmetic operation and both
using one operator. Ex. +=, -=, *=, /=, %=
3. Ternary operator: This operator which requires three operands is called ternary operator. It is also called
conditional operator. Syntax: result= expression1? expression2 :expression 3

Operand: The value(constant), variable or object on which an operation is performed by operator is called operand.
Expression : Combination of operands and operators is called Expression.
Types of expression
1. arithmetic expression:The expression which Represents a numeric value.
there are three types of arithmetic expressions
a. Integer expression : The expression containing all integer constants and variables joined with arithmetic
operators.
b. real expression : The expression containing all real constants and variables joined with arithmetic
operators.
c. mixed expression : Combination of integer and real expression
2. String expression: A expression which represents a string value is called string expression.
3. Boolean or Logical expression:
An expression which contains boolean values i.e. true or false is called Boolean expression. It can contain
arithmetic, relational as well as well as boolean or logical operators.
Escape Sequence Character:These are non graphical characters which can not be typed directly from keyboard. An
escape sequence characters are represented by backslash (\) followed by one or more characters.
Ex: \n, \t, \”,\\
Precedence of operators:An order of operators which is followed to evaluate an expression. Java follows BEDMASin
which * ,% and /, + and – have same precedence and they are evaluated from left to right.
Associativity: When more than one operator has same precedence then their associativity is checked for evaluation.
Comments: A comment is a remark to explain some aspect of the code of a program which are ignored by the compiler.
It if 3 types:
I.Single line comment: it is used make a line as comment. It is denoted by //.
II.Multiline comment: It spread over many lines. It begins with /* and ends with */.
III.Documentation comment: It is used to produce HTML file. It begins with /** and ends with */.

Data Type:To identify the type of data that a variable can hold is known as data type. Data type is classified as
follows:
I. Primitive data type: The data type which is defined by java and is not composed of any
other data type is known as primitive data type. These are also known as predefined or Intrinsic
data type. There are 8 primitive data type .
DATA TYPE SIZE(in DEFAULT RANGE
Bytes) VALUE
byte 1 0 -128 to +127
short 2 0 -32768 to +32767
int 4 0 -231 to +231-
long 8 0l or 0L -263 to +263-1
float 4 0.0F or 0.0f -3.4 E38 to + 3.4E
38
double 8 0.0d or 0.0D -1.7 E308 to + 1.7
E308
char 2 ‘\u0000’ 65536 Unicode
characters
Boolean 1byte(uses false true/false
only 1 bit)

III.Non primitive Data Type: These data types are formed with the help of primitive data types. Ex. array,
class, interfaces. This data type is also called derived or reference or user defined data type. Default value
of String is “” or null

Variable: Variable is a name of memory location to store a value,this value can be changed during the execution of
program. Syntax: datatype variablename; Ex: int x;
Initialization of variable: To provide actual value to the declared variable of same data type as needed is known as
initialization of variable. It is of two types:
Static Initialization:To initialize a variable at compile time is called static initialization.
Dynamic Initialization:To initialize a variable at run time i.e. during the execution of program is called dynamic
initialization.
int a=5; // static initialization int
b=a*a;// dynamic initialization
Scope of variable: The part of program up to which a variable can be used, is called scope of variable.
Life time of variable: The time period till which a variable lives in the memory is known is life time of variable.
Types of variable:

i) Local variable: A variable which is declared in a particular block is called local variable. It can be access in that
bock only.
ii) Instance variable: A variable or data member which is declared in class that can be access in whole class is
called Instance variable. These variables maintain different copy for different objects of a class.
iii) Static variable/Class variable: The data member or variable declared once for a class is known as static/class
variable. These variables maintain a single copy for all the objectsand all objects can share it. static keyword is
used to make a variable as class variable.
Ex: class ABC
{ int x; // instance variable
static int y; // class variable
}

There are two values associated with variable:

i) Data value/ r value:It is data value stored at some location in the memory. This is also called r value. ii)
Location value/l value: It is the address of memory at which data value is stored. It is also called l value.
final keyword: This is used to convert variable to constant.
Example final double pi=3.14; now the value of pi can’t be updated.

Expression: An expression in java is any combination of operator, constants and variables i.e. legal combinations of
tokens.
Pure Expression An expression which contains all the operands of same type is known as Pure Expression. Mixed
Expression An expression which contains the operands areof mixed or different data types known as mixed
Expression. final Keyword: final keyword is used to make a variable as constant i.e. if we add final keyword before
a variable declaration its value can not be change during the execution of program.
finalint x=10;
x=x+5; // error

Type Conversion: When a primitive data type is converted in another data type is known as Type Conversion. It is of two
types:
i) Implicit Type Conversion: when in an expression having different data type, all data types are automatically
converted in bigger data type by compiler itself without programmer intervention, is known as Implicit Type
Conversion.It is also known as Type Promotion or Coercion.

Ex: int a=10; double b=20.5,c; c=a+b; (int to double)

ii) Explicit Type Conversion: When a primitive data type is converted in another data type forcefully using typecast
operator ()is known as Explicit Type Conversion. It also known as Type Casting. Ex: double x=15.8; int y=(int) x;//15 double
value is forcefully converted into int

Class As User Defined Data Type


Class is known as composite data type because it binds one or more primitive data type to be used as single unit.
Defining a Class: Defining a class determines the nature of objects created within the program because the class is a
blue print or template for an object and requires three attributes :-
i. access specifier
ii. class keyword
iii. class name
Syntax for defining a class:
class <class name>
{
Data members;
Functions () {}
}
Object As Instance of Class:Object is known as instance of class because it uses data members and members functions
of class.
new keyword: The new keyword is required to create object and allocate memory for it.
Syntax: class_name name_of_object_=new class_name ();
Ex: abc ob=new abc();
This stament creates an object ob for the class abc.

Dot(.) operator:The members of class can be accessed using dot(.) operator.


class abc
{ int a,b;
public void sum (int a, int b)
{
int s=a+b;
System.out.println(s);
}
public static void main(String args[])
{
abc ob=new abc();
ob.sum(40,20);
}
}
Scanner Class: The class that allows to input or read primitive data types and String is known as Scanner Class. It
can be used to get input from InputStream. The Scanner class is a part of java.util package. This class has many
built in functions. To use Scanner class java.util package must be imported. Syntax:

import java.util.*; or import java.util.Scanner;

The following syntax declares Scanner class and creates its object.
Scanner sc= new Scanner(System.in);
Here Scanner is a class, sc is an object name, System.in an InputStream.

Functions of Scanner Class:

1)nextInt() : This function is used to input an integer value.


2)nextLong() : This function is used to input an long integer value.
3)nextFloat() : This function is used to input a float value.
4)nextDouble() : This function is used to input a double value.
5)next() : This function is used to input a single word without space.
6) nextLine() : This function is used to input a line with or without space.

Conditional Constructs in Java

In Java, program constructs is divided into three parts:


• Sequence
• Selection (if, switch)
• Iteration (for, while and dowhile)

Sequence Constructs: The sequence construct, means the statements are being executed sequentially i.e. line by line.
Selection Construct: The selection constructs means the execution of statements depending upon a condition-test.
This construct is also called decision construct or conditional construct.
Iteration Construct: The iteration construct means repetition of a set of statements depending upon a condition test.
Conditional Constructs are of following types:
i) if: This statement is used to check one or more than one condition. If condition is true then set of statements
inside the block of ‘if’ will execute otherwise not. Syntax:
if(condition)
{
Statements;
}
ii) if-else: If condition is true then set of statements inside the block of ‘if’ will execute otherwise statements
inside the block of ‘else’ will execute.
Syntax:
if(condition)
{
Statements;
}
else
{
Statements;
}

iii) Nested if-else (if-elseif): It is also called ladder if-else. It is used to check a series of condition where only
one condition executes and if all the condition are false then the last ‘else’ statement executes. Syntax:

if(condition1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
----------
----------

else

statementN;

iv) Nested if: Presence of ‘if’ or more ‘if’ statements inside one
‘if’ statement is known as nested-if statement. Syntax:

if(condition)
{
if(condition)
{
Statements;
}
}

Dangling else problem: In the nested if-else , the number of ‘if’ statements are more than the number of
‘else’ statements then an ambiguous situation arises which is known as dangling else problem.

Example: if(a>b)
If(a>c)
System.out.println(a);
else
System.out.println(b);

In this example there is a confusion that given ‘else’ is related with which ‘if’.
To overcome this problem curly braces {} are used.
switch-case The switch statement is a multiway branch statement. It provides an easy way to dispatch execution
to different parts of code based on the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;

case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;

default:
statementDefault;
}
Some Important rules for switch statements:
• Expression can be of type byte, short, int or char. Beginning with JDK7, expression can also be of type
String.
• Duplicate case values are not allowed.
• The default statement is optional.
• The break statement is used inside the switch to terminate a statement sequence.
• The break statement is optional. If omitted, execution will continue on into the next case.

Example:

class SwitchCaseDemo
{
public static void main(String args[])
{ int i = 9;
switch (i)
{ case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}
Output:
i is greater than 2.
break Statement in switch case

break statement is used to control the flow of the execution. The break statement can be used as the last
statement in each case statement list. When a break statement is reached, the switch terminates, and the flow
of control jumps to the next line following the switch statement. Not every case needs to contain a break. If no
break appears, the flow of control will fall through to subsequent cases until a break is reached.

Fall Through in switch Case


Whenever there is no break statement involved in a switch case block. All the statements are executed even if
the test expression is satisfied.
Following is an example of a fall through switch case.
public class Test {
public static void main(char grade) {

// let char grade = 'C';

switch(grade) {
case 'A’:
System.out.println("Excellent!");
break;
case 'B’:
case 'C’:
System.out.println("Well done");
case 'D’:
System.out.println("You passed");
break;
case 'F’:
System.out.println("Better try again");
break;
default:
System.out.println("Invalid grade"); }
System.out.println("Your grade is " + grade);
} }
Output:
Well done
You passed
Your grade is C
default case:
A switch statement can have an optional default case, which must appear at the end of the switch. The default case can
be used for performing a task when none of the cases is true. No break is needed in the default case.

Compound statement or Block Statement: A Sequence of statements grouped together within a pair of curly braces { }
is called compound statement. Eg: { x = 1; y = 0; }

Iterative Constructs in Java


A construct in which a block of statements gets executed repeatedly unless the required task has been completed. Such
repetitive construct is known as iterative construct or a Loop.

Looping constructs can be categorized into two types. They are:

• Entry Controlled Loop


• Exit Controlled Loop
Advantages with looping statement
• Reduce length of Code
• Take less memory space.
• Burden on the developer is reducing.
• Time consuming process to execute the program is reduced.
Entry Controlled Loop: A Looping construct in which the condition is checked in the beginning. If the condition is true,
the control is allowed to enter into the loop otherwise the entry will be denied.

There are two types of looping construct under this category:

• for Loop: A ‘for’ loop is used when number of iterations is fixed and known. It is a fixed or known looping
construct.

Syntax

for (initialization; condition; increment)


{
statement(s);
}

Example :

int i;
for ( i= 0 : i< 5 ; i++)
{
System . out .println ( "Hello !" ) ;
}

• while loop: A ‘while’ loop is used when number of iterations is unfixed or unknown. In this looping construct, a
block of statements gets executed repeatedly unless the given condition is false. It is a unfixed or unknown
looping construct.

Syntax

initialisation
while(condition)

Statement(s)

updation;

}
Example while loop

int i= 0 ;
while ( i< 5)
{
System .out .println (i);
i++ ;
}

Exit Controlled Loop: A Looping construct in which the condition is checked at the end of the body of the loop. Since
the test-condition is not evaluated until the end of the loop, the body of an exit-controlled loop is always executed at
least once.

• do-while: do-while is an exit-controlled loop that repeats a statement or a block of statements until its
test condition remains true.

Syntax
initialisation
do
{
Statement(s)
updation; } while(condition);

Example do..while loop

int i = 20 ;
do
{
System . out . println ( i) ;
i ++ ;
}
while ( i < 10 ) ;

Variations In for loop:


1. Multiple initialisation:
This includes the comma operator. A variant of the for loop is made possible by the comma operator, as in the
following example −
for(x=0, y=0; x+y < 10; ++x)
Here, both x and y control the loop.
2. Omission of any part of for loop:

This includes the missing pieces of the loop definition. An interesting trait of the for loop is that pieces of the
loop definition need not be there.
For example,
for (x=0; x!=456; )
System.out.println(x);
Here, when each time the loop repeats, x is tested to check if it equals 456. The loop conditions become false
and terminates the loop, when 456 is entered.
3. Infinite loop :
This includes the infinite loop. If all of the pieces in the loop definition are missing, an infinite loop is created or
there is incorrect condition or incorrect updation. The break statement is used to break out of the loop, as in
an example given below −
for(;;){
if(ch == 'A')
break;
}
4. Empty loop or Time Delay loop:
A loop that contains no statements is called empty loop.

Example:

a) int i=3; while (++i<5)


{

b) int i;
for ( i=10; i<=100 ;i++); c) int i=1;
{ do
System.out.println(i); {
} }
while (++i<=50);

Jump Statements: Java has three types of jumping statements they are break, continue, and
return. These statements transfer execution control to another part of the program.

i. break: In Java,break statement is used for termination of the loop in which it get executed

Example:

for (int i = 0; i < 10; i++)


{
// terminate loop when i is 5.
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
} }
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
Loop complete.
ii. continue: When the continue statement is encountered, then compiler skip the current
iteration and the next iteration starts.

It is useful to force an early iteration of a loop

Example:

for (int i = 0; i < 10; i++)


{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;

// If number is odd, print it


System.out.print(i + " ");
}
Output:
1 3 5 7 9

ii. return statement:- This jump statement is used to terminate the function in which it get
executed and also it returns a value to function calling statement.
MATH CLASS AND ITS FUNCTIONS
Math class is pre-defined inside java.lang(default package) and all itsfunctions given
below are static. These functions are used for performing mathematical operations in java.

Srn MATH FUNCTION RETURN DESCRIPTION EXAMPLE


o. NAME TYPE
1. Math.pow(x,y) double Calculate x raised to the power y int x=4,y=2; double
r=Math.pow(x,y);
r=16.0;
2. Math.sqrt(x) double Calculate the square root of x int x=25;
double r=Math.sqrt(x); r=5.0

3. Math.cbrt(x) double Calculate the cubic root of x int x=8;


double r=Math.cbrt(x); r=2.0

4. Math.abs(x) same as Calculate the absolute or positive value of int x=-84; int r=Math.abs(x);
paramet given parameter=|x| r=84; int a=90; int
er r2=Math.abs(a); r2=90;(If
the value is already positive
then no change

5. Math.min(x,y) same as Finds the smallest value between the 2 int x=4,y=6; int
paramet parameters i.e. x and y r=Math.min(x,y);
ers r=4;

6. Math.max(x,y) same as Finds the largest value between the int x=4,y=6; int
paramet 2 parameters i.e. x and y r=Math.max(x,y);
ers r=6;

Math.ceil(x) double Gives the nearest larger value of the double x=14.8,y=16.5;
parameter(after making decimal as 0) doubler=Math.ceil(x); r=15.0;
double r=Math.ceil(y);
r=17.0;

9. Math.round(x) int Gives the rounded off value (sme as in doublex=14.5,y=16.43; int
mathematics) r=Math.round(x); r=15;
If decimal part is less than 5 then intr=Math.round(y);
smaller value otherwise the nearest r=16;
largest value
10. Math.rint(x) double Gives the rounded off value (sme as in double
mathematics) x=14.5,y=16.43,z=18.98;
If decimal part is less than 5 then doubler=Math.rint(x); r=14.0;
smaller value and if greater than 5 then doubler=Math.rint(y); r=16.0;
gives the nearest largest value doubler=Math.rint(z); r=19.0;

but if decimal part is 5 then always gives


the nearest even number
11. Math.exp(x) double Calculate the exponential power int x=2; double
(where the approx. value of r=Math.exp(x);
e=2.718)=ex r=7.38905609893065;

12. Math.random() double This function returns any random double r=Math.random();
value between [0 -1) where 0 is r=any value between 0 to 1 in
inclusive and 1 is exclusive i.e. double
value>=0 and value<1

You might also like