Skip to lesson

Constructors with parameters

A parameterized constructor is a constructor that takes parameters. The caller passes the starting values inside new, so every object can start with its own data: new Ticket("Priya", "Chennai", "Bengaluru", 650).

Parameters and arguments

A ticket app books Priya from Chennai to Bengaluru for Rs. 650. The parameters are the variables in the constructor header; the arguments are the values written in new, copied first to first, second to second.

Example 1 · A train ticket with four values

TicketDemo.javaJava
class Ticket {    String passenger;    String from;    String to;    int fare;
    Ticket(String passengerName, String fromCity, String toCity, int ticketFare) {        passenger = passengerName;        from = fromCity;        to = toCity;        fare = ticketFare;    }
    void show() {        System.out.println(passenger + ": " + from + " to " + to + ", Rs. " + fare);    }}
public class TicketDemo {    public static void main(String[] args) {        Ticket t1 = new Ticket("Priya", "Chennai", "Bengaluru", 650);        Ticket t2 = new Ticket("Arjun", "Pune", "Mumbai", 320);        t1.show();        t2.show();    }}
Output
Priya: Chennai to Bengaluru, Rs. 650
Arjun: Pune to Mumbai, Rs. 320

What this code does

  • The four arguments are copied into the four parameters in order, then the body copies them into the fields.
  • One constructor, two different tickets: each object keeps its own values.

It works exactly like calling a method, as in Parameters and arguments (opens in a new tab). Parameters live only while the constructor runs; the fields keep the values for the whole life of the object.

Number, type and order must match

The arguments must match the parameters in number, type and order. When they do not, javac stops at the line with new and says what it expected.

Example 2 · Arguments in the wrong order

OrderDemo.javaJava
class Student {    String name;    int marks;
    Student(String studentName, int studentMarks) {        name = studentName;        marks = studentMarks;    }}
public class OrderDemo {    public static void main(String[] args) {        Student s = new Student(88, "Kavya");        System.out.println(s.name + " " + s.marks);    }}
Sample compiler output
OrderDemo.java:13: error: incompatible types: int cannot be converted to String
        Student s = new Student(88, "Kavya");
                                ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

What this code does

  • The first parameter is a String, so the first argument 88 does not fit. The ^ points at it.
  • Fix: new Student("Kavya", 88), the same order as the header. The Note: line is only a hint and can be ignored.

Example 3 · Too many arguments

CountDemo.javaJava
class Ticket {    String passenger;    int fare;
    Ticket(String name, int amount) {        passenger = name;        fare = amount;    }}
public class CountDemo {    public static void main(String[] args) {        Ticket t = new Ticket("Priya", 650, 12);        System.out.println(t.passenger);    }}
Sample compiler output
CountDemo.java:13: error: constructor Ticket in class Ticket cannot be applied to given types;
        Ticket t = new Ticket("Priya", 650, 12);
                   ^
  required: String,int
  found:    String,int,int
  reason: actual and formal argument lists differ in length
1 error

What this code does

  • required lists the constructor's parameter types; found lists the types you passed.
  • Compare the two lines to see the extra int. Remove it, or add a parameter if the class really needs it.

Two more cases: a decimal for an int parameter gives possible lossy conversion from double to int, but an int for a double parameter is fine (10 becomes 10.0), because nothing is lost.

Same types in the wrong order: no error

With Route(String fromCity, String toCity), the call new Route("Mumbai", "Delhi") compiles even if you meant Delhi to Mumbai. javac checks types, not meaning, and both arguments are String.

Example 4 · Same types swapped: compiles, but wrong

SwapDemo.javaJava
class Route {    String start;    String end;
    Route(String fromCity, String toCity) {        start = fromCity;        end = toCity;    }}
public class SwapDemo {    public static void main(String[] args) {        Route right = new Route("Delhi", "Mumbai");        Route wrong = new Route("Mumbai", "Delhi");   // meant Delhi to Mumbai too        System.out.println(right.start + " -> " + right.end);        System.out.println(wrong.start + " -> " + wrong.end);    }}
Output
Delhi -> Mumbai
Mumbai -> Delhi

What this code does

