0 ratings 0% found this document useful (0 votes) 28 views 23 pages Java Unit 5
The document provides an overview of various Java classes including ArrayList, Vector, HashSet, Hashtable, Stack, Queue, StringTokenizer, Random, Scanner, and Calendar, detailing their features, syntax, and examples of usage. Each class is explained with key characteristics such as synchronization, element storage, and methods available for manipulation. The document serves as a comprehensive guide for understanding these data structures and their applications in Java programming.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save java unit 5 For Later YU musiite avULatayrot Lias9 wat exeINE
ArrayList Class in Java - Explained with Example
121 package It provides a resizable array, which means
The AreayList class in Java is part ofthe 5
elements can be added or removed dynamically itis not synchronized, and allows duplicate elements
Key Features of ArrayList :
+ Maintains insertion order
+ Allows random access like 2r2ys)
+ Can store duplicate values
+ Grows automatically when more elements ate acded
Basic Syntax:
aerayListcrype> Liste = new ArreyLtseeTyperO3
You can use import jave-uéil.Arraylist; to use iin your program.
Example:
Seport Jovautdareaytists
public class ArreyListexemple { +Example:
wa coy Brat
Import Java-utlL-arrayltsts
public class ArrayListixample {
public static void main(steing{] args) <
arraylistestringy fruits = new arraylisto()s
frults.add("Apple");
‘ruits.add(“Banana"):
‘Frusts.a4("Nongo")s
Fruits edd(“Bane
"5 // Duplicates are allowed
1 Oisplaying the Arraytist
systen.out printin("Fruits list: “+ fruits):
systen.out.printin("First fruits ~ 4 frusts.ger(o))s
11 Removing on elenent
feulte.renove("Banana"); // Renove
systen.out.printin("After removing Banana: ~ + rusts):
U Checking size
systen.out.printia("size of List: * + frults.size());
1 seenating through the List
Systen-out-printla(“Al fruits");
for (String fruit + fruits) {
systen.out.printin fruit);‘Common Methods in ArrayList:
Method Description
adele) ‘Acids element tothe end
sao(int sngee, & 6) ‘Aid element at specific index
get(int tndox) Ratuins element at index
renove(0bsect 0) Removes first cccumence of object
renove(ant ings) Removes clement at index
set) Ratuens sumber of elements
contains(obiect 0) ‘Checks if element isin st
aear() Removes all elementsDetenbe about vectareate wth exam
Vector Class in Java ~ Description with Example
‘he vecton classics part of the Jaus.ut ll pactage itimplemants a growable array of object anc
synchronized making i hresd-sfe (unlike serayLtst)
Key Features of Vector:
+ Can grow or shrink dynamically
+ Maintains insertion order
+ Allows duplicate elements
+ Thread-ste(omchronizad methods)
+ Slower than ieayList in single-tweaded environments
Basic Syntax:
Use fapare Javawees. vectors to ince it
Example:=a
Amport java-uti.vectors cor Beat
public class vectorexauple {
public static void mein(String(] args) {
U/ Creating 2 Vector of Integers
‘vectorcinceger> numbers = new veczor4>()s
1 Adding elements
nurbers.2dd(10);
unbers add(29);
unbersadd(38);
runbers.2d4(20)3 // oypltcates ob lowed
1 visplaytng elements
System.out.println("muabers: * + sunbers);
UM Accessing elenent
systen.out.printIn("Elenent at index 2: " + munbers.get(2)):
1, pesoving an ebement
nurbers.renove( integer valueof(2e)): // Renoves First occurrence of 29
Systen.out.println(*After removing 20: " + mumbers);
M1 Checking size
Systen.out.printin("size: ~ + numbers.size())s
U1 Teerating over the vector
Systen.cut.println(“All elements:");
For (Integer num: numbers) {
‘Systen.out.printin(num):Common Methods in Vector:
Method Description
ae ®) ‘Adds element to end
adatint insexs £ 6) Aids element at index
estlint insex) Returns element at index
renove(obiect 0) Removes frst occurence
rewove(int index) Removes element at index
260) Returns current size
cortaane(onjact 9) Checks if lement i in vector
ausro) Clears all elements
seem) checks if ectoris emoty
sirsteleent©) Returns fst element
Aastetenent) Returns last elementExplain about Hashset cass with example
HashSet. Class in Java ~ Explanation with Example
‘The fastset cles in Jova is part ofthe java.util peckage. implements the Set interface, backed by @
hashtable, and is used to store unique elements only (no duplicate)
Gi Key Features of Hashset:
+ Does nt alow duplicate elements
Docs not maintain insertion order
+ Allows rl values
+ Faster aces (uses hashing)
Not synchronized (not thread-safe by defult)
Basic Syntax:
HeskSetctype> settlone = new HeshSet()5
Make sure toimportit using: dmport java.util Wachsee;
Examole:Example:
= cay vem
Anport javacut th tashsets
public class HashectExanple {
public state vold waln(steteg(] a
1) Creating a MoshSet of Strings
aansarcsertng> coureetes = eu ashser63()s
of
1 dang eLenents
ounces. ac4(“inst
countetes.244("USH") 5
couneetese44("cermany")s
counter edd(“Indis"); // nuplicate, will be nares
17 Displaying the teshset
systen.out.printla("Countelest * + countries):
1 checking for on elenent
Systen.ovt.println("Contains USA? * + coumtedes.contalns("USA"))s
1 removing on elenent
countetes.renevec"serna09")3
Syten.out.printla("Atter cenoving Germany: ~ + countries):
17 teevating usteg enhanced for Loop
systen.sut-prénela(“all countries")
for (string country + counertes) (
Syaten.out-println(countey)Explain about Hashtable class with example
Hashtable Class in Java - Explanation with Example
The Hashtable class in Java is patt ofthe javs.ueit package ancl implements the Map interface. It stores
key-value pairs and uses hashing to retrieve values efficiently ke @ dictionary, each key maps to exactly
cone val,
Key Features of Hashtable:
+ Stores cata in key-value eis
+ Keys are unique; valves can be cups
+ Syehronized thread-safe}
+ Does not allow nul keys or nll values
Slower than Wsehtap due to synchronization
Basic Syntax:
table = new Hashtable)
You must import it Snport jeva-util.Heshtabies
Example:publée class tashtabletsonple (
public static void nein(stringl] eras) {
1 Creating @ Hashtable with Integer heys and String values
Herhtablecinteger, String> students = new Mechtebleco();
U1 siting key-value pairs
‘students put(2e1, “Alice
students.put(ie2, “Sob");
students put(103, “Charlie");
1 Displaying the Hoshtoble
systen.cut.printin("students: * + students);
U1 secessing a volue using key
Systen.out printin( “Student with 1D 182: ~ + students. get(102));
1) Renoving a hey-volue pair
“students .renove(161)3
Systen.out.printin( "After comoving 10 101: * + students);
11 checking ‘if @ hey exists
Systen.out.printin( "contains 30 103? * + students. containekey(193));
1 Tearating over the Hashtable
systen.out.printin("All students:")
for (Integer id + students beySet()) {
systea.out.printin("s0: "+ 1d +,
ane: * + students. get(14)):
8 coypublic class StackOperations {
Ocey Year
public static void main(stringL] args) £
1 Creating a Stack of Integers
stackernteger> stack ~ new Stacke>()3
Uf pushing elenents (insertion)
stack.push(22)3
erack.push(22);
erack.push(32);
stack.push(4a)3
WU visplaytng the stack
systen.out.println("stack: " + stack);
U, Peskeing the top elesent (without removing)
systen.out.println(*Tap element (peck): * + steck.peck());
11 Popping elements (renovel. from top)
systen.out.printIn("Popped elenent: " + stack.pop())s
system.out.printin("Stack after pop: * + stack)s
1 Checking if stack is empty
systen.out.println(*Ts stack enpty? " + stack dstmpty()):
// Searching for an elenent (returns 1-bazed position from top, -2 if not found)
systen.out.printin("Position of 20 from top: ” + stack.search(20))s
systen.out.printin( “Position of 0 from top: ~ + stack.zearch(50))s
1) Size of the stack
system.out.printin("size of stack:
© 4 ecack.etz2()))
Uf reeraving through stack
systen.out.printin(“All elesents in stac
for (int num: stack) {
systen.out.println(aun)sSco Beet
Sport jeva.util.LinkedList;
import java.util. Queves
public class queueoperations {
public static void main(Stringl) orgs) {
UI Creating 2 Quewe of Strings
Quevecstring> queue ~ new LinkedListoOe
UI adding elenents to the queue (enquewe)
queve.offer("ALice");
queve.otfer(“Hob”)s
queve.offer("Cherlie");
queve.offer("Datsy");
U7 Displaying the quewe
systen.out.println("queve: " + queue);
U1 Peeking at the front element (without removing)
syster
out println("Front element (peek): " + queve.pesk())s
17 wenoving clenents from the queue (dequeve)
Systen.outprintln("Reoved: " + queue.poll())5
system.out.printin("queve after poll: ~ + queue);
LI Checking if queue ix empty
System.out.println("rs queue enpty? * + queue. tstapty())5
W Size of the queue
system.out.printin("size of queue: " + queue.size())3
U Tterating over the queue
Systen.out.printla("AL1 elements in queve:
for (string rane + queue) {
systen.out.printin(nane):‘¢ StringTokenizer Class in Java - Explanation with Example
‘The stringTokentzer classi Java (rom the java.util package) is used to break a string Into tokens
(smaller pars), often using delimiters ike spaces, commas, or symbols
Key Features of StringTokenizer:
+ Splits sting into muiple tokens
+ Default delimiter is space
+ You can specify custom delimiters fg. 5, 5, ~.ete)
+ Its @ legacy class, sil used but replaced in most cases by string.splE() oF sesaner
Constructor Syntax:
SteingTokentzer st - new StringTokentzer(String str): // uses defoult deLtntter (space
Stringlokenizer st = nes Stringlokentzer(String atr, String deliniter); // custow delinite
(String str, String deliniter, boolean returnDelins);
Example 1: Using Default Delimiter (space)
import jo
util stringtabe
public class Tokentzertxamplet {
public static veid main(String!)
mt
ce eee epee
Stringlokenizer st ~ new StringTokents
ence):
Ask anythingExample 1: Using Default Delimiter (space)
Saport Sova. atl string
public less TkericerEramptet {
ponlic ctatte vous waiestrtnl] are)
system utiprinsin(stenss)y
bile (eecasretokene() {
Syetenut-printin(et-nxtToten();
,
‘Output:Example 19 Custom Delimiter (comma)
Lnpant favauthl. stetagrakentoer;
public class tokenizerexaple2 (
public static volé min(string{]
StringTokendzer st = nen Stringlotenizer(éat
systen.out.printha("#r2")5
iste (st-hastoratokens()
systenout printn(st.nextToten())5
Output:ftom the aus ues package:
Java Program Using Random Class:
sapore jase
public less Rendoniers
public statte vold mala(Sttag(] args) (
andor rand = new Radon(Dt
syaten.otsprintn(10 Rano munbers between © and 200");
for Gt £= OF £¢ 18; HH
ne candunner = rand.nextIat (181); // 0 80 100 Cnc
syctn.out.gratln(candntunbor)
>
?
)
Explanation:
1+ Random rand = ne Randn()i ~ creates 2 rendom number oeneater.
“+ rantnost T0388) — generates a number from Ota 100 inclusive (upper bound i exch, £0 we paseDiscuss about Scanner ase wth expe
‘© Scanner Class in Java ~ Explanation with Example
The Serer dasis part ofthe Jewitt pacage and isused 0 vad input fom vous sourees,
including Keyboard (console les stings.
Gi Key Features of scanner?
Unis mani for keyboard inp
1 Suppons reading aterent data ype nk, date, hein, et
1 Canes input using deren: deters (tut whitespace)
Basic Syntax:
puet Jae. Sarees
‘Common Methods:
ethod eon
seve) sesesacounExample 1: Reading Different Data Types from Keyboard
public class seannerexample {
public static vold nain(Stringl] args) (
Seamer sc = new Scamer(Systen.in)s
system outsprint("enter an integers 2
int mum = seanextInt 5
spstemout.print(“Enter a decimal numbers °)s
double d = sc.nextDosble()s
snerttineOs
‘system out peine("enter your sane: 5
Sering ane = sc.nexttine()s
Syatenout.printla("integers * + num):
System out peinein(Decinel: * + 4):
system out peinela(iones * + nane)z
sesetose()4© Example 2: Reading Words Separated by Space
Scanner sc = new Scaner(System.ims
systemout pine ("enter tno words: *):
String word = sesnert()s
string word = se.next()t
Systensovtprintin("You entered: " ¢ ord #* and "+ ward)
Inout
Output
Gt:
1+ Use nextLine() when you want tread a whole sentence or HineEvaluate Calendar clas with example
Celendar Class in Java - Explanation with Example
‘Te Catencer ass in Java (om java. utd package) Is an abstract cass used to peoxm operations
‘elated to date and time, such 25 getting er setting fos ike year, month, day, hour, minute, ete
Key Features of Calendar:
“+ Suppor: date and time manipulation
1+ Provides constants like calender. VER, Calendar.WEATH, et.
‘+ Replaced in modern lava by Sava,tine,LocaiDate and LocelbeteTine ave 8+), but stil widely used in
legacy systems
+ Can be subelassed by Grepordancatender for typical usage
Creating a Calendar Instance:
calendar gettnetance()s
Example: Disolav Current Date and Time Usina CalendarExample: Display Current Date and Time Using Calendar
iva 2 cor
Inport Java.uttl calendar:
public class CalendorExample (
public static vold main(string() args) {
Calendar cal = Calendar. getanstance()s
Syatenout.printin("Corrent Date and Tie Infos"):
Syaten-out.printla( "Year: * + celaget(Calender.YE8R)):
Syaten.out.println( ‘Month: ~ + (cal-get(Calendar MONTH) +19); //
Systen.out.println( "Day: "+ cal get(Calender.DAY_0F MONTH):
Syaten-out printin( "Your: * + cal-get(Calender.H0U8));
Syaten.out.println( Minute: " + cel.get( Calender MIMJTE))5
Sytem out préneln( “Second
Systen.out.println("AN/O: * + (cal get(Calender.A9 PH)
4 eal get(celendaSEco10));
Setting a Specific Date
cal. set(Calendar. YEAR, 2225);
cal.ret(Calendar MONTH, Calendar OECENBER): // on 23
‘al. set(Calender.08¥_oF nom, 25):
m3"© Generics in Java ~ Explanation with Example
{ene allow you to writ type-safe and reusable code, nroduces in Java 5, generics enable cesses,
Invertaces, and metnods to operate on objects of various types whe proving compile-time type satey.
‘(@ Why Use Generics?
+ Type Safety Detects errs compile tine rather han untime,
+ Code Reusblity ame code wors with citerent datatypes.
+ Elminates Type Casting: No ned fr xpi castng when reviving eect.
G Generic Class Example
crete
public vod 20 value) {
?
pablte T get {
,
Usage:
ec teleteeteneeteeeeTot
public state vold aato(String(] age) {
Uf sox 20 bald roger
onctnteger> into = new Boneo()5
snttox.set(100)5
Systen-out.printin("Integer values ~ + InBox. g8t0)):
Uf sox 29 ola Serta
ontString> stron = new Bor<0(35
strfowset("ello Gereries"}s
systen.out.printn('string value: " + strtoxet());@ Generic with Collections
public class Genericcollectionéxample {
public static void nein(String{] arse) {
aerayListestring? Hat = new ArrayList); // generte enc
Lsteada¢"apple")s
Hetsadé("asnana”)s
for (string fruit + 1st) {
Systen.out.printin Fruits
?
Bounded Generics Example
class Calculatorct extends Maber> (
public dovble square(T mm) (
return nun.doublevalue() * nun.dovblevalue();
)