Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java and C++, The Difference An introduction Unit - 00.

Similar presentations


Presentation on theme: "Java and C++, The Difference An introduction Unit - 00."— Presentation transcript:

1 Java and C++, The Difference An introduction Unit - 00

2 Unit Introduction This unit highlights major differences between Java and C++ This unit highlights major differences between Java and C++

3 Unit Objectives After covering this unit you will under-stand the major areas where Java and C++ differ

4 Different Areas Program Structure Program Structure Console input/output Console input/output Data Types Data Types Arrays Arrays Pointers Pointers Parameter Passing Parameter Passing Exception Handling Exception Handling

5 Different Areas (contd) Inheritance Inheritance Polymorphism Polymorphism Memory Management Memory Management

6 Program Structure File Extension Naming File Extension Naming Java has a restriction of using the.java extension for the source code classes Java has a restriction of using the.java extension for the source code classes C++ does not impose this restriction, and the compiler’s configuration file can be changed to compile the source file with any name C++ does not impose this restriction, and the compiler’s configuration file can be changed to compile the source file with any name File Naming File Naming In Java, the source file should be same as that of the class name inside the source file

7 Program Structure (contd) In Java, there should be only ONE class containing main(), and this class name must match with the source file name In C++, there is no restriction of source file name matching with class name In C++, there is no restriction of source file name matching with class name Compiling the Code Compiling the Code The Java source code is translated into JCode (byte code) by compiler that can be executed by a JVM The Java source code is translated into JCode (byte code) by compiler that can be executed by a JVM The C++ source code is translated into.obj by compiler and is linked into an executable by the linker The C++ source code is translated into.obj by compiler and is linked into an executable by the linker

8 Program Structure (contd) Type of Programs Type of Programs In C++, common program types are executable (.exe), static link library (.lib) and dynamic link library(.dll) In C++, common program types are executable (.exe), static link library (.lib) and dynamic link library(.dll) In Java, common program types are executable, and Applet (running in a web browser) In Java, common program types are executable, and Applet (running in a web browser) Running a Program Running a Program JVM (on any platform) is required to run a Java program (platform independent) JVM (on any platform) is required to run a Java program (platform independent) C++ program is platform dependent C++ program is platform dependent

9 Example: Program Structure Java application example Java application example // HelloApp.java Application package hello;// HelloApp class belongs to hello // package import java.io.*;// use classes in java.io package public class HelloApp { public static void main( String[] args) throws IOException public static void main( String[] args) throws IOException { byte name[] = new byte[20]; byte name[] = new byte[20]; System.out.println("What is your name? "); System.out.println("What is your name? "); System.in.read(name); System.in.read(name); String student = new String(name); String student = new String(name); System.out.println( "Hello, " + student); System.out.println( "Hello, " + student); }}

10 Example: Program Structure (contd) C++ example C++ example // hello.cpp Application #include #include void main (void) { char* name = new char[20]; char* name = new char[20]; cout << ”What is your name? "; cout << ”What is your name? "; cin >> name; cin >> name; char* student = name; cout << "Hello, " << student << ".\n"; cout << "Hello, " << student << ".\n";}

11 Program Structure (contd) Class Declaration Class Declaration Basic syntax difference Basic syntax difference Inheritance Inheritance Abstract classes Abstract classes Final classes Final classes Sections within a class Sections within a class Method Declarations Method Declarations Types of methods (global, instance, static) Types of methods (global, instance, static) Declaration and definition Declaration and definition

12 Program Structure (contd) Java Class Code Example: Java Class Code Example: [public] [abstract] [final] class ClassName { [public][Private][Protected] member Variable Declarations [public][Private][Protected] member Variable Declarations [public][Private][Protected] method Declarations [public][Private][Protected] method Declarations}

13 Program Structure (contd) C++ class code example C++ class code example class className { [public:] [public:] public data members public data members public member functions public member functions [protected:] [protected:] protected data members protected data members protected member functions protected member functions [private:] [private:] private data members private data members private member functions private member functions [public:] [public:] public data members public data members public member functions public member functions};

14 Program Structure (contd) Variable declarations Variable declarations Similarities and differences Similarities and differences Initialization Initialization Constants Constants In Java: In Java: final int X = 10; class Employee { final static int CVSALARY = 3000; // class };// level constant variable In C++: In C++: const int X = 10; #define X 10

15 Program Structure (contd) // declare and initialize pointer variables in C++ char *name = NULL;// name initialized to NULL … name = new char[21]; // memory allocated, one char // for NULL; name is 20 char

16 Console Input/Output Output example Output example Java Java System.out.println("Have a nice day"); C++ C++ cout << "Have a nice day" << endl; Input Example Input Example C++ C++ cin >> x; Java JavaSystem.in.read(x);

17 Data Types In C++ data type size is platform dependent In C++ data type size is platform dependent In Java date type size is constant on all platforms In Java date type size is constant on all platforms Java and C++have similar basic data types Java and C++have similar basic data types

18 Arrays In Java In Java Array is treated as an object in Java Array is treated as an object in Java [] operator is overloaded [] operator is overloaded length, an instance variable length, an instance variable Must allocate memory before using it Must allocate memory before using it Can’t be accessed outside range Can’t be accessed outside range ArrayIndexOutOfBoundsException for exception handling ArrayIndexOutOfBoundsException for exception handling Can be of Primitive and Object types Can be of Primitive and Object types

19 Arrays (contd) In C++ In C++ In C++, an array variable is considered to be nothing more than a pointer to the first element in the array In C++, an array variable is considered to be nothing more than a pointer to the first element in the array Array variables and pointer variables can be used interchangeably Array variables and pointer variables can be used interchangeably

20 Example: Arrays Java example Java example // Array declaration int x[] = new int[5]; // declare and define (recommended) // OR int[] x = new int[5]; // declare and define // OR int x[];// declare only x = new int[size];// define, when size is known // Array initialisation x[0] = 1; x[1] = 2; x[2] = 3; x[3] = 4;

21 Example: Arrays (contd) Java example (contd) Java example (contd) // Array declaration and initialisation int a1[] = {1, 2, 3, 4, 5};// declare, define, initialize // OR // Java 1.1 onwards int y[] = new int[] {1, 2, 3, 4, 5}; // declare, define and // initialize

22 Example: Arrays (contd) C++ example C++ example int list[] = new int[100];// declare and define list // OR int list[100]; // declare and define list // OR int *list;// declare list... list = new int[100];// define list later on // array is initialized explicitly

23 Pointers Pointers Pointers In Java, there are no pointers In Java, there are no pointers In C++, a variable that can hold the address to an object, is called a pointer In C++, a variable that can hold the address to an object, is called a pointer References References In Java, an object variable only is a reference to an object value that is stored elsewhere In Java, an object variable only is a reference to an object value that is stored elsewhere In C++, object variables hold object values In C++, object variables hold object values

24 Pointers (contd) Pointer assignments and Initialization Pointer assignments and Initialization Employee* p = NULL; // initialize p with NULL Employee* q = new Employee("Hacker, Harry", 35000); Employee* r = q; // r and q point to same employee // create an employee object Employee boss("Morris, Melinda", 83000); Employee *t = &boss; // initialize t with boss’s address

25 Parameter Passing By Value By Value Both in Java and C++ Both in Java and C++ By Reference By Reference Only in C++ Only in C++

26 Example: Parameter Passing // By Value (both in C++ and Java) FunctionByVal(int a) { // any changes made to ‘a’ does not affect the original // value } // By Reference (in C++ only) FunctionByRef(int &a) { // any changes made to ‘a’ affects the original value } // Note: Java requires functions to be inside a class. No // global function declarations allowed

27 Exception Handling In Java compile time exceptions need to be caught and are checked at compile time, unlike runtime exceptions In Java compile time exceptions need to be caught and are checked at compile time, unlike runtime exceptions In C++ all exceptions are treated as runtime exceptions and no exceptions are checked at compile time In C++ all exceptions are treated as runtime exceptions and no exceptions are checked at compile time Structural difference Structural difference In Java, there is an (optional) finally block with a try-catch block, whereas in C++ there is no such block In Java, there is an (optional) finally block with a try-catch block, whereas in C++ there is no such block In C++ catching (…) means catching all types In C++ catching (…) means catching all types

28 Example: Exception Handling // Java exception handling void f() throws EmployeeException, OrderException { } void g() { try { f();} catch(EmployeeException e) { // … throw e; } catch(OrderException* o) { // … throw o; } // optional finally clause finally { }}

29 Example: Exception Handling (Contd.) // C++ exception handling void f() throw (EmployeeException, OrderException) { } void g() { try { f();} catch(EmployeeException* e) { // … rethrow;} catch(OrderException* o) { // … rethrow;}catch(…){//…}}

30 Inheritance Single Inheritance Single Inheritance Allowed in Java and C++ Allowed in Java and C++ Multiple Inheritance Multiple Inheritance Allowed only in C++ Allowed only in C++ Syntax Difference Syntax Difference

31 Inheritance (contd) Single inheritance syntax in Java Single inheritance syntax in Java public class extends { } Single inheritance syntax in C++ Single inheritance syntax in C++ class : public { };

32 Inheritance (contd) No multiple inheritance in Java No multiple inheritance in Java Instead, multiple interfaces could be implemented Instead, multiple interfaces could be implemented class extends implements { } Multiple inheritance syntax in C++ Multiple inheritance syntax in C++ class : public, public { };

33 Polymorphism Java Java Using inheritance Using inheritance Using function overloading Using function overloading Using interfaces Using interfaces In C++ In C++ Virtual function Virtual function Pure virtual function Pure virtual function

34 Example: Polymorphism Java example using inheritance Java example using inheritance Public class Employee { public void performDuty() { //... } } public class Developer extends Employee { public void performDuty() { //... } } public class Manager extends Employee { public void performDuty() { //... } }

35 Example: Polymorphism (contd) Java example using Inheritance (contd) Java example using Inheritance (contd) public class Department { public void duty(Employee emp) {emp.performDuty();} public static void main(String[] arg) { Department dpt = new Department(); dpt.duty(new Developer()); dpt.duty(new Manager()); }}

36 Example: Polymorphism (contd) Java example using function overloading Java example using function overloading public class Developer { public void performDuty(int id) {System.out.println(id);} public void performDuty() {System.out.println(-1); } public static void main(String[] arg) { Developer dev = new Developer(); dev.performDuty();dev.performDuty(100);}}

37 Example: Polymorphism (contd) Java example using interfaces Java example using interfaces interface Report () { void print(); } public class Developer implements Report { public void performDuty() { //... } public void print() { //... } } public class Manager implements Report { public void performDuty() { //...} public void print() { //...} }

38 Example: Polymorphism (contd) Java example using interfaces (contd) Java example using interfaces (contd) public class Department { public void doPrinting(Employee emp) {emp.print();} public static void main(String[] arg) { Department dpt = new Department(); dpt.doPrinting(new Developer()); dpt.doPrinting(new Manager()); }}

39 Example: Polymorphism (contd) C++ example C++ example #include #include class Instrument { public: public: virtual void Play() const virtual void Play() const { cout << "Instrument::play" << endl; cout << "Instrument::play" << endl; }}; class Wind : public Instrument { public: public: void Play() const { cout << "Wind::play" << endl; cout << "Wind::play" << endl;}};

40 Example: Polymorphism (contd) C++ example (contd) C++ example (contd) class Piano : public Instrument { public: public: void Play() const { cout << ”Piano::play" << endl; cout << ”Piano::play" << endl; }};

41 Example: Polymorphism (contd) C++ example (contd) C++ example (contd) void tune(Instrument& i) { i.Play(); i.Play(); } int main() { Wind flute;// flute is an instrument Wind flute;// flute is an instrument tune(flute); tune(flute); Piano piano;// piano is also an insturment tune(piano);}

42 Memory Management In Java, Garbage Collection mechanism collects all un-referenced objects In Java, Garbage Collection mechanism collects all un-referenced objects In C++, objects need to be released manually using delete In C++, objects need to be released manually using delete Chance of memory leak is minimised in Java by Garbage Collection mechanism Chance of memory leak is minimised in Java by Garbage Collection mechanism Special care is required to deal with pointers (initialization, referencing) to minimise memory leaks Special care is required to deal with pointers (initialization, referencing) to minimise memory leaks

43 Unit Summary In this unit you have covered the main differences in C++ and Java, in their architectures and implementation In this unit you have covered the main differences in C++ and Java, in their architectures and implementation


Download ppt "Java and C++, The Difference An introduction Unit - 00."

Similar presentations


Ads by Google