SlideShare a Scribd company logo
Chapter 4
Mathematical
Functions,
Characters, and
Strings
StonyBrookUniversity
http://www.cs.stonybrook.edu/~cse114
OBJECTIVES
 To solve mathematics problems by using the methods in the Math class (§4.2).
 To represent characters using the char type (§4.3).
 To represent special characters using the escape sequences (§4.4.2).
 To cast a numeric value to a character and cast a character to an integer (§4.3.3).
 To compare and test characters using the static methods in the Character class (§4.3.4).
 To introduce objects and instance methods (§4.4).
 To represent strings using the String objects (§4.4).
 To return the string length using the length() method (§4.4.1).
 To return a character in the string using the charAt(i) method (§4.4.2).
 To use the + operator to concatenate strings (§4.4.3). 2
 To read strings from the console (§4.4.4).
 To read a character from the console (§4.4.5).
 To compare strings using the equals method and the compareTo methods (§4.4.6).
 To obtain substrings (§4.4.7).
 To find a character or a substring in a string using the indexOf method (§4.4.8).
 To convert a hexadecimal character to a decimal value (HexDigit2Dec) (§4.5.2).
 To format output using the System.out.printf method (§4.6).
3
OBJECTIVES…
STATIC METHODS
⚫Remember the main method header?
public static void main(String[] args)
⚫What does static mean?
⚫associates a method with a particular class name
⚫any method can call a static method either:
⚫directly from within same class OR
⚫using class name from outside class
⚫Application Programming Interface (API) is the list of all
public members of a class
4
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
MATHEMATICAL FUNCTIONS
Java provides many useful methods in the
Math class for performing common
mathematical functions.
5
THE MATHCLASS API
6
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
⚫Class constants (always static):
⚫PI
⚫E
⚫Class static methods:
⚫Trigonometric methods
⚫Exponent methods
⚫Rounding methods
⚫min, max, abs, and random methods
TRIGONOMETRIC METHODS
⚫sin(double a)
⚫cos(double a)
⚫tan(double a)
⚫acos(double a)
⚫asin(double a)
⚫atan(double a)
Radians
•Examples: Math.sin(0)
returns 0.0
Math.sin(Math.PI / 6)
returns 0.5
Math.sin(Math.PI / 2)
returns 1.0
Math.cos(0) returns 1.0
Math.cos(Math.PI / 6)
returns 0.866
Math.cos(Math.PI / 2)
returns 0
(C) PEARSON EDUCATION, INC. & PAUL FODOR (CS STONY BROOK)
EXPONENT METHODS
⚫ exp(double a)
Returnse raised to the power of a.
⚫ log(double a)
Returnsthe natural logarithm of a.
⚫ log10(double a)
Returnsthe 10-basedlogarithm of a.
⚫ pow(double a, double b)
Returnsa raised to the power of b.
⚫ sqrt(double a)
Returnsthe square root of a.
•Examples:
Math.exp(1) returns 2.71
Math.log(2.71)
returns 1.0
Math.pow(2, 3)
returns 8.0
Math.pow(3, 2)
returns 9.0
Math.pow(3.5, 2.5)
returns 22.91765
Math.sqrt(4) returns 2.0
Math.sqrt(10.5)
returns 3.24
(C) PEARSON EDUCATION, INC. & PAUL FODOR (CS STONY BROOK)
ROUNDING METHODS
9
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
⚫ 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 EXAMPLES
10
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Math.ceil(2.1) returns 3.0
Math.ceil(2.0) returns 2.0
Math.ceil(-2.0) returns –2.0
Math.ceil(-2.1) returns -2.0
Math.floor(2.1) returns 2.0
Math.floor(2.0) returns 2.0
Math.floor(-2.0) returns –2.0
Math.floor(-2.1) returns -3.0
Math.round(2.6f) returns 3
Math.round(2.0) returns 2 (long)
Math.round(-2.0f) returns -2
Math.round(-2.6) returns -3 (long)
MIN, MAX, AND ABS
⚫ max(a, b)and min(a, b) Returns
the maximum or minimum of two
parameters.
⚫ abs(a)
 Returns the absolute value of the parameter.
⚫ random()
 Returns arandom double
 value
 in the range [0.0, 1.0).
• Examples:
 Math.max(2, 3)
 returns 3
 Math.max(2.5, 3)
 returns 3.0
 Math.min(2.5,3.6)
 returns 2.5
 Math.abs(-2)
 returns 2
 Math.abs(-2.1)
 returns 2.1
