0% found this document useful (0 votes)
9 views35 pages

Chapter 2

Uploaded by

mmhj6470
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)
9 views35 pages

Chapter 2

Uploaded by

mmhj6470
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/ 35

Chapter -2 Built in Methods

Java Program on overloading method

public class TestMethodOverloading {


/** Main method */
public static void main(String[] args)
{
// Invoke the max method with int parameters
System.out.println("The maximum of 3 and 4 is " + max(3, 4)); ok

// Invoke the max method with the double parameters


System.out.println("The maximum of 3.0 and 5.4 is " + max(3.0, 5.4)); ok

// Invoke the max method with three double parameters


System.out.println("The maximum of 3.0, 5.4, and 10.14 is "+ max(3.0, 5.4,
10.14));
}
/** Return the max of two int values */
public static int max(int num1, int num2)
{
if (num1 > num2)
return num1;
else
return num2;
}
/** Find the max of two double values */
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
/** Return the max of three double values */
public static double max(double num1, double num2, double num3) {
return max(max(num1, num2), num3);
}
Scope of Local
Variables
• A local variable: a variable defined inside a method.
• A local variable must be declared before it can be used.
• Scope: the part of the program where the variable can be
referenced.
• The scope of a local variable starts from its declaration
and continues to
the end of the block that contains the variable.
• You can declare a local variable with the same name
multiple times in different non-nesting blocks in a
method,
• But you cannot declare a local variable twice in nested
blocks.
Scope of Local
Variables, cont.
Scope of Local
Variables, cont.
• A variable declared in the initial action part of a for loop header has its
scope in the entire
loop.
• But a variable declared inside a for loop body has its scope limited in
the loop body from its declaration and to the end of the block that
contains the variable.
class HelloWorld {

Scope of Local
// Fine with no errors
public static void correctMethod()
{ int x = 1;
int y = 1;

Variables, cont.
// Fine with no errors
// i is declared
for (int i = 1; i < 10; i++)
{
public static void correctMethod() { x += i;
int x = 1; System.out.println(i);
int y = 1;
}
// i is declared // i is declared again
for (int i = 1; i < 10; i++) { for (int i = 1; i < 10; i++)
x += i; {
} y += i;
System.out.println(i);
// i is declared again
for (int i = 1; i < 10; i++) { }
y += i; }
}
} public static void incorrectMethod()
{
int x = 1; //local variable
int y = 1;
// Errors for (int i = 1; i < 10; i++)
public static void incorrectMethod() { {
int x = 0;
int x = 1; x += i;
int y = 1; System.out.println(x);
for (int i = 1; i < 10; i++) {
int x = 0; }
x += i; }
public static void main(String[] args)
} { int a = 10; //Global variable
}
correctMethod();
incorrectMethod();
}
Scope of Local
Variables,
• Caution:
cont.
• Do not declare a variable inside a block and then attempt to use it
outside the block.
Here is an
• Example of a common mistake:
for (int i = 0; i < 10; i++)
{
:
}
System.out.println(i);
• The last statement would cause a syntax error, because
variable i is not defined
outside of the for loop. for (int i = 0; i < 10; i++)
{
System.out.println(i);
}
Method
Abstraction
• You can think of the method body as a black box that
contains the detailed
implementation for the method.
Optional arguments for Input Optional return value

Method Header
Black Box
Method body
Benefits of
Methods
• Write a method once and reuse it anywhere.
• Information hiding. Hide the implementation
from the user.
• Reduce complexity.
QUIZ
Identify and correct the errors in the following program:
public class Test {
public static void main(String[] args)
{
nPrintln(5, "Welcome to Java!”);
}

public static void nPrintln(String message, int n)


{
int n = 1;
for (int i = 0; i < n; i++)
System.out.println(message);
}
Quiz
Given two method definitions,

public static double m(double x, double y)


public static double m(int x, double y)

answer which of the two methods is invoked for:

a. double z = m(4, 5);


b. double z = m(4, 5.4);
c. double z = m(4.5, 5.4);
Quiz
Does the return statement in the following method cause syntax errors?

public static void xMethod(double x, double y)


{
System.out.println(x + y);
return x + y;
}

a return statement cannot return a value such as return x + y in a void method.


The Math
Class
• The Math class contains the methods needed to perform basic
mathematical
functions.
– Such as : Math.pow(a, b) and the Math.random().
• This section introduces other useful methods in the Math class.
• They can be categorized as
– Trigonometric methods,
– Exponent methods, and
– Service methods.
• Besides methods, the Math class provides two useful double
constants, PI and
E (the base of natural logarithms). Stop
• You can use these constants as here
• Math.PI
• Math.E in any program.
public class JavaMathExample1

The Math {
public static void main(String[] args)
{

Class
• Class constants:
double x = 28;
double y = 4;

// return the maximum of two numbers


– PI System.out.println("Maximum number of x and y is: " +Math.max(x, y));

– E // return the square root of y


System.out.println("Square root of y is: " + Math.sqrt(y));
• Class methods: //returns 28 power of 4 i.e. 28*28*28*28
– Trigonometric Methods System.out.println("Power of x and y is: " + Math.pow(x, y));

– Exponent Methods // return the logarithm of given value


System.out.println("Logarithm of x is: " + Math.log(x));
– Rounding Methods System.out.println("Logarithm of y is: " + Math.log(y));

– Others: min, max, abs, and // return the logarithm of given value when base is 10
System.out.println("log10 of x is: " + Math.log10(x));
random Methods System.out.println("log10 of y is: " + Math.log10(y));

// return the log of x + 1


System.out.println("log1p of x is: " +Math.log1p(x));

// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));

// return (a power of 2)-1


System.out.println("expm1 of a is: " +Math.expm1(x));
}
}
Trigonometric
Methods • To call a method, write the
following:
• class name
• .
• method name
• round parenthesis
• arguments if any
– variables or litrals
WAP IN JAVA FOR Trigonometric
Methods
public class JavaMathExample2
{
public static void main(String[] args)
{ OUTPUT:-
double a = 30; Sine value of a is: -0.9880316240928618
// converting values to radian
double b = Math.toRadians(a); Cosine value of a is: 0.15425144988758405
// return the trigonometric sine of a
System.out.println("Sine value of a is: " +Math.sin(a)); Tangent value of a is: -6.405331196646276
// return the trigonometric cosine value of a
System.out.println("Cosine value of a is: " +Math.cos(a)); Sine value of a is: NaN
// return the trigonometric tangent value of a
System.out.println("Tangent value of a is: " +Math.tan(a)); Cosine value of a is: NaN
// return the trigonometric arc sine of a
System.out.println("Sine value of a is: " +Math.asin(a)); Tangent value of a is: 1.5374753309166493
// return the trigonometric arc cosine value of a
System.out.println("Cosine value of a is: " +Math.acos(a)); Sine value of a is: 5.343237290762231E12
// return the trigonometric arc tangent value of a
System.out.println("Tangent value of a is: " +Math.atan(a)); Cosine value of a is: 5.343237290762231E12

// return the hyperbolic sine of a Tangent value of a is: 1.0


System.out.println("Sine value of a is: " +Math.sinh(a));
// return the hyperbolic cosine value of a
System.out.println("Cosine value of a is: " +Math.cosh(a));
// return the hyperbolic tangent value of a
System.out.println("Tangent value of a is: "
+Math.tanh(a));
}
Trigonometric
Methods
• sin(double a) Examples:

Math.sin(0) returns 0.0


• cos(double a) Math.sin(Math.PI / 6) returns 0.5
Math.sin(Math.PI / 2) returns 1.0
• tan(double a) Math.cos(0) returns 1.0
Math.cos(Math.PI / 6) returns 0.866
• acos(double a) Math.cos(Math.PI / 2) returns 0
Math.sin(Math.toRadians(90)) returns 1.0
• asin(double a)
• atan(double a)
• toRadians(double angdeg); angdeg is an angle,
in degrees
Exponent
public class JavaMathExample2
{
public static void main(String[] args)

Methods
• exp(double a)
{
System.out.println(Math.pow(2, 8));
System.out.println(Math.exp(1));
System.out.println(Math.log(2.71));
– Returns e raised to the System.out.println(Math.pow(2, 3));
power of a. System.out.println(Math.pow(3, 2));
System.out.println(Math.pow(3.5, 2.5));
• log(double a) System.out.println(Math.sqrt(4));
– Returns the natural System.out.println(Math.sqrt(10.5));

logarithm of a. }
}
• log10(double a)
– Returns the 10-based OUTOUT:
Math.pow(2, 8)) return 256
logarithm of a. Math.exp(1) returns 2.71
Math.log(2.71) returns 1.0
• pow(double a, double b) Math.pow(2, 3) returns 8.0
– Returns a raised to the Math.pow(3, 2) returns 9.0
Math.pow(3.5, 2.5) returns 22.91765
power of b. Math.sqrt(4) returns 2.0
• sqrt(double a) Math.sqrt(10.5) returns 3.24

– Returns the square root of a.


Rounding
Methods
• double ceil(double x)
– x rounded up to its nearest integer. This integer is
returned as a double
value.
• double floor(double x)
– x is rounded down to its nearest integer. This integer is
returned as a
double value.
• double rint(double x)
– x is rounded to its nearest integer. If x is equally close to
two integers, the
even one is returned as a double.
• int round(float x)
– Return (int)Math.floor(x+0.5).
• long round(double x)
– Return (long)Math.floor(x+0.5).
Rounding
Methods
WAP IN JAVA for round method
public class JavaMathExample2
{
public static void main(String[] args)
{ OUTPUT:-
System.out.println(Math.round(0.60)); 1
System.out.println(Math.round(0.40)); 0
System.out.println(Math.round(5)); 5
System.out.println(Math.round(5.1)); 5
System.out.println(Math.round(-5.1)); -5
System.out.println(Math.round(-5.9)); -6

}
}
The min, max, and abs
Method

 max(a, b)and min(a, b)


Returns the maximum or
minimum of two parameters.
 abs(a)
Returns the absolute value of the
parameter.

StOP here
The String
Type
• The char type only represents one character.
• To represent a string of characters, use the data type
called String.
– For example,
String message = "Welcome to Java";

• String is a predefined class in the Java library just like


the System class and Scanner class.
• The String type is not a primitive type. It is known as a
reference type.
• Any Java class can be used as a reference type for a
variable.
Simple Methods for String
Objects
Simple Methods for String
Objects
• The methods in the preceding table are called instance
methods can only be invoked from a specific string instance.

• The syntax to invoke an instance method is


referenceVariable.methodName(arguments);

• Example:
String m1 = "Welcome to Java";
System.out.println("The length of " + m1+ " is " +
m1.length());
Getting Characters from a
String

String message = "Welcome to Java";


System.out.println("The first character in message is " + message.charAt(0));
Converting
Strings
• "Welcome".toLowerCase() returns a new string,
welcome.
• "Welcome".toUpperCase() returns a new
string, WELCOME.
• " Welcome ".trim() returns a new string,
Welcome.
String
Concatenation
String s3 = s1.concat(s2); //or String s3 = s1 + s2;

// Three strings are concatenated


String message = "Welcome " + "to " + "Java";

// String Chapter is concatenated with number 2


String s = "Chapter" + 2; // s becomes
Chapter2

// String Supplement is concatenated with character B


String s1 = "Supplement" + 'B'; // s1 becomes SupplementB
Reading a Character from the
Console
Scanner input = new Scanner(System.in);
System.out.print("Enter a character: ");
String s = input.nextLine();
char ch = s.charAt(0);
System.out.println("The character
entered is " + ch);
Comparing
Strings
Obtaining
Substrings
Method Description

substring(beginIndex) Returns this string’s substring that begins with the character at the specified
beginIndex and extends to the end of the string, as shown in Figure
4.2.
substring(beginIndex, Returns this string’s substring that begins at the specified beginIndex
endIndex) and extends to the character at index endIndex – 1, as shown in
Figure 9.6. Note that the character at endIndex is not part of the
substring.

endIndex not included


More String
Methods
Conversion between Strings and
Numbers
To convert String to integer value:
int intValue = Integer.parseInt(intString);

To convert String to double value:


double doubleValue =
Double.parseDouble(doubleString);

To convert integer or double value


to String:
String s = number + "";
String s = “123455”;
Int a = Integer.parseInt(int s);
Output 12345678
Any
Questions?

You might also like