Constructors with parameters
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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(); }}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
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); }}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 errorWhat this code does
- The first parameter is a
String, so the first argument88does not fit. The^points at it. - Fix:
new Student("Kavya", 88), the same order as the header. TheNote:line is only a hint and can be ignored.
Example 3 · Too many arguments
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); }}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 errorWhat this code does
requiredlists the constructor's parameter types;foundlists 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
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); }}Delhi -> Mumbai Mumbai -> Delhi
What this code does
- Both arguments are
String, sojavacaccepts 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
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); }}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
Studentis created. Student.<init>in the stack trace means "inside theStudentconstructor". The last print never runs.
Example 6 · Catching the bad value and carrying on
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()); } } }}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
Paymentobject never exists. try/catcharoundnewhandles 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?
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
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.
Next step
Check your understanding
12 quick questions