(C) PEARSON EDUCATION, INC. & PAUL FODOR (CS STONY BROOK)
THE RANDOMMETHOD
Generates arandom double value greater than or equal to 0.0 and less
than 1.0 (0 <= Math.random() < 1.0)
Examples:
(int)(Math.random() * 10) Returns a random integer
between 0 and 9.
50 + (int)(Math.random() * 50) Returns a random integer
between 50 and 99.
In general,
a + Math.random() * b Returns a random number between
a and a + b, excluding a + b.
GENERATING RANDOM CHARACTERS
13
(char)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1))
⚫All numeric operators can be applied to the char operands
⚫The char operand is cast into anumber if the other operand isa
number or acharacter.
⚫So,the preceding expression can be simplified asfollows:
(char)('a' + Math.random() * ('z' - 'a'
+ 1))
ASCII CODE FOR COMMONLY USED CHARACTERS
Characters Code Value in Decimal Unicode Value
'0' to '9' 48 to 57 u0030 to u0039
'A' to 'Z'
'a' to 'z'
65 to 90
97 to 122
u0041 to u005A
u0061 to u007A
There is no need to remember them since we can do all mathematical
operations with characters:
(char)('a' + Math.random() * ('z' - 'a' + 1))
'0' <= c && c <= '9'
14
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
COMPARING AND TESTING CHARACTERS
if ('A' <= ch && ch <= 'Z')
System.out.println(ch + " is an uppercase
letter");
if ('a' <= ch && ch <= 'z')
System.out.println(ch + " is a lowercase letter");
if ('0' <= ch && ch <= '9')
System.out.println(ch + " is a numeric
character");
15
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
METHODS IN THE CHARACTER CLASS
Method Description
isDigit(ch)
isLetter(ch)
isLetterOrDigit(ch)
isLowerCase(ch)
isUpperCase(ch)
toLowerCase(ch)
toUpperCase(ch)
Returns true if the specified character is a digit.
Returns true if the specified character is a letter.
Returns true if the specified character is a letter or digit.
Returns true if the specified character is a lowercase letter.
Returns true if the specified character is an uppercase letter.
Returns the lowercase of the specified character.
Returns the uppercase of the specified character.
16
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
THE STRING TYPE
14
String message = "Welcome to Java";
: String
"Welcome to Java"
⚫ The char type only represents one character:
char ch = 'a';
'a'
⚫ To represent a string of characters, use the data type called String.
String is a predefined class in the Java library just like the System class
http://java.sun.com/javase/8/docs/api/java/lang/String.html
⚫ The String type is NOT a primitive type.
⚫ The String type is a reference type.
⚫ A String variable is a reference variable, an "address" which points to an object storing
the value or actual text
MORE ABOUT STRINGS
⚫Each character is stored at an index:
String sentence = "A statement";
012345678910
⚫The String class API has methods to process strings:
System.out.println("charAt(6) is " +
sentence.charAt(6));
System.out.println(sentence.toUpperCase());
System.out.println(sentence.substring(0,7) +
sentence.substring(10));
18
STRINGS ARE IMMUTABLE!
⚫There are no methods to change them once they have been
created
⚫any new assignment will assign a new String reference to the
old variable
String word = "Steven";
word = word.substring(0, 5);
⚫the variable word is now a reference to a new String that
contains "Steve"
19
20
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
STRING CONCATENATION
⚫ “+” is used for making a new string by concatenating strings:
// 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
String s2 = 1 + 2 + "ABC";
// s2 become "3ABC"
21
ESCAPE SEQUENCES FOR SPECIAL CHARACTERS
22
READING A STRING FROM THE CONSOLE
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);
23
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
USEFUL STRING FUNCTIONS
⚫charAt
⚫equals
⚫equalsIgnoreCase
⚫compareTo
⚫startsWith
⚫endsWith
24
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
⚫indexOf
⚫lastIndexOf
⚫Replace
⚫Substring
⚫toLowerCase
⚫toUpperCase
⚫trim
COMPARING STRINGS
⚫Don’t use ‘==’ to compare Strings
⚫it compares their memory addresses and not actual strings
(character sequences)
⚫Instead use the equalsmethod supplied by the String class:
⚫s.equals(t)
⚫returns true if s and t have same letters and sequence
⚫false otherwise
25
COMPARING STRINGS
String word1 = new String("Hello");
String word2 = new String("Hello");
if (word1 == word2){
System.out.println(true);
} else {
System.out.println(false);
}
false
T
wo different addresses
26
String word1 = new String("Hello");
String word2 = new String("Hello");
if (word1.equals(word2)){
System.out.println(true);
} else {
System.out.println(false);
}
true
compares the contents "Hello" with "Hello"
27
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
COMPARING STRINGS
28
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
String word1 = "Hello";
String word2 = "Hello";
if (word1 == word2){
System.out.println(true);
} else {
System.out.println(false);
}
true
⚫Interned Strings: Only one instance of “Hello” is stored
⚫so word1 and word2 will have the same address
29
COMPARING STRINGS
COMPARING STRINGS
String word1 = "Hello";
String word2 = "Hello";
if (word1.equals(word2)){
System.out.println(true);
} else {
System.out.println(false);
}
true
30
COMPARING STRINGS
Method Description
Returns true if this string is equal to string s1.
Returns true if this string is equal to string s1; it is case insensitive.
Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is
greater than, equal to, or greater than s1.
Same as compareTo except that the comparison is case insensitive.
Returns true if this string starts with the specified prefix.
Returns true if this string ends with the specified suffix.
equals(s1)
equalsIgnoreCase(s1)
compareTo(s1)
compareToIgnoreCase(s1)
startsWith(prefix)
endsWith(suffix)
31
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
OrderTwoCities
32
import java.util.Scanner;
public class OrderTwoCities {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two cities
System.out.print("Enter the first city: ");
String city1 = input.nextLine();
System.out.print("Enter the second city: ");
String city2 = input.nextLine();
if (city1.compareTo(city2) < 0)
System.out.println("The cities in alphabetical order are " +
city1 + " " + city2);
else
System.out.println("The cities in alphabetical order are " +
city2 + " " + city1);
}
}
OrderTwoCities
GETTING CHARACTERS FROM A STRING
String message = "Welcome to Java";
System.out.println(
"The first character in message is "
+ message.charAt(0));
33
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
READING A SINGLE 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.print("The character entered is "+ch);
34
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
OBTAINING SUBSTRINGS
Method Description
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.
Returns this string’s substring that begins at the specified beginIndex 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.
substring(beginIndex)
substring(beginIndex,
endIndex)
35
FINDING A CHARACTER OR A SUBSTRING IN A STRING
Method Description
Returns the index of the first occurrence of ch in the string. Returns -1 if not
matched.
Returns the index of the first occurrence of ch after fromIndex in the string.
Returns -1 if not matched.
Returns the index of the first occurrence of string s in this string. Returns -1 if
not matched.
Returns the index of the first occurrence of string s in this string after
fromIndex. Returns -1 if not matched.
Returns the index of the last occurrence of ch in the string. Returns -1 if not
matched.
Returns the index of the last occurrence of ch before fromIndex in this
string. Returns -1 if not matched.
Returns the index of the last occurrence of string s. Returns -1 if not matched.
Returns the index of the last occurrence of string s before fromIndex.
Returns -1 if not matched.
indexOf(ch)
indexOf(ch, fromIndex)
indexOf(s)
indexOf(s, fromIndex)
lastIndexOf(ch)
lastIndexOf(ch,
fromIndex)
lastIndexOf(s)
lastIndexOf(s,
fromIndex)
36
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
FINDING A CHARACTER OR A SUBSTRING IN A STRING
int k = s.indexOf(' '); //3
String firstName = s.substring(0, k);
String lastName = s.substring(k + 1);
37
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
CONVERSION BETWEEN STRINGS AND NUMBERS
String intString = "15";
String doubleString = "56.77653";
int intValue =
Integer.parseInt(intString);
double doubleValue =
Double.parseDouble(doubleString);
String s2 = "" + intValue;
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
CASE STUDY: CONVERTING A HEXADECIMAL DIGIT TO A DECIMAL
VALUE
Write a program that converts a hexadecimal digit into a
decimal value.
39
HexDigit2Dec
https://liveexample.pearsoncmg.com/html/HexDigit2Dec.h
tml
FORMATTING OUTPUT
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
The printf statement:
System.out.printf(format, items);
• format is a string that may consist of
substrings and format specifiers
• A format specifier begins with a percent sign and
specifies how an item should be displayed: a numeric
value, character, boolean value, or a string
FREQUENTLY-USED SPECIFIERS
Specifier Output
%b a boolean value
Example
true or false
%c
%d
a
a
character
decimal integer
'a'
200
%f a floating-point number 45.460000
%e a number in standard scientific notation 4.556000e+01
%s a string "Java is cool"
int count = 5;
double amount = 45.567899;
System.out.printf("count is %d and amount is %.2f", count, amount)
Displays: count is 5 and amount is 45.56
items
BITWISE OPERATIONS IN JAVA
⚫ T
o write programs at the machine-level, often you need to deal with
binary numbers directly and perform operations at the bit- level
⚫ Java provides the bitwise operators and shift operators
⚫The bit operators apply only to integer types (byte, short, int, and
long)
⚫All bitwise operators can form bitwise assignment operators, such as
=: |=, <<=, >>=, and >>>=
⚫ Bitwise AND: &
⚫1010 & 1001 yields 1000
System.out.print(10&9); // 8
⚫The AND of two corresponding bits yields a 1 if both bits are 1,
otherwise 0
BITWISE OPERATIONS IN JAVA
⚫ BitwiseOR:|
⚫The OR of two corresponding bits yields a1 ifeither bit is1
⚫10101110 | 10010010 yields10111110
class BitwiseOR {
public static void main(String[] args) {
int number1 = 12, number2 = 25, result;
result = number1 | number2;
System.out.println(result);
}
}
1100 | 12
11001 25
11101 = 29
43
BITWISE OPERATIONS IN JAVA
⚫ Bitwise exclusive OR: ^
⚫1010 ^ 1001 yields 0011
⚫The XOR of two corresponding bits yields a 1 only if two bits are
different.
⚫ One’s complement: ~
⚫~1010 yields 0101
⚫The operator toggles each bit from 0 to 1 and from 1 to 0.
⚫ Left shift: <<
⚫1010 << 2 yields 101000
System.out.print(10 << 2); // 40
⚫The operator shifts bits in the first operand left by the number of
bits specified in the second operand, filling with 0s on the right.
⚫Right shift with sign extension: >>
⚫1010 >> 2 yields 10
System.out.print(10 >> 2); // 2
⚫The operator shifts bit in the first operand right by the
number of bits specified in the second operand, filling
with the highest (sign) bit on the left.
⚫Unsigned right shift with zero extension: >>>
System.out.print(-10 >>> 2); // 1073741821
⚫The operator shifts bit in the first operand right by the
number of bits specified in the second operand, filling with
0s on the left.
45
BITWISE OPERATIONS IN JAVA
CONSTANTS IN BINARY FORMAT
byte fourTimesThree = 0b1100;
byte data = 0b0000110011;
short number = 0b111111111111111;
int overflow = 0b10101010101010101010101010101011;
long bow = 0b101010101010101010101010101010111L;
⚫ Just be careful not to overflow the numbers with too much data,or else you'll get acompiler
error:
byte data = 0b1100110011;
// Type mismatch: cannot convert from int to byte
⚫New feature in Java7 known asnumeric literals with underscores:
⚫int overflow = 0b1010_1010_1010_1010_1010_1010_1010_1011;
⚫long bow = 0b1 01010101 01010101 01010101 01010111L;
46
CONSTANTS IN OCTAL AND HEXADECIMAL FORMAT
int x = 010;
int y = 0xf;
(C) PEARSON EDUCATION, INC. & PAUL FODOR (CS STONY BROOK)
//octal = 8
//hexadecimal = 15
ADDITIONAL RESOURCES
 https://www.w3schools.com/java/java_math.asp
 https://www.javatpoint.com/java-math
 https://www.geeksforgeeks.org/shift-operator-in-java/
 https://www.programiz.com/java-programming/string
 https://www.tutorialspoint.com/java/java_basic_operators.htm
 https://www.baeldung.com/java-bitwise-operators
