[go: up one dir, main page]

0% found this document useful (0 votes)
7 views56 pages

Lesson - 9 - Work With Selected Classes From The Java API

This lesson covers key Java API classes including String, StringBuilder, and StringBuffer, focusing on their creation, manipulation, and methods. It explains the immutability of String objects, the mutable nature of StringBuilder and StringBuffer, and their differences in thread safety and performance. Additionally, it introduces calendar data manipulation using java.util.Date and java.text.SimpleDateFormat for formatting dates.

Uploaded by

pradeep191988
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)
7 views56 pages

Lesson - 9 - Work With Selected Classes From The Java API

This lesson covers key Java API classes including String, StringBuilder, and StringBuffer, focusing on their creation, manipulation, and methods. It explains the immutability of String objects, the mutable nature of StringBuilder and StringBuffer, and their differences in thread safety and performance. Additionally, it introduces calendar data manipulation using java.util.Date and java.text.SimpleDateFormat for formatting dates.

Uploaded by

pradeep191988
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/ 56

Core Java

Lesson 9—Working with Selected Classes from the Java API

© Simplilearn. All rights reserved.


Learning Objectives

At the end of this lesson, you should be able to:

Create and manipulate Strings

Manipulate data using the StringBuilder class and its methods

Work with StringBuffer class

Create and manipulate calendar data

Declare and use an ArrayList of a given type

Write a simple Lambda expression that consumes a Lambda Predicate


expression
Work with Selected Classes from Java API
Topic 1—String
String

A string is an object that represents a sequence of character (char) values.

An array of char works the same way as a Java string. For example:

