0% found this document useful (0 votes)
14 views

Java Unit-V

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java Unit-V

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

III ECE II SEM JAVA PROGRAMMING

UNIT-V

COLLECTION FRAMEWORKS:
Collection Framework in Java Introduction to Java Collections, Overview of Java Collection
frame work, Generics, commonly used Collection classes Array List, Vector, Hash table,
Stack, Enumeration, Iterator, String Tokenizer, Random, Scanner, calendar and Properties.

Introduction to Java Collections:

Before Collections:
There are 4 ways to store values in JVM
1. Using variables : can store only one value
2. Using class object : can store multiple fixed number of values of different types
3. Using array object : can store multiple fixed number of values of same type
4. Using collections : can store multiple objects of same and different types without size
limitation

What is Collection?
In general terms a collection is a “group of objects”
Technical Definition:

Collection is a container object. It is used for storing homogeneous and heterogeneous,


unique
and duplicate objects without size limitation and further it is used for sending objects at a
time
from one class methods to other class methods as method arguments and return type with
single name across multiple layers of the project.

 Before java 1.2 it is called simply Java.util package


 From java 1.2 onwards its all classes together called as Collections Framework
 From java 5 onwards they have added new concepts called Collections and Generics

The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects.

Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set,List,Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).

A Collection represents a single unit of objects, i.e., a group.

Page 1 of 23
III ECE II SEM JAVA PROGRAMMING

Overview of Java Collection frame work:


The Collection in Java is a framework that provides architecture to store and manipulate the
group of objects.
1. Collections are the containers that groups multiple items in a single unit
2. It provides architecture to store and manipulate a group of objects
3. Using collections various operations can be performed on the data like
 searching,
 sorting,
 insertion,
 manipulation,
 deletion etc.
4. Java collection framework provide many Interfaces and classes

Page 2 of 23
III ECE II SEM JAVA PROGRAMMING

Generic, commonly used Collection classes:


Array List,
Vector,
Hash table,
Stack,
Enumeration,
Iterator,
String Tokenizer,
Random,
Scanner,
calendar and Properties.

List:
Lists are like sets. They store a group of elements. But lists allow duplicate values to be
stored.

Queues:
A Queue represents arrangement of elements in FIFO (First In First Out) order. This means
that an element that is stored as a first element into the queue will be removed first from the
queue.

Page 3 of 23
III ECE II SEM JAVA PROGRAMMING

Sets:
A set represents a group of elements arranged just like an array. The set will grow
dynamically when the elements are stored into it. A set will not allow duplicate elements. If
we try to pass for same element that is already available in the set, then it is not stored into
the set.

Maps:
Maps store elements in the form of key and value pairs. If the key is provided then it’s
correspond value can be obtained. Of course, the keys should have unique values

LIST:

1. ArrayList:

ArrayList is a class implemented using a list interface, in that provides the functionality of
a dynamic array where the size of the array is not fixed.

Syntax:

ArrayList<_type_> var_name = new ArrayList<_type_>();


ArrayList Class Methods:

ArrayList class includes the following methods:

Page 4 of 23
III ECE II SEM JAVA PROGRAMMING

 bolean add(element obj): This method appends the specified element to the end of
the ArrayList. If the element added successfully then the preceding method returns
true.
 Void add(int position, element obj):This method insert the specified element at
specified position in the ArrayList.
 element remove(int position): This method removes the element at the specified
position in the ArrayList.
 void clear(): This method removes all the elements from the ArrayList.
iterator(): returns iterator object that can be used to sequentially access elements of lists

Example:

import java.util.*;
class ArrayListDemo
{
public static void main (String args[])
{
ArrayList<String>arl = new ArrayList<> ();
arl.add("Apple");
arl.add("Mango");
arl.add("Grapes");
arl.add("Guava");
System.out.println("Contents: "+arl);
arl.remove(3);
arl.remove("Apple");
System.out.println("Contents after removing:" +arl);
System.out.println("Size of ArrayList: "+arl.size());
System.out.println("Extracting using Iterator");
Iterator it = arl.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}
}

OUTPUT:

D:\java>javac ArrayListDemo.java
D:\java>java ArrayListDemo

