Java and C++, Java and C++, The DifferenceThe Difference
An introductionAn introduction
Unit - 00Unit - 00
Unit IntroductionUnit Introduction
This unit highlights major This unit highlights major differences between Java and C++differences between Java and C++
Unit ObjectivesUnit Objectives
After covering this unit you will After covering this unit you will under-stand the major areas where under-stand the major areas where Java and C++ differJava and C++ differ
Different AreasDifferent Areas Program StructureProgram Structure Console input/outputConsole input/output Data TypesData Types ArraysArrays PointersPointers Parameter PassingParameter Passing Exception HandlingException Handling
Different Areas (contd)Different Areas (contd) InheritanceInheritance PolymorphismPolymorphism Memory Management Memory Management
Program StructureProgram Structure File Extension NamingFile Extension Naming
Java has a restriction of using the .java Java has a restriction of using the .java extension for the source code classesextension for the source code classes
C++ does not impose this restriction, C++ does not impose this restriction, and the compiler’s configuration file and the compiler’s configuration file can be changed to compile the source can be changed to compile the source file with any namefile with any name
File NamingFile Naming In Java, the source file should be same
as that of the class name inside the source file
Program Structure Program Structure (contd)(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 In C++, there is no restriction of source file name matching with class namename matching with class name
Compiling the CodeCompiling the Code The Java source code is translated into JCode The Java source code is translated into JCode
(byte code) by compiler that can be executed by (byte code) by compiler that can be executed by a JVMa JVM
The C++ source code is translated into .obj by The C++ source code is translated into .obj by compiler and is linked into an executable by the compiler and is linked into an executable by the linkerlinker
Program Structure Program Structure (contd)(contd) Type of ProgramsType of Programs
In C++, common program types are In C++, common program types are executable (.exe), static link library (.lib) executable (.exe), static link library (.lib) and dynamic link library(.dll)and dynamic link library(.dll)
In Java, common program types are In Java, common program types are executable, and Applet (running in a executable, and Applet (running in a web browser)web browser)
Running a ProgramRunning a Program JVM (on any platform) is required to run JVM (on any platform) is required to run
a Java program (platform independent)a Java program (platform independent) C++ program is platform dependentC++ program is platform dependent
Example: Program Example: Program StructureStructure Java application example Java application example
// HelloApp.java Application// HelloApp.java Application
package hello;package hello; // HelloApp class belongs to hello // HelloApp class belongs to hello // package// package
import java.io.*;import java.io.*; // use classes in java.io package// use classes in java.io package
public class HelloApppublic class HelloApp
{{
public static void main( String[] args) throws IOExceptionpublic 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);
}}
}}
Example: Program Structure Example: Program Structure (contd)(contd)
C++ exampleC++ example
// hello.cpp Application// hello.cpp Application
#include <iostream.h>#include <iostream.h>
void main (void)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;char* student = name;
cout << "Hello, " << student << ".\n";cout << "Hello, " << student << ".\n";
}}
Program Structure Program Structure (contd)(contd)
Class DeclarationClass Declaration Basic syntax differenceBasic syntax difference InheritanceInheritance Abstract classesAbstract classes Final classesFinal classes Sections within a classSections within a class
Method DeclarationsMethod Declarations Types of methods (global, instance, Types of methods (global, instance,
static)static) Declaration and definitionDeclaration and definition
Program Structure Program Structure (contd)(contd)
Java Class Code Example:Java Class Code Example:
[public] [abstract] [final] class ClassName[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
}}
Program Structure Program Structure (contd)(contd)
C++ class code exampleC++ class code exampleclass classNameclass className
{{
[public:][public:]
public data memberspublic data members
public member functionspublic member functions
[protected:][protected:]
protected data membersprotected data members
protected member functionsprotected member functions
[private:][private:]
private data membersprivate data members
private member functionsprivate member functions
[public:][public:]
public data memberspublic data members
public member functionspublic member functions
};};
Program Structure Program Structure (contd)(contd)
Variable declarationsVariable declarations Similarities and differencesSimilarities and differences InitializationInitialization
ConstantsConstants In Java:In Java:
final int X = 10;final int X = 10;
class Employeeclass Employee
{{
final static int CVSALARY = 3000; // class final static int CVSALARY = 3000; // class };}; // level constant variable// level constant variable
In C++:In C++:const int X = 10;const int X = 10;
#define X 10#define X 10
Program Structure Program Structure (contd)(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
Console Input/OutputConsole Input/Output Output exampleOutput example
JavaJavaSystem.out.println("Have a nice day");System.out.println("Have a nice day");
C++C++cout << "Have a nice day" << endl;cout << "Have a nice day" << endl;
Input ExampleInput Example C++C++
cin >> x;
JavaJavaSystem.in.read(x);System.in.read(x);
Data TypesData Types In C++ data type size is platform In C++ data type size is platform
dependentdependent In Java date type size is constant In Java date type size is constant
on all platformson all platforms Java and C++have similar basic Java and C++have similar basic
data typesdata types
ArraysArrays In JavaIn Java
Array is treated as an object in JavaArray is treated as an object in Java [] operator is overloaded[] operator is overloaded length, an instance variablelength, an instance variable Must allocate memory before using itMust allocate memory before using it Can’t be accessed outside rangeCan’t be accessed outside range ArrayIndexOutOfBoundsException ArrayIndexOutOfBoundsException
for exception handlingfor exception handling Can be of Primitive and Object typesCan be of Primitive and Object types
Arrays (contd)Arrays (contd)
In C++In C++ In C++, an array variable is considered In C++, an array variable is considered
to be nothing more than a pointer to the to be nothing more than a pointer to the first element in the arrayfirst element in the array
Array variables and pointer variables Array variables and pointer variables can be used interchangeablycan be used interchangeably
Example: ArraysExample: Arrays Java exampleJava example
// Array declaration// Array declaration
int x[] = new int[5]; // declare and define (recommended)int x[] = new int[5]; // declare and define (recommended)
// OR// OR
int[] x = new int[5]; int[] x = new int[5]; // declare and define// declare and define
// OR// OR
int x[];int x[]; // declare only// declare only
x = new int[size];x = new int[size]; // define, when size is known// define, when size is known
// Array initialisation// Array initialisation
x[0] = 1;x[0] = 1;
x[1] = 2;x[1] = 2;
x[2] = 3;x[2] = 3;
x[3] = 4;x[3] = 4;
Example: Arrays (contd)Example: Arrays (contd) Java example (contd)Java example (contd)
// Array declaration and initialisation// Array declaration and initialisation
int a1[] = {1, 2, 3, 4, 5};int a1[] = {1, 2, 3, 4, 5}; // declare, define, // declare, define, initializeinitialize
// OR// OR
// Java 1.1 onwards// Java 1.1 onwards
int y[] = new int[] {1, 2, 3, 4, 5}; // declare, define and int y[] = new int[] {1, 2, 3, 4, 5}; // declare, define and // initialize// initialize
Example: Arrays (contd)Example: Arrays (contd) C++ exampleC++ example
int list[] = new int[100];int list[] = new int[100]; // declare and define list// declare and define list
// OR// OR
int list[100]; int list[100]; // declare and define list// declare and define list
// OR// OR
int *list;int *list; // declare list// declare list
......
list = new int[100];list = new int[100]; // define list later on// define list later on
// array is initialized explicitly// array is initialized explicitly
PointersPointers PointersPointers
In Java, there are no pointersIn Java, there are no pointers In C++, a variable that can hold the In C++, a variable that can hold the
address to an object, is called a address to an object, is called a pointer pointer
ReferencesReferences In Java, an object variable only is a In Java, an object variable only is a
reference to an object value that is reference to an object value that is stored elsewherestored elsewhere
In C++, object variables hold object In C++, object variables hold object values values
Pointers (contd)Pointers (contd) Pointer assignments and Pointer assignments and
InitializationInitialization
Employee* p = NULL; // initialize p with NULLEmployee* p = NULL; // initialize p with NULL
Employee* q = new Employee("Hacker, Harry", 35000); Employee* q = new Employee("Hacker, Harry", 35000);
Employee* r = q; Employee* r = q; // r and q point to same employee// r and q point to same employee
// create an employee object// create an employee object
Employee boss("Morris, Melinda", 83000);Employee boss("Morris, Melinda", 83000);
Employee *t = &boss; // initialize t with boss’s addressEmployee *t = &boss; // initialize t with boss’s address
Parameter PassingParameter Passing By ValueBy Value
Both in Java and C++Both in Java and C++ By ReferenceBy Reference
Only in C++Only in C++
Example: Parameter Example: Parameter PassingPassing
// By Value (both in C++ and Java)// By Value (both in C++ and Java)
FunctionByVal(int a)FunctionByVal(int a)
{{
// any changes made to ‘a’ does not affect the original // any changes made to ‘a’ does not affect the original
// value// value
}}
// By Reference (in C++ only)// By Reference (in C++ only)
FunctionByRef(int &a)FunctionByRef(int &a)
{{
// any changes made to ‘a’ affects the original value// any changes made to ‘a’ affects the original value
}}
// Note: Java requires functions to be inside a class. No // Note: Java requires functions to be inside a class. No
// global function declarations allowed// global function declarations allowed
Exception HandlingException Handling In Java compile time exceptions need to In Java compile time exceptions need to
be caught and are checked at compile be caught and are checked at compile time, unlike runtime exceptionstime, unlike runtime exceptions
In C++ all exceptions are treated as In C++ all exceptions are treated as runtime exceptions and no exceptions runtime exceptions and no exceptions are checked at compile timeare checked at compile time
Structural differenceStructural difference In Java, there is an (optional) In Java, there is an (optional) finallyfinally block block
with a try-catch block, whereas in C++ with a try-catch block, whereas in C++ there is no such blockthere is no such block
In C++ catching (…) means catching all In C++ catching (…) means catching all typestypes
Example: Exception Example: Exception HandlingHandling// Java exception handling// Java exception handling
void f() throws EmployeeException, OrderException {void f() throws EmployeeException, OrderException {
}}
void g() {void g() {
try {try {
f();f();
}}
catch(EmployeeException e) {catch(EmployeeException e) {
// …// …
throw e;throw e;
}}
catch(OrderException* o) {catch(OrderException* o) {
// …// …
throw o;throw o;
}}
// optional // optional finallyfinally clause clause
finally {finally {
}}
}}
Example: Exception Handling Example: Exception Handling (Contd.)(Contd.)
// C++ exception handling// C++ exception handling
void f() throw (EmployeeException, OrderException) {void f() throw (EmployeeException, OrderException) {
}}
void g() {void g() {
try {try {
f();f();
}}
catch(EmployeeException* e) {catch(EmployeeException* e) {
// …// …
rethrow;rethrow;
}}
catch(OrderException* o) {catch(OrderException* o) {
// …// …
rethrow;rethrow;
}}
catch(…){catch(…){
//…//…
}}
}}
InheritanceInheritance Single InheritanceSingle Inheritance
Allowed in Java and C++Allowed in Java and C++ Multiple InheritanceMultiple Inheritance
Allowed only in C++Allowed only in C++ Syntax DifferenceSyntax Difference
Inheritance (contd)Inheritance (contd) Single inheritance syntax in JavaSingle inheritance syntax in Java
public class <ClassName> extends <ParentClass>
{
}
Single inheritance syntax in C++Single inheritance syntax in C++
class <className> : public <ParentClass>
{
};
Inheritance (contd)Inheritance (contd) No multiple inheritance in JavaNo multiple inheritance in Java
Instead, multiple interfaces could be Instead, multiple interfaces could be implementedimplemented
class <className> extends <ParentClass> implements
<SomeInterface>
{
}
Multiple inheritance syntax in C++Multiple inheritance syntax in C++
class <className> : public <ParentClass>, public <SomeOtherClass>
{
};
PolymorphismPolymorphism JavaJava
Using inheritanceUsing inheritance Using function overloadingUsing function overloading Using interfacesUsing interfaces
In C++In C++ Virtual functionVirtual function Pure virtual functionPure virtual function
Example: PolymorphismExample: Polymorphism Java example using inheritanceJava example using inheritance
Public class Employee Public class Employee
{{
public void performDuty() { //... }public void performDuty() { //... }
}}
public class Developer extends Employee public class Developer extends Employee
{{
public void performDuty() { //... }public void performDuty() { //... }
}}
public class Manager extends Employee public class Manager extends Employee
{{
public void performDuty() { //... }public void performDuty() { //... }
}}
Example: Polymorphism Example: Polymorphism (contd)(contd)
Java example using Inheritance Java example using Inheritance (contd)(contd)
public class Department public class Department
{{
public void duty(Employee emp) public void duty(Employee emp)
{{
emp.performDuty();emp.performDuty();
}}
public static void main(String[] arg) public static void main(String[] arg)
{ {
Department dpt = new Department();Department dpt = new Department();
dpt.duty(new Developer());dpt.duty(new Developer());
dpt.duty(new Manager());dpt.duty(new Manager());
}}
}}
Example: Polymorphism Example: Polymorphism (contd)(contd)
Java example using function Java example using function overloadingoverloading
public class Developerpublic class Developer
{{
public void performDuty(int id) {System.out.println(id);}public void performDuty(int id) {System.out.println(id);}
public void performDuty() {System.out.println(-1); }public void performDuty() {System.out.println(-1); }
public static void main(String[] arg) public static void main(String[] arg)
{ {
Developer dev = new Developer();Developer dev = new Developer();
dev.performDuty();dev.performDuty();
dev.performDuty(100);dev.performDuty(100);
}}
}}
Example: Polymorphism Example: Polymorphism (contd)(contd)
Java example using interfacesJava example using interfacesinterface Report ()interface Report ()
{{
void print();void print();
}}
public class Developer implements Reportpublic class Developer implements Report
{{
public void performDuty() { //... }public void performDuty() { //... }
public void print() { //... }public void print() { //... }
}}
public class Manager implements Reportpublic class Manager implements Report
{{
public void performDuty() { //...}public void performDuty() { //...}
public void print() { //...}public void print() { //...}
}}
Example: Polymorphism Example: Polymorphism (contd)(contd)
Java example using interfaces Java example using interfaces (contd)(contd)
public class Department public class Department
{{
public void doPrinting(Employee emp) public void doPrinting(Employee emp)
{{
emp.print();emp.print();
}}
public static void main(String[] arg) public static void main(String[] arg)
{ {
Department dpt = new Department();Department dpt = new Department();
dpt.doPrinting(new Developer());dpt.doPrinting(new Developer());
dpt.doPrinting(new Manager());dpt.doPrinting(new Manager());
}}
}}
Example: Polymorphism Example: Polymorphism (contd)(contd) C++ exampleC++ example
#include <iostream>#include <iostream>
class Instrument class Instrument
{{
public:public:
virtual void Play() const virtual void Play() const
{{
cout << "Instrument::play" << endl;cout << "Instrument::play" << endl;
}}
};};
class Wind : public Instrument class Wind : public Instrument
{{
public:public:
void Play() const void Play() const
{{
cout << "Wind::play" << endl;cout << "Wind::play" << endl;
}}
};};
Example: Polymorphism Example: Polymorphism (contd)(contd)
C++ example (contd)C++ example (contd)class Piano : public Instrument class Piano : public Instrument
{{
public:public:
void Play() const void Play() const
{{
cout << ”Piano::play" << endl;cout << ”Piano::play" << endl;
}}
};};
Example: Polymorphism Example: Polymorphism (contd)(contd)
C++ example (contd)C++ example (contd)
void tune(Instrument& i) void tune(Instrument& i)
{{
i.Play();i.Play();
} }
int main() int main()
{{
Wind flute;Wind flute; // flute is an instrument// flute is an instrument
tune(flute);tune(flute);
Piano piano;Piano piano; // piano is also an insturment// piano is also an insturment
tune(piano); tune(piano);
}}
Memory ManagementMemory Management In Java, Garbage Collection In Java, Garbage Collection
mechanism collects all un-referenced mechanism collects all un-referenced objectsobjects
In C++, objects need to be released In C++, objects need to be released manually using manually using deletedelete
Chance of memory leak is minimised in Chance of memory leak is minimised in Java by Garbage Collection mechanismJava by Garbage Collection mechanism
Special care is required to deal with Special care is required to deal with pointers (initialization, referencing) to pointers (initialization, referencing) to minimise memory leaksminimise memory leaks
Unit SummaryUnit Summary
In this unit you have covered the In this unit you have covered the main differences in C++ and Java, in main differences in C++ and Java, in their architectures and their architectures and implementationimplementation