Java Program to Create an Object for Class and Assign Value in the Object using Constructor

This is a Java Program to Create the Object for Class and to Assign Value in the Object Using Constructor.

Constructor is used to initialise the object. A constructor initializes an object immediately upon creation.

Here is the source code of the Java Program to Create the Object for Class and to Assign Value in the Object Using Constructor. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. public class Demo
  2. {
  3.     int a,b,c;
  4.     Demo()
  5.     {
  6.          a = 5;
  7.          b = 6;
  8.     }
  9.     void change()
  10.     {
  11.         a = 15;
  12.         b = 10;
  13.         c = a + b;
  14.     }
  15.     public static void main(String[] args) 
  16.     {
  17.         Demo obj1 = new Demo();
  18.         System.out.println("a:"+obj1.a);
  19.         System.out.println("b:"+obj1.b);
  20.         obj1.change();
  21.         System.out.println("New a:"+obj1.a);
  22.         System.out.println("New b:"+obj1.b);
  23.         System.out.println("c:"+obj1.c);
  24.     }
  25. }

Output:

$ javac Demo.java
$ java Demo
 
a:5
b:6
New a:15
New b:10
c:25

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.