how to use getter and setter in java code example

Example 1: java setter

public setValue(value) {
  this.value = value;
}

Example 2: setter&getter java

public class Vehicle {
  private String color;
  
  // Getter
  public String getColor() {
    return color;
  }
  
  // Setter
  public void setColor(String c) {
    this.color = c;
  }
}

Example 3: java getter

public getValue() {
  return value;
}

Example 4: setter&getter java

public static void main(String[] args) {
  Vehicle v1 = new Vehicle();
  v1.setColor("Red");
  System.out.println(v1.getColor());
}

// Outputs "Red"

Example 5: Getter and Setter methods

import java.util.Scanner;
class Student {
   private String name;
   private int age;
   Student(){
      this.name = "Rama";
      this.age = 29;
   }
   Student(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void display() {
      System.out.println("name: "+this.name);
      System.out.println("age: "+this.age);
   }
}
public class AccessData{
   public static void main(String args[]) {
      //Reading values from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      int age = sc.nextInt();
      Student obj1 = new Student(name, age);
      obj1.display();
      Student obj2 = new Student();
      obj2.display();
   }
}