Contents: [Apple, Mango, Grapes, Guava]


Contents after removing:[Mango, Grapes]
Size of ArrayList: 2
Extracting using Iterator
Mango
Grapes

Page 5 of 23
III ECE II SEM JAVA PROGRAMMING

2. LinkedList

LinkedList class is an implementation of the LinkedList data structure. It can store the
elements that are not stored in contiguous locations and every element is a separate object
with a different data part and different address part.
Syntax:

LinkedList name = new LinkedList();

LinkedList implements the Collection interface. It uses a doubly linked list internally to store
the elements. It can store the duplicate elements. It maintains the insertion order and is not
synchronized. In LinkedList, the manipulation is fast because no shifting is required.

Example:

import java.util.*;
public class TestLinkedList{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

OUTPUT:

D:\java>javac TestLinkedList.java
D:\java>java TestLinkedList
Ravi
Vijay
Ravi
Ajay

3. Vector

Vector is a Part of the collection class that implements a dynamic array that can grow or
shrink its size as required.

Syntax:

public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess,

Page 6 of 23
III ECE II SEM JAVA PROGRAMMING

Cloneable, Serializable
Vector class Methods:
Vector class includes the following methods:

 Boolean add(element obj):This method appends the specified element to


the end of the vector. If the element is added successfully then the
preceding method returns true.
 void add(int position, element obj): This method insert the specified
element at the specified position in the vector.
 element remove(int position): This method removes the element at the
specified position in the vector.
 Void clear (): Thismethodremoves all the elements from the vector.

Example:

import java.util.*;
class vectorDemo
{
public static void main(String args[])
{
Vector<Integer> v = new Vector<Integer>();
int x[]={22,20,10,40,15,60};
for(int i=0;i<x.length;i++)
{
v.add(x[i]);
}
System.out.println("Vector elements");
for(int i=0;i<v.size();i++)
{
System.out.println(v.get(i));
}
System.out.println("Elements using ListIterator:");
ListIterator lit = v.listIterator();
System.out.println("In forward direction");
while(lit.hasNext())
System.out.print(lit.next()+"\t");
System.out.println("\nIn backward direction");
while(lit.hasPrevious())
System.out.print(lit.previous()+"\t");
}
}

OUTPUT:

D:\java>javac vectorDemo.java
D:\java>java vectorDemo

Page 7 of 23
III ECE II SEM JAVA PROGRAMMING

Vector elements
22
20
10
40
15
60
Elements using ListIterator:
In forward direction
22 20 10 40 15 60
In backward direction
60 15 40 10 20 22

4. Stack:

Stack is a part of Java collection class that models and implements a Stack data structure. It
is based on the basic principle of last-in-first-out(LIFO) .

Syntax:

public class Stack<E> extends Vector<E>

In Java, Stack is a class that falls under the Collection framework that extends the Vector
class.
 It also implements interfaces List, Collection, Iterable, Cloneable, Serializable.
 The class is based on the basic principle of last-in- first-out. In addition to the basic
push and pop operations.
 we must import the java.util package. The stack class arranged in the Collections
framework hierarchy, as shown below.

Creating a Stack:
If we want to create a stack, first, import the java.util package and create an object of the
Stack class.
Stack stk=new Stack();
Methods of the Stack Class:

Stack Class empty() Method


The empty() method of the Stack class check the stack is empty or not. If the stack is empty,
it returns true, else returns false.
Stack Class push() Method
The method inserts an item onto the top of the stack. It works the same as the method
addElement(item) method of the Vector class. It passes a parameter item to be pushed
into the stack.
Stack Class pop() Method

Page 8 of 23
III ECE II SEM JAVA PROGRAMMING

The method removes an object at the top of the stack and returns the same object. It throws
EmptyStackException if the stack is empty.

Example:

import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}

OUTPUT:

Ayush
Garvit
Amit
Ashish

Hashtable Class:

 Hashtable is a collection that stores elements in the form of key-value pairs. If key is
provided its corresponding value can be easily retrieved from the Hashtable. Keys
should be unique.
 The Hashtable class in Java is a concrete implementation of a Dictionary and was
originally a part of java.util package.
 Hashtable is synchronized assuring proper results even if multiple threads act on it
simultaneously.
 Java Hashtable class doesn’t allow null key or value.

Page 9 of 23
III ECE II SEM JAVA PROGRAMMING

We can write Hashtable class as:

Class Hashtable<k, v>

Where ‘k’ represents the type of key element and ‘v’ represents the type of value element.
For example, to store a String as key and an Integer object as its value, we can create the
Hashtable as,

Hashtable<String, Integer>hm = new Hashtable<>();

Hashtable class Methods:

Hashtable class includes the following methods:


 Value put(key, value): This method stores key-value pair into the Hashtable.
 Value get(Object key): This method returns the corresponding value when key is
given. If the key does not have a value associated with it, then it returns null.

Example:

import java.io.*;
import java.util.*;
class HashtableDemo
{
public static void main(String args[]) throws IOException
{
Hashtable<String, Integer>ht = new Hashtable<>();
ht.put("ajay", 50);
ht.put("sachin", 180);
ht.put("kapil", 50);
ht.put("dhoni", 88);
System.out.println("The player names: ");
Enumeration e = ht.keys();
while(e.hasMoreElements())
System.out.println(e.nextElement());
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter player name:");
String name = br.readLine();
name= name.trim();
Integer score= ht.get(name);
if(score != null)
{
int sc=score.intValue();
System.out.println(name +" scored: "+sc);
}
else System.out.println("player not found");
}
}

Page 10 of 23
III ECE II SEM JAVA PROGRAMMING

OUTPUT:

D:\java>javac HashtableDemo.java
D:\java>java HashtableDemo
The player names:
dhoni
kapil
ajay
sachin
Enter player name:
kapil
kapil scored: 50

Remove: map.remove(102); map is hash table name and 102 is key

import java.io.*;
import java.util.*;
class HashtableRemove
{
public static void main(String args[]) throws IOException
{
Hashtable<String, Integer>ht = new Hashtable<>();
ht.put("ajay", 50);
ht.put("sachin", 180);
ht.put("kapil", 50);
ht.put("dhoni", 88);
System.out.println("The player names: ");
System.out.println("Before remove: "+ ht);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Remove player name:");
String name = br.readLine();
ht.remove(name);
System.out.println("After remove: "+ht);
}
}

OUTPUT:

D:\java>javac HashtableRemove.java
D:\java>java HashtableRemove
The player names:
Before remove: {dhoni=88, kapil=50, ajay=50, sachin=180}
Enter Remove player name:
sachin
After remove: {dhoni=88, kapil=50, ajay=50}

Enumeration Class in Java:

Page 11 of 23
III ECE II SEM JAVA PROGRAMMING

 A Java enumeration is a class type.we don’t need to instantiate an enum using new
keyword, it has the same capabilities as other classes.
 The following characteristics make enum a ‘special’ class:
 enum constants cannot be overridden.
 enum doesn’t support the creation of objects.
 enum can’t extend other classes.
 enum can implement interfaces like classes.

Example:

enum Color{
RED,
GREEN,
YELLO,
BLUE;
}
public class Testenum{
public static void main(String args[])
{
Color c1=Color.RED;
Color c2=Color.GREEN;
Color c3=Color.YELLO;
Color c4=Color.BLUE;
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
System.out.println(c4);
}
}

OUTPUT:

D:\java>javac Testenum.java
D:\java>java Testenum
RED
GREEN
YELLO
BLUE

Iterator Class in Java:

 Iterators in Java are used in the Collection framework to retrieve elements one by one.
It is a universal iterator as we can apply it to any Collection object.
 By using Iterator, we can perform both read and remove operations. It is an improved
version of Enumeration with the additional functionality of removing an element.

Page 12 of 23
III ECE II SEM JAVA PROGRAMMING

 The iterator is the only cursor available for the entire collection framework. An
iterator object can be created by calling the iterator() method present in the Collection
interface.

Syntax:

Iterator itr = c.iterator();

Here “c” is any Collection object. ‘Itr’ is of type Iterator interface and
refers to “c”.

Advantages of Java Iterator:


 We can use it for any Collection class.
 It supports both READ and REMOVE operations.
 It is a Universal Cursor for Collection API.
 Method names are simple and easy to use them.
Methods of Iterator Interface in Java:
The iterator interface defines three methods as listed below:
1. hasNext(): Returns true if the iteration has more elements.
publicbooleanhasNext();
2. next(): Returns the next element in the iteration. It throws NoSuchElementException if no
more element is present.
public Object next();
3. remove(): Removes the next element in the iteration. This method can be called only once
per call to next().
public void remove();

It supports only Forward direction iteration that is a Uni-Directional Iterator.

Page 13 of 23
III ECE II SEM JAVA PROGRAMMING

Example:

import java.util.ArrayList;
import java.util.Iterator;
public class TestIterator {
public static void main(String[] args)
{
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = 0; i< 10; i++)
al.add(i);
System.out.println(al);
Iterator<Integer>itr = al.iterator();
while (itr.hasNext())
{
int i = itr.next();
System.out.print(i + " ");
if (i % 2 != 0)
itr.remove();
}
System.out.println("\n"+al);
}
}

OUTPUT:

D:\java>javac TestIterator.java
D:\java>java TestIterator
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0123456789
[0, 2, 4, 6, 8]

Stringtokenizer in Java:

 The java.util package has a class called StringTokenizer that is used to tokenize
strings.
 we can break a sentence into words and conduct several operations, such as counting
the amount of tokens or splitting a sentence into tokens.
 This StringTokenizer includes constructors and methods that allow to separate a
sentence into tokens. StringTokenizer, tokenize the string on the basis of the
delimiters provided to the String tokenizer class object.
 Whitespaces, tab, newlines, carriage returns, and form feeds are considered common
delimiters.
 These delimiters are used by default, however users can define their own delimiters
by including them as arguments in the parameter.

Page 14 of 23
III ECE II SEM JAVA PROGRAMMING

Constructors of the StringTokenizer Class

There are 3 constructors defined in the StringTokenizer class.

Methods of the StringTokenizer Class

The six useful methods of the StringTokenizer class are as follows:

Page 15 of 23
III ECE II SEM JAVA PROGRAMMING

Example-1:

import java.util.StringTokenizer;
public class TokenizerEx1{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("This is String Tokenizer program");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}

OUTPUT:

D:\java>javac TokenizerEx1.java
D:\java>java TokenizerEx1
This
is
String
Tokenizer
program

Example-2:
import java.util.*;
class StringTokenEx2
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter a line of numbers: ");
String input = s.next();
StringTokenizer st = new StringTokenizer(input,"@");
while(st.hasMoreTokens())
{
int n = Integer.parseInt(st.nextToken());
System.out.println("Number is: "+n);
}
}
}

OUTPUT:

D:\java>javac StringTokenEx2.java
D:\java>java StringTokenEx2
Enter a line of numbers:
1@45@521@23
Number is: 1
Number is: 45
Number is: 521

Page 16 of 23
III ECE II SEM JAVA PROGRAMMING

Number is: 23

Example-3:

import java.util.*;
class StringTokenEx3
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Enter a Text: ");
String input = s.next();
StringTokenizer st = new StringTokenizer(input,"#");
while(st.hasMoreTokens())
{
System.out.println("Token is: "+st.nextToken());
}
}
}

OUTPUT:

D:\java>javac StringTokenEx3.java
D:\java>java StringTokenEx3
Enter a Text:
venkat#ramana#cse#dept
Token is: venkat
Token is: ramana
Token is: cse
Token is: dept

Random class in Java:


 Random class is used to generate pseudo-random numbers in java. An instance of this class is
thread-safe. This class provides various method calls to generate different random data types
such as float, double, int.

 The algorithms implemented by Random class use a protected utility method than can supply
up to 32 pseudo-randomly generated bits on each invocation.

The Java Random class is a part of the java.util package and contains inbuilt methods to
generate random numbers.
import java.util.Random;

Page 17 of 23
III ECE II SEM JAVA PROGRAMMING

Built-in Methods

The most frequently used built-in methods for generating random numbers, are the following:

 nextInt(): Returns a random int value within the range: $ -2,147,483,648<=value<=


2,147,483, 647$
 nextInt(int range): Returns a random int value within the range: $ 0 <= value < range