END

More Related Content

Similar to 04slide Update.pptx

Computer programming 2 Lesson 11
Computer programming 2  Lesson 11Computer programming 2  Lesson 11
Computer programming 2 Lesson 11
MLG College of Learning, Inc
 
© Copyright 2013 by Pearson Education, Inc. All Rights Res.docx
© Copyright 2013 by Pearson Education, Inc. All Rights Res.docx© Copyright 2013 by Pearson Education, Inc. All Rights Res.docx
© Copyright 2013 by Pearson Education, Inc. All Rights Res.docx
LynellBull52
 
String slide
String slideString slide
String slide
Daman Toor
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
Dharma Kshetri
 
The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88
Mahmoud Samir Fayed
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
M C6java7
M C6java7M C6java7
M C6java7
mbruggen
 
LiangChapter4 Unicode , ASCII Code .ppt
LiangChapter4 Unicode , ASCII Code  .pptLiangChapter4 Unicode , ASCII Code  .ppt
LiangChapter4 Unicode , ASCII Code .ppt
zainiiqbal761
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
Unit 3 arrays and_string
Unit 3 arrays and_stringUnit 3 arrays and_string
Unit 3 arrays and_string
kirthika jeyenth
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
Intro C# Book
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
teach4uin
 
Strings
StringsStrings
Strings
Imad Ali
 
