Java Predefined Class
In this post, I will talk about some predefined classes as well as commonly used APIs in Java. The post will cover object class, date class, date format class, calendar class, system class, string builder class and wrapper class. In addition, I will demonstrate some methods of those classes and show some examples.
Object Class
java.lang.Object class is the ultimate base class of any other class, which means all classes can use methods from the ‘Object’ class.
toString
public class Demo {
public static void main(String[] args) {
// Person inherits Object
Person p = new Person("Jason", 21);
// Both methods print the address of the objet in the heap
System.out.println(p.toString()); // com.itheima.demo.Person@36baf30c
System.out.println(p); // com.itheima.demo.Person@36baf30c
}
}
// Scanner and ArrayList override this method because it does not print the address
Override toString: let it print the attributes of the object
@Override
public String toString() {
return "Person{name = " + name + ", age = " + age + "}";
}
equals
Source Code
// Based on the source code, we know this method returns a boolean value. In addition, this method compares values for primitive data type and compares addresses for reference data type.
public boolean equals(Object obj) {
return (this == obj);
}
public class Demo {
public static void main(String[] args) {
Person p1 = new Person("Jason", 21);
Person p2 = new Person("kevin", 20);
System.out.println(p1.equals(p2)); // False: p1 and p2 have different addresses
System.out.println(p1.equals(p1)); // True: p1 and itself have the same address
}
}
Override equals: let it compare the attributes of two objects
Issue: There exists polymorphism so we can only compare the attributes from the base class.
Solution: We can use object down casting to convert the base class object to the derived class object.
@Override
public boolean equals(Object obj) {
// Improve the efficiency
if (obj == null) return false;
if (this == obj) return true;
// Avoid ClassCastException
if (obj instanceof Person) {
Person p = (Person) obj;
return this.name.equals(p.name) && this.age == p.age;
}
return false;
}
Date Class
java.util.Date is a class for displaying date and time. It is accurate to the millisecond.
private static void demo01() {
// Date() obtains the current date and time of system
Date date = new Date();
System.out.println(date);
}
private static void demo02() {
// Convert millisecond to date
Date date = new Date(0L);
System.out.println(date);
}
private static void demo03() {
// Convert time to millisecond
Date date = new Date();
long time = date.getTime();
System.out.println(time);
}
DateFormat Class
java.text.DateFormat is an abstract class for formatting the date and time. java.text.SimpleDateFormat inherits from that abstract class; therefore we can use this derived class to create objects.
Patterns: y - year | M - month | d - day | H - hour | m - minute | s - second
// Formatting date
private static void demo01() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println(sdf.format(date)); // 2022-11-18 17:12:59
}
// Parsing date
private static void demo02() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse("2022-11-18 17:06:19");
System.out.println(date); // Fri Nov 18 17:06:19 ACDT 2022
}
Calculating how many days a person lives case study
public class Demo {
public static void main(String[] args) throws ParseException {
// Get the date of birth
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your date of birth(yyyy-MM-dd): ");
String birthdayDateString = sc.next();
// Parse the string to date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date birthdayDate = sdf.parse(birthdayDateString);
// Convert date to millisecond
long time = birthdayDate.getTime();
// Get current date
long todayTime = new Date().getTime();
// Difference
long diff = todayTime - time;
// Convert millisecond to day
System.out.println(diff / 1000 / 60 / 60 /24);
}
}
Program Output
Please enter your date of birth(yyyy-MM-dd):
2001-09-13
7736
Calendar Class
java.util.Calendar is an abstract class. It provides many methods to manipulate calendar fields (year, month, day of month, hour). Calendar class has a static method called ‘getInstance()’ which returns a derived class object.
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
System.out.println(c);
//java.util.GregorianCalendar[time=1668756793556,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Australia/Adelaide",offset=34200000,dstSavings=3600000,useDaylight=true,transitions=142,lastRule=java.util.SimpleTimeZone[id=Australia/Adelaide,offset=34200000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=9,startDay=1,startDayOfWeek=1,startTime=7200000,startTimeMode=1,endMode=3,endMonth=3,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=1]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2022,MONTH=10,WEEK_OF_YEAR=47,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=322,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=6,HOUR_OF_DAY=18,MINUTE=3,SECOND=13,MILLISECOND=556,ZONE_OFFSET=34200000,DST_OFFSET=3600000]
}
Fields
public static final int YEAR = 1;
public static final int MONTH = 2;
public static final int DATE = 5;
public static final int DAY_OF_MONTH = 5;
public static final int HOUR = 10;
public static final int MINUTE = 12;
public static final int SECOND = 13;
// get(int field) method
private static void demo01() {
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.MONTH)); // Range from 0 - 11
}
// set(int field, int value) method
private static void demo02() {
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, 1);
System.out.println(c.get(Calendar.MONTH));
}
// add(int field, int value) method: modify specific field
private static void demo03() {
Calendar c = Calendar.getInstance();
c.add(Calendar.YEAR, -20);
System.out.println(c.get(Calendar.YEAR));
}
// getTime() method: convert calendar to date
private static void demo04() {
Calendar c = Calendar.getInstance();
Date date = c.getTime();
System.out.println(date);
}
System Class
java.lang.System class provides a lot of static methods which can obtain system-related information or implement system-level operations.
// currentTimeMillis() method: returns current time (in milliseconds)
// Can be used to test the time a program executes
private static void demo01() {
long before = System.currentTimeMillis();
for (int i = 1; i < 9999; i++) System.out.println(i);
long after = System.currentTimeMillis();
System.out.println("It takes " + (after - before) + " milliseconds for execution!"); // It takes 44 milliseconds for execution!
}
// arraycopy(Object src, int srcPos, Object dest, int destPos, int length) method: copies elements in one array to another array
private static void demo02() {
// Copy first 3 elements
int[] src = {1, 2, 3, 4, 5};
int[] dest = {6, 7, 8, 9, 10};
System.out.println(Arrays.toString(dest));
System.arraycopy(src, 0, dest, 0, 3);
System.out.println(Arrays.toString(dest)); // [1, 2, 3, 9, 10]
}
StringBuilder Class
String is constant, it cannot be changed because it is modified by the keyword ‘final’.
@Stable
private final byte[] value;
If we concatenate strings, many strings will be created and therefore it will waste some memory space.
StringBuilder class (java.lang.StringBuilder) can improve the efficiency of manipulating strings and takes up less space. It is implemented by an array without being modified by the keyword ‘final’.
byte[] value;
In addition, it is initialized by a capacity of 16 characters.
@IntrinsicCandidate
public StringBuilder() {
super(16);
}
// Construct a string builder
private static void demo01() {
StringBuilder bd1 = new StringBuilder();
System.out.println(bd1); // bd1: ""
StringBuilder bd2 = new StringBuilder("abc");
System.out.println(bd2); // bd2: "abc"
}
// append() method: returns this (StringBuilder)
private static void demo02() {
StringBuilder bd3 = new StringBuilder();
bd3.append("abc").append(1).append(true).append(8.8);
System.out.println(bd3); // abc1true8.8
}
// toString() method: converts StringBuilder to String
private static void demo03() {
// String -> StringBuilder
String str1 = "Hello";
StringBuilder bd4 = new StringBuilder(str1);
bd4.append(" World!");
// StringBuilder -> String
String str2 = bd4.toString();
System.out.println(str2);
}
Wrapper Class
Primitive data are easy to use. However, there is no method to manipulate these data. Therefore, we can use wrapper class to include these data as well as some useful methods.
Wrapper class: byte - Byte | short - Short | int - Integer | long - Long | float - Float | double - Double | char - Character | boolean - Boolean
Wrap Data
// Using constructor to wrap data
private static void demo01() {
Integer int1 = new Integer(1);
System.out.println(int1);
Integer int2 = new Integer("1");
System.out.println(int2);
}
// Using static method to wrap data
private static void demo02() {
Integer int3 = Integer.valueOf(1);
System.out.println(int3);
Integer int4 = Integer.valueOf("1");
System.out.println(int4);
}
Unwrap Data
// Using intValue() method to unwrap data
private static void demo03() {
Integer int1 = new Integer(1);
System.out.println(int1);
// Unwrap data
int i1 = int1.intValue();
System.out.println(i1);
}
Automatic Wrapping / Unwrapping Data
private static void demo01() {
Integer i1 = 1; // Automatically wrap int as Integer
i1 = i1 + 2; // Automatically unwrap Integer as int, because Integer cannot calculate numbers. And then, it automatically wraps int as Integer back.
ArrayList<Integer> list = new ArrayList<>();
list.add(1); // Automatically wrap int as Integer
int a = list.get(0); // Automatically unwrap Integer as int
}
Primitive Data Type and String Conversion
// Primitive data type -> String
private static void demo01() {
int i1 = 100;
// Method 1: Adding ""
String s1 = i1 + "";
// Method 2: Using Integer.toString()
String s2 = Integer.toString(i1);
// Method 3: Using String.valueOf()
String s3 = String.valueOf(i1);
}
// String -> Primitive data type
private static void demo02() {
String s1 = "100";
String s2 = "101.1";
// Approach 1: Using Integer.parseXxx()
int i1 = Integer.parseInt(s1);
// Approach 2: Using Double.parseDouble()
double d1 = Double.parseDouble(s2);
}