Using Predefined Classes in Java: Objects, Object Variables and LocalDate
Learn to work with objects from the Java library: constructors and new, the difference between objects and object variables, references and null, why Java has LocalDate instead of a date type, factory methods, accessor vs. mutator methods, and a complete calendar program.
kvi5hnuCode Sprout team member11 min readOn this page
Before writing your own classes, let's use some from the standard library and see the mechanics of objects: constructing them, storing them in variables, and calling their methods.
You've already used Math, but it isn't a typical class. It only bundles functions (Math.sqrt, Math.random) and holds no data, so you never create Math objects. You use its methods without knowing how they're implemented, which is encapsulation at work, but there's no object state involved. Typical classes have objects with state, and that's what this article is about.
Constructors and new
To work with objects, you first construct them with an initial state, then call methods on them.
You construct objects with constructors: special methods whose job is to create and initialize new instances. A constructor always has the same name as its class. The classic example in the standard library is java.util.Date, whose objects represent points in time, such as December 31, 1999, 23:59 GMT.
Combine the constructor with the new operator:
new Date()
This expression constructs a new Date object initialized to the current date and time. You can pass the new object straight to a method:
System.out.println(new Date()); // Fri Nov 13 10:15:42 CET 2026
or call a method on it:
String s = new Date().toString();
In both examples the object is used once and then forgotten. Usually you want to keep the object, so you store it in a variable:
Date rightNow = new Date();
Objects versus Object Variables
There's an important difference between an object and an object variable:
Date startTime; // startTime doesn't refer to any object yet
This defines a variable that can refer to objects of type Date. The variable isn't an object, and right now it doesn't even refer to one. You can't call Date methods through it yet:
String s = startTime.toString(); // compile error: variable startTime might not have been initialized
First make it refer to an object. Either construct a new one:
startTime = new Date();
or make it refer to an existing object:
startTime = rightNow;
Now both variables refer to the same object:

Here is the central idea: a variable of a class type never holds the object itself; it holds a reference to it. The object lives on the heap, and the variable stores where to find it. What new hands back is exactly such a reference. In
Date startTime = new Date();
the expression new Date() creates a Date object and its value is a reference to it; that reference is then stored in startTime.
null
Assigning null says explicitly that a variable points at nothing right now:
startTime = null;
...
if (startTime != null) {
System.out.println(startTime);
}
Calling a method through a null reference throws a NullPointerException. The section on working with null references in the next article shows ways to handle it.
The LocalDate Class
A Date represents a point in time, internally the number of milliseconds since the epoch, 00:00 UTC on January 1, 1970. (UTC, Coordinated Universal Time, is for practical purposes the same as GMT.) That's useful for timestamps, but not for the calendar information people use, such as "December 31, 1999". That description depends on a calendar system. The Gregorian calendar is used in most of the world, but the same instant has different names in the Chinese or Hebrew calendars.
So the library designers separated two concerns: keeping time, and naming days in a calendar. The modern java.time package (Java 8) has:
Instant: a point in time (the modern replacement forDate),LocalDate: a date in the familiar calendar notation, without a time or time zone,LocalTime,LocalDateTime,ZonedDateTime,Duration,Period, and more.
Separating time measurement from calendars is good object-oriented design: use different classes for different concepts.
Factory methods instead of constructors
You don't use a constructor to make LocalDate objects. You call static factory methods, which construct the object for you:
LocalDate today = LocalDate.now(); // the current date
LocalDate launch = LocalDate.of(2023, 3, 14); // a specific date
Factory methods can have descriptive names (now, of, parse), validate their arguments, and return cached or specialized objects. LocalDate.of(2026, 2, 30) throws a DateTimeException ("Invalid date 'FEBRUARY 30'") instead of silently creating a strange date. Factory methods are discussed in detail in the static methods article.
Asking a date for information
int year = launch.getYear(); // 2023
int month = launch.getMonthValue(); // 3
int day = launch.getDayOfMonth(); // 14
That may seem pointless, since you just supplied those values. But dates are often computed, and then you need these methods to find out about them:
LocalDate review = launch.plusDays(500);
year = review.getYear(); // 2024
month = review.getMonthValue(); // 7
day = review.getDayOfMonth(); // 26
LocalDate keeps its date in encapsulated instance fields. Without looking at the source, you can't tell how it stores the date, and that's the point: what matters are the methods it exposes. (LocalDate actually stores year, month and day fields, but it could change that without breaking your code.)
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
public class Solution {
public static void main(String[] args) {
LocalDate launch = LocalDate.of(2023, 3, 14);
System.out.println(launch.getYear() + " " + launch.getMonthValue() + " "
+ launch.getDayOfMonth() + " " + launch.getDayOfWeek() + " " + launch.getMonth());
LocalDate later = launch.plusDays(500);
System.out.println(later + " " + launch);
System.out.println(launch.isLeapYear() + " " + launch.lengthOfMonth() + " "
+ LocalDate.of(2024, 2, 1).lengthOfMonth());
System.out.println(launch.plusMonths(2) + " " + launch.withDayOfMonth(1) + " "
+ launch.isBefore(later));
System.out.println(ChronoUnit.DAYS.between(launch, later) + " " + Period.between(launch, later));
System.out.println(LocalDate.parse("2026-11-13").getDayOfWeek() + " " + launch.getDayOfYear());
System.out.println(LocalDate.of(2026, 1, 31).plusMonths(1));
try {
LocalDate.of(2026, 2, 30);
} catch (DateTimeException e) {
System.out.println(e.getMessage());
}
}
}
2023 3 14 TUESDAY MARCH
2024-07-26 2023-03-14
false 31 29
2023-05-14 2023-03-01 true
500 P1Y4M12D
FRIDAY 73
2026-02-28
Invalid date 'FEBRUARY 30'
Notice that adding one month to January 31 gives February 28: LocalDate adjusts to the last valid day instead of failing. Period P1Y4M12D is ISO-8601 notation for "1 year, 4 months, 12 days".
Deprecated methods
Date also has getDay, getMonth and getYear methods, but they're deprecated. A deprecated method is one the library designers now consider a mistake, kept only for compatibility. These were deprecated back in Java 1.1, when the designers realized calendar logic belonged in separate classes. You can still call them, but the compiler warns you, and deprecated APIs may be removed in future versions (some are explicitly marked "for removal").
Accessor and Mutator Methods
Look again at:
LocalDate review = launch.plusDays(500);
Is launch now 500 days later? No. plusDays returns a new LocalDate and leaves the original unchanged, just as String.toUpperCase returns a new string. LocalDate objects are immutable: no method ever changes them.
Compare the legacy GregorianCalendar class:
GregorianCalendar someDay = new GregorianCalendar(2023, 2, 14);
// quirk of that class: months are numbered 0 to 11, so 2 means March
someDay.add(Calendar.DAY_OF_MONTH, 500);
year = someDay.get(Calendar.YEAR); // 2024
month = someDay.get(Calendar.MONTH) + 1; // 7
day = someDay.get(Calendar.DAY_OF_MONTH); // 26
Here add changes the state of someDay. That's why it's called someDay rather than launch: after the call it no longer holds the launch date.
- A mutator method changes the state of the object it's called on (
GregorianCalendar.add). - An accessor method only reads the state without modifying it (
LocalDate.getYear,GregorianCalendar.get).
Immutable classes like String and LocalDate are easier to reason about: you can share them freely, pass them to any method, and use them from multiple threads without worrying that something changes them behind your back. Modern Java libraries favor immutability.
Putting It Together: A Calendar Program
This program prints one month as a grid that starts on Sunday, with a chosen day shown in brackets:
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 [13] 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
To lay out the grid it needs two facts: how many days the month has, and which weekday the 1st falls on. java.time supplies both:
YearMonth.from(date)describes the month;lengthOfMonth()gives 28, 29, 30 or 31, leap years included.atDay(1).getDayOfWeek().getValue()gives the weekday of the 1st in ISO numbering, 1 = Monday … 7 = Sunday. Taking it% 7turns that into the number of empty cells before the 1st in a Sunday-first grid (Sunday → 0, Monday → 1, …).- Print the header, the blank cells, and then the days 1 to the length of the month, starting a new row after every seventh cell.
import java.time.LocalDate;
import java.time.YearMonth;
public class Solution {
public static void main(String[] args) {
LocalDate marked = LocalDate.of(2026, 11, 13); // LocalDate.now() shows today instead
YearMonth month = YearMonth.from(marked);
int blanks = month.atDay(1).getDayOfWeek().getValue() % 7; // Sunday-first grid
System.out.println(" Su Mo Tu We Th Fr Sa");
int cell = 0;
for (; cell < blanks; cell++) {
System.out.print(" ");
}
for (int day = 1; day <= month.lengthOfMonth(); day++, cell++) {
if (cell > 0 && cell % 7 == 0) {
System.out.println();
}
String text = day == marked.getDayOfMonth() ? "[" + day + "]" : " " + day + " ";
System.out.printf("%4s", text);
}
System.out.println();
}
}
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 [13] 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
A fixed date keeps the output stable; swap in LocalDate.now() for the current month. Notice that the program never computes a weekday or a month length itself. It relies only on the public methods of LocalDate and YearMonth, with no idea how they work inside. That's the whole point of encapsulation.
LocalDate API Summary
| Method | Description |
|---|---|
static LocalDate now() | the current date |
static LocalDate of(int year, int month, int day) | a specific date (month 1–12) |
static LocalDate parse(CharSequence text) | from ISO text such as "2026-11-13" |
int getYear(), int getMonthValue(), int getDayOfMonth() | the parts of the date |
Month getMonth(), DayOfWeek getDayOfWeek(), int getDayOfYear() | richer information; DayOfWeek.getValue() gives 1 (Monday) … 7 (Sunday) |
LocalDate plusDays(long n) / minusDays(long n) | the date n days after/before (also plusWeeks, plusMonths, plusYears) |
LocalDate withDayOfMonth(int d) | the same month, different day |
boolean isBefore(…), isAfter(…), isLeapYear(); int lengthOfMonth() | queries |
The date-and-time API has much more: time zones, formatting with DateTimeFormatter, durations and periods. It's a large topic of its own.
Common questions
Why does LocalDate use factory methods instead of constructors?
Factory methods can have meaningful names (of, now, parse, ofYearDay), validate their arguments, and return cached or specialised instances. A constructor always creates a new object of exactly that class. Many modern APIs (List.of, Path.of, Optional.of) follow the same style.
How do I format a LocalDate as text?
toString() gives ISO format, 2026-11-14. For other formats, use DateTimeFormatter: date.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")), or DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG) for the user's locale. Use LocalDate.parse(text, formatter) to go the other way.
How do I compute the number of days between two dates?
Use ChronoUnit.DAYS.between(start, end), which returns a long. start.until(end) returns a Period (years, months and days), which is right for ages but awkward for plain day counts.
Is Date deprecated?
The class itself isn't deprecated, but most of its constructors and its calendar methods (getYear, getMonth and others) have been deprecated since Java 1.1. New code should use java.time. Use Date only to talk to old APIs, and convert with date.toInstant() and Date.from(instant).
Should I use LocalDate.now() in code that I want to test?
Calling now() directly makes tests depend on the real date. Pass in a java.time.Clock and call LocalDate.now(clock). In tests, use Clock.fixed(...) to set any date you need.
Summary
- Construct objects with
newand a constructor (same name as the class), or with static factory methods such asLocalDate.ofandLocalDate.now. - An object variable holds a reference to an object; it isn't the object. Assigning one variable to another makes both refer to the same object.
nullmeans "no object". - Java object variables behave like C++ pointers, but they're safe: no pointer arithmetic, no dangling pointers, garbage collection instead of
delete. Dateis a point in time;LocalDateis a calendar date. Prefer the immutablejava.timeclasses over legacyDate/Calendar.- Accessor methods read state; mutator methods change it.
LocalDate.plusDaysreturns a new object, whileGregorianCalendar.addmutates. - Avoid deprecated methods;
jdeprscanand-Xlint:deprecationhelp find them.
Practice Questions
What's wrong with this code? LocalDate d; System.out.println(d.getYear());
d is declared but never initialized. It doesn't refer to any object, so the compiler reports "variable d might not have been initialized". Assign it first, e.g. LocalDate d = LocalDate.now();.
After LocalDate a = LocalDate.of(2026, 1, 1); LocalDate b = a; b = b.plusDays(1);, what are a and b?
a is 2026-01-01 and b is 2026-01-02. plusDays doesn't modify the object; it returns a new one, which is assigned to b. a still refers to the original, unchanged object.
Is String.toUpperCase an accessor or a mutator? Is GregorianCalendar.set?
toUpperCase is an accessor: it returns a new string and leaves the original unchanged (strings are immutable). GregorianCalendar.set is a mutator: it changes the calendar object's state.
Why does LocalDate use factory methods like LocalDate.of instead of public constructors?
Factory methods can have meaningful names (now, of, parse, ofYearDay), validate arguments, and return cached or specially chosen objects. Constructors must always create a new instance of exactly that class and are all named after the class.
How would you print the date that is 90 days from today, and its day of the week?
LocalDate due = LocalDate.now().plusDays(90);
System.out.println(due + " " + due.getDayOfWeek());
Previous: Introduction to Object-Oriented Programming in Java
Next: Defining Your Own Classes in Java: Fields, Constructors and Methods
Related reading
- Introduction to Object-Oriented Programming in Java
- Java Arrays: Sorting, the Arrays Class, Multidimensional and Ragged Arrays
- Java Arrays: Declaring, Initializing, for-each Loops and Copying
- Java Loops: while, do-while and for
- Java Arithmetic Operators and the Math Class: Division, Remainder, floorMod and More

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.