Work with Selected Classes from the Java API Tutorial

Welcome to the Work with selected classes from the java API tutorial offered by Simplilearn. The tutorial is a part of the Java certification course.

In this tutorial, we will work with java.utility classes, and classes that will allow us how to format and work with date and time.

In the next section, we will look at the objectives of the Work with selected classes from the java API tutorial.

Objectives

From the Work with selected classes from the java API tutorial, you will learn 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

Let's begin working with selected classes from the Java API in terms of strings.

Java String

A string is an object that represents a sequence of character values. An array of char works the same way as a Java string.
For example: Given below is a character array, which has a sequence of characters associated with it.

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

String s = new String (ch);

Or

String s = “sample java”;

When we create a string object saying, string s is equal to a new string; then, we simply pass the character array to it and it will convert the character array into a string. In this example, string ‘s’ can be equal to a direct string value like simple Java or also converted from a character array into a string.

In the next section, we will look at the String Objects in Java.

String Objects in Java

The java.lang.String class is used to create a string object. String objects are immutable and cannot be modified or changed. This means that, once a string object is created its data or state cannot be changed, however, a new string object can be created.
Consider the example shown.

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

}  

}

Here, we have a simple class with the entry point of a static void main. The string object ‘s’ is equal to Abdul.

Next, we will try to add or append a new value called Kalam to the stream string.

The command string.concatenate, means that we're adding the value Kalam to the value Abdul and then we will try and print out the string.

We then observe that the output continues to be Abdul. This means that the strings are immutable, it also infers that when a string object is created and a value is assigned to it, it is fixed and the value of the string object at the same memory location cannot be modified where the current string has allocated space in the ram.

If modification of the string value is required, then the allocation of a new memory location would be necessary and only then we will be able to modify the string value. Thus we infer that the string objects are immutable and cannot be modified and changed at their current memory location.

In the next section, we will look at the list of symbols in the regular expression.

List of Symbols in Regular Expression

Now let's look at the list of symbols in terms of the regular expressions.

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

The beginning of the entire string

\z

End of the entire string

\Z

End of the entire string, except allowable final line terminator

e*

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

(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"

\b

Matches the word boundaries when outside the brackets

\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.

Regular expressions allow you to do matching with strings and they're very effective in terms of validations and you can validate the string value or the value that the user is assigning to your class member variables.

In instances where you want to put a restriction, that the stream should be in a certain format or it should be of a certain length or probably the user is assigning a zip code to your class value and you want to validate that the zip code should be in abc dash xyz format, you can do that using these set of regular expressions.

The carrot symbol matches the beginning of the line and the dollar matches the end of the line. In the next section let us see an example of using some of the regular expressions along with the matches method of the Java API.

In the next section, we will look at the matches() method in Java.

matches() Method

Some of the main points under the matches() method include -

  • A matches() method checks, whether the string matches with a specified regular expression.

  • If the string fits in the specified regular expression, then this method returns true. Otherwise, it will return false.

Let us consider the example given below.

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

In the above set of codes, String str is equal to a new string. This string provides the java string methods. Next, we want to do a match. Thus, we use the string dot matches dot asterisk string dot asterisk, this means, we're looking for the word ‘String’ if it is present anywhere within the ‘Java String Methods’ string value. If it is a match, it renders true and if you look at the output it says that the string is actually present in this line java string methods.

In the second matches that we do, we check if the word ‘strings’ with an s is present inside this line now since this is not present it will return false the third match checks if the word methods is actually present in the street and here we see that the word methods is actually present in the line ‘Java String Methods’, now since it is not present, it returns as false.

The third match checks if the word methods are present in the ‘Java String Methods’ line, and since the word methods are present, the value returned will be true.

In the next section, we will look at the character sequence interface in Java.

CharSequence Interface

The character sequence interface used in Java is used to represent a sequence of characters. It is implemented by the String, StringBuffer, and StringBuilder classes available in the Java API.

[image]

Thus, all three classes implement the character sequence interface.

Java string class provides many methods to perform operations on the string, such as -

  • compare() - which is used to compare two strings and checking quality,

  • concat() - if you want to add the value of the two strings together,

  • equals() - if you want to check whether the value that both the strings hold are the same,

  • split() - whether you want to split and break the string into small parts and tokens based on a separator like a comma or space,

  • length() - to give you the length of the string,

  • replace() - if you want to replace one word in the string of one value or character in the string,

  • compareTo(),

  • intern(),

  • substring(), and so on.

These are the methods defined in the character sequence interface and hence, most of the string class available in java will give the set of methods available on them.

In the next section, we will look at the compareTo() Method in Java.

compareTo() Method

The function of the compareTo() method in Java includes -

  • The compareTo() method compares a given string with the current string lexicographically. This means it will actually do a comparison based on the ASCII character of the alphabets present in the string

  • It returns a positive number, negative number, or 0. This means that, if the string s1 is greater than s2, it returns a positive number if string s1 is less than s2 it returns a negative number and if string s1 is equal to s2 it goes ahead and returns a zero.

That is,

if s1 > s2, it returns positive number

if s1 < s2, it returns negative number

if s1 == s2, it returns 0

Let's look at the compareTo() method with an example.

String—compareTo() Example

Here, we are declaring a set of strings, s1, s2,s3,s4,s5. Each string has a different value. The first two strings have a similar value assigned to them and the other three strings have different values.

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

We can infer from the above code that -

  • (s1.compareTo(s2) returns zero because both the strings have the same value.

  • (s1.compareTo(s3) returns the value minus five. This is because ‘H’ is five times lower than ‘M’ in terms of its ASCII key code.

  • When we compare to (s1.compareTo(s4), it returns a negative one because ‘L’ is one, times lower than ‘M’, in terms of the ASCII code.

  • When we compare (s1.compareTo(s5) that is “Hello” with “Flag”, it returns 2 because ‘H’ is two times greater than ‘F’ from the ASCII code perspective.

The output of this particular example is also shown under the code box.

In the next section, let us look at the concat() method in Java.

concat() Method

Let's now look at the concat() method.  

  • The contact method available as part of the string class combines the specified string to the end of the current string. In short, it simply does an addition or an append operation.

  • It returns a combined stream. Therefore, the method defined below is the public string concat another string; So that it takes another string and appends it to the existing string.

public String concat(String anotherString)

Next, let us look at an example of the contact method.

String—concat() Example

Let us now look at an example of the concat method.

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

In the example shown above, we have a class called ConcatExample, an entry point method called static void main, String s1 with a start value of "java string". To it, we are saying, s1.concat and we're passing the value sample.

Now when we print s1, you can observe the output as it is shown under the code snippet. Now, when we say ‘s1=s1.concat(" Sample example for String Concat")’, we observe that since we have now concatenated this new value and stored the return back into s1, and since the strings are immutable there is a new memory location that has been created.

Thus, s1 has started pointing to this new memory location. The new memory location where the object s1 has been allocated now holds the new value which says “Sample example for String Concat” and a reference to this new memory location is returned and stored in s1.

Hence, when we say s1, we get the new value which was concatenated to the initial value, which is- ‘Sample example for String Concat’. If we hadn’t assigned the reference of the new memory location back to s1, then it wouldn’t have worked and we would have got back the old value because strings are immutable and the value cannot be updated at the original memory location.

In the next section, let us learn about the equals() method in Java.

equals() Method

Let us now look at the equals method available on the string

  • The string equals method, compares two given strings based on the content of the string

  • If any character is not matched, it returns false

  • If all characters are matched, it returns true

  • It overrides the equals method of object clas

public boolean equals(Object anotherObject)

Thus, we have public boolean equals and the name of the object. Let us now look at an example for the equals method.

equals() Method Example

Let us now look at an example of the equals() method. Here, we are declaring 4 strings. Each string has different values. Since the value of String s1 and String s2 are the same, the command (s1.equals(s2)); returns true since the content and the casing is the same.

Whereas, since String s1 and String s3 have same values but different casing, the command  (s1.equals(s3)); returns false.

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

In this example, we're declaring four strings. Each string has different values. String s1 and s2, however, have the same value, so when we say String ‘s1.equals(s2)’ the value returned will be true. This is because the content and the casing is the same.

On the other hand when we say String ‘s1.equals(s3)’, the casing is not the same; we have a small sample and we have a sample in all caps, so the value returned will be false.

In the last line of the code, we have ‘s1.equals(s4)’. Here, we are trying to equate the word ‘Sample’ with the word ‘Java’ and check if it has the same value. It is quite evident that the value returned will be false, because the content held in both the variables is not the same.

Let us now move on to the next method available for string operations which is the split() method.

Java Certification Training caught your attention? Check out the course preview now!

split() Method

In the string split method, the string is split based on a given regular expression and returns a character array.

public String split(String regex)

and,

public String split(String regex, int limit)

Here, two options are available; two overloads for the string split. We can either pass a regex expression that splits the string wherever it finds that expression within the string, or we could use a regex expression and a limit, where we can say, split the string until this particular limit is met.

Let us look at an implementation of this method.

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)

{

System.out.println(w);

}

}}

Output:

java

string

split

method

sample

Here, we have the entry point public void main, String s1 and a line associated with it which is "java string split method sample". We now call the split function and we pass slash s, which means, search for blanks or whitespace characters. So every time a blank or space is encountered within the string, the string will be split and those values will be stored into the array called words.

Using a for loop as shown in the code, for every string object w, which is a temporary object we are creating of the type stream that is found inside the array words, go ahead, return, and print that particular value.

Therefore, as seen, w will stand for every value that is existing in this words array of the stream. And, since the split function would have split the string into individual values everywhere or every time it found a space, the words array would contain individual words based on the splitting that has been done.

Therefore, when we iterate over these words carry it actually prints ‘java’ and due to the presence of the space after this, so it splits the word string into a new element in the words array.

Once again, the word ‘split’ has space after it so it is cut and put in as a separate element in the words array and it does the same thing for the words ‘method’ and ‘sample’. The practical implementation of these methods is really important because, while working with live data from a database, and want to split up content that is sent to you so that you can process individual elements in that content in that case these methods are really useful.

In the next section, let us look at the substring method in Java.

substring() Method

The substring method is a method on the string class that returns a new string that is a part of the primary string. It has two overloads, it takes the start index or the start and the end index.

Let us now look at an example

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

We have string s1=“samplesubstring". When we say s1.substring (2,4), on having a zero-based index, ‘S’ is at zero, ‘A’ is at one, and ‘M’ is at two. So it starts splitting at 2.

That is the reason for it to have a start of ‘M’ and it stops set 4, and thus P is at position four and hence it returns M and P.

In the second example or the second line of code, we see s1.substring(2), which means it starts breaking the stream from the second position onwards since it's a zero-based index, ‘S’ is at zero, ‘A’ is at one, and ‘M’ is at two.

So, it starts splitting at M, and since we haven’t given an end index, it simply goes ahead and returns the entire string after the second position. Which is what is obtained as an output of this program.

In the next section, we will learn the format() Method in Java.

format() Method

Let us now go to the next method available on the string class which is the format method.

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

and,

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

The format method has two overloads. You can pass the string format that is to be formatted and some object arguments. You can also pass in locale information.

Let us now take a look at an example.

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);

System.out.println(sf2);

System.out.println(sf3);

}}

