Data Member

  • A DATA MEMBER in Java is a piece of memory that can contain a data value. They are called member variables or fields .
  • They are defined outside of any methods but inside the class and are used in different methods.
  • Field is the preferred term in Java. Member variable is the preferred term in C++.
  • In C language we define variables which holds a value but in Java data members holds the value and data of real world.
  • Data Member are classified into two types static data member and instance data member.
  • NOTE: We do not write instance while we code beacase if we do not write static or anything so it will consider as instance data member or non-static data member.
  • In Java Variables / Fields / Data Members / Properties of an object are the same things.

Static Data Member

  • Static data members are those whose memory space is created only once, whenever the class is loaded in the main memory irrespective of no of objects are created.
  • SDM are used to store common property of each object.
  • Programmatically static data member declaration must be preceded by static keyword.
  • Each and every static data member must be access with respective class name.
  • Example:
    Class name.static data member name
  • Static data member are also known as Class Level Data Members because they depends on class name and independent from object name.
  • Syntax:
    static datatype x, y, z, .... ;
  • Default value null or 0
  1. public class Employee
  2. {
  3. static String cname;
  4. public static void main (String args[])
  5. {
  6. System.out.println(cname);
  7. Employee.cname="HCL";
  8. System.out.println(Employee.cname);
  9. }
  10. }
  11. To Compile - javac employee.java
  12. To Run - java Employee
  13. Result - null
    HCL

Instance Data Member

  • Instance data members are those whose memory space is created each and every time whenever an object is created.
  • IDM are always meant for storing specific values.
  • Each and every instance data member must be access with respective object name.
  • Example: Objname.instance data member name
  • Instance data members are also known as Object Level Data Members because they depend on object name and independent from class name.
  • Syntax: datatype x, y, z, .... ;
  • Default value null or 0
  1. public class Employee
  2. {
  3. static String cname="HCL";
  4. String ename;
  5. public static void main (String ...a)
  6. {
  7. Employee e1 = new Employee();
  8. Employee e2 = new Employee();
  9. e1.ename="Uves";
  10. System.out.println(cname);
  11. System.out.println(e1.ename);
  12. System.out.println(e2.ename);
  13. }
  14. }
  15. To Compile - javac employee.java
  16. To Run - java Employee
  17. Result - HCL
    Uves
    null

| Copyright ©2016 | All Rights Reserved |
| Design by Uves Khan |

Free Web Hosting