Transition from C++ to Java Walt Savitch University of California, San Diego

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Chapter 1: Computer Systems
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
Chapter 10 Introduction to Arrays
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
Slides prepared by Rose Williams, Binghamton University Chapter 1 Getting Started 1.1 Introduction to Java.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12A Separate Compilation and Namespaces For classes this time.
Pointer. Warning! Dangerous Curves C (and C++) have just about the most powerful, flexible and dangerous pointers in the world. –Most other languages.
Introduction to Java Programming, 4E
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
Outline Java program structure Basic program elements
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Introduction to Java A lab course by Dr. Junaid Ahmed Zubairi SUNY Fredonia.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Honors 101, Fall 2006 Please do not sit in back of room! Lots of info on web page Join the mailing list Download Eclipse and start using it Read the text.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Java CourseWinter 2009/10. Introduction Object oriented, imperative programming language. Developed: Inspired by C++ programming language.
Lecture 1: Overview of Java. What is java? Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Introduction to Java Programming with JBuilder 4
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Introduction to Information and Computer Science Computer Programming Lecture c This material (Comp4_Unit5c), was developed by Oregon Health and Science.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
S.W. Ma/CIM/LWL41211/2 Prog. IIA Page 1 HKIVE (Lee Wai Lee Campus) Department of CIM Course : Year 2 Module : Programming IIA Textbook : Introduction.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
From BlueJ to NetBeans SWC 2.semester.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Java and C++, The Difference An introduction Unit - 00.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Introduction to Java Programming with Forte Y. Daniel Liang.
Basics of Java IMPORTANT: Read Chap 1-6 of How to think like a… Lecture 3.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Chapter 1 Section 1.1 Introduction to Java Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Walt Savitch University of California, San Diego
Operator Overloading Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September 2006.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
FIRST JAVA PROGRAM. JAVA PROGRAMS Every program may consist of 1 or more classes. Syntax of a class: Each class can contain 1 or more methods. public.
Introduction to programming in the Java programming language.
National Taiwan University Department of Computer Science and Information Engineering National Taiwan University Department of Computer Science and Information.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Pengantar OOP Class-Java. 2 Software Development Tools Using Sun Java SDK alone Source File(s) (.java) Programmer Compiler (javac) Class File(s) (.class)
Component 4: Introduction to Information and Computer Science Unit 5: Overview of Programming Languages, Including Basic Programming Concepts Lecture 3.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
By Mr. Muhammad Pervez Akhtar
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Object Oriented Programming Lecture 2: BallWorld.
Introduction to Java Programming, 4E Y. Daniel Liang.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
Working with Java.
Java Programming Language
Transition from C++ to Java
Focus of the Course Object-Oriented Software Development
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Classes, Objects and Methods
FINAL EXAM Final Exam Tuesday, May 3: 1:00 - 3:00 PM (Phys 112)
Presentation transcript:

Transition from C++ to Java Walt Savitch University of California, San Diego

Java: even a simple program is not simple. public class Program1 { public static void main(String[] arg) { System.out.println("Hello World"); }

Some Similarities between C++ and Java Simple (primitive) types: int, double, char Control Structures if-else, switch, while, for Arithmetic expressions Both have a string type: C++ string, Java String. Arrays Both have classes. Both have a "main".

Some Differences between C++ and Java Java has automatic garbage collection. C++ does not. C++ has operator overloading. Java does not. C++ says "function". Java says "method". These require no explanation, unless students already know C++.

More Differences C++ classes can be avoided. Java classes cannot reasonably be avoided. C++ has built in console I/O. Java has no standard console input (but does have standard console output.) C++ and Java divide a program into pieces (for separate compilation) in different ways. These require some explanation.

C++ classes can be avoided. Java classes cannot reasonably be avoided.

Every compilation unit in Java is a class. A program is a class with a method named main: public class Program1 { public static void main(String[] arg) {

In Java, every method is a member of some class. You cannot have a freestanding (global) function in Java.

You can fake a "no classes" program in Java by making all methods static. But don’t do it!

A Sample Java Class

public class PetRecord { private String name; private int age;//in years public PetRecord(String initName, int initAge) { name = initName; if ((initAge < 0)) System.out.println("Error"); else age = initAge; }

public void writeOutput() { System.out.println("Name: " + name); System.out.println("Age: " + age + " years"); } }

C++ has built in console I/O. Java has no standard console input (but Java does have standard console output.)

C++: has cin, cout, cerr Java has: System.out.print and System.out.println but NO console input. Solutions?

Solutions: AP does not require console input. There are classes for console input that are not part of Java but written in Java: e.g., SavitchIn.readInt() JOptionPane, simple GUI I/O

C++ and Java divide a program into pieces (for separate compilation) in different ways.

C++: Traditionally has an interface (header) file, implementation file(s), application (driver) file. C++: Can confine a program to a single file if you want.

Java: A compilation unit is always a class definition. Every class is in a separate file (except for some special cases). No header files. Normally, you have no one file programs in Java.

More Subtle Differences C++ has pointer types. –Java has no pointer types. Assignment (=) and equality comparison (==) have minor differences. C++ gives a choice of parameter types. –Java: No choice of parameter types. Exception handling can be avoided in C++ –Exception handling is needed for some fundamental things in Java, e.g. file I/O.

Java has no pointer types But Java does have "pointers". In Java class (and array) types are REFERENCE TYPES. A reference is a "pointer". All class values in Java are handled as references, but it is all automatic. In Java primitive types are just like in C++.

In Java a primitive type variable holds values, just as in C++. int n = 42; Java a class type variable contains a reference ("pointer") to the object (value). However, this is all automatic. There are no pointer types as such in Java. PetRecord myDog = new PetRecord("Fido", 3); Note that all class objects are created dynamically.

Assignment (=) and equality comparison (==) have minor differences. On primitive (simple) types, = and == are the same in C++ and Java. In Java, = and == on classes (or arrays) are comparing references ("pointers"), and you cannot overload (redefine) = and == in Java.

Assignment (=) and equality comparison (==) have minor differences. If (n = 0) …. In C++ this is probably an error with no error message, assuming you meant to use ==. In Java this generates a compiler error. In Java ints neither are nor can they be type cast to Booleans

C++: a choice of parameter types. Java: no choice of parameter types. C++: Call-by-value –void f(int n); C++: Call-by-reference –void f(int& n); Other C++ variants: –void f(const int& n); –void f(const int n);

C++: a choice of parameter types. Java: no choice of parameter types. Java all parameters are call-by-value. But, it is almost like there are different parameter types for primitive types and classes.

Java: no choice of parameter types, but All primitive type parameters are automatically call-by- value. public void f(int n) {...} All class types are automatically something very much like call-by- reference. public void f(String n) {...}

C++: a choice of parameter types. Java: no choice of parameter types. Java Full Story: In Java primitive types are just like in C++. In Java class (and array) types are REFERENCE TYPES. A reference is a "pointer". All class values in Java are handled as references, but it is all automatic. All parameters are call-by-value of a reference.

C++: a choice of parameter types. Java: no choice of parameter types. Java Full Story: In Java all parameters are call-by-value. Parameter is a local variable initialized to the value of the argument. Primitive types no surprises. Class type (local) variables hold references. Class parameters are call-by-value of a reference.

Java: no choice of parameter types. public void change(PetRecord r) { r.name = "FooFoo"; } This really changes its PetRecord argument. public void change(int n) { n = 42; } This does not change its int argument.

Java: no choice of parameter types. public void change(int n) { n = 42; } This does not change its int argument. There is no way to write a Java method that has a parameter for an int variable and that changes the value of an argument variable.

There is no way to write a Java method that has a parameter for an int variable and that changes the value of an argument variable. So, how do you manage to cope? int n = computeNewValue(); OR use class objects.

public class Stuff { private int n;.... public void changeTheN(Stuff s) { s.n = 42; }

Exception handling can be avoided in C++ Exception handling is needed for some fundamental things in Java, e.g. file I/O. Solutions: AP requirements do not include file I/O. Teach exception handling. Fake it with "magic formulas"

AP Exception Requirements Covers exceptions as error messages. Does not cover try/throw/catch. Does not cover throws clause (declaring exceptions).

Exception handling in Java Fake it with "magic formulas" approach: public class TextFileOutputDemo { public static void main(String[] arg) throws IOException { PrintWriter outputStream = new PrintWriter(…)); outputStream.println("To file");

public class TextFileOutputDemo { //without magic formula: public static void main(String[] arg) { PrintWriter outputStream = null; try { outputStream = new PrintWriter( new FileOutputStream("out.txt")); } catch(FileNotFoundException e) {…} outputStream.println("To file");

Style Comparison C++/Java Java uses loooong names: e.g. FileNotFoundException while C++ uses some abbreviations Java spelling conventions: ClassName, variableName, methodName, LITERAL_NAME Java has an official commenting style: javadoc

Extracts an interface from a class definition. May not need full blown details for AP course, but be consistent with javadoc. Comments before method headings: /** javadoc comment style. */

Getting a Java Course Off-the-Ground Need some "magic formulas," but Move to real classes quickly. Do something about console input: add console input class use JOptionPane use magic formulas

"Magic Formulas" public class ProgramName { public static void main(String[] arg) { means "begin". Use this to explain simple flow of control then quickly move to classes and explain what this means.

Console Input You need to do something. Use SavitchIn or some other console input class or Use a very messy magic formula or Explain the formula (still messy) or Use JOptionPane.

GUIs (Graphical User Interfaces, i.e., Windowing Interfaces)

GUIs Not part of the AP requirements. Applets: Designed to be used over the internet. Can be used for ordinary programs, but have some problems and no easier than regular windowing systems. "Regular Windowing Systems": Swing Library is the latest version.

Java Software Java is well standardized. SDK (aka JDK) Java compiler is free. java.sun.com Works well with Windows and Unix: Want Java 2, version 1.4 or higher (Standard Edition is enough) Mac users have traditionally had limited choices, but things are better now. JJ works with all operating systems.

Java Software for Mac Good (free?) Java compiler for Mac OS X (I’m told): Some of the good IDE’s for Mac Code Warrior, BlueJ. JJ Works for any operating system.

IDEs Windows: –TextPad (shareware): – use with Sun SDK –Forte (free): java.sun.com –Borland: Mac: –BlueJ (free): –CodeWarrior: JJ: Works with all operating systems. –

Text Books Lots to choose from. For example, Walter Savitch Java: An Introduction to Computer Science and Programming, Prentice-Hall.