Skip to main content

← Back to Overview

Java Program - Using Methods (setValue)

Concept Explanation

What is it?

Methods are blocks of code that perform a specific task. A setValue method (often called a "setter") is used to assign values to class fields after an object has been created.

Why is it important?

It promotes modularity. Instead of putting all logic in main, you separate data assignment into dedicated methods.


Implementations

class Car {
String model;
int year;

// Method to set values
void setValues(String m, int y) {
model = m;
year = y;
}

void display() {
System.out.println("Car Model: " + model);
System.out.println("Year: " + year);
}
}

public class MethodDemo {
public static void main(String[] args) {
Car myCar = new Car();

// Calling the method
myCar.setValues("Toyota Camry", 2022);

myCar.display();
}
}

Explanation

  • Parameters: String m and int y are local variables.
  • Assignment: Inside the method, model = m copies the value from the parameter to the instance variable.
  • Separation: This approach separates creation (new Car()) from initialization (setValues).

📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir