Mathematical Operations in Java
The Math Class
The Math class in Java provides various mathematical functions and constants. Here are some practical examples:
package com.example.math;
public class MathOperations {
public static void main(String[] args) {
// Mathematical constants
System.out.println("Value of PI: " + Math.PI);
// Absolute value
System.out.println("Absolute value of -15: " + Math.abs(-15));
// Square root
System.out.println("Square root of 64: " + Math.sqrt(64));
// Power calculation
System.out.println("2 raised to the power of 5: " + Math.pow(2, 5));
// Rounding operations
System.out.println("Floor of 7.8: " + Math.floor(7.8));
System.out.println("Ceiling of 3.2: " + Math.ceil(3.2));
System.out.println("Round of 4.5: " + Math.round(4.5));
// Random number generation
System.out.println("Random value between 0 and 1: " + Math.random());
}
}
The Random Class
The Random class provides more sophisticated random number generation capabilities:
package com.example.random;
import java.util.Arrays;
import java.util.Random;
public class RandomGenerator {
public static void main(String[] args) {
Random randomGenerator = new Random();
// Different types of random values
System.out.println("Random boolean: " + randomGenerator.nextBoolean());
System.out.println("Random double: " + randomGenerator.nextDouble());
System.out.println("Random float: " + randomGenerator.nextFloat());
System.out.println("Random integer: " + randomGenerator.nextInt());
// Random integer within a range (0 to 99)
System.out.println("Random integer (0-99): " + randomGenerator.nextInt(100));
// Generate random bytes
byte[] randomBytes = new byte[5];
randomGenerator.nextBytes(randomBytes);
System.out.println("Random bytes: " + Arrays.toString(randomBytes));
}
}
Date and Time Hadnling
The Date Class
The Date clas represents a specific instant in time:
package com.example.datetime;
import java.util.Date;
public class DateExample {
public static void main(String[] args) {
Date currentDate = new Date();
// Getting components of date
System.out.println("Year: " + (currentDate.getYear() + 1900));
System.out.println("Month: " + (currentDate.getMonth() + 1)); // Month is 0-based
System.out.println("Day of month: " + currentDate.getDate());
System.out.println("Day of week: " + currentDate.getDay()); // Sunday is 0
System.out.println("Hours: " + currentDate.getHours());
System.out.println("Minutes: " + currentDate.getMinutes());
System.out.println("Seconds: " + currentDate.getSeconds());
// Time in milliseconds since January 1, 1970
System.out.println("Time in milliseconds: " + currentDate.getTime());
// Create date from milliseconds
Date specificDate = new Date(1672531200000L); // January 1, 2023
System.out.println("Specific date: " + specificDate);
}
}
The Calendar Class
The Calendar class provides more advanced date manipulation:
package com.example.datetime;
import java.util.Calendar;
public class CalendarExample {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
// Getting calendar fields
System.out.println("Year: " + calendar.get(Calendar.YEAR));
System.out.println("Month: " + (calendar.get(Calendar.MONTH) + 1));
System.out.println("Day of month: " + calendar.get(Calendar.DAY_OF_MONTH));
System.out.println("Day of week: " + calendar.get(Calendar.DAY_OF_WEEK));
System.out.println("Day of year: " + calendar.get(Calendar.DAY_OF_YEAR));
System.out.println("Week of month: " + calendar.get(Calendar.WEEK_OF_MONTH));
System.out.println("Week of year: " + calendar.get(Calendar.WEEK_OF_YEAR));
System.out.println("Hour (12-hour format): " + calendar.get(Calendar.HOUR));
System.out.println("Hour (24-hour format): " + calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("Minute: " + calendar.get(Calendar.MINUTE));
System.out.println("Second: " + calendar.get(Calendar.SECOND));
// Setting calendar values
calendar.set(2023, Calendar.NOVEMBER, 15);
System.out.println("Set date: " + calendar.get(Calendar.YEAR) + "-" +
(calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH));
// Time in milliseconds
System.out.println("Time in milliseconds: " + calendar.getTimeInMillis());
}
}
The SimpleDateFormat Class
SimpleDateFormat allows formatting and parsing dates:
package com.example.datetime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) throws ParseException {
Date now = new Date();
// Formatting date to string
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(now);
System.out.println("Formatted date: " + formattedDate);
// Custom format
SimpleDateFormat customFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
String customFormatted = customFormatter.format(now);
System.out.println("Custom formatted date: " + customFormatted);
// Parsing string to date
String dateStr = "2023-12-25";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
Date parsedDate = parser.parse(dateStr);
System.out.println("Parsed date: " + parsedDate);
}
}
Precision Arithmetic
The BigInteger Class
BigInteger handles arbitrarily large integers:
package com.example.bignumbers;
import java.math.BigInteger;
public class BigIntegerExample {
public static void main(String[] args) {
BigInteger largeNum1 = new BigInteger("12345678901234567890");
BigInteger largeNum2 = new BigInteger("98765432109876543210");
// Addition
BigInteger sum = largeNum1.add(largeNum2);
System.out.println("Sum: " + sum);
// Subtraction
BigInteger difference = largeNum2.subtract(largeNum1);
System.out.println("Difference: " + difference);
// Multiplication
BigInteger product = largeNum1.multiply(largeNum2);
System.out.println("Product: " + product);
// Division
BigInteger quotient = largeNum2.divide(largeNum1);
System.out.println("Quotient: " + quotient);
// Modulo
BigInteger remainder = largeNum2.mod(largeNum1);
System.out.println("Remainder: " + remainder);
// Power
BigInteger power = largeNum1.pow(2);
System.out.println("Power: " + power);
}
}
The BigDecimal Class
BigDecimal provides precise decimal arithmetic:
package com.example.bignumbers;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalExample {
public static void main(String[] args) {
// Demonstrating floating-point precision issues
System.out.println("Floating-point issue: " + (0.1 + 0.2));
// Using BigDecimal for precision
BigDecimal decimal1 = new BigDecimal("0.1");
BigDecimal decimal2 = new BigDecimal("0.2");
BigDecimal preciseSum = decimal1.add(decimal2);
System.out.println("Precise sum: " + preciseSum);
// Division with precision control
BigDecimal dividend = new BigDecimal("10");
BigDecimal divisor = new BigDecimal("3");
BigDecimal result = dividend.divide(divisor, 4, RoundingMode.HALF_UP);
System.out.println("Division result: " + result);
// Rounding
BigDecimal number = new BigDecimal("123.4567");
BigDecimal rounded = number.setScale(2, RoundingMode.CEILING);
System.out.println("Rounded number: " + rounded);
}
}
Regular Expressions
Pattern Matching Fundamentals
Regular expressions provide powerful pattern matching capabilities:
package com.example.regex;
public class RegexBasics {
public static void main(String[] args) {
String testString = "HelloWorld123";
// Basic pattern matching
boolean matchesDigits = testString.matches("\\d+"); // Only digits
System.out.println("Only digits: " + matchesDigits);
boolean matchesLetters = testString.matches("[a-zA-Z]+"); // Only letters
System.out.println("Only letters: " + matchesLetters);
// Phone number validation
String phoneNumber = "13812345678";
boolean isValidPhone = phoneNumber.matches("1[3-9]\\d{9}");
System.out.println("Valid phone number: " + isValidPhone);
// Email validation
String email = "user@example.com";
boolean isValidEmail = email.matches("\\w+@\\w+\\.\\w+");
System.out.println("Valid email: " + isValidEmail);
}
}
Advanced Pattern Operations
More complex regex operations including splitting and replacement:
package com.example.regex;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexAdvanced {
public static void main(String[] args) {
String text = "Java,Python;C++|JavaScript";
// Splitting by multiple delimiters
String[] languages = text.split("[,;|]");
System.out.println("Split languages: " + Arrays.toString(languages));
// Finding all occurrences
String source = "The quick brown fox jumps over the lazy dog";
Pattern pattern = Pattern.compile("\\b\\w{4}\\b");
Matcher matcher = pattern.matcher(source);
System.out.println("Four-letter words:");
while (matcher.find()) {
System.out.println(matcher.group());
}
// Replacing patterns
String result = source.replaceAll("\\s+", "_");
System.out.println("Replaced spaces: " + result);
// Extracting parts of strings
String dateStr = "Date: 2023-12-25";
Pattern datePattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2})");
Matcher dateMatcher = datePattern.matcher(dateStr);
if (dateMatcher.find()) {
System.out.println("Year: " + dateMatcher.group(1));
System.out.println("Month: " + dateMatcher.group(2));
System.out.println("Day: " + dateMatcher.group(3));
}
}
}