Data Types and Variables

Similar documents
CSE 307: Principles of Programming Languages

CS201 - Introduction to Programming Glossary By

Short Notes of CS201

20 Most Important Java Programming Interview Questions. Powered by

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Written by John Bell for CS 342, Spring 2018

Compiler Construction

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java Primer 1: Types, Classes and Operators

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Java Overview An introduction to the Java Programming Language

INHERITANCE. Spring 2019

Name of subject: JAVA PROGRAMMING Subject code: Semester: V ASSIGNMENT 1

Implementing Object Equivalence in Java Using the Template Method Design Pattern

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

22c:111 Programming Language Concepts. Fall Types I

A brief introduction to C programming for Java programmers

C11: Garbage Collection and Constructors

Declarations and Access Control SCJP tips

Programming Languages Third Edition. Chapter 7 Basic Semantics

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Points To Remember for SCJP

2 rd class Department of Programming. OOP with Java Programming

Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

CS558 Programming Languages

Definition of DJ (Diminished Java)

C++ Programming: Polymorphism

Programming Language Concepts: Lecture 2

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Class, Variable, Constructor, Object, Method Questions

Objects Managing a Resource

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Concepts of Programming Languages

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Programming Languages, Summary CSC419; Odelia Schwartz

STRUCTURING OF PROGRAM

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

1 Shyam sir JAVA Notes

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Designing Robust Classes

15CS45 : OBJECT ORIENTED CONCEPTS

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

Fundamentals of Object Oriented Programming

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Introduction to Java Written by John Bell for CS 342, Spring 2018

The Java Programming Language

CS558 Programming Languages

Student Performance Q&A:

Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B

Introduction to Programming Using Java (98-388)

Java Review Outline. basics exceptions variables arrays modulo operator if statements, booleans, comparisons loops: while and for

Implications of Substitution עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Messages, Instances and Initialization

JAVA BASICS II. Example: FIFO

Index COPYRIGHTED MATERIAL

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

C10: Garbage Collection and Constructors

The role of semantic analysis in a compiler

Object-Oriented Programming

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Types and Static Type Checking (Introducing Micro-Haskell)

THE ORTHOGONALITY IN C++ *

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Compiler Construction

Selected Java Topics

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

G Programming Languages - Fall 2012

CS304- Object Oriented Programming LATEST SOLVED MCQS FROM FINALTERM PAPERS. MC

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

explicit class and default definitions revision of SC22/WG21/N1582 =

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות

Topic IV. Parameters. Chapter 5 of Programming languages: Concepts & constructs by R. Sethi (2ND EDITION). Addison-Wesley, 1996.

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

CS360 Lecture 5 Object-Oriented Concepts

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Topic 9: Type Checking

Topic 9: Type Checking

Chapter 6. Data Types

CLASS DESIGN. Objectives MODULE 4

EMBEDDED SYSTEMS PROGRAMMING OO Basics

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

CSCI312 Principles of Programming Languages!

Pace University. Fundamental Concepts of CS121 1

Java Fundamentals (II)

JAVA MOCK TEST JAVA MOCK TEST IV

Chapter 7. Inheritance

JavaScript: Sort of a Big Deal,

Transcription:

A P P E N D I X H A C++ / Java ComPArison New Languages Learning to move from one language to another is a fact of life for today s software professionals. Whether or not C++ is your first programming language, it will undoubtedly not be your last. It is not uncommon for a software professional to be fluent in at least a half dozen or more programming languages of various types. Categories of languages include general purpose languages (C++, Java, C#, Smalltalk), scripting languages (Perl, Python), Web-based languages (Javascript, PHP, Curl), functional languages (ML, Haskell), AI languages (Common Lisp, Prolog), and many others. Java and C++ are currently the two most commonly used general purpose programming languages. For this reason many programmers find it useful to have at least a passing familiarity with both languages. Fortunately, Java was inspired by C++ and many features, such as the control flow statements if, while, and for, were adopted almost without change. In this appendix we will describe the most basic differences between the two languages. Further information on the Java language can be found in [1] (see page H7). Information on moving to C++ if Java is your first programming language can be found in [2]. Data Types and Variables In C++ the number of bits used by an integer is implementation dependent. While many compilers use 32-bit integers, there are some machines that use 16-, 20-, 36-, or even 64-bit integers. In Java the language specifies that an integer must be exactly 32 bits. The Boolean type is called boolean in Java, not bool as in C++. The Java string type is called String. It is similar to the C++ string type, but note the following differences. Java strings cannot be modified (they are implicitly const, in C++ terms). Java strings store 16-bit Unicode characters, not 8-bit ASCII characters. You can concatenate strings with any type of object in Java, while in C++ strings can only be combined with strings. To compare strings in Java, use the member functions equals or compareto. Both take an argument string. The function equals returns a Boolean, while compareto returns an integer value that is less than zero if the first string is smaller than the H1

H2 Appendix H A C++ / Java Comparison second, zero if they are equal, and greater than zero if the first is larger than the second. String p = "abc"; String q = "pqr"; if (p.compareto(q) < 0)... Many member functions in the Java string class have functionality (substrings, indexing) similar to, but names different from their C++ counterparts. Java does not have explicit pointer values or references, although internally pointers are used extensively (see the section on Objects, below). Variables, Constants, and Functions The Java compiler is obligated to check that local variables and data members are initial ized before they are used. This eliminates a common error in C++ programs. It is not possible to create global variables or functions that are not associ ated with a class in Java. That is, the only functions in Java are member functions. Member functions in Java are often called methods. Java does not have the const reserved word. An analogous reserved word, final, means that a value can not be reassigned. While not exactly the same (a final value can change its internal state, while a const in C++ cannot change in any way), the two are frequently used in the same fashion. Classes Although classes in C++ and Java are similar in intent, there are a number of superficial differences between them: In Java inheritance is signaled by the reserved word extends, rather than a colon. In Java the visibility modifiers public, protected, and private are attached to each data member and member function independently, rather than dividing the class definition into sections. All classes inherit from a base class in Java. If no explicit base class is specified, the class Object is used as a base class. Therefore, all classes ultimately inherit from a single base class named Object. The member function bodies are placed directly in the class definition, rather than being written separately. There is no semicolon at the end of a class. There is no virtual reserved word. All member functions are implicitly virtual (and thereby potentially subject to being overridden).

Appendix H A C++ / Java Comparison H3 There is no data member initializer list. Data members are initialized by an assignment state ment in the body of a constructor. To pass data values to the constructor for a base class, the reserved word super is used. The reserved word super is also used to refer to a base class when a derived class wishes to invoke an overridden member function. This replaces the use of qualified names in C++ programs. The member function changesalary in the example below illustrates this use. The following is an example Java class definition: public class Manager extends Employee public Manager(String name, int salary, double bp) super(name, salary); // Invoke constructor for Employee base class bonus_percent = bp; bonus = bp * salary; void changebonus(double new_bp) bonus_percent = new_bp; bonus = bonus_percent * salary; void changesalary(int new_salary) super.changesalary(new_salary); // Invoke function from base class bonus = bonus_percent * new_salary; private int bonus; private double bonus_percent; Interfaces Java supports a concept called an interface. An interface looks superficially like a class, but uses the reserved word interface rather than class. An interface cannot include variable data members (although it can include constants that is, data members declared using the modifier final), and does not provide implementations for mem ber functions. In C++ terms, it is as if each member function were a pure virtual. An interface is therefore a description of a set of desired behaviors, with no implemen tation. The following illustrates the syntax: /** Interface for collections that can be searched. */ interface LookUp

H4 Appendix H A C++ / Java Comparison /** @param name the name being examined @return true if the name is part of the collection */ public boolean contains(string name); /** @param name the name of the value desired @return object associated with a given name */ public Object find(string name); A class indicates that it supports the interface with the implements reserved word. It must then provide an implementation for each member function defined by the interface. class SearchableContainer implements LookUp... public boolean contains(string name) Implementation here Java does not support multiple inheritance of classes. However, it does allow a class to implement multiple interfaces. Objects The most notable difference between Java and C++ is the treatment of objects. In Java object variables are treated internally as pointers. The Java literature refers to object variables as references, although they are not exactly the same as C++ refer ences. (For example, Java object variables can be reassigned, whereas C++ refer ences cannot. Java object variables can be null, but C++ references can never be NULL.) This means that all Java objects must be created using the new reserved word, as in the following: Employee sarah = new Employee( Sarah Smith, 67000); Parentheses are required even if there are no arguments being passed to the constructor. Note carefully that the variable is declared as a simple name, not as a pointer. Java does not have the pointer/non-pointer distinction. Even arrays must be created using the new operator. The size is not included as part of the declaration, but instead as part of the new operation: Employee[] department = new Employee[10]; // Create 10 new Employee values The number of elements in an array can be determined using a data member named length, as in department.length. Assignment in Java is equivalent to the assignment of pointers in C++. That is, assignment establishes the two values as referring to the same object, instead of making a true copy as in C++: Manager fred = new Manager("Fred Smith", 47000, 120); Manager james = fred; // Now they refer to the same object. james.changebonus(200); // Now fred s bonus is also changed.

Appendix H A C++ / Java Comparison H5 To make a true copy in Java you must explicitly define a member function that returns a clone. Functions In Java every function is associated with a class. There are no global variables, nor ordinary (that is, nonmember) functions. To execute a Java program you specify the starting class, and the function named main in that class is invoked. The function main does not return a value in Java. Function invocations pass object references by value. There is no equivalent to the C++ pass by value or pass by reference. This is illustrated by the following: class RewardSystem // Functions can only be found in classes public void yearendupdate(manager man) man.changebonus(0.35); // Update bonus to 35% man = new Manager("Sally Jones", 47000, 23); // Unlike C++ pass by reference, will NOT change the value of the // actual argument. RewardSystem man_class = new RewardSystem(); Manager fred = new Manager("Fred Smith", 47000, 120); man_class.yearendupdate(fred); // Will have the effect of changing // the value fred.bonus Arrays and Array Lists All Java arrays are allocated on the heap: String[] names = new String[100]; Note that the [] is placed with the type, not the variable name. The analog to the C++ vector is the ArrayList. You use the get and set methods, not the [] operator, to access the elements: ArrayList<String> names; names.add("harry"); // The analog of push_back names.add("lisa"); for (int i = 0; i < names.size(); i++) String name = names.get(i); names.set(i, "***");

H6 Appendix H A C++ / Java Comparison Memory Management In C++ the programmer is explicitly required to manage dynamic memory using the new and delete operators. Java includes a garbage collection system as part of its runtime library. The garbage collector monitors a running program and automati cally recovers memory when it can no longer be used. This eliminates many mem ory leaks that can plague C++ programs. Exception Handling Exception handling is much more tightly integrated in Java than it is in C++. There are two categories of exceptions: checked exceptions (similar to runtime_error in C++), and unchecked exceptions (similar to logic_error in C++). Member functions that potentially can throw a checked exception must declare this using the throws reserved word. The compiler ensures that an invocation of such a function occurs in the context of a try/catch statement that will handle the exception. Values thrown must be objects from a class that is derived from a system class named Throwable. There are other small differences in the various forms of the catch statement; these are described in [2]. public class Employee... void initializefromfile(file f) throws IOException... if (...) throw new IOException("Cannot Initialize"); Employee fred = new Employee(); File fin = new File("fred.data"); try fred.initializefromfile(fin); catch (IOException e) System.out.println("Received I/O Exception " + e); catch (Exception e) // Catch any other type of exception System.out.println("Received other exception " + e);

Appendix H A C++ / Java Comparison H7 Standard Library While the Java language is arguably smaller and simpler than C++, the same cannot be said for the standard library. The Java standard library is enormous, covering such features as internationalization, networking, mathematics, sound, Web applications and services, databases, and much more. Because the library is continually being added to, no reference can be entirely comprehensive. Most programmers are familiar with only a tiny fraction of this library. The most up-to-date information can be found at the official Java Web site, http://java.sun.com. Further Reading 1. Cay Horstmann, Big Java, 4th ed. (John Wiley & Sons, Inc., 2010). 2. Timothy Budd, C++ for Java Programmers (Addison-Wesley, 1999).