Week6_P_String.pptx
Week6_P_String.pptxWeek6_P_String.pptx
Week6_P_String.pptx
OluwafolakeOjo
 
Oct27
Oct27Oct27
Oct27
Tak Lee
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptx
AnkurRajSingh2
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
Mohamed Krar
 
String in programming language in c or c++
String in programming language in c or c++String in programming language in c or c++
String in programming language in c or c++
Azeemaj101
 

Similar to 04slide Update.pptx (20)

Computer programming 2 Lesson 11
Computer programming 2  Lesson 11Computer programming 2  Lesson 11
Computer programming 2 Lesson 11
 
© Copyright 2013 by Pearson Education, Inc. All Rights Res.docx
© Copyright 2013 by Pearson Education, Inc. All Rights Res.docx© Copyright 2013 by Pearson Education, Inc. All Rights Res.docx
© Copyright 2013 by Pearson Education, Inc. All Rights Res.docx
 
String slide
String slideString slide
String slide
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
M C6java7
M C6java7M C6java7
M C6java7
 
LiangChapter4 Unicode , ASCII Code .ppt
LiangChapter4 Unicode , ASCII Code  .pptLiangChapter4 Unicode , ASCII Code  .ppt
LiangChapter4 Unicode , ASCII Code .ppt
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Unit 3 arrays and_string
Unit 3 arrays and_stringUnit 3 arrays and_string
Unit 3 arrays and_string
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
Strings
StringsStrings
Strings
 
