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

Slides:



Advertisements
Similar presentations
C++ Language Fundamentals. 2 Contents 1. Introduction to C++ 2. Basic syntax rules 3. Declaring and using variables.
Advertisements

INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Web Application Development Slides Credit Umair Javed LUMS.
Lab Information Security Using Java (Review) Lab#0 Omaima Al-Matrafi.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
Lab#1 (14/3/1431h) Introduction To java programming cs425
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Java Data Types  Everything is an Object  Except Primitive Data Types  For efficiency  Platform independent  Portable  “slow”  Objects are often.
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
CMSC 341 Introduction to Java Based on tutorial by Rebecca Hasti at
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Programming in Java; Instructor:Moorthy Introduction, Objects, Classes, Libraries1 Programming in Java Introduction.
OOP Languages: Java vs C++
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Programming Languages and Paradigms Object-Oriented Programming.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
Pointer Data Type and Pointer Variables
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Java Programming Robert Chatley William Lee
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
By Noorez Kassam Welcome to JNI. Why use JNI ? 1. You already have significantly large and tricky code written in another language and you would rather.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Copyright Curt Hill Variables What are they? Why do we need them?
Core Java Introduction Byju Veedu Ness Technologies httpdownload.oracle.com/javase/tutorial/getStarted/intro/definition.html.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Pengantar OOP Class-Java. 2 Software Development Tools Using Sun Java SDK alone Source File(s) (.java) Programmer Compiler (javac) Class File(s) (.class)
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Classes, Arrays & Pointers. Compiler & Linker expectations file1.cppfile2.cppfilen.cpp …. file1.ofile2.ofilen.o …. Linker application (executable) Compiler.
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
OOP Basics Classes & Methods (c) IDMS/SQL News
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
Exception Handling How to handle the runtime errors.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
C++ General Characteristics: - Mixed typing system - Constructors and destructors - Elaborate access controls to class entities.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Java and C# - Some Commonalities Compile into machine-independent, language- independent code which runs in a managed execution environment Garbage Collection.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Chapter 2 Objects and Classes
JAVA MULTIPLE CHOICE QUESTION.
Inheritance and Polymorphism
Student Book An Introduction
Chapter 2 Objects and Classes
Java Programming Language
The Building Blocks Classes: Java class library, over 1,800 classes:
CS201: Data Structures and Discrete Mathematics I
From C++ to Java Java history: Oak, toaster-ovens, internet language, panacea What it is O-O language, not a hybrid (cf. C++) compiled to byte-code, executed.
(Computer fundamental Lab)
Presentation transcript:

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

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

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

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

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

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

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

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

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); }}

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";}

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

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}

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};

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

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

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);

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

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

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

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;

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

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

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

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

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++

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

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

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 { }}

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(…){//…}}

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

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 { };

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 { };

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

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() { //... } }

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()); }}

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);}}

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() { //...} }

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()); }}

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;}};

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; }};

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);}

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

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