0% found this document useful (0 votes)
18 views54 pages

Presentation 6

The document provides an overview of character representation in Java, focusing on char, ASCII, and Unicode standards. It explains the immutability of String objects, various String methods, and introduces the StringBuilder class for efficient string manipulation. Additionally, it covers pattern matching using regular expressions and their application in validating specific formats.

Uploaded by

kakefon876
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)
18 views54 pages

Presentation 6

The document provides an overview of character representation in Java, focusing on char, ASCII, and Unicode standards. It explains the immutability of String objects, various String methods, and introduces the StringBuilder class for efficient string manipulation. Additionally, it covers pattern matching using regular expressions and their application in validating specific formats.

Uploaded by

kakefon876
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/ 54

IT 214

Object
Oriented
Programming
Dr. Abdulaziz Saleh Algablan
[email protected] :Email
2023

1
Topics

Regular Date and


Char String
Expression Time

StringBuilder
ASCII Unicode Immutable Methods
Class

2
Char
• In Java single characters are represented by the data type char.
• Character constants are written as symbols enclosed in single quotes:
• For example, ‘a’, ‘X’, and ‘5’.
• In the early days of computing, different computers used not only
different coding schemes but also different character sets.
• Individualized coding schemes did not allow computers to share information.
• Documents created by using one scheme are complete rubbish if we try to
read these documents by using another scheme.

3
ASCII Encoding
• To avoid this problem, U.S. computer manufacturers devised several coding
schemes.
• One of the coding schemes widely used today is ASCII (American Standard
Code for Information Interchange).
• The standard ASCII codes work just fine as long as we are dealing with the
English language
• because all letters and punctuation marks used in English are included in the ASCII
codes.
• But what about different currency symbols?
• What about non-European languages? Chinese, Japanese, and Korean all
use different coding schemes to represent their character sets?
4
5
ASCII Encoding
char aCap = 65;
System.out.println(aCap); // prints: A

char[] set = {73, 84, 50, 49,52};


System.out.println(set); // prints: ?

6
Unicode
• To accommodate the character symbols of non-English languages, the Unicode
Consortium established the Unicode Worldwide Character Standard.
• Commonly known simply as Unicode.
• Support the interchange, processing, and display of the written texts of diverse
languages.
• The standard currently contains 34,168 distinct characters, which cover the major
languages of the Americas, Europe, the Middle East, Africa, India, Asia, and Pacifica.
• To accommodate such a large number of distinct character symbols, Unicode
characters occupy 2 bytes.
• 7 bits are sufficient to represent a character in ASCII; however, most computers typically
reserve 1 byte, (8 bits)
• Some Unicode character codes are the same as ASCII codes.
7
Unicode
• Java, being a language for the Internet, uses the Unicode standard for
representing char constants.
• Java uses the Unicode standard internally to store characters.
• Note: To use foreign characters for input and output in Java programs,
the operating system and the development tool used for Java
programs must be capable of handling the foreign characters.