  • Both arguments are String, so javac accepts either order. There is no error at all.
  • Only the output shows the bug: the second trip runs the wrong way.

Clear parameter names like fromCity and toCity are the best guard; most editors show them as you type the call. For now parameter names differ from field names; The this keyword (opens in a new tab) shows how to give them the same names.

Refuse bad values with IllegalArgumentException

Marks must be 0 to 100, and every Student passes through its constructor. Check the value there and throw IllegalArgumentException when it is wrong, as in throw and throws (opens in a new tab).

Example 5 · Refusing bad marks: the program stops

CrashDemo.javaJava
class Student {    String name;    int marks;
    Student(String studentName, int studentMarks) {        if (studentMarks < 0 || studentMarks > 100) {            throw new IllegalArgumentException("Marks must be 0 to 100, got " + studentMarks);        }        name = studentName;        marks = studentMarks;    }}
public class CrashDemo {    public static void main(String[] args) {        Student s1 = new Student("Aarav", 85);        System.out.println(s1.name + ": " + s1.marks);        Student s2 = new Student("Rohan", 150);        System.out.println(s2.name + ": " + s2.marks);    }}
Sample output
Aarav: 85
Exception in thread "main" java.lang.IllegalArgumentException: Marks must be 0 to 100, got 150
	at Student.<init>(CrashDemo.java:7)
	at CrashDemo.main(CrashDemo.java:18)

What this code does

  • The check runs before any field is set. For 150 the constructor throws, and no second Student is created.
  • Student.<init> in the stack trace means "inside the Student constructor". The last print never runs.

Example 6 · Catching the bad value and carrying on

PaymentDemo.javaJava
class Payment {    String to;    int amount;
    Payment(String receiver, int rupees) {        if (rupees < 1 || rupees > 100000) {            throw new IllegalArgumentException("Amount must be Rs. 1 to Rs. 100000");        }        to = receiver;        amount = rupees;    }}
public class PaymentDemo {    public static void main(String[] args) {        int[] amounts = {250, 0, 1200};        for (int i = 0; i < amounts.length; i++) {            try {                Payment p = new Payment("Kavya", amounts[i]);                System.out.println("Paid Rs. " + p.amount + " to " + p.to);            } catch (IllegalArgumentException e) {                System.out.println("Rejected: " + e.getMessage());            }        }    }}
Output
Paid Rs. 250 to Kavya
Rejected: Amount must be Rs. 1 to Rs. 100000
Paid Rs. 1200 to Kavya

What this code does

  • A UPI-style payment of Rs. 0 is refused inside the constructor, so that Payment object never exists.
  • try/catch around new handles the refusal, and the loop goes on to the next amount.

The throw stops the constructor, so new never finishes and no object is handed back: no Student with 150 marks can exist. In a stack trace the constructor appears as Student.<init>; <init> is the name the JVM uses for constructors.

Predict the output

Predict what the constructor stores

Read the code and pick what it prints.

Round 1 of 2

Marks above 100 should be refused. What does this print?

class Student {
String name;
int marks;
Student(String studentName, int studentMarks) {
name = studentName;
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException("Bad marks");
}
marks = studentMarks;
}
}
public class MarksCheck {
public static void main(String[] args) {
Student s = new Student("Aarav", 150);
System.out.println(s.name + " " + s.marks);
}
}
Check the parameter (studentMarks), not the field (marks): the field is still 0 when the check runs.

A failed new leaves the variable alone

s already holds seat S1-10 when a second booking, for seat 80, throws. Since new never finishes, the assignment s = ... never runs, and s keeps its old reference. Step through it.

Trace the code

A constructor that throws

class Seat {
String coach;
int number;
Seat(String c, int n) {
if (n < 1 || n > 72) {
throw new IllegalArgumentException("No seat " + n);
}
coach = c;
number = n;
}
}
public class SeatTrace {
public static void main(String[] args) {
Seat s = new Seat("S1", 10);
try {
s = new Seat("S2", 80);
System.out.println("Changed seat");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("Final: " + s.coach + "-" + s.number);
}
}

Variables

c
S1
n
10

Output

(nothing printed yet)

Line 6new Seat("S1", 10) makes an object with defaults and runs the constructor. 10 is inside 1 to 72, so there is no throw.

Step 1 of 8

Next step

Check your understanding

12 quick questions