Now that we have covered C++ in some detail, discussing concepts of object-oriented programming as applied to C++, it makes sense to discuss the similarities and differences between C++ as we have used it so far, and Java as we have begun to use it. The good news is that there are enough similarities between the languages to allow a programmer to have a choice to use the correct language for the application to be developed, without having to enter a whole new thought process.
This section will discuss some general differences between the syntax used in the C++ and Java languages. There are some key differences between Java and C++ that must be noted when dealing with a discussion of data types:
In Java the char type has 2-bytes to allow support for international character sets as opposed to the single byte in C++. The boolean type in Java is a true boolean type and not just the int value of 0 and non-zero, as in C++. The value stored in a boolean type variable must either be boolean myFlag = 1; // not allowed - even if you try to use a cast A reference in Java to use objects is similar to the way that we use objects in C++. Account a = new Account(500.0); In C++ the In Java when we create a reference without calling a constructor, it will be initialised to Account a; This account reference Type conversion - Historically C++ casts between pointers and references were unchecked. This has been improved in recent years, preventing us from using a pointer to invoke a method on an object that the pointer "is aware of" but the object "is not aware of". In Java casts that always succeed are allowed, but casts that will always fail are detected at compile time. In C++ and Java, the compiler performs type checking during the first pass, preventing the incorrect use of arguments in methods, assignments etc. This is called static type checking. The Java language includes dynamic type checking, where some type checking is also performed at run-time, providing for powerful checks, but leading to a performance decrease. As discussed previously, we have the block comment and end of line comment formats in C++. These formats are supported by Java and have the exact same syntax. Java has the addition of a third type of comment beginning with /** and ending with */ relating to the javadoc tool that is in the /** This is a method to lodge money to the account object * @author Derek Molloy * @version 1.0 * @param amount - The amount to be lodged * @return void */ public void makeLodgement(float amount) { ... } Once you have written the code, you can run the javadoc application on the specified file/package. This will then generate the HTML format documentation for your code. The Java API documentation was created using an internal SUN version of javadoc. The Java garbage collector manages all memory in Java. It reclaims all
When discussing Memory management and Garbage Collectors it is useful to discuss some aspects of how memory is laid out while the program is running, in particular how memory is arranged. There are six different places to store data:
There are generally few problems with this fact as Java provides suitable replacement through the use of well-formatted references. In Java all methods must be defined within a class. There are no global methods or variables. This might seem unreasonable, but it works well. For example, the mathematical routine square root can be accessed through the Native strings in C++ are represented by an array of characters, terminated by '/0'. Strings in Java are objects of the In Java, when you declare an array of a class, you could say: Integer[] a = new Integer[5]; But this creates only an array of references, you must then instantiate each reference, using a[1] = new Integer(); Even for the default constructor (as shown). In C++, when you declare: Integer[5]; C++ would call the default constructor for each instance of the array, and there would be no need to explicitly call 'new' again to instantiate each reference of the array. This form of initialisation only allows you to call the default constructor (or constructor with no parameters). In C++, you can create an array of objects, with each object sitting right next to each other in memory, which lets you move from one object to another, simply by knowing the address of the first object. This is impossible in Java. In C++ you can also create arrays, of pointer or references to objects. This is more closely related to how Java arrays work. Java arrays are always an array of references to objects (except if you create arrays of the basic data types, int, float, double etc.). If you were to use an array of pointers or references, you would have an array of null references (just like Java). The syntax would be like: This C++ code segment shows how to create an array of #include <iostream> #include <string> using namespace std; class A{ private: int x; public: A(int); A(); virtual void display(); }; A::A() {} A::A(int y): x(y) {} void A::display() { cout << "Object has the value " << x << endl; } class B{ private: A arr[10]; //default A constructor A() is called here (10 times). public: B(); virtual void display(); }; B::B() { for(int i = 0; i < 10; i++) arr[i] = A(i); //the non-default constructor // A(int) is called here (10 times). } void B::display() { for(int i = 0; i < 10; i++) arr[i].display(); } int main(){ B b; b.display(); } A Java array is guaranteed to be initialized and cannot be accessed outside of its range. The range checking comes at the price of having a small amount of memory overhead on each array as well as verifying the index at run time, but the assumption is that the safety and increased productivity is worth the expense Java has run-time bounds checking on arrays, throwing an exception when an operation is performed that is out of bounds. There is a special instance variable called When you create an array of objects in Java, you are really creating an array of references, and each of those references is automatically initialized to a special value with its own keyword In Java all variables of the standard types (as detailed in the section called “Data Types”) and references are passed by value (i.e., never by reference or by pointer). For example: public class Test { public void square(int x) { x = x*x; } public Test() { int y = 5; System.out.println(" The value of y is " + y); // outputs 5 square(y); System.out.println(" The value of y is " + y); // outputs 5 } public static void main(String[] args) { new Test(); } } In Java if you pass an object to a method, you are always passing a reference to the object (NB: NOT passing by reference, you are passing this reference by value). This means that even though you are passing the reference by value, you are always operating on the original object., just as if you had used pass-by-reference in C++. For Example: 1 2 3 public class SomeClass 4 { 5 public int x = 2; // just for demonstration - set public 6 } 7 8 public class Test 9 { 10 public void square(SomeClass s) { s.x = s.x * s.x; } 11 12 public Test() 13 { 14 SomeClass y = new SomeClass(); 15 System.out.println(" The value of SomeClass x is " + y.x); 16 // outputs 2 17 18 square(y); 19 System.out.println(" The value of SomeClass x is " + y.x); 20 // outputs 4 21 } 22 23 public static void main(String[] args) 24 { 25 new Test(); 26 } 27 } 28 29 When dealing with assignments in Java we have a very important difference between code written in C++ and code written in Java, that on initial inspection seems exactly the same. Looking at the C++ version: /* In C++ */ Account a(600); CurrentAccount b(500,5000); //bal = 500, overdraft = 5000 a = b; a.display(); // results in "I am an account" being displayed // with no mention of overdraft and a balance // of 500. The compiler would have prevented b = a; Looking at the equivalent Java version: /* In Java */ Account a; CurrentAccount b = new CurrentAccount(500,5000); a = b; a.display(); // results in "I am a current account" // with an overdraft of 5000 and a balance of 500 In C++ when we assign Constructors work almost exactly the same way in C++ and Java. If you do not define a constructor for a class then it is allocated a default constructor. If we do define a constructor then we must use it. The only significant difference is that there is no copy constructor in Java. There are no destructors in Java, even thought there is a Like C++, in Java we have
In Java there is no direct equivalent to Inheritance in Java does not change the protection level of the members in the base class. You cannot specify In C++ methods are non-virtual by default, so to replace the behaviour (allow over-riding) of a method in the derived class you have to explicitly use the C++ allows multiple inheritance - Java does not! As discussed previously in the C++ section of the notes, multiple inheritance is complex for the programmer, in that they must make complex decisions about the way that the data of the base class is to be inherited. In Java, we do not have multiple inheritance but we do have the use of Interfaces. Interfaces are a special kind of abstract class that have no data or implemented code. Interfaces might not sound too useful, but they allow a form of multiple inheritance, without having the associated difficulties of dealing with data. This replacement behaviour works very well and does not impact on development, once you get used to the change. There is no scope resolution operator in Java - such as In Java we have the facility to define a class inside of another class. We refer to this class as an inner class. The only issue worth mentioning with inner classes is that they have full access to the private data and methods of the class in which they are nested. Because of this, we do not need to pass state pointers to methods that need callback. In C++ we had inline methods, generally short methods that the compiler in effect cuts-and-pastes the method code into the final program, leading to greater efficiency as the assembly language program counter is not jumping around in the final executable. There is of course a trade-off between speed of execution and size of the executable. There are no inline methods in Java - well that's not entirely true. It is up to the compiler to decide whether a method should or should not be inline. There is a keyword in Java called There are no forward declarations of classes/methods necessary in Java. The compiler takes care of all definitions of methods and does not throw an error until it is sure that the method or class has not been defined elsewhere. The standard Java libraries are supplied by Oracle and are comprehensive. In C++, the programmer uses third party code libraries that do not integrate very well with each vendor. Java provides comprehensive standard libraries from application development to networking and database access providing us with a fully integrated development language. Exception handling allows run-time errors to be handled directly by the programmer. An exception object is thrown from the line of code where the error occurred and is caught by a suitable exception handler, specially designed for that type of error. Exceptions are in effect control statements that allow a different path of execution when errors occur to the normal path when no errors occur. In the Java and C++ languages exceptions cannot be ignored by the programmer, rather they must deal with them, leading to more robust applications. Exceptions exist outside of object-oriented languages, but in object-oriented languages an object is used to describe the exception. While we did not cover exceptions in C++, they are available. However, exception specifications in Java are vastly superior to those in C++. Instead of the C++ approach of calling a function at run-time when an exception is thrown, Java exception specifications are checked and enforced at compile-time. In addition, Java over-ridden methods must conform to the exception specification of the base-class version of that method: they can throw the specified exceptions or exceptions derived from those. This provides much more robust exception-handling code. Java has support built into the language for multi-threading, C++ does not. I will add more to this document as issues arise. If you notice any errors or omissions in the document then please drop me an e-mail. [10] See: http://www.hpl.hp.com/personal/Hans_Boehm/ and http://www.hpl.hp.com/personal/Hans_Boehm/gc/index.html These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way. |