8
Unicode
public static void main( String[] args )
{
char waw = 65262;
System.out.println(waw);
char[] set = {65194, 65268,65248 , 65262};
System.out.println(set);

9
String
• String literals, which are written as a sequence of characters in double
quotation marks like :
• “IT 214”
• “12”
• Stored in memory as String objects.
• The declaration
String color = "blue”
initializes String variable color to refer to a String object that contains
the string "blue".
10
String Class
• Class String is used to represent strings in Java
public static void main( String[] args )
{
char[] charArray = { 'H', 'a', 'p', 'p’, 'y', ' ', 'd', 'a',
'y' };
String s = new String( "hello" );
// use String constructors
String s1 = new String();
String s2 = new String( s );
String s3 = new String( charArray );
String s4 = new String( charArray, 6, 3 );
}

11
String Class
• Char to represent String.
public static void main( String[] args )
{
String str = "abc";

//is equivalent to:

char data[] = {'a', 'b', 'c'};


String str = new String(data);

12
String
• String objects are immutable.
• Their contents (set of chars) cannot be changed after they’re created
(in the heap).
• But the String variable (reference) can be changed.
• The String class does not provide methods that allow the contents of
a String object to be modified.

13
Immutable String
Stack Heap

• String objects are immutable.


• For example, step 1:
public static void main( String[] args )
{
String s1 = “This is IT214”;
s1 = “I am happy today”;
String s2 = “This is IT214”; String Object
s1
value = “This is
IT214”
}

14
Immutable String
Stack Heap

• String objects are immutable. String Object

• For example, step 2: value = “I am


happy
public static void main( String[] args ) today”
{
String s1 = “This is IT214”;
s1 = “I am happy today”;
String s2 = “This is IT214”;
String Object
s1
value = “This is
} IT214”
• reassigning a String variable with a different String
creates a new String Object.

15
Immutable String
Stack Heap

• String objects are immutable. String Object

• For example, step 3: s2


value = “I am
happy
public static void main( String[] args ) today”
{
String s1 = “This is IT214”;
s1 = “I am happy today”;
String s2 = “This is IT214”;
String Object
s1
value = “This is
} IT214”

• Java checks if the String object is already found in


the heap, if yes, it will be reused and there is no
creation of a new String Object.
16
Immutable String
Stack Heap

• String objects are immutable. String Object

• Changing the string variable s2


value = “I am
happy
will create another string today”

object (if its not already in the


heap).
• Java reuses String objects that String Object

has been created earlier. s1


value = “This is
IT214”

17
String Methods
contains() checks whether the string contains a substring
substring() returns the substring of the string
replace() replaces the specified old character with the specified new
character
replaceAll() replaces all substrings matching the regex pattern
replaceFirst() replace the first matching substring
charAt() returns the character present in the specified location
indexOf() returns the position of the specified character in the string
compareTo() compares two strings in the dictionary order
18
String Methods
compareToIgnoreCase() compares two strings ignoring case differences
trim() removes any leading and trailing whitespaces
format() returns a formatted string
split() breaks the string into an array of strings
toLowerCase() converts the string to lowercase
toUpperCase() converts the string to uppercase
toCharArray() converts the string to a char array
startsWith() checks if the string begins with the given string
endsWith() checks if the string ends with the given string
isEmpty() checks whether a string is empty of not
19
String Methods
• trim() -- generate a new String object that removes all white-space
characters that appear at the beginning and/or end of the String on
which trim operates.
• “ Hello ”.trim()  “Hello”
• charAt(int index)
• Accessing a character outside the bounds of a String (i.e., an index less than 0
or an index greater than or equal to the String’s length) results in a
StringIndexOutOfBoundsException.

20
String format()
String formatedString; stringVar;
Float floatVar; int intVar;
formatedString = String.format("The value of the
float variable is %f, while the value of the
integer variable is %d, and the string is
%s",floatVar, intVar, stringVar);
// Also, printf works similarly:
System.out.printf("I like the article %s. %n",
stringVar);

21
String format()
• String formatting is also known as String interpolation.
• It is the process of inserting a custom string or variable in predefined text.

22
String substring()
String s = “IT214”;
String substring1 = s.substring(2); // 214
String substring2 = s.substring(0,2); // IT

23
String trim()
String s=" Sachin ";

System.out.println(s.trim());
//will print:
//Sachin

24
String Split()
// Java program to demonstrate working of split()
public class TestSplit {
public static void main(String args[])
{
String str = "GeeksforGeeks:A Computer Science Portal";
String[] arrOfStr = str.split(":");

for (String a : arrOfStr)


System.out.println(a);
}
} GeeksforGeeks
A Computer Science Portal
25
Compare Strings
• Comparing references with == can lead to logic errors.
• Because == compares the references to determine whether they refer
to the same object, not whether two objects have the same contents.
• When two identical (but separate) objects are compared with ==, the
result will be false.
• When comparing objects to determine whether they have the same
contents, use method equals.

26
equals() method
• The method returns true if the contents of the objects are equal.
• Method equals uses a lexicographical comparison
• it compares the integer Unicode values that represent each character in each
String.
• Thus, if the String "hello" is compared with the string "HELLO", the result is
false, because the integer representation of a lowercase letter is different
from that of the corresponding uppercase letter.

27
Example
String s1 = new String("hello"); 99162322
System.out.println(s1.hashCode());
99162322
String s2 = new String("hello");
System.out.println(s2.hashCode()); 99162322
String s3 = "hello"; false
System.out.println(s3.hashCode());
false
System.out.println(s1 == s2); // prints "false" false
System.out.println(s1 == s3); // prints "false"
----- Equals -------
System.out.println(s2 == s3); // prints "false"
true
System.out.println("----- Equals -------"); true
System.out.println(s1.equals(s2)); // prints "true" true
System.out.println(s1.equals(s3)); // prints "true"
System.out.println(s2.equals(s3)); // prints "true"
28
equalsIgnoreCase() method
• It ignores whether the letters in each String are uppercase or
lowercase when performing the comparison.

29
compareTo( String anotherString)
•Compares two string lexicographically.
•Ali
•Alex
•John
int out = s1.compareTo(s2);
// where s1 and s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
30
contains(string)
• Returns true if string contains contains the given string
String s1="geeksforgeeks"
String s2="geeks"
s1.contains(s2) // return true

31
StringBuilder Class
• In programs that frequently perform string concatenation, or other
string modifications, it’s often more efficient to implement the
modifications with class StringBuilder.
• Class StringBuilder provides overloaded append to allow values of
various types to be appended to the end of a StringBuilder.
• StringBuilders are not thread safe.
• If multiple threads require access to the same dynamic string information, use
class StringBuffer. Classes StringBuilder and StringBuffer provide identical
capabilities, but class StringBuffer is thread safe.

32
StringBuilder Class
• In programs that frequently perform string concatenation, or other
string modifications, it’s often more efficient to implement the
modifications with class StringBuilder.
• Class StringBuilder provides overloaded append to allow values of
various types to be appended to the end of a StringBuilder.
• StringBuilders are not thread safe.
• If multiple threads require access to the same dynamic string information, use
class StringBuffer. Classes StringBuilder and StringBuffer provide identical
capabilities, but class StringBuffer is thread safe.

33
StringBuilder Class

34
String s1 = "Hi";
System.out.println(s1);
System.out.println("Hash code: "+s1.hashCode());
s1 = s1+" there";
System.out.println(s1);
Hi
System.out.println("Hash code: "+s1.hashCode());
Hash code: 2337
System.out.println("-----------");
Hi there
StringBuilder s2 = new StringBuilder("Hi "); Hash code: 653358757
System.out.println(s2); -----------
Hi
System.out.println("Hash code: "+s2.hashCode());
s2.append(" there");
Hash code: 498931366
System.out.println(s2); Hi there
Hash code: 498931366
System.out.println("Hash code: "+s2.hashCode()); -----------
System.out.println("-----------"); Hash code 2060468723
StringBuilder s3 = new StringBuilder("Hi ");
System.out.println("Hash
35 code "+s3.hashCode());
Exercises
• Calculate the zakat by implementing a method that takes a String
entry that consists of names and amount of money as follows:
String entry = “Ali, Khaled, Zaid, Bander:
2100, 32000, 23493, 704245”.

• Here Ali has 2100 R.S

36
Pattern Matching
• Word processor features such as finding a text and replacing a text
with another text are two specialized cases of a pattern-matching
problem.

37
The matches Method
• Let’s begin with the matches method from the String class.
• In its simplest form:
str.equals("Hello");
str.matches("Hello");
• the two statements both evaluate to true.
• However, they are not truly equivalent.
• because, unlike equals, the argument to the matches method can be a
pattern, a feature that brings great flexibility and power to the matches
method.

38
Regular Expression - Example
• Suppose we assign a three-digit code to all incoming students.
• The first digit represents the major
• 5 stands for the computer science major.
• Second digit represents:
• 1 is for student in Qassim, 2 is for out-of-Qassim students, and 3 is for foreign
students.
• Third digit represents the residence of the student.
• On-campus dormitories are represented by digits from 1 through 7.
• Students living off campus are represented by digit 8.
• For example, the valid encodings for students majoring in computer science
and living off campus are 518, 528, and 538.
39
Regular Expression
• The valid three-digit code for computer science majors living in one of
the on-campus dormitories can be expressed succinctly as:

• The pattern is called a regular expression that allows us to denote a


large (often infinite)
40
set of words succinctly.
Regular Expression
• The valid three-digit code for computer science majors living in one of the
on-campus dormitories can be expressed succinctly as 5[123][1-7].

String student1Number = "513" ;


String reqularExperssion = "[5][1-3][1-7]";
boolean isLivingOnCampus= student1Number.matches(reqularExperssion);
System.out.println(student1Number.matches(reqularExperssion));

41
Regular Expression

42
Regular Expression
Metacharacter Description

| Find a match for any one of the patterns separated by | as in: [cat|dog|fish]

. . :Find just one instance of any character. Ex


^ Finds a match as the beginning of a string as in: [^Hello]

$ $Finds a match at the end of the string as in: World


d\ Find a digit. Ex: [\d]

s\ Find a whitespace character. Ex: [\s]

b\ Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this:
WORD\b

43
Regular Expression
• Symbols * or + to designate a sequence of unbounded length.
• The symbol * means 0 or more times,
• The symbol + means 1 or more times
expression Description

]+a[ Find one character from the options between the brackets. Like a, aa, aaaa but not b

]a^[ Find one character NOT between the brackets

]0-9[ Find one character from the range 0 to 9

44
Regular Expression
Character classes
• [abc] a, b, or c (simple class)
• [^abc] Any character except a, b, or c (negation)
• [a-zA-Z] a through z or A through Z, inclusive (range)
• [a-d[m-p]] a through d, or m through p: [a-dm-p] (union)
• [a-z&&[def]] d, e, or f (intersection)
• [a-z&&[^bc]] a through z, except for b and c: [ad-z] (subtraction)
• [a-z&&[^m-p]] a through z, and not m through p: [a-lq-z](subtraction)

Predefined character classes
• . Any character (may or may not match line terminators)
• \d A digit: [0-9]
• \D A non-digit: [^0-9]
• \h A horizontal whitespace character: [ \t\xA0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000]
• \H A non-horizontal whitespace character: [^\h]
• \s A whitespace character: [ \t\n\x0B\f\r]
• \S A non-whitespace character: [^\s]
• \v A vertical whitespace character: [\n\x0B\f\r\x85\u2028\u2029]
• \V A non-vertical whitespace character: [^\v]
• \w A word character: [a-zA-Z_0-9]
• \W A non-word character: [^\w]

45
Regular Expression
import java.io.*;
import java.util.regex.*;
class GFG {
public static void main(String[] args)
{
// Should be single character a to z
System.out.println(Pattern.matches("[a-z]", "g"));

// Check if all the elements are non-numbers


System.out.println(Pattern.matches("\\D+", "Gfg"));

// Check if all the elements are non-spaces


System.out.println(Pattern.matches("\\S+", "gfg"));
}
}
46
Regular Expression
• The replaceAll Method
public String replaceAll(String regex, String replace_str)

47
Date and Time in Java
• Date and time often are used in programs.
• Java does not have a built-in Date class, but we can import the
java.time package to work with the date and time API.
• The time package includes many date and time classes.
• For example:

48
Date and Time in Java
Class Description

LocalDate Represents a date (year, month, day (yyyy-MM-dd))

LocalTime Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns))

LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)

DateTimeFormatter Formatter for displaying and parsing date-time objects

49
Example
import java.time.LocalDate;
import java.time.LocalTime;

public class TestTime {


public static void main(String[] args) {
LocalDate localDateInstance = LocalDate.now();
System.out.println(localDateInstance);
int day= localDateInstance.getDayOfMonth();
System.out.println(day);
LocalTime localTimeInstance = LocalTime.now(); 2023-10-12
System.out.println(localTimeInstance); 12
16:22:57.773201
}

}
50
Example
import java.time.LocalDateTime;
import java.time.DateTimeFormatter;
public class TestTime {
public static void main(String[] args) {
LocalDateTime myDateObj = LocalDateTime.now();
System.out.println("Before formatting: " + myDateObj);
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy
HH:mm:ss");
String formattedDate = myDateObj.format(myFormatObj);
System.out.println("After formatting: " + formattedDate);
}
} Before formatting: 2023-10-12T16:25:48.684734
After formatting: 12-10-2023 16:25:48
51
DateTimeFormatter ofPattern()
• The ofPattern() method accepts all sorts of values, if you want to display
the date and time in a different format.
• For example:
Value Example
yyyy-MM-dd "1988-09-29"
dd/MM/yyyy "29/09/1988"
dd-MMM-yyyy "Sep-1988-29"
E, MMM dd yyyy "Thu, Sep 29 1988"

52
Compare Dates
import java.time.LocalDate; import java.time.LocalTime;

public class CompareDates {

public static void main(String[] args) {

LocalDate date1 = LocalDate.now();

LocalDate date2 = LocalDate.of(2022, 4, 3);

if (date1.isAfter(date2)) { // isAfter() method

System.out.println(date1 + " is after " + date2);}

if (date1.isBefore(date2)) { // isBefore() method

System.out.println(date1 + " is before " + date2);}

if (date1.isEqual(date2)) { // isEqual() method

System.out.println(date1 + " is equal to " + date2);}

int diff = date1.compareTo(date2); // compareTo() method

if (diff > 0) {

System.out.println(date1 + " is greater than " + date2);

} else if (diff < 0) {


2023-10-12 is after 2022-04-03
System.out.println(date1 + " is less than " + date2);
2023-10-12 is greater than 2022-
} else {

System.out.println(date1 + " is equal to " + date2);}}}


04-03
53
Date and Time Uses
• Typical example of Java programs using dates and time are:
• Programs that manage booking of hotels.
• Programs that schedule tasks.
• Time zones are important to consider when dealing with date and
time in global scale:
• Especially for users form different geographical locations.
• java.time.ZonedDateTime can be used to take time zone in consideration.
• The LocalDateTime has no time zone.

54

You might also like