char[] ch={‘s','a',‘m',‘p',‘l',‘e',‘j',‘a',‘v',‘a'};

String s =new String(ch);

or
String s = “samplejava”;

The java.lang.String class is used to create string object.


String

A string object is immutable and cannot be modified or changed.

Once string object is created, its data or state cannot be changed; however, a new string object can
be created.
class Testimmutablestring{
public static void main(String args[]){
String s=“Abdul";
s.concat(“Kalam");//concat() method appends the string at the
end//
System.out.println(s);//will print Abdul because strings are//
immutable objects
}
}

Output:
Abdul
List of Symbols in Regular Expression
Subexpression Matches
^ Matches the beginning of the line
$ Matches the end of the line
Matches any single character, except newline (Using m option allows it to match the
.
newline as well)
[...] Matches any single character in brackets
[^...] Matches any single character not in brackets
\A Beginning of the entire string
\z End of the entire string
\Z End of the entire string, except allowable final line terminator
re* Matches 0 or more occurrences of the preceding expression
re+ Matches 1 or more of the previous thing
re? Matches 0 or 1 occurrence of the preceding expression
re{ n} Matches exactly n number of occurrences of the preceding expression
re{ n,} Matches n or more occurrences of the preceding expression
re{ n, m} Matches at least n and at most m occurrences of the preceding expression
a| b Matches either a or b
List of Symbols in Regular Expression (Contd.)

(re) Groups regular expressions and remembers the matched text


(?: re) Groups regular expressions without remembering the matched text
(?> re) Matches the independent pattern without backtracking
\w Matches the word characters
\W Matches the non-word characters
\s Matches the whitespace. Equivalent to [\t\n\r\f]
\S Matches the non whitespace
\d Matches the digits [0-9]
\D Matches the non-digits
\A Matches the beginning of the string
\Z Matches the end of the string (If a newline exists, it matches just before newline)
\z Matches the end of the string
\G Matches the point where the last match finished
\n Back-reference to capture group number "n"
Matches the word boundaries when outside the brackets
\b
Matches the backspace (0x08) when inside the brackets.
List of Symbols in Regular Expression (Contd.)

\B Matches the non-word boundaries.


\n, \t, etc. Matches newlines, carriage returns, tabs, etc.
\Q Escape (quote) all characters up to \E.
\E Ends quoting begun with \Q.
matches() Method

A matches() method checks whether the String matches with the specified regular expression.

If the String fits in the specified regular expression, then this method returns true; otherwise, it
returns false.
public class MatchesExample{
public static void main(String args[]){
String str = new String("Java String Methods");

System.out.print("Regex: (.*)String(.*) matches string? " );


System.out.println(str.matches("(.*)String(.*)"));

System.out.print("Regex: (.*)Strings(.*) matches string? " );


System.out.println(str.matches("(.*)Strings(.*)"));

System.out.print("Regex: (.*)Methods matches string? " );


System.out.println(str.matches("(.*)Methods"));
}
} Output:
Regex: (.*)String(.*) matches string? true
Regex: (.*)Strings(.*) matches string? false
Regex: (.*)Methods matches string? true
CharSequence Interface

The CharSequence interface is used to represent sequence of characters.

It is implemented by String, StringBuffer, and StringBuilder classes.

CharSequence

Implements

String StringBuffer StringBuilder

Java string class provides many methods to perform operations on string, such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring(), and so on.
compareTo() Method

The compareTo() method compares a given string with the current string lexicographically.

It returns a positive number, negative number, or 0.

if s1 > s2, it returns positive number


if s1 < s2, it returns negative number
if s1 == s2, it returns 0
String—compareTo() Example

public class CompareToExample


{
public static void main(String args[])
{
String s1=“Hello";
String s2=“Hello";
String s3=“Meklo";
String s4=“Hemlo";
String s5=“Flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f“
}}
Output:
0
-5
-1
2
concat() Method

The String concat() method combines the specified string to the end of current string.

It returns a combined string.

public String concat(String anotherString)


String—concat() Example

public class ConcatExample


{
public static void main(String args[])
{
String s1="java string";
s1.concat(“Sample");
System.out.println(s1);
s1=s1.concat(" Sample example for String Concat");
System.out.println(s1);
}}

Output:
Sample
Sample example for String Concat
equals() Method

The String equals() method compares two given strings based on the content of the strings.

If any character is not matched, it returns false.

If all characters are matched, it returns true.

It overrides the equals() method of Object class.

public boolean equals(Object anotherObject)


equals() Method Example

public class EqualsExample


{
public static void main(String args[])
{
String s1=“Sample";
String s2=“Sample";
String s3=“SAMPLE";
String s4=“Java";
System.out.println(s1.equals(s2));//true because content and case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
}}
Output:
true
false
true
split() Method
The string split() method splits the string based on a given regular expression and returns a
char array.

public String split(String regex)


and,
public String split(String regex, int limit)

Example:
public class SplitExample
{
public static void main(String args[])
{
String s1="java string split method sample";
String[] words=s1.split("\\s");//splits the string based on whitespace
//using java foreach loop to print elements of string array
for(String w:words) Output:
{ java
string
System.out.println(w);
split
} method
}} sample
substring() Method
The string substring() method returns a new string that is a part of the primary string.

public String substring(int startIndex)


and
public String substring(int startIndex, int endIndex)

Example:

public class SubstringExample


{
public static void main(String args[])
{
String s1=“samplesubstring";
System.out.println(s1.substring(2,4)); //returns mp
System.out.println(s1.substring(2)); //returns mplesubstring
}}

Output:
mp
mplesubstring
replace() Method
The string replace() method returns a string that results when all occurrences of old char or
CharSequence are replaced with new char or CharSequence.

public static String format(String format, Object... args)


and,
public static String format(Locale , String format, Object... args)

Example:
public class FormatExample
{
public static void main(String args[])
{
String name=“james";
String sf1=String.format("name is %s",name);
String sf2=String.format("value is %f",32.33434);
String sf3=String.format("value is %32.12f",32.33434);//returns 12 char fractional part filling with 0
System.out.println(sf1);
Output:
System.out.println(sf2); name is James
System.out.println(sf3); value is 32.334340
value is 334340000000
}}
Working with Selected Classes using Java API
Topic 2—StringBuilder Class
StringBuilder Class

The StringBuilder class, like the String class, has a length() method that returns the length of
the character sequence in the builder.

It is used to create mutable (modifiable) string.

StringBuilder objects are like String objects, except that they can be modified. Internally, these
objects are treated like variable-length arrays that contain a sequence of characters.
StringBuilder Class

Constructor Description

StringBuilder() Creates an empty string builder with a capacity of 16 (16 empty elements)

Constructs a string builder containing the same characters as the specified


StringBuilder(CharSequence cs)
CharSequence, plus an extra 16 empty elements trailing the CharSequence

StringBuilder(int initCapacity) Creates an empty string builder with the specified initial capacity

Creates a string builder whose value is initialized by the specified string,


StringBuilder(String s)
plus an extra 16 empty elements trailing the string
StringBuilder Class Example

// creates empty builder, capacity 16

StringBuilder sb = new StringBuilder();

// adds 9 character string at beginning


sb.append("Greetings");

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Length() = 9 Capacity() = 16
StringBuilder Method

This sets the length of the character sequence. If newLength is less


than length(), the last characters in the character sequence are truncated.
void setLength(int newLength)
If newLength is greater than length(), null characters are added at the end
of the character sequence.

void ensureCapacity(int
minCapacity) This ensures that the capacity is at least equal to the specified minimum.
Various StringBuilder Methods

StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[] str)
StringBuilder append(char[] str, int offset, int len)
Appends the argument to this string builder. The data is
StringBuilder append(double d)
converted to a string before the append operation takes
StringBuilder append(float f) place.
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object obj)
StringBuilder append(String s)

The first method deletes the subsequence from start to


StringBuilder delete(int start, int end)
end-1 (inclusive) in the StringBuilder's char sequence.
StringBuilder deleteCharAt(int index) The second method deletes the character located at
index.
Various StringBuilder Methods (Contd.)
StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int Inserts the second argument into the string builder. The
offset, int len) first integer argument indicates the index before which
StringBuilder insert(int offset, double d) the data is to be inserted. The data is converted to a
string before the insert operation takes place.
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long lng)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String s)

