by Jesmin Akther | Jun 19, 2021 | JAVA
Java String
In Java, string is an object of sequence of char values like an array of characters. There are two ways to create String object:
String literal and new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
char[] names={‘d’,’r’,’a’,’f’,’t’,’s’,’b’,’o’,’o’,’k’,’.’,’c’,’o’,’m’};
- String site=new String(names); //String new keyword
Is same as:
String names =”draftsbook.com”; // String Literal
Each time create a string literal, the JVM checks the “string constant pool” first. If the string already in the pool, a reference to the pool instance is returned. If the string doesn’t exist in the pool, a new string instance is created and placed in the pool. For instance:
String site1=” draftsbook.com “;
String site2=” draftsbook.com “; //It doesn’t create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string object with the value “draftsbook.com “in string constant pool. So, it will create a new object. After that it will find the string with the value “draftsbook.com “in the pool, it will not create a new object but will return the reference to the same instance. Keep in mind that String objects are stored in a special memory area known as the “string constant pool”. Why Java uses String literal? In order to make Java more memory efficient. Because no new objects are created if it exists already in the string constant pool. Learn about or easily understand String, StringBuffer read this writing What is the defference among String, StringBuffer and StringBuilder.
2) By new keyword
String site=new String(“draftsbook.com”);//creates two objects and one reference variable.
In such case, JVM will create a new string object in normal or non-pool or a heap memory in addition to the literal ” draftsbook.com ” will be positioned in the string constant pool. The variable site will refer to the object in a heap.Learn about or easily understand String, StringBuffer read this writing What is the defference among String, StringBuffer and StringBuilder.
Java String Example
public class ExString{
public static void main(String args[]){
String site1=" draftsbook.com ";//creating string by java string literal
char[] names={'d','r','a','f','t','s','b','o','o','k',’.’,’c’,’o’,’m’};
String site2=new String(names);//converting char array to string
String site3=new String("https://draftsbook.com/");//creating java string by new keyword
System.out.println(site1);
System.out.println(site2);
System.out.println(site3);
}
}
OUTPUT
draftsbook
draftsbook.com
Home
Java String class allows a several number of methods to do operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.Learn about or easily understand String, StringBuffer read this writing What is the defference among String, StringBuffer and StringBuilder.
The interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in java by using these three classes.
The Java String is immutable which means it cannot be changed. Whenever alteration any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.
- Java String class methods
The java.lang.String class provides many useful methods to perform operations on sequence of char values.Learn about or easily understand String, StringBuffer read this writing What is the defference among String, StringBuffer and StringBuilder.
Method and Description of Java:
- char charAt(int index) : This method returns char value for the particular index
- int length() : This method returns string length
- static String format(String format, Object… args): This method returns a formatted string.
- static String format(Locale l, String format, Object… args) : This method returns formatted string with given locale.
- String substring(int beginIndex) : This method returns substring for given begin index.
- String substring(int beginIndex, int endIndex): This method returns substring for given begin index and end index.
- boolean contains(CharSequence s) : This method returns true or false after matching the sequence of char value.
- static String join(CharSequence delimiter, CharSequence… elements): This method returns a joined string.
- static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) : This method returns a joined string.
- boolean equals(Object another): This method checks the equality of string with the given object.
- boolean isEmpty(): This method checks if string is empty.
- String concat(String str) : This method concatenates the specified string.
- String replace(char old, char new) : This method replaces all occurrences of the specified char value.
- String replace(CharSequence old, CharSequence new) : This method replaces all occurrences of the specified CharSequence.
- static String equalsIgnoreCase(String another): This method compares another string. It doesn’t check case.
- String[] split(String regex) : This method returns a split string matching regex.
- String[] split(String regex, int limit) : This method returns a split string matching regex and limit.
- String intern(): This method returns an interned string.
- int indexOf(int ch) : This method returns the specified char value index.
- int indexOf(int ch, int fromIndex) : This method returns the specified char value index starting with given index.
- int indexOf(String substring): This method returns the specified substring index.
- int indexOf(String substring, int fromIndex): This method returns the specified substring index starting with given index.
- String toLowerCase(): This method returns a string in lowercase.
- String toLowerCase(Locale l): This method returns a string in lowercase using specified locale.
- String toUpperCase() : This methodreturns a string in uppercase.
- String toUpperCase(Locale l) : This method returns a string in uppercase using specified locale.
- String trim(): This method removes beginning and ending spaces of this string.
- static String valueOf(int value): This methodconverts given type into string. It is an overloaded method.
Strings are actually are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings.Learn about or easily understand String, StringBuffer read this writing What is the defference among String, StringBuffer and StringBuilder.
Creating Strings
The most direct way to create a string is to write −
String greeting = “Hello world!”;
Whenever invoke a string literal in code, the compiler creates a String object with its value in this case, “Hello world!’. Since with other object, can create String objects by using the new keyword and a constructor. The String class has 11 constructors that allow to provide the initial value of the string using different sources, such as an array of characters.
Example
public class stringExample {
public static void main(String args[]) {
char[] hArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String hString = new String(hArray);
System.out.println( hString );
}
}
Output
hello.
The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then use String Buffer & String Builder Classes.
String Length
One accessor method that can use with strings is the length() method, which returns the number of characters contained in the string object. The following program is an example of length(), method String class.
Example
public class stringExample {
public static void main(String args[]) {
String palindrome = "Mim saw It as Sin";
int lengthPalin = palindrome.length();
System.out.println( "String Length is : " + lengthPalin);
}
}
Output
String Length is: 17
Concatenating Strings : The String class includes a method for concatenating two strings,
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. can also use the concat() method with string literals, as in
“My name is “.concat(“Md”)
Strings are more commonly concatenated with the + operator, as in
“Hello,” + ” world” + “!”
OUTPUT
“Hello, world!”
Let us look at the following example
public class stringExample {
public static void main(String args[]) {
String stringSen = "saw It as ";
System.out.println("Mim " + stringSen + "Sin");
}
}
Output
Dot saw I was Mim
Creating Format Strings
The methods printf() and format() are use to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. Using String’s static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of:
Example
System.out.printf(“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);
You can write as:
String fs;
fs = 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);
System.out.println(fs);
String Methods
A few list of methods supported by String class are given below:
Method & Description:
The method is used to returns the character at the specified index.
The method is used to Compares this String to another Object.
- int compareTo(String anotherString)
The method is used to Compares two strings lexicographically.
- int compareToIgnoreCase(String str)
The method is used to Compares two strings lexicographically, ignoring case differences.
- String concat(String str)
The method is used to Concatenates the specified string to the end of this string.
- boolean contentEquals(StringBuffer sb)
The method is used to Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.
- static String copyValueOf(char[] data)
The method is used to Returns a String that represents the character sequence in the array specified.
- static String copyValueOf(char[] data, int offset, int count)
The method is used to Returns a String that represents the character sequence in the array specified.
- boolean endsWith(String suffix)
The method is used to Tests if this string ends with the specified suffix.
- boolean equals(Object anObject)
The method is used to Compares this string to the specified object.
- boolean equalsIgnoreCase(String anotherString)
The method is used to Compares this String to another String, ignoring case considerations.
The method is used to Encodes this String into a sequence of bytes using the platform’s default charset, storing the result into a new byte array.
- byte[] getBytes(String charsetName)
The method is used to Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
- void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
The method is used to Copies characters from this string into the destination character array.
The method is used to Returns a hash code for this string.
The method is used to Returns the index within this string of the first occurrence of the specified character.
- int indexOf(int ch, int fromIndex)
The method is used to Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
The method is used to Returns the index within this string of the first occurrence of the specified substring.
- int indexOf(String str, int fromIndex)
The method is used to Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
The method is used to Returns a canonical representation for the string object.
The method is used to Returns the index within this string of the last occurrence of the specified character.
- int lastIndexOf(int ch, int fromIndex)
The method is used to Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
- int lastIndexOf(String str)
The method is used to Returns the index within this string of the rightmost occurrence of the specified substring.
- int lastIndexOf(String str, int fromIndex)
The method is used to Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
The method is used to Returns the length of this string.
- boolean matches(String regex)
The method is used to Tells whether or not this string matches the given regular expression.
- boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
The method is used to Tests if two string regions are equal.
- boolean regionMatches(int offset, String other, int onset, int len)
The method is used to Tests if two string regions are equal.
- String replace(char oldChar, char newChar)
The method is used to Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
- String replaceAll(String regex, String replacement
The method is used to Replaces each substring of this string that matches the given regular expression with the given replacement.
- String replaceFirst(String regex, String replacement)
The method is used to Replaces the first substring of this string that matches the given regular expression with the given replacement.
- String[] split(String regex)
The method is used to Splits this string around matches of the given regular expression.
- String[] split(String regex, int limit)
The method is used to Splits this string around matches of the given regular expression.
- boolean startsWith(String prefix)
The method is used to Tests if this string starts with the specified prefix.
- boolean startsWith(String prefix, int toffset)
The method is used to Tests if this string starts with the specified prefix beginning a specified index.
- CharSequence subSequence(int beginIndex, int endIndex)
The method is used to Returns a new character sequence that is a subsequence of this sequence.
- String substring(int beginIndex)
The method is used to Returns a new string that is a substring of this string.
- String substring(int beginIndex, int endIndex)
The method is used to Returns a new string that is a substring of this string.
The method is used to Converts this string to a new character array.
The method is used to Converts all of the characters in this String to lower case using the rules of the default locale.
- String toLowerCase(Locale locale)
The method is used to Converts all of the characters in this String to lower case using the rules of the given Locale.
The method is used to This object (which is already a string!) is itself returned.
The method is used to Converts all of the characters in this String to upper case using the rules of the default locale.
- String toUpperCase(Locale locale)
The method is used to Converts all of the characters in this String to upper case using the rules of the given Locale.
The method is used to Returns a copy of the string, with leading and trailing whitespace omitted.
- static String valueOf(primitive data type x)
The method is used to Returns the string representation of the passed data type argument.
by Jesmin Akther | Jun 17, 2021 | JAVA
Java Keywords
Java keywords are also known as reserved words. They are particular words that acts as a key to a code. These are predefined words by Java so it cannot be used as a variable or object name.
Let’s know the list of Java Keywords. A list of Java keywords or reserved words are given below:
abstract:
This keyword is used to declare abstract class. Abstract class can provide the implementation of interface. It can have abstract and non-abstract methods.
boolean:
The Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values only.
break:
Java break keyword is used to break loop or switch statement. It breaks the current flow of the program at specified condition.
byte:
The byte keyword is used to declare a variable that can hold an 8-bit data values.
case:
The java case keyword is used to with the switch statements to mark blocks of text.
catch:
Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try block only.
char:
The char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters
class:
In Java, the class keyword is used to declare a class.
continue:
In Java, the continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
default:
The default keyword in java is used to specify the default block of code in a switch statement.
do:
The Java do keyword is used in control statement to declare a loop. It can iterate a part of the program several times.
double:
The Java double keyword is used to declare a variable that can hold a 64-bit floating-point numbers.
else:
The default Java else keyword is used to indicate the alternative branches in an if statement.
enum:
The Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or default.
extends:
The default Java extends keyword is used to indicate that a class is derived from another class or interface.
final: The default Java final keyword is used to indicate that a variable holds a constant value. It is applied with a variable. It is used to restrict the user.
finally: The default Java finally keyword indicates a block of code in a try-catch structure. This block is always executed whether exception is handled or not.
float: The Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly when some conditions become true. If the number of iteration is fixed, it is recommended to use for loop.
if: The default Java if keyword tests the condition. It executes the if block if condition is true.
implements: The default Java implements keyword is used to implement an interface.
import: The Java import keyword makes classes and interfaces available and accessible to the current source code.
instanceof: The default Java instanceof keyword is used to test whether the object is an instance of the specified class or implements an interface.
int: The default Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
interface:
The default Java interface keyword is used to declare an interface. It can have only abstract methods.
long: The default Java long keyword is used to declare a variable that can hold a 64-bit integer.
native: The default Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native Interface).
new: The default Java new keyword is used to create new objects.
null:
The default Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage value.
package:
The default Java package keyword is used to declare a Java package that includes the classes.
private:
The default Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed only in the class in which it is declared.
protected:
The default Java protected keyword is an access modifier. It can be accessible within package and outside the package but through inheritance only. It can’t be applied on the class.
public:
The default Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has the widest scope among all other modifiers.
return:
The default Java return keyword is used to return from a method when its execution is complete.
short:
The default Java short keyword is used to declare a variable that can hold a 16-bit integer.
static:
The default Java static keyword is used to indicate that a variable or method is a class method. The static keyword in Java is used for memory management mainly.
strictfp:
The default Java strictfp is used to restrict the floating-point calculations to ensure portability.
super:
The default Java super keyword is a reference variable that is used to refer parent class object. It can be used to invoke immediate parent class method.
switch:
The Java switch keyword contains a switch statement that executes code based on test value. The switch statement tests the equality of a variable against multiple values.
synchronized:
Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.
this:
In Java this keyword can be used to refer the current object in a method or constructor.
throw:
The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw custom exception. It is followed by an instance.
throws:
The Java throws keyword is used to declare an exception. Checked exception can be propagated with throws.
transient:
In Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.
try:
In Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be followed by either catch or finally block.
void:
In Java void keyword is used to specify that a method does not have a return value.
volatile:
In Java volatile keyword is used to indicate that a variable may change asynchronously.
while:
In Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.
Here is a few example with keywords:
public abstract class AbstractClass {
// This method is abstract ; it does not have a body
public abstract void abstractMethod();
// it is implemented in the abstract class and gives a default behavior.
public void concreteMethod() {
System.out.println("Already coded.");
}
}
The above code abstract keyword use here first method has no body as it is a abstract.
AbstractClass myObject = new AbstractClass() {
public void abstractMethod() {
System.out.println("Implementation.");
}
};
Above example code uses keyword new and the code has implemented method which has body.
by Jesmin Akther | Jun 13, 2021 | JAVA
Wrapper classes in Java
The wrapper class in Java offers the mechanism to translate primitive into object and object into primitive. This feature has obtained from Java J2SE 5.0, autoboxing and unboxing. Actually, these feature convert primitives into objects and objects into primitives automatically. The automatic conversion of primitive into an object is known as autoboxing and unboxing. Wrapper class is a class whose object wraps or contains primitive data types.
In more details:
When create an object to a wrapper class, it contains a field and, in this field, there can store primitive data types. In other words, wrap a primitive value into a wrapper class object.
Necessity of Wrapper Classes,
- These classes convert primitive data types into objects.
- Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).
- The classes in java.util package handles only objects and hence wrapper classes help in this scenario.
- Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.
- An object is needed to support synchronization in multithreading.
Use of Wrapper classes in Java
As Java is an object-oriented programming language(OOP), need to deal with objects many times such as in Collections, Serialization, Synchronization, etc. To use the wrapper classes need
- Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value.
- Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes.
- Synchronization: Java synchronization works with objects in Multithreading.
- util package: The java.util package provides the utility classes to deal with objects.
- Collection Framework: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight wrapper classes are given below:
Primitive Type |
Wrapper class |
boolean |
Boolean |
char |
Character |
byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
Autoboxing
The automatic alteration of primitive data type into its equivalent wrapper class is known as autoboxing, for instance, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Wrapper class Example: Primitive to Wrapper
//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample{
public static void main(String args[]){
//Converting int into Integer
int a=10;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
}
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper classes to convert the wrapper type into primitives. Wrapper class Example: Wrapper to Primitive
//Java program to convert primitive into objects (Autoboxing example of int to Integer)
public class WrapperExample{
public static void main(String args[])
{
//Converting int into Integer
int a=10;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
}
Output:
3 3 3
Java Wrapper classes Example
//Java Program to convert all primitives into its corresponding wrapper objects
public class WrapperExample{
public static void main(String args[]){
byte b=100;
short s=200;
int i=300;
long l=400;
float f=500.0F;
double d=600.0D;
char c='a';
boolean b2=true;
//Autoboxing: Converting primitives into objects
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;
//Printing objects
System.out.println("Show values");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);
//Unboxing: Converting Objects to Primitives
byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;
//Printing primitives
System.out.println(" Show primitive values");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}}
Output:
Show object values
Byte object: 100
Short object: 200
Integer object: 300
Long object: 400
Float object: 500.0
Double object: 600.0
Character object: a
Boolean object: true
Show primitive values
byte value: 100
short value: 200
int value: 300
long value: 400
float value: 500.0
double value: 600.0
char value: a
boolean value: true
Custom Wrapper class in Java
Java Wrapper classes wrap the primitive data types, that is why it is known as wrapper classes. We can also create a class which wraps a primitive data type. So, we can create a custom wrapper class in Java.
//Creating the custom wrapper class
class WrapperExample {
private int i;
WrapperExample (){}
WrapperExample (int i){
this.i=i;
}
public int getValue(){
return i;
}
public void setValue(int i){
this.i=i;
}
@Override
public String toString() {
return Integer.toString(i);
}
}
//Test the custom wrapper class
public class TestWrapperExample {
public static void main(String[] args){
WrapperExample j=new WrapperExample (10);
System.out.println(j);
}
Output:
10
by Jesmin Akther | Jun 13, 2021 | JAVA
Java HashSet
In a HashSet, every item is unique which is known as collection. It is found in the java.util packages. This collection uses a hash table for storage. It inherits the AbstractSet class and implements Set interface. A list can contain duplicate elements whereas Set contains unique elements only.
The importantfeatures about Java HashSet class are:
- It stores the elements by using a mechanism called hashing.
- It contains unique elements only.
- It allows null value.
- It class is none synchronized.
- It doesn’t maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
- It is the best approach for search operations.
Java HashSet Declaration:
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
Constructors of Java HashSet
- HashSet():It is used to construct a default HashSet.
- HashSet(int capacity):It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
- HashSet(int capacity, float loadFactor):It is used to initialize the capacity of the hash set to the given integer value capacity and the specified load factor.
- HashSet(Collection<? extends E> c):It is used to initialize the hash set by using the elements of the collection c.
Methods of Java HashSet class
- add(E e):It is used to add the specified element to this set if it is not already present.
- clear():It is used to remove all of the elements from the set.
- object clone(): It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
- contains(Object o):It is used to return true if this set contains the specified element.
- isEmpty():It is used to return true if this set contains no elements.
- iterator():It is used to return an iterator over the elements in this set.
- remove(Object o):It is used to remove the specified element from this set if it is present.
- int size():It is used to return the number of elements in the set.
Example
//Create a HashSet object called letters that will store strings:
import java.util.HashSet; // Import the HashSet class
HashSet<String> lettes = new HashSet<String>();
Add Items: The HashSet class has many useful methods. For example, to add items to it, use the add() method:
Example
// Import the HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> lettes = new HashSet<String>();
lettes.add("A");
lettes.add("B");
lettes.add("C");
lettes.add("B");
lettes.add("E");
System.out.println(lettes);
}
}
OUTPUT:
A B C E
In the example above, even though Bis added twice it only appears once in the set because every item in a set has to be unique.
- Check If an Item Exists: In order to check whether an item exists in a HashSet, use the contains() method:
Example
lettes.contains(“B”);
- Remove an Item: In order to remove an item, use the remove() method:
Example
lettes.remove(“A”);
To remove all items, use the clear() method:
Example
lettes.clear();
HashSet Size
In order to find out how many items there are, use the size method:
Example
lettes.size();
HashSet Loop: Loop through the items of an HashSet with a for-each loop:
Example
for (String i : letters) {
System.out.println(i);
}
Other Types:
In order To use other types, such as int, you must specify an equivalent wrapper class: Integer. For other primitive types, use: Boolean for boolean, Character for char, Double for double, etc:
Example
Use a HashSet that stores Integer objects:
import java.util.HashSet;
public class ExMain {
public static void main(String[] args) {
// Create a HashSet object called numbers
HashSet<Integer> numbers = new HashSet<Integer>();
// Add values to the set
numbers.add(4);
numbers.add(7);
numbers.add(8);
// Show which numbers between 1 and 10 are in the set
for(int i = 1; i <= 10; i++) {
if(numbers.contains(i)) {
System.out.println(i + " was found!");
} else {
System.out.println(i + " was not found!");
}
}
}
}
OUTPUT
1 was not found!
2 was not found!
3 was not found!
4 was found!
5 was not found!
6 was not found!
7 was found!
8 was found!
9 was not found!
10 was not found!
by Jesmin Akther | Jun 7, 2021 | JAVA
Date and Time in Java
Example of Constructor
- Date( ) this constructor initializes the object with the current date and time.
- Date(long millisec) this constructor accepts an argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970.
Following are the some methods of the date class.
Method |
Description |
boolean after(Date date) |
Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false. |
boolean before(Date date) |
Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false. |
Object clone( ) |
Duplicates the invoking Date object. |
int compareTo(Date date) |
Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date. |
int compareTo(Object obj) |
Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException. |
boolean equals(Object date) |
Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false. |
long getTime( ) |
Returns the number of milliseconds that have elapsed since May 1, 2020. |
int hashCode( ) |
Returns a hash code for the invoking object. |
void setTime(long time) |
Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, May 1, 2020. |
String toString( ) |
Converts the invoking Date object into a string and returns the result. |
Getting Current Date and Time
This is a very easy method to get current date and time in Java. You can use a simple Date object with toString() method to print the current date and time as follows:
Example
import java.util.Date;
public class ExampleDateDemo {
public static void main(String args[]) {
Date date = new Date(); // This statement Instantiate a Date object
System.out.println(date.toString()); // display time and date using toString()
}
}
This will produce the following result:
Output
Mon Jun 07 11:55:32 UTC 2021
Date Comparison
Following are the three ways to compare two dates:
- Method getTime( ) to obtain the number of milliseconds that have passed since midnight, June 1, 2021, for both objects and then compare these two values.
- methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 21).before(new Date (99, 2, 21)) returns true.
- Method compareTo( ) method, which is defined by the Comparable interface and implemented by Date.
Date Format Using SimpleDateFormat class:
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. This class allows you to start by choosing any user-defined patterns for date-time formatting.
Example
import java.util.*;
import java.text.*;
public class ExampleDateDemo {
public static void main(String args[]) {
Date dNow = new Date( );
SimpleDateFormat ft =
new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println("Current Date: " + ft.format(dNow));
}
}
This will produce the following result:
Output
Current Date: Mon 2021.06.07 at 01:04:15 PM UTC
Simple DateFormat Format Codes
In order to specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:
Character Description
G Era designator, Example: AD
y Year in four digits, Example: 2001
M Month in year, Example: July or 07
d Day in month, Example: 10
h Hour in A.M./P.M. (1~12) Example:12
H Hour in day (0~23), Example:22
m Minute in hour 30, Example:
s Second in minute, Example:55
S Millisecond Example:234
E Day in week Example:Tuesday
D Day in year Example:360
F Day of week in month Example:2 (second Wed. in July)
w Week in year Example:40
W Week in month Example:1
a A.M./P.M. marker Example:PM
k Hour in day (1~24) Example:24
K Hour in A.M./P.M. (0~11) Example:10
z Time zone Example:Eastern Standard Time
‘ Escape for text Delimiter
” Single quote `
Date Format Using printf
Date and time formatting can be done very easily using printf method. You use a two-letter format, starting with t and ending in one of the letters of the table as shown in the following code.
Example
import java.util.Date;
public class ExampleDateDemo {
public static void main(String args[]) {
Date date = new Date(); // Instantiate a Date object
String str = String.format("Current Date/Time : %tc", date ); // display time and date
System.out.printf(str);
}
}
This will produce the following result −
Output
Current Date/Time : Mon Jun 07 13:08:21 UTC 2021
It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted. The index must immediately follow the % and it must be terminated by a $.
Example
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new Date();// Instantiate a Date object
System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);// display time and date
}
}
This will produce the following result:
Output
Due date: June 07, 2021
Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again.
Example
import java.util.Date;
public class ExampleDateDemo {
public static void main(String args[]) {
Date date = new Date(); // This statement Instantiate a Date object
System.out.printf("%s %tB %<te, %<tY", "Due date:", date); // This statement display formatted date
}
}
This will produce the following result −
Output
Due date: June 7, 2021
Date and Time Conversion Characters
Character |
Description |
c |
Complete date and time; Example: Mon May 04 09:51:52 CDT 2009 |
F |
ISO 8601 date |
D |
U.S. formatted date (month/day/year). Example: 02/09/2004 |
T |
24-hour time |
r |
12-hour time |
R |
24-hour time, no seconds. Example: |
Y |
Four-digit year (with leading zeroes). Example: |
y |
Last two digits of the year (with leading zeroes). Example: |
C |
First two digits of the year (with leading zeroes) |
B |
Full month name |
b |
Abbreviated month name |
m |
Two-digit month (with leading zeroes) |
d |
Two-digit day (with leading zeroes) |
e |
Two-digit day (without leading zeroes) |
A |
Full weekday name |
a |
Abbreviated weekday name. Example: |
j |
Three-digit day of year (with leading zeroes) . Example: |
H |
Two-digit hour (with leading zeroes), between 00 and 23 |
k |
Two-digit hour (without leading zeroes), between 0 and 23 |
I |
Two-digit hour (with leading zeroes), between 01 and 12 |
l |
Two-digit hour (without leading zeroes), between 1 and 12 |
M |
Two-digit minutes (with leading zeroes) . Example: |
S |
Two-digit seconds (with leading zeroes) |
L |
Three-digit milliseconds (with leading zeroes) |
N |
Nine-digit nanoseconds (with leading zeroes) |
P |
Uppercase morning or afternoon marker |
p |
Lowercase morning or afternoon marker |
z |
RFC 822 numeric offset from GMT |
Z |
Time zone |
s |
Seconds since 1970-01-01 00:00:00 GMT. Example: |
Q |
Milliseconds since 1970-01-01 00:00:00 GMT. Example: |
There are other useful classes related to Date and time. For more details, you can refer to Java Standard documentation.
Parsing Strings into Dates
The SimpleDateFormat class has some additional methods, notably parse( ), which tries to parse a string according to the format stored in the given SimpleDateFormat object.
Example
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
SimpleDateFormat ft = new SimpleDateFormat (“yyyy-MM-dd”);
String input = args.length == 0 ? “1818-11-11″ : args[0];
System.out.print(input + ” Parses as “);
Date t;
try {
t = ft.parse(input);
System.out.println(t);
} catch (ParseException e) {
System.out.println(“Unparseable using ” + ft);
}
}
}
A sample run of the above program would produce the following result −
Output
1818-11-11 Parses as Wed Nov 11 00:00:00 UTC 1818
Sleep for a While
You can sleep for any period of time from one millisecond up to the lifetime of your computer. For example, the following program would sleep for 3 seconds −
Example
import java.util.*;
public class SleepDemo {
public static void main(String args[]) {
try {
System.out.println(new Date( ) + “\n”);
Thread.sleep(5*60*10);
System.out.println(new Date( ) + “\n”);
} catch (Exception e) {
System.out.println(“Got an exception!”);
}
}
}
This will produce the following result:
Output
Mon Jun 07 13:13:30 UTC 2021
Mon Jun 07 13:13:33 UTC 2021
Measuring Elapsed Time
Sometimes, you may need to measure point in time in milliseconds. So let’s re-write the above example once again −
Example
import java.util.*;
public class DiffDemo {
public static void main(String args[]) {
try {
long start = System.currentTimeMillis( );
System.out.println(new Date( ) + “\n”);
Thread.sleep(5*60*10);
System.out.println(new Date( ) + “\n”);
long end = System.currentTimeMillis( );
long diff = end – start;
System.out.println(“Difference is : ” + diff);
} catch (Exception e) {
System.out.println(“Got an exception!”);
}
}
}
This will produce the following result :
Output
Mon Jun 07 13:14:57 UTC 2021
Mon Jun 07 13:15:00 UTC 2021
Difference is : 3036
GregorianCalendar Class
GregorianCalendar is a concrete implementation of a Calendar class that implements the normal Gregorian calendar with which you are familiar. We did not discuss Calendar class in this tutorial, you can look up standard Java documentation for this. The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time in the default locale and time zone. GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar. There are also several constructors for GregorianCalendar objects:
Constructor |
Description |
GregorianCalendar() |
This Constructor constructs a default GregorianCalendar using the current time in the default time zone with the default locale. |
GregorianCalendar(int year, int month, int date) |
This Constructor constructs a GregorianCalendar with the given date set in the default time zone with the default locale. |
GregorianCalendar(int year, int month, int date, int hour, int minute) |
This Constructor constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale. |
GregorianCalendar(int year, int month, int date, int hour, int minute, int second) |
This Constructor constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale. |
GregorianCalendar(Locale aLocale) |
This Constructor constructs a GregorianCalendar based on the current time in the default time zone with the given locale. |
GregorianCalendar(TimeZone zone) |
This Constructor constructs a GregorianCalendar based on the current time in the given time zone with the default locale. |
GregorianCalendar(TimeZone zone, Locale aLocale) |
This Constructor constructs a GregorianCalendar based on the current time in the given time zone with the given locale. |
Here is the list of few useful support methods provided by GregorianCalendar class:
Method |
Description |
void add(int field, int amount) |
Adds the specified (signed) amount of time to the given time field, based on the calendar’s rules. |
protected void computeFields() |
Converts UTC as milliseconds to time field values. |
protected void computeTime() |
Overrides Calendar Converts time field values to UTC as milliseconds. |
boolean equals(Object obj) |
Compares this GregorianCalendar to an object reference. |
int get(int field) |
Gets the value for a given time field. |
int getActualMaximum(int field) |
Returns the maximum value that this field could have, given the current date. |
int getActualMinimum(int field) |
Returns the minimum value that this field could have, given the current date. |
int getGreatestMinimum(int field) |
Returns highest minimum value for the given field if varies. |
Date getGregorianChange() |
Gets the Gregorian Calendar change date. |
int getLeastMaximum(int field) |
int getLeastMaximum(int field) Returns lowest maximum value for the given field if varies. |
int getMaximum(int field) |
Returns maximum value for the given field. |
Date getTime() |
Gets this Calendar’s current time. |
long getTimeInMillis() |
Gets this Calendar’s current time as a long. |
TimeZone getTimeZone() |
Gets the time zone. |
int getMinimum(int field) |
Returns minimum value for the given field. |
int hashCode() |
Overrides hashCode. |
boolean isLeapYear(int year) |
Determines if the given year is a leap year. |
void roll(int field, boolean up) |
Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields. |
void set(int field, int value) |
Sets the time field with the given value. |
void set(int year, int month, int date) |
Sets the values for the fields year, month, and date. |
Example
import java.util.*;
public class ExampleGregorianCalendarDemo {
public static void main(String args[]) {
String months[] = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”,
“Oct”, “Nov”, “Dec”};
int year; // Create a Gregorian calendar initialized with the current date and time in the default timezone.
GregorianCalendar gcalendar = new GregorianCalendar();
System.out.print(“Date: “);// Display current time and date information.
System.out.print(months[gcalendar.get(Calendar.MONTH)]);
System.out.print(” ” + gcalendar.get(Calendar.DATE) + ” “);
System.out.println(year = gcalendar.get(Calendar.YEAR));
System.out.print(“Time: “);
System.out.print(gcalendar.get(Calendar.HOUR) + “:”);
System.out.print(gcalendar.get(Calendar.MINUTE) + “:”);
System.out.println(gcalendar.get(Calendar.SECOND));
if(gcalendar.isLeapYear(year)) { // Test if the current year is a leap year
System.out.println(“The current year is a leap year”);
}else {
System.out.println(“The current year is not a leap year”);
}
}
}
This will produce the following result −
Output
Date: Jun 7 2021
Time: 1:16:54
The current year is not a leap year
For a complete list of constant available in Calendar class, you can refer the standard Java documentation.
Java Dates 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 package includes many date and time classes. For example:
- LocalDate class: Represents a date (year, month, day (yyyy-MM-dd))
- LocalTime class: Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns))
- LocalDateTime class: Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)
- DateTimeFormatter class:Formatter for displaying and parsing date-time objects
If you don’t know what a package is, read our Java Packages article .
Current Date
To display the current date, import the java.time. LocalDate class, and use its now() method:
Example
import java.time.LocalDate; // import the LocalDate class
public class ExampleMain {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // This is Create a date object
System.out.println(myObj); // This is Display the current date
}
}
The output will be:
2021-06-07
Current Time
To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method:
Example
import java.time.LocalTime; // This is import the LocalTime class
public class ExapleMain {
public static void main(String[] args) {
LocalTime myObj = LocalTime.now();
System.out.println(myObj);
}
}
The output will be:
14:47:34.528
Display Current Date and Time
In order to display the current date and time, import the java.time.LocalDateTime class, and use its now() method:
Example
import java.time.LocalDateTime; // import the LocalDateTime class
public class ExampleMain {
public static void main(String[] args) {
LocalDateTime myObj = LocalDateTime.now();
System.out.println(myObj);
}
}
The output will be:
2021-06-07T14:48:24.914
Formatting Date and Time
The “T” in the example above is used to separate the date from the time. You can use the DateTimeFormatter class with the ofPattern() method in the same package to format or parse date-time objects. The following example will remove both the “T” and nanoseconds from the date-time:
Example
import java.time.LocalDateTime; // This Import the LocalDateTime class
import java.time.format.DateTimeFormatter; //This Import the DateTimeFormatter class
public class ExampleMain {
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);
}
}
output:
Before formatting: 2021-06-07T14:50:38.049
After formatting: 07-06-2021 14:50:38
The ofPattern() method receive all of values, if you want to display the date and time in a different format. For example:
Value
yyyy-MM-dd Example: “2020-05-29″
dd/MM/yyyy Example:”29/05/2020″
dd-MMM-yyyy Example:”29-May -2020″
E, MMM dd yyyy Example:”Thu, May 29 2020”