LearnFrenzy
Sign in Take a free test

Java Programming · Topic 8 of 28

Constructors and the this Keyword

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Programs & Examples

Constructors and the this Keyword · Study material

A Time class with three constructors

Time can be built from hours and minutes, from a total number of minutes or from a "HH:MM" string. All three chain to one validating constructor.

class Time {
    private final int hour, minute;

    Time(int hour, int minute) {
        if (hour < 0 || hour > 23 || minute < 0 || minute > 59) throw new IllegalArgumentException("bad time " + hour + ":" + minute);
        this.hour = hour;
        this.minute = minute;
    }

    Time(int totalMinutes) { this(Math.floorMod(totalMinutes, 1440) / 60, Math.floorMod(totalMinutes, 1440) % 60); }

    Time(String hhmm) { this(Integer.parseInt(hhmm.split(":")[0]), Integer.parseInt(hhmm.split(":")[1])); }

    Time plusMinutes(int m) { return new Time(hour * 60 + minute + m); }

    @Override public String toString() { return String.format("%02d:%02d", hour, minute); }
}

public class Main {
    public static void main(String[] args) {
        Time start = new Time("22:45");
        System.out.println(start + " " + start.plusMinutes(90) + " " + new Time(-30) + " " + new Time(9, 5));
        try {
            new Time(24, 0);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Output

22:45 00:15 23:30 09:05
bad time 24:0

Initialisation order traced

The initialisation-order example prints a line at every step, so you can see static blocks run once and field initialisers and instance blocks run before the constructor body for each object.

Copy constructor and static factory

The Playlist example shows why a copy constructor must copy the list, and how a static factory gives construction a readable name.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Java Programming

Java is one of the most used languages in the world – for enterprise software, Android apps, banking systems and backend services. This section covers core Java from syntax and data types to OOP, strings, arrays, exceptions, collections and multithreading, with clear explanations and practice questions for every topic.

Why it matters

  • Java is the main language in service-company placement tests and many product companies
  • OOP, String, collections and exception questions appear in nearly every Java interview
  • Strong core Java is the base for Spring Boot, Android and backend development
  • Java questions are common in university exams and certification tests

Who it is for

  • School students (Class 11–12 / ICSE computer applications) learning Java
  • College students (B.Tech, BCA, MCA) preparing for exams, labs and projects
  • Freshers preparing for placements, Java developer roles and technical interviews
  • Developers revising core Java before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Java developer interviews
  • Service company tests
  • University exams
  • Certification exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links