StringBuilder replace(int start, int end, String s)


Replaces the specified character(s) in this string builder.
void setCharAt(int index, char c)

StringBuilder reverse() Reverses the sequence of characters in this string builder.

Returns a string that contains the character sequence in


String toString()
the builder.
Work with Selected Classes from Java API
Topic 3—Working with StringBuffer
Working with StringBuffer

A StringBuffer is a string that can be modified.

At any point in time, it contains a particular sequence of characters, but the length and content of
the sequence can be changed through certain method calls.

The append method adds the characters at the end of the buffer.

The insert method adds the characters at a specified point.

The principal operations on a StringBuffer are the append and insert methods, which are
overloaded so as to accept data of any type.

The append method always adds the characters at the end of the buffer; the insert method adds
the characters at a specified point.
Working with StringBuffer (Contd.)

Example for append method:


class StringBufferExample
{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Welcome ");
sb.append("Java"); //now original string is changed
System.out.println(sb); //prints Welcome Java
}
}

Example for insert method:


class StringBufferExample2
{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Welcome ");
sb.insert(1,"Java"); //now original string is changed
System.out.println(sb); //prints WJavaelcome
}
}
Compare StringBuilder and StringBuffer

StringBuilder StringBuffer

Multiple threads are allowed to operate at a time Single thread is allowed to operate at a time

Not thread safe Thread safe

Methods are not Synchronized Methods are Synchronized

Faster than StringBuffer Slower than StringBuilder

Storage area is Heap Storage area is Heap

Mutable Mutable
Compare StringBuilder and StringBuffer (Contd.)

Mutable: An object is mutable when you can change its value, and it actually creates a new
reference in memory of this object.

Example:

int i=0;
while(i<10){

System.out.println(a);
i+=1;
}
Compare StringBuilder and StringBuffer (Contd.)

Immutable: An object is immutable when you cannot change its value once it is referenced.

The only thing you can do is redeclare the object. This will result in loss of all the values.

Some of the classes that are immutable in Java are the Wrapper classes like Integer, Float,
Double, Character, and Byte.

For example:

Integer a=0;
while(a<10){

System.out.println(a);
a+=1;
}
Work with Selected Classes from Java API
Topic 4—Create and Manipulate Calendar Data
Java.util.Date Class

The java.util.Date class represents date and a specific instant in time, with millisecond precision.

It offers methods and constructors to deal with date and time in Java.

