Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Utility and Common Classes

Tech May 18 4

The Arrays class is a utility class for array operations, providing numerous static methods to work with arrays efficiently.

  • toString(): Converts an array to a string representation
  • sort(): Sorts elements in an array
  • copyOf(): Creates a copy of an array with specified length

Date Class

The Date class represents a specific instant in time.


// Current system time
Date currentTime = new Date();
System.out.println(currentTime);

// Get milliseconds since January 1, 1970, 00:00:00 GMT
long milliseconds = currentTime.getTime();
System.out.println(milliseconds);

Note: Most methods in the Date class are deprecated and replaced by methods in the Calendar class.

DateFormat Class

The DateFormat class is an abstract class for formatting and parsing dates in a language-independent manner. It's commonly used through its subclass SimpleDateFormat.

Formatting (Date to String)


// Create a date formatter
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(currentTime);
System.out.println(formattedDate); // e.g., 2023-05-15 14:30:45

Parsing (String to Date)


// Parse string to date
Date parsedDate = new Date();
try {
    parsedDate = formatter.parse("2022-12-25 10:15:30");
} catch (ParseException e) {
    e.printStackTrace();
}

System.out.println(parsedDate); // Sat Dec 25 10:15:30 CST 2022

BigDecimal Class

The BigDecimal class is used for precise decimal calculations, avoiding floating-point precision issues.


// Avoid precision loss by using strings
double value1 = 0.1;
double value2 = 0.2;

// Convert to BigDecimal using strings to avoid precision issues
BigDecimal decimal1 = new BigDecimal(Double.toString(value1));
BigDecimal decimal2 = new BigDecimal(Double.toString(value2));
BigDecimal result = decimal1.add(decimal2);
System.out.println(result.doubleValue());

Common Methods

  • add(): Addition
  • subtract(): Subtraction
  • multip(): Multiplication
  • divide(): Division
  • doubleValue(): Convert to double

Handling Division with Remainders


BigDecimal dividend = new BigDecimal("11");
BigDecimal divisor = new BigDecimal("3");
// Round half up, with 4 decimal places
BigDecimal divisionResult = dividend.divide(divisor, 4, BigDecimal.ROUND_HALF_UP);
System.out.println(divisionResult.doubleValue()); // 3.6667

Calendar Class

The Calendar class provides methods for converting between specific instants in time and calendar fields. It replaced many deprecated Date methods.

Creating and Getting Values


// Create a Calendar instance
Calendar calendar = Calendar.getInstance();

// Get year
int currentYear = calendar.get(Calendar.YEAR);

// Get month (note: January is 0, so we add 1)
int currentMonth = calendar.get(Calendar.MONTH) + 1;

// Get day of month
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

System.out.println(currentYear + "年" + currentMonth + "月" + dayOfMonth + "日");

Common Methods

  • add(): Add or subrtact time units
  • set(): Set a specific field value
  • get(): Get a field value
  • getTime(): Convert to Date object

Modifying Calendar


// Create Calendar instance
Calendar cal = Calendar.getInstance();

// Get current year
int year = cal.get(Calendar.YEAR);

// Set year to 2020
cal.set(Calendar.YEAR, 2020);

// Add 2 days
cal.add(Calendar.DAY_OF_MONTH, 2);

// Convert to Date
Date modifiedDate = cal.getTime();
System.out.println(modifiedDate);

Math Class

The Math class contains basic mathematical operations, with all methods being static.

Basic Operations

  • abs(): Absolute value
  • ceil(): Smallest integer greater than or equal to the argument
  • floor(): Largest integer less than or equal to the argument
  • round(): Closest long to the argument (rounding half up)

Examples


double absValue = Math.abs(-5.7); // 5.7
double ceilValue = Math.ceil(3.3); // 4.0
double floorValue = Math.floor(3.7); // 3.0
long roundedValue = Math.round(5.5); // 6

System Class

The System class provides system-level operations and access to system environment variables.

Common Methods

  • currentTimeMillis(): Current time in milliseconds
  • arraycopy(): Copy elements from one array to another
  • System.in: Standard input stream (keyboard)
  • System.out: Standard output stream (console)
  • System.err: Standard error output stream
  • gc(): Request garbage collection
  • exit(): Terminate the JVM

Examples

Current Time


System.out.println(System.currentTimeMillis());

Array Copy


int[] source = new int[]{1, 2, 3, 4, 5};
int[] destination = new int[]{6, 7, 8, 9, 10};
// Copy first 3 elements from source to destination
System.arraycopy(source, 0, destination, 0, 3);
// After execution:
// source: [1, 2, 3, 4, 5]
// destination: [1, 2, 3, 9, 10]

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.