Week6_P_String.pptx
Week6_P_String.pptxWeek6_P_String.pptx
Week6_P_String.pptx
 
Oct27
Oct27Oct27
Oct27
 
Arrays & Strings.pptx
Arrays & Strings.pptxArrays & Strings.pptx
Arrays & Strings.pptx
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
String in programming language in c or c++
String in programming language in c or c++String in programming language in c or c++
String in programming language in c or c++
 

Recently uploaded

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
Neo4j
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 

Recently uploaded (20)

20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
GraphSummit Singapore | Enhancing Changi Airport Group's Passenger Experience...
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 

04slide Update.pptx

  • 2. OBJECTIVES  To solve mathematics problems by using the methods in the Math class (§4.2).  To represent characters using the char type (§4.3).  To represent special characters using the escape sequences (§4.4.2).  To cast a numeric value to a character and cast a character to an integer (§4.3.3).  To compare and test characters using the static methods in the Character class (§4.3.4).  To introduce objects and instance methods (§4.4).  To represent strings using the String objects (§4.4).  To return the string length using the length() method (§4.4.1).  To return a character in the string using the charAt(i) method (§4.4.2).  To use the + operator to concatenate strings (§4.4.3). 2
  • 3.  To read strings from the console (§4.4.4).  To read a character from the console (§4.4.5).  To compare strings using the equals method and the compareTo methods (§4.4.6).  To obtain substrings (§4.4.7).  To find a character or a substring in a string using the indexOf method (§4.4.8).  To convert a hexadecimal character to a decimal value (HexDigit2Dec) (§4.5.2).  To format output using the System.out.printf method (§4.6). 3 OBJECTIVES…
  • 4. STATIC METHODS ⚫Remember the main method header? public static void main(String[] args) ⚫What does static mean? ⚫associates a method with a particular class name ⚫any method can call a static method either: ⚫directly from within same class OR ⚫using class name from outside class ⚫Application Programming Interface (API) is the list of all public members of a class 4 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 5. MATHEMATICAL FUNCTIONS Java provides many useful methods in the Math class for performing common mathematical functions. 5
  • 6. THE MATHCLASS API 6 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook) ⚫Class constants (always static): ⚫PI ⚫E ⚫Class static methods: ⚫Trigonometric methods ⚫Exponent methods ⚫Rounding methods ⚫min, max, abs, and random methods
  • 7. TRIGONOMETRIC METHODS ⚫sin(double a) ⚫cos(double a) ⚫tan(double a) ⚫acos(double a) ⚫asin(double a) ⚫atan(double a) Radians •Examples: Math.sin(0) returns 0.0 Math.sin(Math.PI / 6) returns 0.5 Math.sin(Math.PI / 2) returns 1.0 Math.cos(0) returns 1.0 Math.cos(Math.PI / 6) returns 0.866 Math.cos(Math.PI / 2) returns 0 (C) PEARSON EDUCATION, INC. & PAUL FODOR (CS STONY BROOK)
  • 8. EXPONENT METHODS ⚫ exp(double a) Returnse raised to the power of a. ⚫ log(double a) Returnsthe natural logarithm of a. ⚫ log10(double a) Returnsthe 10-basedlogarithm of a. ⚫ pow(double a, double b) Returnsa raised to the power of b. ⚫ sqrt(double a) Returnsthe square root of a. •Examples: Math.exp(1) returns 2.71 Math.log(2.71) returns 1.0 Math.pow(2, 3) returns 8.0 Math.pow(3, 2) returns 9.0 Math.pow(3.5, 2.5) returns 22.91765 Math.sqrt(4) returns 2.0 Math.sqrt(10.5) returns 3.24 (C) PEARSON EDUCATION, INC. & PAUL FODOR (CS STONY BROOK)
  • 9. ROUNDING METHODS 9 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook) ⚫ 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).
  • 10. ROUNDING METHODS EXAMPLES 10 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook) Math.ceil(2.1) returns 3.0 Math.ceil(2.0) returns 2.0 Math.ceil(-2.0) returns –2.0 Math.ceil(-2.1) returns -2.0 Math.floor(2.1) returns 2.0 Math.floor(2.0) returns 2.0 Math.floor(-2.0) returns –2.0 Math.floor(-2.1) returns -3.0 Math.round(2.6f) returns 3 Math.round(2.0) returns 2 (long) Math.round(-2.0f) returns -2 Math.round(-2.6) returns -3 (long)
  • 11. MIN, MAX, AND ABS ⚫ max(a, b)and min(a, b) Returns the maximum or minimum of two parameters. ⚫ abs(a)  Returns the absolute value of the parameter. ⚫ random()  Returns arandom double  value  in the range [0.0, 1.0). • Examples:  Math.max(2, 3)  returns 3  Math.max(2.5, 3)  returns 3.0  Math.min(2.5,3.6)  returns 2.5  Math.abs(-2)  returns 2  Math.abs(-2.1)  returns 2.1 (C) PEARSON EDUCATION, INC. & PAUL FODOR (CS STONY BROOK)
  • 12. THE RANDOMMETHOD Generates arandom double value greater than or equal to 0.0 and less than 1.0 (0 <= Math.random() < 1.0) Examples: (int)(Math.random() * 10) Returns a random integer between 0 and 9. 50 + (int)(Math.random() * 50) Returns a random integer between 50 and 99. In general, a + Math.random() * b Returns a random number between a and a + b, excluding a + b.
  • 13. GENERATING RANDOM CHARACTERS 13 (char)((int)'a' + Math.random() * ((int)'z' - (int)'a' + 1)) ⚫All numeric operators can be applied to the char operands ⚫The char operand is cast into anumber if the other operand isa number or acharacter. ⚫So,the preceding expression can be simplified asfollows: (char)('a' + Math.random() * ('z' - 'a' + 1))
  • 14. ASCII CODE FOR COMMONLY USED CHARACTERS Characters Code Value in Decimal Unicode Value '0' to '9' 48 to 57 u0030 to u0039 'A' to 'Z' 'a' to 'z' 65 to 90 97 to 122 u0041 to u005A u0061 to u007A There is no need to remember them since we can do all mathematical operations with characters: (char)('a' + Math.random() * ('z' - 'a' + 1)) '0' <= c && c <= '9' 14 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 15. COMPARING AND TESTING CHARACTERS if ('A' <= ch && ch <= 'Z') System.out.println(ch + " is an uppercase letter"); if ('a' <= ch && ch <= 'z') System.out.println(ch + " is a lowercase letter"); if ('0' <= ch && ch <= '9') System.out.println(ch + " is a numeric character"); 15 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 16. METHODS IN THE CHARACTER CLASS Method Description isDigit(ch) isLetter(ch) isLetterOrDigit(ch) isLowerCase(ch) isUpperCase(ch) toLowerCase(ch) toUpperCase(ch) Returns true if the specified character is a digit. Returns true if the specified character is a letter. Returns true if the specified character is a letter or digit. Returns true if the specified character is a lowercase letter. Returns true if the specified character is an uppercase letter. Returns the lowercase of the specified character. Returns the uppercase of the specified character. 16 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 17. THE STRING TYPE 14 String message = "Welcome to Java"; : String "Welcome to Java" ⚫ The char type only represents one character: char ch = 'a'; 'a' ⚫ To represent a string of characters, use the data type called String. String is a predefined class in the Java library just like the System class http://java.sun.com/javase/8/docs/api/java/lang/String.html ⚫ The String type is NOT a primitive type. ⚫ The String type is a reference type. ⚫ A String variable is a reference variable, an "address" which points to an object storing the value or actual text
  • 18. MORE ABOUT STRINGS ⚫Each character is stored at an index: String sentence = "A statement"; 012345678910 ⚫The String class API has methods to process strings: System.out.println("charAt(6) is " + sentence.charAt(6)); System.out.println(sentence.toUpperCase()); System.out.println(sentence.substring(0,7) + sentence.substring(10)); 18
  • 19. STRINGS ARE IMMUTABLE! ⚫There are no methods to change them once they have been created ⚫any new assignment will assign a new String reference to the old variable String word = "Steven"; word = word.substring(0, 5); ⚫the variable word is now a reference to a new String that contains "Steve" 19
  • 20. 20 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 21. STRING CONCATENATION ⚫ “+” is used for making a new string by concatenating strings: // 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 String s2 = 1 + 2 + "ABC"; // s2 become "3ABC" 21
  • 22. ESCAPE SEQUENCES FOR SPECIAL CHARACTERS 22
  • 23. READING A STRING FROM THE CONSOLE 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); 23 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 24. USEFUL STRING FUNCTIONS ⚫charAt ⚫equals ⚫equalsIgnoreCase ⚫compareTo ⚫startsWith ⚫endsWith 24 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook) ⚫indexOf ⚫lastIndexOf ⚫Replace ⚫Substring ⚫toLowerCase ⚫toUpperCase ⚫trim
  • 25. COMPARING STRINGS ⚫Don’t use ‘==’ to compare Strings ⚫it compares their memory addresses and not actual strings (character sequences) ⚫Instead use the equalsmethod supplied by the String class: ⚫s.equals(t) ⚫returns true if s and t have same letters and sequence ⚫false otherwise 25
  • 26. COMPARING STRINGS String word1 = new String("Hello"); String word2 = new String("Hello"); if (word1 == word2){ System.out.println(true); } else { System.out.println(false); } false T wo different addresses 26
  • 27. String word1 = new String("Hello"); String word2 = new String("Hello"); if (word1.equals(word2)){ System.out.println(true); } else { System.out.println(false); } true compares the contents "Hello" with "Hello" 27 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook) COMPARING STRINGS
  • 28. 28 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 29. String word1 = "Hello"; String word2 = "Hello"; if (word1 == word2){ System.out.println(true); } else { System.out.println(false); } true ⚫Interned Strings: Only one instance of “Hello” is stored ⚫so word1 and word2 will have the same address 29 COMPARING STRINGS
  • 30. COMPARING STRINGS String word1 = "Hello"; String word2 = "Hello"; if (word1.equals(word2)){ System.out.println(true); } else { System.out.println(false); } true 30
  • 31. COMPARING STRINGS Method Description Returns true if this string is equal to string s1. Returns true if this string is equal to string s1; it is case insensitive. Returns an integer greater than 0, equal to 0, or less than 0 to indicate whether this string is greater than, equal to, or greater than s1. Same as compareTo except that the comparison is case insensitive. Returns true if this string starts with the specified prefix. Returns true if this string ends with the specified suffix. equals(s1) equalsIgnoreCase(s1) compareTo(s1) compareToIgnoreCase(s1) startsWith(prefix) endsWith(suffix) 31 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook) OrderTwoCities
  • 32. 32 import java.util.Scanner; public class OrderTwoCities { public static void main(String[] args) { Scanner input = new Scanner(System.in); // Prompt the user to enter two cities System.out.print("Enter the first city: "); String city1 = input.nextLine(); System.out.print("Enter the second city: "); String city2 = input.nextLine(); if (city1.compareTo(city2) < 0) System.out.println("The cities in alphabetical order are " + city1 + " " + city2); else System.out.println("The cities in alphabetical order are " + city2 + " " + city1); } } OrderTwoCities
  • 33. GETTING CHARACTERS FROM A STRING String message = "Welcome to Java"; System.out.println( "The first character in message is " + message.charAt(0)); 33 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 34. READING A SINGLE 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.print("The character entered is "+ch); 34 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 35. OBTAINING SUBSTRINGS Method Description 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. Returns this string’s substring that begins at the specified beginIndex 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. substring(beginIndex) substring(beginIndex, endIndex) 35
  • 36. FINDING A CHARACTER OR A SUBSTRING IN A STRING Method Description Returns the index of the first occurrence of ch in the string. Returns -1 if not matched. Returns the index of the first occurrence of ch after fromIndex in the string. Returns -1 if not matched. Returns the index of the first occurrence of string s in this string. Returns -1 if not matched. Returns the index of the first occurrence of string s in this string after fromIndex. Returns -1 if not matched. Returns the index of the last occurrence of ch in the string. Returns -1 if not matched. Returns the index of the last occurrence of ch before fromIndex in this string. Returns -1 if not matched. Returns the index of the last occurrence of string s. Returns -1 if not matched. Returns the index of the last occurrence of string s before fromIndex. Returns -1 if not matched. indexOf(ch) indexOf(ch, fromIndex) indexOf(s) indexOf(s, fromIndex) lastIndexOf(ch) lastIndexOf(ch, fromIndex) lastIndexOf(s) lastIndexOf(s, fromIndex) 36 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 37. FINDING A CHARACTER OR A SUBSTRING IN A STRING int k = s.indexOf(' '); //3 String firstName = s.substring(0, k); String lastName = s.substring(k + 1); 37 (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 38. CONVERSION BETWEEN STRINGS AND NUMBERS String intString = "15"; String doubleString = "56.77653"; int intValue = Integer.parseInt(intString); double doubleValue = Double.parseDouble(doubleString); String s2 = "" + intValue; (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
  • 39. CASE STUDY: CONVERTING A HEXADECIMAL DIGIT TO A DECIMAL VALUE Write a program that converts a hexadecimal digit into a decimal value. 39 HexDigit2Dec https://liveexample.pearsoncmg.com/html/HexDigit2Dec.h tml
  • 40. FORMATTING OUTPUT (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook) The printf statement: System.out.printf(format, items); • format is a string that may consist of substrings and format specifiers • A format specifier begins with a percent sign and specifies how an item should be displayed: a numeric value, character, boolean value, or a string
  • 41. FREQUENTLY-USED SPECIFIERS Specifier Output %b a boolean value Example true or false %c %d a a character decimal integer 'a' 200 %f a floating-point number 45.460000 %e a number in standard scientific notation 4.556000e+01 %s a string "Java is cool" int count = 5; double amount = 45.567899; System.out.printf("count is %d and amount is %.2f", count, amount) Displays: count is 5 and amount is 45.56 items
  • 42. BITWISE OPERATIONS IN JAVA ⚫ T o write programs at the machine-level, often you need to deal with binary numbers directly and perform operations at the bit- level ⚫ Java provides the bitwise operators and shift operators ⚫The bit operators apply only to integer types (byte, short, int, and long) ⚫All bitwise operators can form bitwise assignment operators, such as =: |=, <<=, >>=, and >>>= ⚫ Bitwise AND: & ⚫1010 & 1001 yields 1000 System.out.print(10&9); // 8 ⚫The AND of two corresponding bits yields a 1 if both bits are 1, otherwise 0
  • 43. BITWISE OPERATIONS IN JAVA ⚫ BitwiseOR:| ⚫The OR of two corresponding bits yields a1 ifeither bit is1 ⚫10101110 | 10010010 yields10111110 class BitwiseOR { public static void main(String[] args) { int number1 = 12, number2 = 25, result; result = number1 | number2; System.out.println(result); } } 1100 | 12 11001 25 11101 = 29 43
  • 44. BITWISE OPERATIONS IN JAVA ⚫ Bitwise exclusive OR: ^ ⚫1010 ^ 1001 yields 0011 ⚫The XOR of two corresponding bits yields a 1 only if two bits are different. ⚫ One’s complement: ~ ⚫~1010 yields 0101 ⚫The operator toggles each bit from 0 to 1 and from 1 to 0. ⚫ Left shift: << ⚫1010 << 2 yields 101000 System.out.print(10 << 2); // 40 ⚫The operator shifts bits in the first operand left by the number of bits specified in the second operand, filling with 0s on the right.
  • 45. ⚫Right shift with sign extension: >> ⚫1010 >> 2 yields 10 System.out.print(10 >> 2); // 2 ⚫The operator shifts bit in the first operand right by the number of bits specified in the second operand, filling with the highest (sign) bit on the left. ⚫Unsigned right shift with zero extension: >>> System.out.print(-10 >>> 2); // 1073741821 ⚫The operator shifts bit in the first operand right by the number of bits specified in the second operand, filling with 0s on the left. 45 BITWISE OPERATIONS IN JAVA
  • 46. CONSTANTS IN BINARY FORMAT byte fourTimesThree = 0b1100; byte data = 0b0000110011; short number = 0b111111111111111; int overflow = 0b10101010101010101010101010101011; long bow = 0b101010101010101010101010101010111L; ⚫ Just be careful not to overflow the numbers with too much data,or else you'll get acompiler error: byte data = 0b1100110011; // Type mismatch: cannot convert from int to byte ⚫New feature in Java7 known asnumeric literals with underscores: ⚫int overflow = 0b1010_1010_1010_1010_1010_1010_1010_1011; ⚫long bow = 0b1 01010101 01010101 01010101 01010111L; 46
  • 47. CONSTANTS IN OCTAL AND HEXADECIMAL FORMAT int x = 010; int y = 0xf; (C) PEARSON EDUCATION, INC. & PAUL FODOR (CS STONY BROOK) //octal = 8 //hexadecimal = 15
  • 48. ADDITIONAL RESOURCES  https://www.w3schools.com/java/java_math.asp  https://www.javatpoint.com/java-math  https://www.geeksforgeeks.org/shift-operator-in-java/  https://www.programiz.com/java-programming/string  https://www.tutorialspoint.com/java/java_basic_operators.htm  https://www.baeldung.com/java-bitwise-operators
  • 49. END

Editor's Notes

  1. In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned.