Monday 17 February 2020

Independent compilation in Java language


                    In this post, we will see Independent compilation in Java language

                     Check following programs.                     Here, we will write two programs Add.java and Sub.java . Add.java consists of function/method add() for addition of two numbers while Sub.java consists of sub() for subtraction.
                     We will access these functions/methods from Sample.java.  

                      Watch following video:

Watch on YouTube: https://www.youtube.com/watch?v=zC800XEJzA8

                     Check following program code.

Program (Add.java)

class Add
{
int add(int x, int y)
{
return x+y;
}
}
  

Program (Sub.java)

class Sub
{
int sub(int x, int y)
{
return x-y;
}
}
 
Program (Sample.java)

class Sample
{
public static void main(String args[])
{
int x=3,y=5;
int sum,s;
Add a=new Add();
Sub b=new Sub();
sum=a.add(x,y);
s=b.sub(x,y);

System.out.println("Addition: "+sum);
System.out.println("Addition: "+s);
}
}
  

Output (How to compile and execute)
>>> javac Add.java
>>> javac Sub.java
>>> javac Sample.java
>>> java Sample
Addition: 8
Addition: -2


Independent Compilation

                    C, C++, Java follows independent compilation i.e. we can compile above modules/files in any order. It doesn't affect on final output.

Check following:

Output
>>> javac Sample.java
>>> javac Sub.java
>>> javac Add.java
>>> java Sample
Addition: 8
Addition: -2

     
                   While language Ada follows Separate compilation i.e. Compilation should be done in proper order. Files which define functions should be compiled first and then compile the file which call these functions.

No comments:

Post a Comment