Class that contains a String instance variable and methods to set and get its value in Java


A class declaration can contain a String instance and methods to set and get its value in Java.

A program that demonstrates this is given as follows:

Example

 Live Demo

class Name {
   private String name;
   public void setName(String n) {
      name = n;
   }
   public String getName() {
      return name;
   }
}
public class Demo {
   public static void main(String[] args) {
      Name n = new Name();
      n.setName("John Smith");
      System.out.println("The name is: " + n.getName());
   }
}

Output

The name is: John Smith

Now let us understand the above program.

The Name class is created with a data member name and member functions setName() and getName() that set and get its value respectively. A code snippet which demonstrates this is as follows:

class Name {
   private String name;
   public void setName(String n) {
      name = n;
   }
   public String getName() {
      return name;
   }
}

In the main() method, an object n of class Name is created. Then setName() method is called with string value "John Smith". The name is printed by the calling the method getName(). A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String[] args) {
      Name n = new Name();
      n.setName("John Smith");
      System.out.println( "The name is: " + n.getName());
   }
}

Updated on: 30-Jul-2019

471 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements