Other Utility classes:
1. StringTokenizer
🔹 Purpose: Used to break a string into tokens using a delimiter (default is space).
🔹 Code Example:
import [Link];
public class TokenExample {
public static void main(String[] args) {
String sentence = "Java is simple and powerful";
StringTokenizer st = new StringTokenizer(sentence);
while ([Link]()) {
[Link]([Link]());
}
}
}
🔹 Explanation:
- StringTokenizer breaks the sentence into words.
- hasMoreTokens() checks if more tokens are available.
- nextToken() returns the next token from the string.
2. Date ([Link])
🔹 Purpose: Used to get the current date and time.
🔹 Code Example:
import [Link];
public class DateExample {
public static void main(String[] args) {
Date currentDate = new Date();
[Link]("Current date and time: " + currentDate);
}
}
🔹 Explanation:
- new Date() gives the current date and time.
- The toString() method prints it in a readable format.
3. Calendar ([Link])
🔹 Purpose: Used to get individual date components.
🔹 Code Example:
import [Link];
public class CalendarExample {
public static void main(String[] args) {
Calendar calendar = [Link]();
[Link]("Year: " + [Link]([Link]));
[Link]("Month: " + ([Link]([Link])
+ 1));
[Link]("Day: " +
[Link](Calendar.DAY_OF_MONTH));
}
}
🔹 Explanation:
- [Link]() returns the current date.
- Months are zero-based (January = 0), so we add 1.
4. GregorianCalendar
🔹 Purpose: A subclass of Calendar for more specific operations like leap year check.
🔹 Code Example:
import [Link];
public class GregorianCalendarExample {
public static void main(String[] args) {
GregorianCalendar gc = new GregorianCalendar();
[Link]("Current Date: " + [Link]());
[Link]("Year: " + [Link]([Link]));
[Link]("Is Leap Year: " +
[Link]([Link]([Link])));
}
}
🔹 Explanation:
- getTime() returns the current date.
- isLeapYear(year) checks if the given year is a leap year.
5. Scanner
🔹 Purpose: Used to take input from the user.
🔹 Code Example:
import [Link];
public class ScannerExample {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]();
[Link]("Hello, " + name + "! You are " + age + " years
old.");
}
}
🔹 Explanation:
- Scanner reads input from the keyboard.
- nextLine() reads a full line, nextInt() reads an integer.