0% found this document useful (0 votes)
3 views40 pages

Chapter 2 (Examples) Tagged

Uploaded by

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

Chapter 2 (Examples) Tagged

Uploaded by

yzn4w4grgm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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
[Link]("The maximum of 3 and 4 is " + max(3, 4)); ok

// Invoke the max method with the double parameters


[Link]("The maximum of 3.0 and 5.4 is " + max(3.0, 5.4)); ok

// Invoke the max method with three double parameters


[Link]("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.
Scope of Local Variables,
class HelloWorld {
// Fine with no errors
public static void correctMethod()
{ int x = 1;

cont.
// Fine with no errors
int y = 1;
// i is declared
for (int i = 1; i < 10; i++)
public static void correctMethod() { {
int x = 1; x += i;
[Link](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;
[Link](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;
for (int i = 1; i < 10; i++)
// Errors {
public static void incorrectMethod() { int x = 0; //error
x += i;
int x = 1;
[Link](x);
int y = 1;
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,
cont.
• Caution:
• 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++)
{
:
}
[Link](i); error

• 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++)
{
[Link](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 / Advantages 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++)
[Link](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)


{
[Link](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 : [Link](a, b) and the [Link]().
• 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).
• You can use these constants as
• [Link]
• Math.E in any program.
The Math
Class
• Class constants:
– PI
– E
• Class methods:
– Trigonometric Methods
– Exponent Methods
– Rounding Methods
– Others: min, max, abs, and random
Methods
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 by using Math
class.
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 = [Link](a); Cosine value of a is: 0.15425144988758405
// return the trigonometric sine of a
[Link]("Sine value of a is: " +[Link](a)); Tangent value of a is: -6.405331196646276
// return the trigonometric cosine value of a
[Link]("Cosine value of a is: " +[Link](a)); Sine value of a is: NaN
// return the trigonometric tangent value of a
[Link]("Tangent value of a is: " +[Link](a)); Cosine value of a is: NaN
// return the trigonometric arc sine of a
[Link]("Sine value of a is: " +[Link](a)); Tangent value of a is: 1.5374753309166493
// return the trigonometric arc cosine value of a
[Link]("Cosine value of a is: " +[Link](a)); Sine value of a is: 5.343237290762231E12
// return the trigonometric arc tangent value of a
[Link]("Tangent value of a is: " +[Link](a)); Cosine value of a is: 5.343237290762231E12
// return the hyperbolic sine of a
[Link]("Sine value of a is: " +[Link](a)); Tangent value of a is: 1.0
// return the hyperbolic cosine value of a
[Link]("Cosine value of a is: " +[Link](a));
// return the hyperbolic tangent value of a
[Link]("Tangent value of a is: " +[Link](a));
}
}
List of the Trigonometric
Methods
• sin(double a)
Examples:

[Link](0) returns 0.0


• cos(double a) [Link]([Link] / 6) returns 0.5
[Link]([Link] / 2) returns 1.0
• tan(double a) [Link](0) returns 1.0
[Link]([Link] / 6) returns 0.866
• acos(double a) [Link]([Link] / 2) returns 0
[Link]([Link](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)
{
[Link]([Link](2, 8));
[Link]([Link](1));
[Link]([Link](2.71));
– Returns e raised to the power [Link](Math.log10(2.71));
of a. [Link]([Link](2, 3));
[Link]([Link](3, 2));
• log(double a) [Link]([Link](3.5, 2.5));
– Returns the natural logarithm [Link]([Link](4));
[Link]([Link](10.5));
of a.
}
• log10(double a) }
– Returns the 10-based OUTOUT:
[Link](2, 8)) return 256
logarithm of a. [Link](1) returns 2.71
[Link](2.71) returns 1.0
• pow(double a, double b) Math.log10(2.71) returns 0.4329
– Returns a raised to the power [Link](2, 3) returns 8.0
[Link](3, 2) returns 9.0
of b. [Link](3.5, 2.5) returns 22.91765
• sqrt(double a) [Link](4) returns 2.0
[Link](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)[Link](x+0.5).
• long round(double x)
– Return (long)[Link](x+0.5).
Rounding
Methods
WAP IN JAVA for round method using Math class.
public class JavaMathExample2
{
public static void main(String[] args) OUTPUT:-
{ The Reounding Methods
[Link]("The Reounding Methods");
[Link]([Link](-5.1)); -5.0
[Link]([Link](5.9)); 6.0
[Link]([Link](-5.5)); -6.0
[Link]([Link](5.1)); 5.0
[Link]([Link](-5.1)); -5.0
[Link]([Link](5.9)); 6.0
[Link]([Link](9.60)); 10
[Link]([Link](-5.60)); -5
}
}
The min, max, and abs Method by using Math
class
public class JavaMathExample2
{
public static void main(String[] args)
{
[Link]("The max, min & abs
value");
[Link]([Link](10, 20));
[Link]([Link](15, 9));
[Link]([Link](-5.9));

}
}
 max(a, b)and min(a, b) Output:
Returns the maximum or minimum
20
of two parameters. 9
5.9
 abs(a)
Returns the absolute value of the
parameter.
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


[Link](arguments);

• Example:
String m1 = "Welcome to Java";
[Link]("The length of " + m1+ " is " +
[Link]());
Getting Characters from a
String

String message = "Welcome to Java";


[Link]("The first character in message is " + [Link](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 = [Link](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
WAP in java about Methods use in String
Objects
public class JavaMathExample2
{
public static void main(String[] args)
{
String m1 = "Welcome to Java";
[Link]("The first character in message is " + [Link](0));
[Link]("The length of " + m1+ " is " + [Link]());
[Link]("The last character in message is " + [Link](14));
[Link]([Link]());
[Link]([Link]());
[Link]([Link]()); OUTPUT:-
The length of Welcome to Java is 15
String s1 = "Mohmmed "; The first character in message is W
String s2 = "Hussain"; The last character in message is a
String s3 = [Link](s2); WELCOME TO JAVA
[Link](s3); welcome to java
} Welcome to Java
Mohmmed Hussain
}
Reading a Character from the
Console
Scanner input = new Scanner([Link]);
[Link]("Enter a character: ");
String s = [Link]();
char ch = [Link](0);
[Link]("The character
entered is " + ch);
List out the Comparing Strings of Java
WAP in java for Comparing Strings
public class StringComparison { OUTPUT
public static void main(String[] args) { Using equals: false
String s1 = "Hello World"; Using equalsIgnoreCase: true
String s2 = "hello world"; Using compareTo: -32
String prefix = "Hello"; Using compareToIgnoreCase: 0
String suffix = "World"; Using startsWith: true
// Using equals Using endsWith: true
[Link]("Using equals: " + [Link](s2)); // false
// Using equalsIgnoreCase
[Link]("Using equalsIgnoreCase: " + [Link](s2)); // true
// Using compareTo
[Link]("Using compareTo: " + [Link](s2)); // positive number (as 'H' > 'h')
// Using compareToIgnoreCase
[Link]("Using compareToIgnoreCase: " + [Link](s2)); // 0
// Using startsWith
[Link]("Using startsWith: " + [Link](prefix)); // true
// Using endsWith
[Link]("Using endsWith: " + [Link](suffix)); // true
}
}
WAP in java for Comparing Strings
public class StringComparison {
public static void main(String[] args) {
String s1 = "Hello World";

// Different prefixes to check


String prefix1 = "Hello"; // Should return true
String prefix2 = "World"; // Should return false
String prefix3 = "Hello W"; // Should return true

// Using startsWith with different prefixes


[Link]("Starts with 'Hello': " + [Link](prefix1)); // true
[Link]("Starts with 'World': " + [Link](prefix2)); // false
[Link]("Starts with 'Hello W': " + [Link](prefix3)); // true
}
}
OUTPUT
Starts with 'Hello': true
Starts with 'World': false
Starts with 'Hello W': true
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
public class IndexOfExamples {
public static void main(String[] args) { Output :
String text1 = "programming";
String text2 = "hello world"; // Output: 1
String text3 = "abc abc abc"; // Output: 4
String text4 = "banana"; // Output: 6
String text5 = "one two one two";
// Output: 4
[Link]("1. indexOf('r') in \"" + text1 + "\": " + [Link]('r')); // Output: 5
// Output: 3
[Link]("2. indexOf('r', 2) in \"" + text1 + "\": " + [Link]('r', 2)); // Output: 12
[Link]("3. indexOf(\"world\") in \"" + text2 + "\": " + [Link]("world")); // Output: 4

[Link]("4. indexOf(\"abc\", 4) in \"" + text3 + "\": " + [Link]("abc", 4));

[Link]("5. lastIndexOf('a') in \"" + text4 + "\": " + [Link]('a'));

[Link]("6. lastIndexOf('a', 4) in \"" + text4 + "\": " + [Link]('a', 4));

[Link]("7. lastIndexOf(\"two\") in \"" + text5 + "\": " + [Link]("two"));

[Link]("8. lastIndexOf(\"two\", 10) in \"" + text5 + "\": " + [Link]("two", 10));


}
}
Conversion between Strings and
Numbers
To convert String to integer value: public class Main {
int intValue = [Link](intString); public static void main(String[] args) {
// Initialize a number as a string
String s = "123455";
To convert String to double value:
double doubleValue = // Parse the string to an integer
[Link](doubleString); int a = [Link](s);

// Output the result after adding 123


To convert integer or double value to int result = a + 123; // Adjust the number
[Link](result);
String: }
String s = number + ""; }
String s =“123455”; Output 123578
inta= [Link](int s);
Output 12345678
Any
Questions?

You might also like