- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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()); } }
- Related Articles
- Instance variable in Java
- What is the number wrapper class and its methods in Java?
- What is the character wrapper class and its methods in Java?
- How many ways can get the instance of a Class class in Java?
- Static methods vs Instance methods in Java
- instance variable hiding in Java
- What is Regex class and its class methods in C#?
- What is the importance of the Throwable class and its methods in Java?
- Instance variable as final in Java
- What is instance variable hiding in Java?
- What is the System.Console class and its methods in C#?
- C++ string class and its applications?
- What are class variables, instance variables and local variables in Java?
- Class with a constructor to initialize instance variables in Java
- Java String toUpperCase() and toLowerCase() methods

Advertisements