0% found this document useful (0 votes)
22 views69 pages

J 6,7,8,9

Uploaded by

Johny Singh
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)
22 views69 pages

J 6,7,8,9

Uploaded by

Johny Singh
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
You are on page 1/ 69

Lecture-06

By
Dr. Bharati Mishra
Topics
• Common Mathematical Functions
• Character Data Type and Operation
• The String Type
• Case Study, Formatting Console Output
Math Class in Java

• Java includes 8 primitive data types


• byte, short, int, long, float, double, char, boolean
• The Math class contains static methods for common mathematical
operations (for which an operator does not exist in Java)
• Call those methods: Math.<MethodName>
Math.pow(2, 5);

3
Java's Math class
Method name Description
Math.abs(value) absolute value
Math.ceil(value) moves up to ceiling
Math.floor(value) moves down to floor
Math.log10(value) logarithm, base 10
Math.max(value1, value2) larger of two values
Math.min(value1, value2) smaller of two values
Math.pow(base, exp) base to the exp power
Math.random() random double between 0 and 1
Math.rint(value) Round int, nearest whole number
Math.sqrt(value) square root
Math.sin(value) sine/cosine/tangent of
Math.cos(value) an angle in radians
Math.tan(value) Constant Description
Math.toDegrees(value) convert degrees to Math.E 2.7182818...
Math.toRadians(value) radians and back
Math.PI 3.1415926...

4
No output?
• Simply calling these methods produces no visible result.
Math.pow(3, 4); // no output

• Math method calls use a Java feature called return values


that cause them to be treated as expressions.
• The program runs the method, computes the answer, and
then "replaces" the call with its computed result value.
Math.pow(3, 4); // no output
81.0; // no output
• To see the result, we must print it or store it in a variable.
double result = Math.pow(3, 4);
System.out.println(result); // 81.0

5
Calling Math methods
Math.methodName(parameters)
• Examples:
double squareRoot = Math.sqrt(121.0);
System.out.println(squareRoot); // 11.0
int absoluteValue = Math.abs(-50);
System.out.println(absoluteValue); // 50
System.out.println(Math.min(3, 7) + 2); // 5

• The Math methods do not print to the console.


• Each method produces ("returns") a numeric result.
• The results are used as expressions (printed, stored, etc.).

6
Return
• return: To send out a value as the result of a method.
• The opposite of a parameter:
• Parameters send information in from the caller to the method.
• Return values send information out from a method to its caller.
• A call to the method can be used as part of an expression.

-42 Math.abs(-42)

42
main
2.71

3
Math.round(2.71)

7
Why return and not print?

• It might seem more useful for the Math methods to print


their results rather than returning them. Why don't they?
• Answer: Returning is more flexible than printing.
• We can compute several things before printing:
double pow1 = Math.pow(3, 4);
double pow2 = Math.pow(10, 6);
System.out.println("Powers are " + pow1 + " and " + pow2);

• We can combine the results of many computations:


double k = 13 * Math.pow(3, 4) + 5 - Math.sqrt(17.8);

8
• What is output by the following code?
double a = -1.9;
double b = 2.25;
System.out.print( Math.floor(a) +
" " + Math.ceil(b) + " " + a);
A. 3.0
B. -2.0 3.0 -2.0
C. -1.0 3.0 -1.0
D. -1 3 -1.9
E. -2.0 3.0 -1.9

9
Math questions
• Evaluate the following expressions:
Math.abs(-1.23)
Math.pow(3, 2)
Math.pow(10, -2)
Math.sqrt(121.0) - Math.sqrt(256.0)
Math.round(Math.PI) + Math.round(Math.E)
Math.ceil(6.022) + Math.floor(15.9994)
Math.abs(Math.min(-3, -5))
• Math.max and Math.min can be used to bound numbers.
Consider an int variable named age.
What statement would replace negative ages with 0?
What statement would cap the maximum age to 40?

10
Quirks of real numbers
• Some Math methods return double or other non-int
types.
int x = Math.pow(10, 3); // ERROR: incompat. types

• Some double values print poorly (too many digits).


double result = 1.0 / 3.0;
System.out.println(result); // 0.3333333333333
• The computer represents doubles in an imprecise way.
System.out.println(0.1 + 0.2);

• Instead of 0.3, the output is 0.30000000000000004


11
• What is the output of the following code?
int x = 5;
int y = 7;
System.out.print(m(x, y) + " " + x + " " + m(y, x));

public static int m(int x, int y) {


x += 2;
System.out.print(x + " ");
y -= 2;
return x * y;
}
A. 7 9 35 5 27
B. 7 7 35 7 27
C. 7 5 9 27 35
D. 35 7 5 9 27
E. None of A - D are correct

12
Case Study-01
• In physics, the displacement of a moving body represents
its change in position over time while accelerating.
• Given initial velocity v0 in m/s, acceleration a in m/s2, and
elapsed time t in s, the displacement of the body is:
• Displacement = v0 t + ½ a t 2
• Write a method displacement that accepts v0, a, and
t and computes and returns the change in position.
• example: displacement(3.0, 4.0, 5.0) returns
65.0

13
Case Study-02
• Find the angles of a triangle, given the vertices of the triangle.
Character

• Java provides a wrapper class for each primitive


data type
• All in java.lang package
• Primitive data values can be treated as objects
• char
• Primitive data type
• Character class
• Wrapper
Character

• Character class
Character

• Character class
Character charObject = new Character('b');

▪ charObject.compareTo(new Character('a')) returns 1


▪ charObject.compareTo(new Character('b')) returns 0
▪ charObject.compareTo(new Character('c')) returns -1
▪ charObject.compareTo(new Character('d') returns –2
▪ charObject.equals(new Character('b')) returns true
▪ charObject.equals(new Character('d')) returns false
String
String
• String is a reference type (class)

//String is a class
String message = new String("Welcome to Java");

//Since strings are used frequently, Java provides a //shorthand


initializer for creating a string:
String message = "Welcome to Java";

//You can also create a string from an array of


// characters (char)
char[] charArray = {‘W’, ‘e’, ‘l’, ‘c’, ‘o’, ‘m’, ‘e’};
String message = new String(charArray);
String
• A String object is immutable
• i.e. its contents cannot be changed.
• Does the following code change the contents of
the string?

String s = "Java";
s = "HTML";
Trace Code
String s = "Java";
s = "HTML";
Interned String
• To improve efficiency and save memory:
• JVM uses a unique instance for string literals with
the same character sequence.
• Such an instance is called interned.
Interned String
If you use the string initializer, no new object is
created, if the interned object is already created.
String Comparison

To compare strings, do not use ==


String Comparison

Difference between “==“ vs. “equals()”

String s1 = new String("Welcome");


String s2 = "Welcome";

if (s1.equals(s2))
{
// s1 and s2 have the same contents
}

if (s1 == s2)
{
// s1 and s2 have the same reference
}
String Comparison

To compare strings, do not use >=, <=

String s1 = new String("Welcome");


String s2 = "Welcome";

if (s1.compareTo(s2) > 0)
{
// s1 is greater than s2
// lexicographically, i.e. unicode order
}
else if (s1.compareTo(s2) == 0)
{
// s1 and s2 have the same contents
}
else
// s1 is less than s2
String

• Length
• Retrieving individual characters
• Concatenating string
String

• Finding string length using the length()


method:

String message = "Welcome";


int msgLength= message.length();
//7
String

• Retrieving individual characters in a string:


• Do not use message[0]
• Use message.charAt(index)
• Index starts from 0
Concatenation

1. String concatenation
String s3 = s1.concat(s2);

2. String concatenation
String s3 = s1 + s2;

• Both have the same effect


s1 + s2 + s3 + s4 + s5 =
(((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5);
Reading a String
• next() method on Scanner object is used
• Example:
Scanner input = new Scanner(System.in);
System.out.print("Enter three words separated by spaces: ");
String s1 = input.next();
String s2 = input.next();
String s3 = input.next();
System.out.println("s1 is " + s1);
System.out.println("s2 is " + s2);
System.out.println("s3 is " + s3);
Reading a Line
•The next() method reads a string that ends with a whitespace
character.
• nextLine() method to read an entire line of text.
Scanner input = new Scanner(System.in);
System.out.println("Enter a line: ");
String s = input.nextLine();
System.out.println("The line entered is " + s);
Reading a character from 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);
Extraction

• String extraction
Extraction

• You can extract a single character from a string


using the charAt() method.
• You can extract a substring from a string using
the substring() method.
String Message = "Welcome to Java";
String s2 = Message.substring(0, 11) + "HTML";
More

• Converting, replacing, and splitting String


More

• Converting, replacing, and splitting String

String s1 = "Welcome".toLowerCase();
//s1 is a new String: “welcome”
String s2 = "Welcome".toUpperCase();
//s2 is a new string: “WELCOME”
String s3 = " Welcome ".trim();
//s3 is a new string: “Welcome”
String s4 = "Welcome".replace('e', 'A');
//s4 is a new string: “WAlcomA”
String s5 = "Welcome".replaceFirst("e", "AB");
//returns a new string, WABlcome.
String s6 = "Welcome".replaceAll("e", "AB");
//s6 is a new string: “WABlcomAB”
String s7 = "Welcome".replaceAll("el", "AB");
//s7 is a new string: “WABlcome”
More

• The following code displays “Java HTML Perl”

String[] tokens = "Java#HTML#Perl".split("#“,0);

for (int i = 0; i < tokens.length; i++)


System.out.print(tokens[i] + " ");
More

• You can match, replace, or split a string by


specifying a pattern.
• This is an extremely useful and powerful feature,
commonly known as regular expression.
• Regular expression is complex to beginning
students. For this reason, only two simple
patterns are used in this section.
Regular Expression

• Regular expression:

"Java".matches("Java");
"Java".equals("Java");

"Java is fun".matches("Java.*");
"Java is cool".matches("Java.*");
Regular Expression

• The replaceAll(), replaceFirst(), and split()


methods can be used with a regular expression.
Regular Expression

• For example, the following statement returns a


new string that replaces $, +, or # by the string
NNN.

String s = "a+b$#c".replaceAll("[$+#]", "NNN");


System.out.println(s);

• Here the regular expression [$+#] specifies a


pattern that matches $, +, or #.
• So, the output is “aNNNbNNNNNNc”.
Regular Expression

• The following code splits the string into an array


of strings delimited by some punctuation marks.
Find
• Finding a Character or a Substring in a String
Find
• "Welcome to Java".indexOf('W')
• returns 0.
• "Welcome to Java".indexOf('x')
• returns -1.
• "Welcome to Java".indexOf('o', 5)
• returns 9.
• "Welcome to Java".indexOf("come")
• returns 3.
• "Welcome to Java".indexOf("Java", 5)
• returns 11.
• "Welcome to Java".indexOf("java", 5)
• returns -1.
• "Welcome to Java".lastIndexOf('a')
• returns 14.
Conversions

• A String is not an array!


• But, can be converted.
Conversions

• The String class provides several static valueOf ()


methods for converting a character, an array of
characters, and numeric values to strings.
• These methods have the same name valueOf with
different argument types.
• For example, to convert a double value to a string,
use String.valueOf(5.44)
• The return value is string “5.44”.
Numbers & Strings

• The String class provides several static valueOf ()


methods
Program

• Checking whether a string is a palindrome:


• A string that reads the same forward and backward.
• Dad, Mom, noon

CheckPalindrome Run
StringBuilder & StringBuffer
StringBuilder

• The StringBuilder/StringBuffer class is


an alternative to the String class.
• In general, a StringBuilder/StringBuffer can be
used wherever a string is used.
• StringBuilder/StringBuffer is more flexible than
String.
• You can add, insert, or append new contents into a
string buffer
• whereas the value of a String object is fixed once the
string is created.
StringBuilder

• The StringBuilder class


StringBuilder
StringBuilder

• The StringBuilder class


StringBuffer

• StringBuffer is very similar to StringBuilder


• It has synchronized methods
• Use it in mutli-threaded applications
Program

• Ignoring non-alphanumeric characters when


checking palindromes

PalindromeIgnoreNonAlphanumeric Run
Command Line Arguments
More on main

• You can call a regular method by passing actual


parameters. Can you pass arguments to main?
• Of course, yes. For example, the main method in
class B is invoked by a method in A, as shown
below:
Command Line args

• Command line arguments

class TestMain
{
public static void main(String[] args)
{
...
}
}
Command Line args

• In the main method, get the arguments from


args[0], args[1], ..., args[n]
• which corresponds to arg0, arg1, ..., argn in the
command line.
Program
• Write a program that will perform binary
operations on integers. The program receives
three parameters: an operator and two integers.

java Calculator 2 + 3

Calculator java Calculator 2 - 3

java Calculator 2 / 3
Run
java Calculator 2 “*” 3 61
Formatting Output
Formatting Output

• The methods println() and print() do not allow for


easy formatting
• Instead use printf()
System.out.printf ("format string", dataValue1, dataValue2, ....);
• One format specifier for every data value.
• Format specifiers always begin with the % symbol.
• The format string and all data values are separated
by commas ( NO + signs).
• The data values are NOT within double quotes.
Formatting Output

• %s s stands for a string


• %f stands for floating point number
• System.out.printf("%s, %s", "Hello", "World!");
• Output: “Hello, World!”
• System.out.printf(“%.1f pounds” ,28.8968);
• Output: “28.8 pounds”
Formatting Output

Specifier Output Example


%b a boolean value true or false
%c a character 'a'
%d a decimal integer 200
%f a floating-point number 45.460000
%e a number in scientific notation 4.556000e+01
%s a string "Java is cool"
Formatting Specifier

• Format specifiers in more detail

% flag width .precision type

Maximum number
A flag (such as of digits after
Tells the decimal point
compiler to - to left justify)
expect a
specifier … Minimum
number of Data type (e.g. %f)
characters to
show
Width

• Width: minimum number of characters to show


• If the string representation of the value does not
fill the minimum length, the field will be
left-padded with spaces.
• If the converted value exceeds the minimum
length, however, the converted result will not be
truncated.
• Example
• System.out.printf("%6d",52)
• Output: " 52" (four spaces on the left)
Flag

• By default, data is right justified.


• If a dash - follows the % symbol of a format
specifier, then the data value will be left justified.
The - is called a format flag.
• Example
• System.out.printf("%-6d",52)
• Output: “52 " (four spaces on the right)
Precision

• How many digits after decimal point

double percentage = 99.3456789;


System.out.printf("%10.4f”, percentage );

• Output: “ 99.3456”

You might also like