It implements Serializable, Cloneable, and Comparable<Date> interface.

It is inherited by the following interfaces:

java.sql.Date

java.sql.Time

java.sql.Timestamp
Java.util.Date Class Example

Example of printing date in Java using java.util.Date class.

long millis=System.currentTimeMillis();
java.util.Date date=new java.util.Date(mi
llis);
System.out.println(date);

Output:
Wed Mar 27 08:22:02 IST 2017
Java SimpleDateFormat Class

In Java, the SimpleDateFormat is a concrete class that provides methods to format and parse date
and time.

It inherits java.text.DateFormat class.


Example
Formatting date in Java using java.text.SimpleDateFormat class

import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formatter.format(date);
System.out.println(strDate);
} Output:
13/04/2017
}
java.util.Calendar and GregorianCalendar

In Java, the java.util.Calendar class is used to perform date and time arithmetic

Java only comes with a Gregorian calendar implementation, the java.util.GregorianCalendar class.

GregorianCalendar is a subclass of Calendar, which provides the standard calendar system that is
used globally.

Calendar calendar = new GregorianCalendar();

int year = calendar.get(Calendar.YEAR);


int month = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); // Jan = 0, not 1
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);
Create and Manipulate Calendar Data

You can create and manipulate calendar data using the following functions:

java.time.LocalDate

java.time.LocalTime

java.time.LocalDateTime

java.time.Period

java.time.format.DateTimeFormatter
java.time.LocalDate
This is an immutable class with the default date format of yyyy-mm-dd. The functionality is similar to
java.sql.Date API.

import java.time.LocalDate;
import java.time.ZoneId;

public class LocalDateExample


{
public static void main(String[] args)
{
LocalDate localDateToday = LocalDate.now();
System.out.println("Today's Date : "+localDateToday);
LocalDate localDateZone = LocalDate.now(ZoneId.of("America/Los_Angeles"));
System.out.println("Today's Date at Zone America/Los_Angeles : "+localDateZone);
}
}

Output:
Today's Date : 2017-06-14
Today's Date at Zone America/Los_Angeles : 2017-06-14
java.time.LocalTime
java.time.LocalTime class is similar to LocalDate. It povides human readable time in the format hh:mm:ss.zzz. This
class also provides the ZoneId support to get the time for the given ZoneId.

import java.time.LocalTime;
import java.time.ZoneId;

public class LocalTimeExample


{
public static void main(String[] args)
{
LocalTime currentTime = LocalTime.now();
System.out.println("Current Time : " + currentTime);
LocalTime localTimeZone = LocalTime.now(ZoneId.of("America/Los_Angeles"));
System.out.println("Current Time at America/Los_Angeles : " + localTimeZone);
}
} Output:
Current Time : 15:37:00:518
Current Time at America/Los_Angeles : 03:07:00.518
java.time.LocalDateTime
LocalDateTime is an immutable object that presents a date-time. The default format for the date-
time value is yyyy-MM-dd-HH-mm-ss.zzz. LocalDateTime class provides a factory method that takes
LocalDate and LocalTime arguments to create LocalDateTime instance.

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;

public class LocalDateTimeExample


{
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Current Date Time : " + localDateTime);

LocalDateTime localDateTimeZone = LocalDateTime.now(ZoneId.of("America/Los_Angeles"));


System.out.println("Current Date Time at America/Los_Angeles : " + localDateTimeZone);
}
Output:
} Current Date Time : 2017-06-14T15:37:00:518
Current Date Time at America/Los_Angeles : 2017-06-14T03:07:00.518
java.time.Period

Period provides the quantity or amount of time in terms of years, months, and days.

import java.time.LocalDate;
import java.time.Period;

public class PeriodExample


