CHAPTER 25

MOVING FROM C++ TO JAVA

Many programmers learn C++ before learning Java. Unwittingly, one starts comparing the two languages. Since both the languages are object oriented and Java has kept the basic syntax of C++, learning Java can be much faster (if not simpler) for C++ programmers.

This section is divided in three parts. In the first part, we will compare keywords in the two languages and the effect thereof. In the second part, we will examine all the differences in the two languages in detail. In the third part, we will show how small- and medium-sized C++ programs can be converted into Java programs.

25.1 Part I: Comparing Keywords

25.1.1 Keywords

Let us start on a positive note. If you know C++, you know the heart of Java. The following is the list of keywords which are common to both C++ and Java. They are used in more or less the same manner.

ch25-ufig1

Now, let us see the keywords which are different in the two languages. The following are the keywords of C++ which are absent in Java.

ch25-ufig2

In Java, keywords const and goto are reserved for future use.

Java is developed as a machine-independent, safe, and secure language. Naturally, it debars any attempts which are machine dependent as well as potentially unsafe. Most of the keywords of C++ which are removed by Java fall in this category. Let us see the impact of their removal in brief. (See Table 25.1)

 

Table 25.1 Keywords of C++ not Supported by Java

Keyword Implications of absence
asm No support for assembly language. We cannot embed assembly code in the source
auto As it is a default behaviour, its absence has no implications
delete No freeing of memory per force. This task is assigned to in-built mechanism called garbage collection
enum Cannot associate names to numbers. (This facility adds elegance to a code. The new version of Java has introduced some functionality recently. It has introduced class Enum.)
extern No external variables in a file
friend A non-class method cannot access private data of the class
inline No high-speed execution of certain functions
operator No operator overloading
register Cannot force a variable to be located in a high-speed register
signed No implications, as all numeric data are signed in Java
sizeof Cannot find size of variables and objects directly
struct No implication as a class can represent a struct
template Generic programming not available. (However, from version 5 generic programming is supported by Java.)
typedef Cannot specify complex data type
union Memory sharing by different types of variables is not possible
unsigned A chance to handle twice the larger number is lost
virtual Cannot force child class to redefine a function
const Cannot declare a const directly (However, keyword final gives a somewhat similar result)

After looking at what is not supported, let us see the keywords which are newly added in Java.

The following are the keywords of Java which are not part of C++.

ch25-ufig3

Its implications in brief are described in Table 25.2.

 

Table 25.2 Keywords of Java which are not Present in C++

Keyword Implications of addition
boolean Natural handling of conditions and other Boolean quantities
byte Natural handling of most primitive data type. Also reduces the memory requirement if data needs only a byte
extends Just emphasizes inheritance. Replaces “:” from C++
final Makes a variable non-modifiable. Another way to declare constants
Prevents a method being overridden
Makes a class non-inheritable
finally Adds power to try-catch mechanism
implements Support for interface
import Allows us to use packages. Somewhat equivalent to #include
instanceof Allows verifying whether an object belongs to a particular class
interface New way of looking at objects. No equivalence in C++
native Allows using methods developed in languages other than Java
package Allows user to keep reusable code together. In some way similar to pre-compiled header files
strictfp Forces strictness while performing floating-point calculations
super Helps in reaching base class variables
synchronised Helps prevent threads from invoking methods concurrently
throws Used in exceptions
transient Marks the field which is not used in serialization

25.2 Part II: Differences as a Programming Language

Now let us turn our attention to the differences in the two languages from the perspective of programming language. Let us discuss them in step by step.

Identifiers: Character $ is not allowed as a part or start of a variable name in C++. It is allowed in Java. As Java uses Unicode, many non-English letters are available as characters for forming identifiers.

Data types: In Java, all integer types are stored as signed quantities. There is no unsigned tag in Java. This is not a great disadvantage. Modern computers have memory in Megabytes. Saving of few bytes has no significance today. Many years before, when personal computers were introduced, they had only 640 kilobytes of memory (RAM). Unsigned integers were relevant those days as the maximum value stored by them was twice as that of the signed variable.

There is no direct equivalent of enum in Java. However, its effect can be obtained by defining an interface. In our opinion, enum adds elegance to a code. It may be noted that from version 5 (JDK 5) that Java supports enum in some peculiar object-oriented way. In our opinion, it is not very user-friendly. However, use of interface is simpler in place of enum.

Java does not support pointers as a data type. Those switching from C/C++ find some difficulty. However, computer scientists have discussed advantages and disadvantages of pointers at length. Inadvertent use of pointers many times produce errors which are difficult to debug. The decision of the developers of Java not to allow user-defined pointers is a very good decision in our opinion. It must be stated that generic advantages of pointers are not lost in Java. Java internally uses pointers as object references. We can have dynamic data structures in Java without any difficulty.

At present, Java does not support keyword const. If we want C++ like action of const on a variable, we have to make use of keyword final.

Operators and expressions: Java has added an operator “>>>”. While shifting bits to right, it treats the number as unsigned.

Relational expressions return Boolean value in Java. In C++, such expressions return integer. In C/C++ true and false are represented by 1 and 0, respectively. However, change by Java adds more elegance and safety from inadvertent errors.

In Java modulo operator (%) can accept floating-point operands. This is a useful operator with integer operands. However, so far we have not found a great use of this operator with floating-point operands.

In Java, you can assign a character variable to integer but not vice versa, whereas in C++ you are allowed to do so. Actually, in C++ the size of char and int is same. Also, language tacitly tries to consider both data types as identical. In Java, the type int is four bytes. Hence, direct assignment to char (which is two bytes) is not possible.

Java does not allow floating-point values to be assigned to integer-type variables directly (without typecasting).

The operators “>>” and “<<” are no longer used in input/output. We have to use methods from various classes available from io package.

Initialization of variables: C++ does not flag compilation error, when un-initialized variables are used. This is sure to create unexpected errors. Java refuses to compile such a code. In this case, Java is a better language than C++.

Statements: j+k;, which is a valid expression statement in C++, is invalid in Java. Actually, such a statement cannot have any action. Hence, Java is right in disallowing it.

break and continue statements in C++ cannot have labels. Java supports labelled break and continue. This allows a structured way of leaving a loop.

Loops: Both the languages allow declaring a control variable inside the for loop. In Java, such a variable is visible only within the scope of the for loop. But in C/C++, it is visible even outside the scope of the for loop.

Functions: In C/C++ (old style), if a method does not have any parameter, we can write void as the parameter list. This is not allowed in Java.

In Java, every function is a method belonging to some class. There is no concept like general or global (not belonging to a class) functions as in C/C++.

In Java, basic parameter passing is only by value. C++ allows parameter passing both by value and by reference. Primitive data types are strictly passed by value. It implies that you cannot write method swap(int x, int y).

Aggregate data types are to be passed by reference. The programmer does not have any choice over it. Hence, swapping of objects is possible but you have to write the code properly.

In C++, you can add keyword const to parameters. This facility is absent in Java. Thus, parameter passing is far less flexible in Java than in C/C++. In C++, it is the programmer who decides how to pass any parameter.

Local variables of methods could be static in C++. They retain their values after invocation of the method. This concept is not supported in Java. Keyword static cannot be applied to local variables.

In C++, function main returns int. In Java, it returns void. In C++, for main() parameters are optional, while for Java parameter (String[] args) is mandatory.

Arrays: In Java, if an array index value is out of range, runtime error occurs. This is a very good feature. It does not produce unintended errors. This feature is not supported in C/C++.

In Java arrays are created (memory allocated) only using operator new. In C/C++, the operator new may or may not be used.

Strings: Strings in Java are not null terminated as in C++. Strings are objects of class String. This class is very rich in methods. In C++, strings are not immutable while in Java they are.

To provide mutable strings, Java offers a separate class called StringBuffer. C++ does not need such a separate class.

Strings cannot be lexicographically compared using operators like “>” or “<=” in Java. This is possible in C++.

Constructors: The concepts of default constructor in C++ and Java are a bit different. When you define a class without any constructor, the System supplies a default constructor. In Java, it initializes the members to zero values whereas in C++ members are not initialized to zero values.

In case we have defined one or more constructors and one of them is without parameters, that constructor becomes the default constructor.

In C++, when you declare an object without any constructor, default constructor gets called. In Java, there is no way an object comes in to existence without call to new. It naturally needs explicit call to some constructor, one without parameters (default) or otherwise.

In Java, when you write a sub-class constructor, call to super is optional, when a super-class constructor without parameter exists. Only in this context, Java has any significance to the term “default constructor”.

Access specifier: In Java, access specifier applies only to what it precedes. In C++, access specifier is followed by “:”. The access specifier applies to all variables that follow.

Inheritance: Java does not support multiple inheritance. In this case, C++ can be considered as more powerful than Java. However, there is very limited use of this facility. It also brings in its own complications. (See Programming in C++ by Bhave Patekar.)

Polymorphism: In Java, there is no keyword virtual. Consider a case where there is a method in sub-class with the same name as one in super-class. When a super-class reference refers to sub-class object, it always invokes methods in sub-class. It means what a C++ programmer achieves by declaring a function virtual, a Java program achieves it automatically.

Interface: There is no direct equivalent of interface in C++. Hence, C++ cannot give a uniform look and feel to its objects in a simple and straightforward manner. In this regard, Java scores over C++.

Graphics: There is no equivalent of method putpixel in Java. Use of drawLine has to be made to draw a point.

Packages: Packages are like header files in C++. Just as header files are ready to use, contents of a package is also ready to use. Both of them contain classes. In C++, header files can contain constants and functions. In Java, constants and functions (methods) do not have any existence outside a class. Hence, all required constants have to be embedded in either a class or an interface. All required methods are required to be put inside some suitable class. Packages can contain only classes and interfaces.

Exception Handling: Java supports keyword finally. This provides additional functionality to exception handling. As this keyword is absent in C/C++, this functionality is not available to programmers.

C++ does not require that an exception should be caught.

Applets: The concept of applets has been introduced for the first time in Java. Hence, there is no equivalence of it in C++. In this case, Java is more useful than C++.

25.2.1 Facilities in C++ missing in Java

In this section, we will discuss a few facilities of C++ which are not supported by Java. Those who learn Java as the first language do not find any difficulty in learning and using the language. However, those who know C/C++ before learning Java start comparing facilities of C++ with Java. Not finding many of these may make learners uncomfortable. This section tries to make C++ programmers comfortable while learning Java. We will not only discuss the facilities of C++ which are not supported by Java but also try to show some way out in such circumstances.

  1. No unsigned integers: Integer types are always signed in Java. We know that signed integer variables can also handle unsigned integer values. Hence, there will not be any difficulty while programming. Simply use the appropriate integer type (byte, short, int, or long) in place of an unsigned integer type. (See Program x1.cpp.) It will be worthy to note that if you need to handle very large integers (which you could not do in C++), there is a class BigInteger in Java.
  2. No typedef: This facility is grossly under utilized by C/C++ programmers. We find very few situations when it is necessary to use typedef. It may be noted that a class can have a member of any user-defined type. Hence, it will be quite easy to create a data structure created using typedef by suitably defining one or more classes.
  3. Pre-processor directives: Though pre-processor is a powerful concept, most C/C++ programmers use only two facilities, that is #include and #define.

    As far as #define is concerned, it only does the textual substitution. If we are using it in place of constants, then we have two choices in Java. We can either use keyword final or use an interface to define a constant. (See Program x2.)

    In C++ with #include you can put some uncompiled code (text file) in the source file. This facility is not available in Java. You have to actually copy that code in your source file.

    In C++, you can also include pre-compiled code (header files). In Java, you can replace it with import statement. Please note that the names of libraries in the two languages can be different. If there is no equivalence in Java, you have to develop a package first and then use import statement.

  4. No global variables and functions: In Java, all variables and function (methods) belong to some class. If we talk of small or medium (single file) programs, the class which is the main program class can contain variables and methods which can work as global. The trick is to declare them as static and simply forget that there is nothing like global in Java. (See Program x3 in this regard).

    If you are a serious programmer and writing a very huge program, you have to be a bit careful.

  5. No goto: Computer scientists voted out (or vetoed?) goto thirty years ago. If you still consider it a necessary statement in programming, something is really wrong with your training.
  6. No automatic-type conversion if loss: This is really a safety enhancement in Java. No reason to complain.
  7. No structures and union: The concept of class includes type struct. A class defined with all public members and no method is 100% substitute for struct. (See Program x4.)

    As far as union is concerned, Java has no direct solution. Programmers have to think of a suitable alternative. However, this facility is used only remotely in programming. Hence, an average programmer will not feel the loss of facility.

  8. No default arguments: With say two default arguments, we can call a method in three different ways. This faculty is not present in Java. But we know that Java allows us to overload the methods, that is we can have many methods with same name but different signatures. It means that we will have to define different overloaded methods. If you think that it will be tedious, you are wrong.
  9. Operator overloading: Java does not support the facility of operator overloading. You know that this facility was added to programming languages later. The programs with objects were written even earlier. So we have to use the old style of writing methods to accomplish the results. (See Program money1.cpp and Program 25.6 in Section 25.3.6)
  10. No destructors: Java does not support the concept of destructor. When the object goes out of scope, at a suitable time later, the garbage collector does the necessary work of removing the object from memory. If a programmer wants to perform a specific task (like releasing resources), he has to define method finalize() in that class. The garbage collector calls this method before removing the object from the memory.
  11. No delete operator: This is a natural as the task of deleting objects is assigned to the garbage collector. In C++, one may attempt new and delete cycles to use the available memory efficiently. In the old days when the memory of the computer was small, it was important to give power of destruction to the programmer. In present times, it is really not necessary. These days, memory is never seen as the bottleneck. Therefore, non-availability is not a disadvantage. On the other hand, inadvertent use of delete creates problems. Such problems are automatically avoided in Java.
  12. Operators<<and>>not overloaded in input/output: These operators were overloaded to merely add an alternate simple coding to the otherwise use of scanf/printf statements. This facility was not available in C. We may say Java in this respect follows C and not C++.

    It may be noted that printf statement is added in Java5. It serves the purpose of output. For input, one should use scanner class.

  13. No Pointer arithmetic: Pointer arithmetic was once considered the greatest tool for a programmer. However, it is not so today. In early days of computers, RAM memory was very less. Programmers had to manage within limited memory. Nowadays, pen drives of the size of a key chain have Megabytes of memory. Hence, any manipulation thereof is simply not required.

    In C/C++, pointers were used to create and manage arrays. Since this concept does not exist in Java, non-availability of pointer arithmetic is in no way a minus point of Java.

    On the other side, it is very hard to detect errors (bugs) entered into programs with the use of pointers. It takes thousands of man-days to remove them. If one starts using Java, these efforts are as good as gained.

  14. Absence of operator (->): This operator was exclusively designed for use with pointers. As pointers are not supported, there is no place for this operator in Java.
  15. Absence of scope resolution operator: Since Java class definition includes (textually) the member method definitions, this operator is not required in Java.

    If you see the following method defined in C++, say

     

    ThisClass::thatMethod() { }

    you have to physically move the code of thatMethod to ThisClass in Java programming.

  16. No multiple inheritance: Java does not support multiple inheritance. If you have to convert C++ class with multiple inheritance, you have no simple alternative. The whole class has to be redefined. When one of the super-class is abstract, we may convert it into an interface and then use it.
  17. Objects as parameter passing only by reference: You cannot pass objects by value. The only thing you should see is that the method does not modify any of the fields of the parameter. Such fields (variables) should not appear on the left-hand side of the assignment statement.

25.2.2 Facilities in Java not present in C++

As this book is on Java, all the features of Java are discussed in detail in the present text. Therefore, in this section we will discuss very briefly about those features of Java which are absent in C++.

  1. Multi-threading: Java supports multi-threading. Earlier versions of C/C++ did not support multi-threading. However, modern compilers of C++ have introduced some library functions to support multi-threading.
  2. Package: Packages are very useful in supplying already developed classes and interfaces. Though this feature is not available in C++, libraries of C++ roughly provide the same functionality.
  3. Interface: Interface is totally new in Java. There is no equivalence of it in C++. Some authors consider it just as an indirect way of providing multiple inheritance. We do not agree fully with this use. Proper use of interface gives elegant exterior view of objects, which is not possible with any of the available C++ features.
  4. Garbage collection: Java has provided in-built mechanism of garbage collection, thus reducing the burden on the programmer.
  5. Type String: Java supports type String and StringBuffer as in-built types. For this reason, its use is much less error prone than a null-terminated string of C/C++.
  6. Documentation comments: Java supports the facility of documentation comments, which has no equivalence in C/C++.

25.3 C++ to Java Through Programs

In this section, we will see few programs from C++ converted into Java. Let us start with a simple program.

25.3.1 Exercise one

As mentioned earlier, Java does not support unsigned integers. The Java integer can handle far larger values than even unsigned int of C++. Let us test this fact with our first conversion program.

Let us consider a simple C++ program using unsigned int. We know that in C++, type int can handle a maximum positive value of approximately 32 kilobytes. When we use type int, we will get an incorrect answer. However, unsigned int range extends to approximately 64 kilobytes. Hence, C++ program produces correct answer. If we convert it into Java, the Java program also gives us the correct answer.

Problem: Write a C++ program to demonstrate the use of keyword unsigned. Also write an equivalent Java program.

Solution: The following table shows a C++ program and the converted Java program (Program 25.1) side by side.

PROGRAM x1.cpp PROGRAM 25.1 Conversion I
Line number C++ program Equivalent Java program
     1 //    x1.cpp //    x1.java
     2 #include<IOSTREAM.H>  
     3   class x1
     4   {
     5 int main() public static void main(String args[])
     6 { unsigned int k =20000; { int k =20000;
     7   cout<< k<<endl; System.out.println( k );
     8    k=k*2;     k=k*2;
     9    cout<< k<<endl; System.out.println( k );
     10   return 0; //    return 0;
     11 }   }
     12   }

Both the programs produce identical output. It is shown as follows.

 

Output

 20000

 40000

Note the various points

Line number Remarks
   1 name of program changes from x1.cpp to x1.java
   2 #include is absent in Java program.
   3 class x1 has no equivalence in C++.
   4  
   5 main in Java is public static void. It also has parameter “String args[]”
   6  
   7 println statement replaces cout statement.
   8  
   9 println statement replaces cout statement.
   10 as java main is void it cannot return 0. Statement is commented out.
   11  
   12  

25.3.2 Exercise two

Here we will show how to handle directive #define in Java.

Let us take the familiar example of pass, fail, and percentage. See the following C++ program.

Problem: Write a simple C++ program to print pass/fail remark and the percentage. For passing, you need minimum 40 marks out of 100. Use #define to define constants MAX and MIN.

Solution: See the following C++ program.

 

PROGRAM x2.cpp

 //       x2.cpp

 #include<IOSTREAM.H>

 #define MAX 100

 #define MIN 40

 int main()

 { int mark = 75;

      if ( mark >= MIN ) cout<< "1. Passes" <<endl;

         else cout << "1. fails" <<endl;

      cout<< "2. Percentage = "<< 100.0* mark/MAX <<endl;

   return 0;

 }

We have explained earlier that there are two ways to do this task. In this example, we will demonstrate both the styles in this program.

See the corresponding Java program. (See Program 25.2)

 

PROGRAM 25.2 Conversion II

 //       x2.java

 class x2 implements exam

 { final static int MIN = 40 ; // Note-1

 public static void main(String args[])

      {

          int mark = 75;

          if ( mark >= MIN )System.out.println("1. Passes" );

                else System.out.println( "1. fails" );

          System.out.println("2. Percentage = " + 100.0* mark/MAX );

      }

 }

 interface exam

 { final static int MAX = 100 ; // Note-2

 }

If we run this program, we will get the following output.

 

Output

  1. Passes
  2. Percentage = 75.0

Let us explain the points involved in comments Note 1 and Note 2.

Note 1: We are using MIN as a constant. We have declared it as static and final.

Note 2: Here we have declared MAX as a constant, inside an interface named exam. The main class x2 implements exam.

25.3.3 Exercise three

In this section, we will see how to handle global variables and functions in a Java program. First, see the simple C++ program.

Problem: Define a class Student with fields for marks and percentage. Define a global variable to represent maximum marks 100. Also define a global method for calculating percentage.

Solution: See the following C++ program.

 

PROGRAM x3.cpp

 //    x3.cpp

 #include<IOSTREAM.H>

 int Max = 100; // global variable

 float percent( int marks) // global function

    {  return 1.0*marks/Max ;

    } ;

 class Student

       {  public:

          int marks ;

          float per ;

          Student(int m)

             {   marks= m;

                    per = percent(marks);

             }

       };

 int main()

 { Student myBest = Student(99);

   cout<< "Percentage = " << myBest.per <<endl;

   return 0;

 }

Now see the equivalent Java program. (See Program 25.3)

 

PROGRAM 25.3 Conversion III

 //    x3.java

 class x3

 {

       static int Max = 100; // global variable

       static float percent( int marks) // global function

          {  return (float) ( 1.0*marks/Max );

          }

   public static void main(String args[])

          {

             Student myBest = new Student(99);

             System.out.println("Percentage = " + myBest.per);

          }

 static class Student

   {      int marks ;

          float per ;

          Student(int m)

      {   marks= m;

          per = percent(marks);

      }

   };

 }

If you run the program, you will get the sample output as follows.

 

Output

 Percentage = 0.99

Please note that

  1. Global variable Max is declared static.
  2. The global method percent() is also declared static.
  3. Class Student is using method percent which is global. It is not defined in class Student.

25.3.4 Exercise four

In this section, we will see how to handle structures from C++ in a Java program. Let us first see the C++ program using structure.

Problem: Write a C++ program which defines and use structure colour. It should have integer fields red, green, and blue.

Solution: See the following C++ program.

 

PROGRAM x4.cpp (Uses Structures)

 //    x4.cpp

 #include<IOSTREAM.H>

 struct Color { int red,green,blue ;} ;

 int main()

 { Color yellow ={256,255,0} ;

   cout<< "red value "<< yellow.red <<endl;

   return 0;

 }

Let us study the converted Java program. (See Program 25.4)

 

PROGRAM 25.4 Conversion IV

 //   x4.Java

 class color { int red, green, blue ;}

 class x4

 {

   public static void main(String args[])

      {

          color yellow = new color();

          yellow.red = 255 ;

          yellow.green = 255 ;

          yellow.blue = 0 ;

          System.out.println("red value "+ yellow.red );

      }

 }

If you run the program, you will get the following output.

 

Output

 red value 255

Please note the following points:

  1. struct Color gets converted into class color.
  2. There is no constructor for this class.
  3. All the members have default access. It is as good as public.

25.3.5 Exercise five

In this section, we will try to take a sample program and literally convert it line by line. It will give us a thorough insight in structure of Java program.

Let us take a case of simple factorial program. A code in C++ is given hereafter. We will show how this program can be converted into Java in simple steps.

Problem: Write a C++ program to find the factorial of a given integer.

Solution: See the following program.

C++ Program: Finding Factorial
  1 //   factor1.cpp
  2 #include<IOSTREAM.H>
  3 #include<conio.h>
  4 long factor(int n ) ;
  5 int main()
  6 {    int n;
  7         long fact;
  8         cout << “program factor1.cpp starts” << endl;
  9         cout << “give n between 2 to 10 :” ;
  10         cin >> n;
  11         if ( (n<1)|| ( n>10) )
  12                       cout << cout << “error in input” ;
  13               else
  14               {   fact =factor(n);
  15                     cout << “factorial of n “ << n
  16                          << “ is “ << fact<< endl;
  17               }
  18       getch();
  19       return 0;
  20 }
  21 long factor(int n)
  22 {   int i; long temp =1;
  23     for (i=2;i<=n;i++)
  24           temp = temp * i ;
  25     return temp;
  26 }

Let us study what changes are needed in the aforementioned program.

Line1 We have to change the file name from factor1.cpp to factor1.java. Hence, the comment also has to be changed to factor1.java.
Line 2 In place of #include<IOSTREAM.H> we need import java.util.* ; This provides us the input capability.
Line 3 There is no equivalent of conio.h. Hence, this line is removed. Consequently, line 18, that is getch(), has to be removed.
Line 4 This is function declaration. It is not required in Java. It has to be removed.
Line 5 The syntax of main is different. public static void main(String args[])takes the place of int main().
Line 19 As main is of type void,return 0 at the main is to be removed.

With these changes, the program may look like the following:

  1 //     factor1.java
  2 import java.util.* ;
  3 //
  4 //
  5 public static void main(String args[])
  6 {  int n;
  7       long fact;
  8       cout << “program factor1.cpp starts” << endl;
  9       cout << “give n between 2 to 10 :” ;
  10       cin >> n;
  11       if ( (n<1)|| ( n>10) )
  12                 cout << cout << “error in input” ;
  13       else
  14             {    fact =factor(n);
  15                     cout << “factorial of n “ << n
  16                           << “ is “ << fact<< endl;
  17             }
  18 //
  19 //
  20 }
  21 long factor(int n)
  22 {  int i; long temp =1;
  23    for (i=2;i<=n;i++)
  24         temp = temp * i ;
  25    return temp;
  26 }

Well, these changes are not sufficient. Let us see what more.

We know that the whole program should be a public class named factor1. Hence, we have to add three lines class factor1, {“ and “}. We also know that function factor has to be part of this class. Hence, we have to add the closing curly bracket at the end of program. This will include the function in a class. This function factor has to be declared static.

With these changes, the program may look like the following:

  1 //    factor1.java
  2 import java.util.* ;
  3 //
  4 //
  5 public static void main(String args[])
{
  6 {    int n;
  7        long fact;
  8        cout << “program factor1.cpp starts” << endl;
  9        cout << “give n between 2 to 10 :” ;
  10        cin >> n;
  11        if ( (n<1)|| ( n>10) )
  12                   cout << cout << “error in input” ;
  13              else
  14              { fact =factor(n);
  15                   cout << “factorial of n “ << n
  16                         << “ is “ << fact<< endl;
  17              }
  18   //
  19   //
  20 }
  21 long factor(int n)
  22 {     int i; long temp =1;
  23       for (i=2;i<=n;i++)
  24             temp = temp * i ;
  25       return temp;
  26 }
  }

Lastly, we know that operator “<<” are not overloaded in Java. Also, there is no cout. Hence, we have to replace these output statements with appropriate System.out.print statement. Note that different entities printed are separated by plus sign (+) in Java. For input, we have to use the class Scanner and method nextInt().

With these changes, the Java program would look like the following: (See Program 25.5)

 

PROGRAM 25.5 Conversion V

 //  factor1.java

 import java.util.* ;

 class factor1

 {

   public static void main(String args[])

   {  int n;

      long fact;

      System.out.println( “program factor1.java starts”);

      System.out.print( “give n between 2 to 10 :” );

      Scanner cin = new Scanner(System.in);

      n = cin.nextInt();

      if ( (n<1)|| ( n>10) )

                System.out.println(“error in input”) ;

         else

            { fact =factor(n);

              System.out.println(“factorial of “ + n

                        + “ is “ + fact );

            }

      return ;

   }

   static long factor(int n)

   {  int i; long temp =1;

     for (i=2;i<=n;i++)

       temp = temp * i ;

     return temp;

   }

 }

If we run the program, we will get the following output.

 

Output

 program factor1.java starts

 give n between 2 to 10 :5

 factorial of 5 is 120

25.3.6 Exercise six

