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

Exploring Java Language_3rdUnit_Day3

The document provides an overview of several Java classes including StringTokenizer, BitSet, HashMap, and date/time handling with java.util.Date, java.time, and Calendar. It highlights the usage, key methods, and examples for each class, emphasizing the advantages of newer classes over legacy ones. Additionally, it discusses operations and functionalities that can be performed with these classes, showcasing their importance in Java programming.

Uploaded by

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

Exploring Java Language_3rdUnit_Day3

The document provides an overview of several Java classes including StringTokenizer, BitSet, HashMap, and date/time handling with java.util.Date, java.time, and Calendar. It highlights the usage, key methods, and examples for each class, emphasizing the advantages of newer classes over legacy ones. Additionally, it discusses operations and functionalities that can be performed with these classes, showcasing their importance in Java programming.

Uploaded by

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

String Tokenizer

The StringTokenizer class in Java is part of the java.util package and is used to break a
string into tokens. It's a legacy class, and while it's still available for use, newer classes like
String.split() or Scanner are generally preferred for more robust and flexible string parsing.

Key Points about StringTokenizer:

 Legacy Class: Introduced in early versions of Java, before regular expressions were
added to the language.
 Breaking Strings: Used to break a string into tokens based on specified delimiters.
 Tokens: Each token is a substring separated by one or more delimiters.

Constructors:

1. StringTokenizer(String str): Constructs a tokenizer for the specified string.


2. StringTokenizer(String str, String delim): Constructs a tokenizer for the specified
string, using the specified delimiter.
3. StringTokenizer(String str, String delim, boolean returnDelims): Constructs a
tokenizer for the specified string, using the specified delimiter, and specifies whether
to return the delimiters as tokens.

Common Methods:

 hasMoreTokens(): Returns true if there are more tokens.


 nextToken(): Returns the next token.
 nextToken(String delim): Returns the next token, using the specified delimiter.
 countTokens(): Returns the number of remaining tokens.

Example of StringTokenizer:

import java.util.StringTokenizer;
public class StringTokenizerExample {
public static void main(String[] args) {
String str = "Hello,World,Java,Programming";
StringTokenizer st = new StringTokenizer(str, ",");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}

In this example, the string "Hello,World,Java,Programming" is broken into tokens using the
comma "," as the delimiter. The StringTokenizer iterates over each token and prints it.
Comparison with String.split():

While StringTokenizer is useful, the String.split() method introduced in Java 1.4 is generally
preferred because it offers more flexibility through regular expressions.

Example using String.split():

public class StringSplitExample {


public static void main(String[] args) {
String str = "Hello,World,Java,Programming";
String[] tokens = str.split(",");

for (String token : tokens) {


System.out.println(token);
}
}
}

In this example, the String.split() method splits the string based on the comma delimiter, and
each token is printed using an enhanced for loop.

The StringTokenizer class is a legacy class used to break a string into tokens. Although still
available, newer methods like String.split() and Scanner are typically preferred for their
flexibility and ease of use. If you need to work with simple tokenization tasks,
StringTokenizer can still be handy.
BitSet

The BitSet class in Java is part of the java.util package and is used to create a dynamic array
of bits, which can grow as needed. It is an efficient way to handle sets of bits or booleans
where space efficiency is critical. Here’s an in-depth look at the BitSet class:

Key Characteristics of BitSet

 Dynamic Size: A BitSet can grow as needed to accommodate more bits.


 Efficient Storage: Internally uses a long array to store bits, providing space efficiency.
 Operations: Supports logical operations such as AND, OR, XOR, and NOT.

Common Constructors

1. BitSet(): Creates a new BitSet with a default initial size of 64 bits.


2. BitSet(int nbits): Creates a new BitSet with the specified initial size.

Key Methods

 set(int bitIndex): Sets the bit at the specified index to true.


 clear(int bitIndex): Clears the bit at the specified index, setting it to false.
 get(int bitIndex): Returns the value of the bit at the specified index.
 flip(int bitIndex): Flips the bit at the specified index.
 cardinality(): Returns the number of bits set to true.
 and(BitSet set): Performs a logical AND of this target bit set with the argument bit
set.
 or(BitSet set): Performs a logical OR of this bit set with the bit set argument.
 xor(BitSet set): Performs a logical XOR of this bit set with the bit set argument.
Example of BitSet:

import java.util.BitSet;

public class BitSetExample {


public static void main(String[] args) {
BitSet bitSet1 = new BitSet();
BitSet bitSet2 = new BitSet();

// Setting bits
bitSet1.set(0);
bitSet1.set(2);
bitSet1.set(4);

bitSet2.set(1);
bitSet2.set(2);
bitSet2.set(3);

// Printing the bit sets


System.out.println("BitSet1: " + bitSet1);
System.out.println("BitSet2: " + bitSet2);

// Logical AND
BitSet andSet = (BitSet) bitSet1.clone();
andSet.and(bitSet2);
System.out.println("AND: " + andSet);

// Logical OR
BitSet orSet = (BitSet) bitSet1.clone();
orSet.or(bitSet2);
System.out.println("OR: " + orSet);

// Logical XOR
BitSet xorSet = (BitSet) bitSet1.clone();
xorSet.xor(bitSet2);
System.out.println("XOR: " + xorSet);

// Flip bit at index 1


bitSet1.flip(1);
System.out.println("BitSet1 after flip: " + bitSet1);
}
}

Advantages of Using BitSet

 Memory Efficiency: It uses a compact representation to store bits, making it memory


efficient.
 Fast Operations: Logical operations on bit sets are generally very fast due to the
internal representation using a long array.
 Dynamic Growth: BitSet can grow automatically as more bits are needed, unlike
fixed-size arrays of booleans.

The BitSet class in Java is a powerful and efficient way to manage sets of bits. It provides a
range of operations that allow for efficient manipulation of bits, making it suitable for
scenarios where space efficiency and fast operations are important.
Map & HashMap
import java.util.HashMap;

public class Maps {


public static void main(String[] args) {

HashMap<String, Integer> empIds = new HashMap<>();


empIds.put("Raju", 12345);
empIds.put("Basha", 54321);
empIds.put("Antony", 86421901);

System.out.println(empIds);
System.out.println(empIds.get("Basha"));
System.out.println(empIds.containsKey("George"));
System.out.println(empIds.containsValue(86421901));

empIds.put("Raju", 99999);
System.out.println(empIds);

empIds.replace("Joker", 111);
System.out.println(empIds);

empIds.putIfAbsent("John", 222);
System.out.println(empIds);

empIds.remove("John");
System.out.println(empIds);
}
}

Output:
{Basha=54321, Raju=12345, Antony=86421901}
54321
false
true
{Basha=54321, Raju=99999, Antony=86421901}
{Basha=54321, Raju=99999, Antony=86421901}
{Basha=54321, John=222, Raju=99999, Antony=86421901}
{Basha=54321, Raju=99999, Antony=86421901}
Date & Time

Handling dates in Java can be accomplished in a few ways, depending on the version of Java you're
using. Here's an overview of two common approaches:

Using java.util.Date

java.util.Date is one of the earliest classes used to handle dates in Java, although it's largely
considered obsolete now. Still, it's good to know for historical context.

import java.util.Date;

public class DateExample {


public static void main(String[] args) {
Date d = new Date();
System.out.println("Current Date: " + d);
}
}

Output:
Current Date: Mon Dec 30 20:28:14 UTC 2024

Using java.time (Java 8 and later)

With Java 8, a new date and time API was introduced to address many of the shortcomings of the
older Date and Calendar classes. This API is more powerful and flexible.

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class NewDateExample {


public static void main(String[] args) {
// Current date
LocalDate currentDate = LocalDate.now();
System.out.println("Current Date: " + currentDate);

// Current date and time


LocalDateTime currentDateTime = LocalDateTime.now();
System.out.println("Current Date and Time: " + currentDateTime);

// Formatting date and time


DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-
dd HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);
System.out.println("Formatted Date and Time: " +
formattedDateTime);
}
}

Output
Current Date: 2024-12-30
Current Date and Time: 2024-12-30T20:28:50.634807233
Formatted Date and Time: 2024-12-30 20:28:50
The java.time package includes several classes like LocalDate, LocalTime, LocalDateTime,
and DateTimeFormatter that make working with dates and times much easier and more
intuitive.

Calendar

The java.util.Calendar class in Java is used for manipulating dates in a more flexible way
than the original java.util.Date class. Here’s how you can use it:
Basic Usage

import java.util.Calendar;

public class CalendarExample {


public static void main(String[] args) {
// Create a calendar instance
Calendar calendar = Calendar.getInstance();

// Get the current date and time


int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // January is 0, so
add 1
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

System.out.println("Current Date and Time: " + year + "-" + month +


"-" + day + " " + hour + ":" + minute + ":" + second);
}
}

Output
Current Date and Time: 2024-12-30 20:31:9

Adding or Subtracting Time

You can easily add or subtract time to/from a Calendar instance:

import java.util.Calendar;

public class CalendarAddExample {


public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();

// Print the current date


System.out.println("Current Date: " + calendar.getTime());

// Add 5 days to the current date


calendar.add(Calendar.DAY_OF_MONTH, 5);
System.out.println("Date after adding 5 days: " +
calendar.getTime());

// Subtract 3 months from the current date


calendar.add(Calendar.MONTH, -3);
System.out.println("Date after subtracting 3 months: " +
calendar.getTime());
}
}

Output:
Current Date: Mon Dec 30 20:33:27 UTC 2024
Date after adding 5 days: Sat Jan 04 20:33:27 UTC 2025
Date after subtracting 3 months: Fri Oct 04 20:33:27 UTC 2024

Setting Specific Date and Time


You can set the Calendar to a specific date and time:

import java.util.Calendar;

public class CalendarSetExample {


public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();

// Set a specific date: 25th December 2024


calendar.set(Calendar.YEAR, 2024);
calendar.set(Calendar.MONTH, Calendar.DECEMBER);
calendar.set(Calendar.DAY_OF_MONTH, 25);
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);

System.out.println("Specific Date and Time: " +


calendar.getTime());
}
}

Output:
Specific Date and Time: Wed Dec 25 10:30:00 UTC 2024

Comparing Dates
You can also compare dates using the Calendar class:

import java.util.Calendar;

public class CalendarCompareExample {


public static void main(String[] args) {
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();

// Set calendar2 to a specific date


calendar2.set(2024, Calendar.DECEMBER, 25);

if (calendar1.before(calendar2)) {
System.out.println("calendar1 is before calendar2");
} else if (calendar1.after(calendar2)) {
System.out.println("calendar1 is after calendar2");
} else {
System.out.println("calendar1 is equal to calendar2");
}
}

Output:
calendar1 is after calendar2

You might also like