{
public static void main(String[] args) {
LocalDate localDate1 = LocalDate.of(2016, 06, 16);
LocalDate localDate2 = LocalDate.of(2017, 10, 15);
Period = Period.between(localDate1, localDate2);
System.out.println(“16-June-2016 to 15-September-2017 :Years ("
+ period.getYears() + "), Months(" + period.getMonths()
+ "), Days(" + period.getDays() + ")");
}

} Output:
16-June-2016 to 15-September-2017 :Years (1), Months(2), Days(29)
java.time.format.DateTimeFormatter
In Java 8, the preferred date/time classes are no longer maintained in the java.util package. The
new date/time handling classes are part of java.time package.
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {


public static void main(String[] args) {
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss
z");
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter.ofPattern("dd/MMM/YYYY");
ZonedDateTime zonedDateTime = ZonedDateTime.now();
String formatter1 = dateTimeFormatter1.format(zonedDateTime);
String formatter2 = dateTimeFormatter2.format(zonedDateTime);
String formatter3 = dateTimeFormatter3.format(zonedDateTime);
System.out.println(formatter1);
System.out.println(formatter2);
Output:
System.out.println(formatter3); 2017/06/15 15:14:51 IST
} 2017/06/15
15/Jul/2017
}
Work with Selected Classes from Java API
Topic 4—Declare and Use of Arraylist
Arraylist Class

Java ArrayList class inherits AbstractList class and implements List interface.

It uses a dynamic array for storing the elements.

The important points about Java ArrayList class are as follows:

It maintains insertion order.

It can contain duplicate elements.

It allows random access because array works at the index basis.

It is non-synchronized.

In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any
element is removed from the array list.
Class Declaration and Its Use

The java.util.ArrayList class provides resizable-array and implements the List interface for Arraylist.
public class ArrayList<E>
extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable

import java.util.*;
class TestCollection1
{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add(“John"); //Adding object in arraylist
list.add(“James");
list.add(“Mathews");
list.add(“Nitin"); //Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
Output:
System.out.println(itr.next()); John
} James
} Mathews
Nitin
}
JDBC
Topic 5—Predicate with Lambda Expression
Predicate with Lambda Expression
To create a Database:
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateExample
{
public static void main(String[] args) {
Child child1 = new Child(3);
Child child2 = new Child(2);
Child child3 = new Child(7);
Child child4 = new Child(10);
Child child5 = new Child(6);
Child child6 = new Child(9);
Child child7 = new Child(8);
List<Child> childs = Arrays.asList(new Child[] { child1, child2,
child3, child4, child5, child6, child7 });
List<Child> filtered = ChildPredicates.filterChilds(childs,
ChildPredicates.filterByAge(8));
for (Child : filtered) {
System.out.println(child.getAge());
}}}
Predicate with Lambda Expression (Contd.)
To get Predicate with Lambda Expression:
class ChildPredicates
{
static Predicate<Child> filterByAge(int x) {
return a -> a.getAge() > x;
}
static List<Child> filterChilds(List<Child> childs,
Predicate<Child> predicate) {
return childs.stream().filter(predicate)
.collect(Collectors.<Child> toList());
}}
class Child {
int age;
public Child(int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}}
Key Takeaways

StringBuilder objects are like String objects, except that they can be modified.
Internally, these objects are treated like variable-length arrays that contain a
sequence of characters.

In Java, string is basically an object that represents a sequence of char values. An


array of characters works same as Java string.

You can create and manipulate Calendar Data using functions

Java ArrayList class uses a dynamic array for storing the elements. It inherits
AbstractList class and implements List interface.

Sample program to predicate using Lambda Expression.


Quiz
QUIZ
Which of the following statements about java.lang.String is true?
1

a. String is a final class

b. Anything you write within “ ” is considered a String object

c. String object is modifiable

d. You can convert any object to String by calling toString() method of parent Object class
QUIZ
Which of the following statements about java.lang.String is true?
1

a. String is a final class

b. Anything you write within “ ” is considered a String object

c. String object is modifiable

d. You can convert any object to String by calling toString() method of parent Object class

The correct answer is a, b, and d.


String is a final class and anything we write within “ “ is considered as String object. We can convert
any String by calling tostring() method of parent Object class.
QUIZ
Which of these are thread safe classes?
2

a. String

b. StringBuilder

c. StringBuffer

d. LocalDate
QUIZ
Which of these are thread safe classes?
2

a. String

b. StringBuilder

c. StringBuffer

d. LocalDate

The correct answer is a, c, and d.


String, StringBuffer, and LocalDate are thread safe classes.
Thank You

You might also like