Output:

name is James

value is 32.334340

value is 334340000000

Here we can observe a string name “James”,  we will format this name with a %s identifier. The output thus obtained when we print, it says ‘name is James’. If this value is formatted with a %f identifier, and the value 32.33434 is passed, we can observe the extended position that is provided because of the %f format specified.

Consider another example of the format specifier of %32.12f, which means it returns twelve characters fractional part filling with zero and the outcome of using these format specifiers can be observed.

Thus, there are the various format specifiers that we can use for passing to this formatting method and it would go ahead and format the string based on the format specifier that is provided.

In the next section, we will look at the StringBuilder class in Java.

StringBuilder Class

Now, let us work with selected classes which is StringBuilder and a part of the Java API

  • The string builder 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 or strings that can be modifiable in terms of the existing memory location they occupy, you can go ahead and modify the current value at the same location where the original variable has been created and stored

  • The objects are like string objects except that they can be modified at the current location where they are stored in memory. Internally these objects are treated with variable-length arrays that contain a sequence of the characters.

The string builder class has a series of methods available with it. The table below explains it.

Constructor

Description

StringBuilder()

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

StringBuilder(CharSequence cs)

Constructs a string builder containing the same characters as the specified CharSequence, plus an extra 16 empty elements trailing the CharSequence

StringBuilder(int initCapacity)

Creates an empty string builder with the specified initial capacity

StringBuilder(String s)

Creates a string builder whose value is initialized by the specified string, plus an extra 16 empty elements trailing the string

In the next section, we will look at the example for the StringBuilder class in Java.

StringBuilder Class Example

In this illustration and example, we see that when we create a StringBuilder object, we actually get an initial capacity off sixteen elements. But if we say sb.append("Greetings") and we want to store the value greetings. The length occupied by the capacity of sixteen elements will be only nine.

// creates empty builder, capacity 16

StringBuilder sb = new StringBuilder();

// adds 9 character string at beginning

sb.append("Greetings");

In the next section, we will look at the StringBuilder method in Java.

StringBuilder Method

These two StringBuilder methods are -

void setLength(int newLength)

This sets the length of the character sequence. If newLength is less than the length(), the last characters in the character sequence are truncated. If newLength is greater than the 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.

The string builder also has additional methods called setLength. This sets the length off the character sequence. If newLength is less than length, the last characters in the character sequence are truncated. If newLength is greater than Length. Nullcharacters are added at the end of the character sequence.

