Pages

Wednesday, January 25, 2017

JAVA PROGRAM TO FIND SUMMATION OF TWO COMPLEX NUMBER USING STATIC FUNCTION AND MEMBER DATA

Hello Friends,Welcome back to Technology learning Raj Roushan after such a long time.
Today I am telling about java program by requesting by my friends.Today i am going to tell you how to write java program to find summation of two complex number Using static method and member data.And why static function can not access the non-static member variable of class.

Java Program

import java.io.*;
class complex
{
int r,i;
int relno,imgno; //this is not accessible by accessible by static class this will generate an error
static int relno,imgno;//this is accessible because static function can access static data
complex()
{
r =0;
i=0;
}
public static void sum(complex c,complex d)
{
relno=c.r+d.r;
imgno=c.i+d.i;
System.out.println("The sum is "+relno+"+"+imgno+"i");
}
public void read()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nEnter the real part");
r=Integer.parseInt(br.readLine());
System.out.println("\nEnter the imaginary part");
i=Integer.parseInt(br.readLine());
System.out.println("\nYou have entered : "+r+"+"+i+"i");
}
public static void main(String s[])throws IOException
{
complex c=new complex();
complex d=new complex();
System.out.println("First number");
c.read();
System.out.println("\nSecond number");
d.read();
/*complex add=new complex();
add.sum(c,d);    this is wrong because object is not required for calling static function i will explain in below*/
sum(c,d);
}
}
The output


non-static member variables of a class always belong to an object – meaning that every object has it’s own personal copy of non-static member variables (also known as instance variables). And, static functions have no object to work with since they belong to the class as a whole. Remember that you can call a static function without an object – and for that exact reason a static function can not call instance variables.