$
 nextDouble(): Returns a random double value within the range: $ 0.0 <= value < 1.0
$
 nextFloat(): Returns a random float value within the range: $ 0.0 <= value < 1.0 $
 nextLong(): Returns a random long value.

Constructors:

 Random(): Creates a new random number generator

Example:
import java.util.Random;
class generateRandom
{
public static void main( String args[] )
{
Random random = new Random();
System.out.println("A random int: " + random.nextInt());
System.out.println("A random int from 0 to 49: "+ random.nextInt(50));
System.out.println("A random double: "+ random.nextDouble());
System.out.println("A random float: "+ random.nextFloat());
System.out.println("A random long: "+ random.nextLong());
System.out.println("A random boolean value : "+random.nextBoolean());
}
}

OUTPUT:

D:\java>javac generateRandom.java
D:\java>java generateRandom

A random int: 184527216


A random int from 0 to 49: 39
A random double: 0.20138075128315613
A random float: 0.5097792
A random long: -3660440709354551913
A random boolean value : true

D:\java>java generateRandom

Page 18 of 23
III ECE II SEM JAVA PROGRAMMING

A random int: 173938481


A random int from 0 to 49: 14
A random double: 0.6799569486549941
A random float: 0.5796123
A random long: -4843693657563246228
A random boolean value : false

Scanner Class in Java:


 Scanner class in Java is found in the java.util package. Java provides various ways to
read input from the keyboard, the java.util.Scanner class is one of them.
 The Java Scanner class breaks the input into tokens using a delimiter which is
whitespace by default. It provides many methods to read and parse various primitive
values.
 The Java Scanner class is widely used to parse text for strings and primitive types
using a regular expression.
 It is the simplest way to get input in Java. By the help of Scanner in Java, we can get
input from the user in primitive types such as int, long,
 double, byte, float, short, etc.

How to get Java Scanner


To get the instance of Java Scanner which reads input from the user, we need to pass the
input stream (System.in) in the constructor of Scanner class.

For Example:

Scanner sc = new Scanner(System.in);

Method Description
nextBoolean() Used for reading Boolean value
nextByte() Used for reading Byte value
nextDouble() Used for reading Double value
nextFloat() Used for reading Float value
nextInt() Used for reading Int value
nextLine() Used for reading Line value(multi Line String)
nextLong() Used for reading Long value
nextShort() Used for reading Short value
next() Used for reading string value (single line )

Example-1:
import java.util.Scanner;
public class ScannerExample {
public static void main(String args[]){

Page 19 of 23
III ECE II SEM JAVA PROGRAMMING

Scanner sc = new Scanner(System.in);


System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}

OUTPUT:

Enter your name: VENKAT


Name is: VENKAT

Example-2:
import java.util.Scanner;
public class ScannerClassExample1 {
public static void main(String args[]){
String s ="WELCOME TO CSE DEPARTMENT";
Scanner scan = new Scanner(s);
System.out.println("String: " +scan.nextLine());
scan.close();
System.out.println("--------Enter Your Details-------- ");
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.next();
System.out.println("Name: " + name);
System.out.print("Enter your Age: ");
int i = in.nextInt();
System.out.println("Age: " + i);
System.out.print("Enter your salary: ");
double d = in.nextDouble();
System.out.println("Salary: " + d);
in.close();
}
}
OUTPUT:

D:\java>javac ScannerClassExample1.java
D:\java>java ScannerClassExample1
String: WELCOME TO CSE DEPARTMENT
--------Enter Your Details--------
Enter your name: Mr.K.Chakrapani
Name: Mr.K.Chakrapani
Enter your Age: 32
Age: 32
Enter your salary: 55,000
Salary: 55000.0

Page 20 of 23
III ECE II SEM JAVA PROGRAMMING

Java Calendar Class:

 Java Calendar class is an abstract class that provides methods for converting date
between a specific instant in time and a set of calendar fields such as MONTH,
YEAR, HOUR, etc.
 It inherits Object class and implements the Comparable, Serializable, Cloneable
interfaces.
 It is an Abstract class, so we cannot use a constructor to create an instance. Instead,
we will have to use the static method Calendar.getInstance() to instantiate and
implement a sub-class.
 Calendar.getInstance(): return a Calendar instance based on the current time in the
default time zone with the default locale.
 Calendar.getInstance(TimeZone zone)
 Calendar.getInstance(Locale aLocale)
 Calendar.getInstance(TimeZone zone, Locale aLocale)

METHOD DESCRIPTION

abstract void add(int field, int amount) It is used to add or subtract the specified
amount of time to the given calendar field,
based on the calendar’s rules.

int get(int field) It is used to return the value of the given


calendar field.

abstract intgetMaximum(int field) It is used to return the maximum value for the
given calendar field of this Calendar instance.

abstract intgetMinimum(int field) It is used to return the minimum value for the
given calendar field of this Calendar instance.

Date getTime() It is used to return a Date object representing


this Calendar’s time value.

Fields
There are many fields in the Calendar class. Here are some of the most important ones:

 YEAR: The field indicating the year.


 MONTH: The field indicating the month.
 DAY_OF_MONTH: The field indicating the day of the month.
 DATE: Synonym for DAY_OF_MONTH.
 HOUR: The field indicating the hour of the day.
 MINUTE: The field indicating the minute within the hour.
 SECOND: The field indicating the second within the minute.
 MILLISECOND: The field indicating the millisecond within the second.

Page 21 of 23
III ECE II SEM JAVA PROGRAMMING

Example-1: (get time)

import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
System.out.println("Current Calendar's Year: " + calendar.get(Calendar.YEAR));
System.out.println("Current Calendar's Day: " + calendar.get(Calendar.DATE));
System.out.println("Current MINUTE: " + calendar.get(Calendar.MINUTE));
System.out.println("Current SECOND: " + calendar.get(Calendar.SECOND));
calendar.add(Calendar.DATE, -5);
System.out.println("5 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 2);
System.out.println("2 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 3);
System.out.println("3 years later: " + calendar.getTime());
}
}
OUTPUT:

D:\java>javac CalendarExample1.java
D:\java>java CalendarExample1
The current date is : Fri Jun 07 18:05:13 IST 2024
Current Calendar's Year: 2024
Current Calendar's Day: 7
Current MINUTE: 5
Current SECOND: 13
5 days ago: Sun Jun 02 18:05:13 IST 2024
2 months later: Fri Aug 02 18:05:13 IST 2024
3 years later: Mon Aug 02 18:05:13 IST 2027

Example-2: ( set time )

import java.util.Calendar;
public class CalendarExample2 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("****BEFORE SET TIME****");
System.out.println("The current date is : " + calendar.getTime());
System.out.println("Current Calendar's Year: " + calendar.get(Calendar.YEAR));
System.out.println("Current Calendar's Day: " + calendar.get(Calendar.DATE));
System.out.println("Current MINUTE: " + calendar.get(Calendar.MINUTE));
System.out.println("Current SECOND: " + calendar.get(Calendar.SECOND));
calendar.set(Calendar.YEAR, 2023);
calendar.set(Calendar.MONTH, Calendar.MAY);
calendar.set(Calendar.DAY_OF_MONTH, 5);
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 30);

Page 22 of 23
III ECE II SEM JAVA PROGRAMMING

calendar.set(Calendar.SECOND, 0);
System.out.println("****AFTER SET TIME****");
System.out.println("The current date is : " + calendar.getTime());
System.out.println("Current Calendar's Year: " + calendar.get(Calendar.YEAR));
System.out.println("Current Calendar's Day: " + calendar.get(Calendar.DATE));
System.out.println("Current MINUTE: " + calendar.get(Calendar.MINUTE));
System.out.println("Current SECOND: " + calendar.get(Calendar.SECOND));
}
}

OUTPUT:

D:\java>javac CalendarExample2.java
D:\java>java CalendarExample2
****BEFORE SET TIME****
The current date is : Fri Jun 07 18:16:17 IST 2024
Current Calendar's Year: 2024
Current Calendar's Day: 7
Current MINUTE: 16
Current SECOND: 17
****AFTER SET TIME****
The current date is : Fri May 05 12:30:00 IST 2023
Current Calendar's Year: 2023
Current Calendar's Day: 5
Current MINUTE: 30
Current SECOND: 0

Page 23 of 23

You might also like