Operator overloading is not supported in Java. The tasks operators perform are to be delegated to methods in Java. In this program, we will define class Money. It will have an operator “+” overloaded. This operator will help us to add two amounts (objects of type Money). First, we will see a complete C++ program.

Problem: Write a C++ program to illustrate the overloading of operator “+”. For this purpose develop and use class Money.

Solution: See the following C++ program.

 

PROGRAM money1.cpp

 //   money1.cpp

 #include<iostream.h>

 #include<stdlib.h>

 #include<conio.h>

 class Money

          {   long rupee, paise ;

              public:

              void print() ;

              Money() ;

              Money(long p, long q);

              Money operator + ( Money a2 );

          } ;

 int main()

 { cout << “program money1.cpp starts” <<endl;

   Money amt1, amt2, amt3 ;

   amt1= Money( 25,15);

   amt2= Money( 22,12);

   amt1.print();

   amt2.print();

   cout << “after adding” << endl ;

   amt3 = amt1 + amt2 ;

   amt3.print();

   getch();

 return 0;

 }

 void Money::print()

 { cout << “Amount is Rs “;

   cout << rupee << “.” << paise << “/-“<< endl;

 }

 Money::Money()

 { rupee = paise=0; //initializing to zero value

 }

 Money::Money(long p, long q)

 {

   if ( (p<0) || (q<0) || (q>99) )

      {  cout<< “initialisation error ”<<endl;

            cout << “initialising with ZERO value”<<endl;

            p=q=0 ;

      }

      else

         {  rupee = p;

               paise = q;

         }

 }

 Money Money::operator+( Money a2 )

 { Money temp;

   temp.rupee = this->rupee + a2.rupee;

   temp.paise = this->paise + a2.paise;

   if (temp.paise >= 100 )

      {   temp.paise -=100;

          temp.rupee += 1;

      }

   return temp;

 }

Now let us study a Java program. This program will also have class Money. Instead of overloaded operator, it will have a method add(). It will return the object of type Money.

See the complete Java program. (See Program 25.6)

 

PROGRAM 25.6 Conversion VI

 //          money1.java

 class Money

       { long rupee, paise ;

          void print()

            { System.out.println( “Amount is Rs “);

              System.out.println(rupee + “.” + paise + “/-“) ;

            } ;

         Money()

            { rupee = paise=0; //initializing to zero value

            } ;

         Money(long p, long q)

            { if ( (p<0) || (q<0) || (q>99) )

                 {   System.out.println( “initialization error”);

                     System.out.println( “initializing with ZERO value”);

                     p=q=0 ;

                 }

                 else

                     {  rupee = p;

                        paise = q;

                     }

             } ;

          Money add ( Money a2 )

             {  Money temp= new Money();

                temp.rupee = this.rupee + a2.rupee;

                temp.paise = this.paise + a2.paise;

                if (temp.paise >= 100 )

                   {   temp.paise -=100;

                       temp.rupee += 1;

                   }

                return temp;

             } ;

        } ;

 public class money1

 {

   public static void main(String argv[])

   {  System.out.println( “program money1.java starts” );

      Money amt1, amt2, amt3 ;

      amt1= new Money( 25,15);

      amt2= new Money( 22,12);

      amt1.print();

      amt2.print();

      System.out.println( “after adding” ) ;

      amt3 = amt1.add( amt2) ;

      amt3.print();

    }

 }

If we run the program, we will get the following output.

Output

 program money1.java starts

 Amount is Rs

 25.15/-

 Amount is Rs

 22.12/-

 after adding

 Amount is Rs

 47.27/-

25.4 Rules for C++ to Java Conversion

  1. Replace unsigned byte, unsigned short, and unsigned int by simply int in Java. Replace unsigned long of C++ by simple long in Java.
  2. Replace #define max 100 by either final int max = 100; or interface.
  3. Replace all #include with appropriate import statements.
  4. In single file program, replace all global variables and functions by static variables and static methods in main program class.
  5. Replace structure by class without methods.
  6. Replace all C++ strings by StringBuffer. If strings in C++ are not being modified in the program, you may use class String in Java.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.24.106