Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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());
}
}Advertisements