The next method, available in the class, ensures capacity, which passes or takes, or integer value, which is minimum capacity. This ensures that the capacity that is provided to you as part of the string builder object storage space is at least equal to the specified minimum capacity that you have provided.

In the next section, let us look at the various StringBuilder methods in Java.

Various StringBuilder Methods

These are the additional set off stringbuilder methods that are available.

StringBuilder append(boolean b)

StringBuilder append(char c)

StringBuilder append(char[ ] str)

StringBuilder append(char[ ] str, int offset, int len) StringBuilder append(double d)

StringBuilder append(float f)

StringBuilder append(int i)

StringBuilder append(long lng)

StringBuilder append(Object obj)

StringBuilder append(String s)

Appends the argument to this string builder. The data is converted to a string before the append operation takes place.

StringBuilder delete(int start, int end)

StringBuilder deleteCharAt(int index)

The first method deletes the subsequence from start to end-1 (inclusive) in the StringBuilder's char sequence.

The second method deletes the character located at the index.

You have multiple overloads available off the append method, which take booleans, characters, character array, floats, integers, long values, and strings. These append the arguments that you pass to the existing value held in the StringBuilder object, and the data is automatically converted to a string before the append operation takes place.

The next set of methods available is delete, which takes the start and the end position. The deleteCharAt which takes the index position.

The first method deletes the sequence from start to end, inclusive in the string builders character sequence. In the second method, which is deleteCharAt, deletes the character located at the index position.

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 offset, int len)

StringBuilder insert(int offset, double d)

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)

Inserts the second argument into the string builder. The first integer argument indicates the index before which the data is to be inserted. The data is converted to a string before the insert operation takes place.

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

void setCharAt(int index, char c)

Replaces the specified character(s) in this string builder.

StringBuilder reverse()

Reverses the sequence of characters in this string builder.

String toString()

Returns a string that contains the character sequence in the builder.

Insert is different from append as, append will add the new value to the end of the string, with the insert you can inject the new value somewhere in between the string based on the offset value that you are providing.Then we have the insert method available on the string builder, which also has multiple overloads. You can give the offset value with boolean character, character arrays or double float or integers values that you want to insert at a particular position inside the string builder.

Working with StringBuffer

Some points about the StringBuffer is as given below -

  • 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.  

Let's, look at an example for working with StringBuffer.

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

}

}  

This is an example for append method.

Here we see a StringBuffer object has a start value of welcome. The command, sb.append("Java"), means that we want to add the word Java to the existing string welcome. Next, we print out the string. The output thus obtained will be “Welcome Java”. This proves that these objects are mutable.

The value of the existing object that has been present in the memory can be changed and the value can be updated at the same location.

Next, we will look at an example of the 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

}

}

Here, we are creating a StringBuffer object and assigning it a value of Welcome. Then, we say sb.insert (StringBuffer.insert) and we insert java at position 1. Since position 1 is the position of the letter ‘e’ in the string Welcome after the letter ‘W’ and so when we print the object, we see the word java has been inserted in between the current string. Thus the output obtained is WJavaelcome.

In the next section, let us look at the comparison between StringBuilder and StringBuffer.

Compare StringBuilder and StringBuffer

Let us now compare StringBuilder and StringBuffer.

StringBuilder

StringBuffer

Multiple threads are allowed to operate at a time

A 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

The storage area is Heap

The storage area is Heap

Mutable

Mutable

In StringBuilder, the data object is mutable, which means that once you store the value at a  memory location using a StringBuilder object, you're free to change that value.

In StringBuffer also, the data object is mutable, which means that the data that you store at the memory locations using a StringBuffer object, can be updated.

Compare StringBuilder and StringBuffer (contd.)

In this section, let us learn in detail about Mutable and Immutable.

Mutable

Mutable can be defined as an object is mutable when you can change its value and it actually creates a new reference in memory of this object.

For example,

int i=0;

while(i<10) {

System.out.println(i);

i+=1;

}

In this example, we have integer i=0. Integer is a mutable value; which means that, in the memory location of the ram, we have a value called ‘i’ on the stack and an initial value of zero. As the while loop progresses, we can observe that the value of the ‘i’ keeps getting updated with a new value. The value of ‘i’ gets updated to 1,2, or 3 at the same location where the current value of ‘i’ is located. Therefore, it is mutable as the memory location can be updated with a new value.

Immutable

An object is immutable when you cannot change its value once it is referenced. The only thing that can be done is to redeclare the object, which means it will start pointing to a new memory location. 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;

}

In this example, we have taken an integer value ‘a’.

Let's move to the creation and manipulation of the calendar data.

Let us now look at the next topic, which is the creation and manipulation of the calendar data.

Java.util.Date Class

We will now look at the 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

The Java.util.Date Class can be created as shown in the example below. Here, we are creating an object of this class equal to new java.util.Date and we are passing the milliseconds to it and we print system.out.println(date), and thus the output will be obtained.

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

long millis=System.currentTimeMillis();

java.util.Date date=new java.util.Date(millis);

System.out.println(date);

Output: Wed Mar 27 08:22:02 IST 2017

Java SimpleDateFormat Class

Let us now learn about the SimpleDateFormat Class in java.

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

  • It inherits java.text.DateFormat class.

Let us now look at the example for formatting date in Java using java.text.SimpleDateFormat class.

In the example shown below, we are importing the java.text.SimpleDateFormat package so that we can use APIs from that package. We are also importing import java.util.Date.

Example:

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

Thus, the output obtained is the date formatted as per the simple date formatter class that we had provided in a dd mm yyyy format.

java.util.Calendar and GregorianCalendar

Some of the main points under the java.util.Calendar and GregorianCalendar include -

  • 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);

In this code sample, we are creating an object of type calendar and associating it with a new Gregorian calendar object.

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

Next, we will learn about these functions to understand what they do.

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

Thus, we can see that the output actually gives us the date personalized to a particular country and city. This is the zone capability which can also be provided as localized information in terms of the zoneId when you want to generate a local date zone.

java.time.LocalTime

java.time.LocalTime class is similar to LocalDate. It provides 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

On running this code, the time that is printed now is localized time to that particular city and country.

java.time.LocalDateTime

LocalDateTime is an immutable object that presents a date-time. The default format for the datetime 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

The output obtained is in year, month, day, hours, minutes, seconds, and milliseconds. The moment we create another object of the class and pass the zone id to it, it will actually give you the same output with localized time information specific to that particular country and city.

java.time.Period

Let us now look at the code for java.time.Period class.

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)

The java.time.Period class provides the quantity or amount of time in terms of years months and days.

java.time.format.DateTimeFormatter

The preferred date/time classes are no longer maintained in the java.util package. The new date/time handling classes are part of the 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);

System.out.println(formatter3);

}

}

Output: 2017/06/15 15:14:51 IST 2017/06/15 15/Jul/2017

Let us now look at the use of the ArrayList class in the Java API.

How about investing your time in the Java Certification Training? Take a look at the course preview now!

ArrayList Class

Java ArrayList class inherits AbstractList class and implements List interface. It uses a dynamic array for storing the elements, this means that it does not have a fixed capacity, length or size. Depending on the amount of the elements that you add to the ArrayList, being a collection class, it will keep auto incriminating its size depending on the values that are stored inside it.

The ArrayList will also assist you to store different data types at the same time, unlike an array.

The important points about Java ArrayList are as follows -

  • It maintains the insertion order. In terms of the sequence in which you insert elements into the list

  • It can contain duplicate elements.

  • It allows random access because array works at the index spaces. However, in the ArrayList, you can go ahead and randomly access elements inside the ArrayList.

  • It is non-synchronized

  • In Java ArrayList class, manipulation is slow because a lot of shifting of elements and values in the memory has to occur if any element is removed or deleted from the  ArrayList.

In the next section let us learn about the Class Declaration and its use.

Class Declaration and Its Use

Let us now look at an example of the java.util.ArrayList class provides a 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();      //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()) {                                // while new record still available in arraylist

System.out.println(itr.next());                   // print the available value

}

}

}

Output:

John

James

Mathews

Nitin

Predicate with Lambda Expression in Java

Let us look at predicates with lambda expressions in Java.

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;

}}

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());

}}}

Lambda expression allows passing on an entire expression as a parameter to a function. It also gives the capability to write less code to do the filtering of data, sorting of data, by making use of the arrow operator.

Thus by the above two programs, we can understand that a lambda expression and a predicate function being used effectively, largely reduces the effort and the number of lines of code we would have written to other write the same program by using the if condition.

Summary

Let us now look at what we have learned in this Work with selected classes from the java API tutorial:

  • 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, the 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.

Conclusion

With this, we come to an end to the Work with selected classes from the java API tutorial.

Find our Java Certification Training Online Classroom training classes in top cities:


Name Date Place
Java Certification Training 14 Dec -2 Feb 2020, Weekend batch Your City View Details
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.

Request more information

For individuals
For business
Name*
Email*
Phone Number*
Your Message (Optional)
We are looking into your query.
Our consultants will get in touch with you soon.

A Simplilearn representative will get back to you in one business day.

First Name*
Last Name*
Email*
Phone Number*
Company*
Job Title*