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.
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.
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.
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++.
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 |
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 nounsigned
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 supportsenum
in some peculiar object-oriented way. In our opinion, it is not very user-friendly. However, use of interface is simpler in place ofenum
.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 ofconst
on a variable, we have to make use of keywordfinal
.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
andint
is same. Also, language tacitly tries to consider both data types as identical. In Java, the typeint
is four bytes. Hence, direct assignment tochar
(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 fromio
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
andcontinue
statements in C++ cannot have labels. Java supports labelledbreak
andcontinue
. 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 thefor loop
. But in C/C++, it is visible even outside the scope of thefor 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
returnsint
. In Java, it returnsvoid
. In C++, formain()
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 operatornew
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 functionvirtual
, 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 ofdrawLine
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++.
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.
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.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.#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.
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.
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.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.
finalize()
in that class. The garbage collector calls this method before removing the object from the memory.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.<<
” 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.
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.
(->)
: This operator was exclusively designed for use with pointers. As pointers are not supported, there is no place for this operator 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.
abstract
, we may convert it into an interface and then use it.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++.
In this section, we will see few programs from C++ converted into Java. Let us start with a simple program.
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.
Both the programs produce identical output. It is shown as follows.
Output
20000
40000
Note the various points
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
Passes
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
.
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
Max
is declared static
.percent()
is also declared static
.Student
is using method percent
which is global. It is not defined in class Student
.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:
struct Color
gets converted into class color
.public
.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.
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:
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:
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);
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
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:
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)
// 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.
program money1.java starts
Amount is Rs
25.15/-
Amount is Rs
22.12/-
after adding
Amount is Rs
47.27/-
unsigned byte, unsigned short,
and unsigned int
by simply int
in Java. Replace unsigned long
of C++ by simple long
in Java.#define max 100
by either final int max
= 100
; or interface.#include
with appropriate import
statements.StringBuffer
. If strings in C++ are not being modified in the program, you may use class String
in Java.18.118.24.106