39
COMP 150-CCP COMP 150-CCP Concurrent Programming Concurrent Programming Lecture 6: Java for C++ Programmers Dr. Richard S. Hall [email protected] Concurrent programming – February 5, 2008

Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

  • Upload
    others

  • View
    11

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

COMP 150-CCPCOMP 150-CCPConcurrent ProgrammingConcurrent Programming

Lecture 6:Java for C++ Programmers

Dr. Richard S. [email protected]

Concurrent programming – February 5, 2008

Page 2: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

AgendaAgenda

● High-level description of differences● Hello world comparison● Class source files● Primitive types● Packages● Class path● Compiling and executing● Stack implementation comparison● Interfaces, generics, nested classes● Java Runtime Libraries● Programming tools

Page 3: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java & C++ SimilaritiesJava & C++ Similarities

● Object-oriented languages Classes and methods Inheritance and overloading

● Similar C-like syntax

Page 4: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java & C++ DifferencesJava & C++ Differences

● Java programs are not native executables● No header files in Java● No macro preprocessor in Java● No structs in Java● Garbage collection in Java, no explicit delete● No multiple inheritance

Java also defaults to virtual methods● No operator overloading● No global scope in Java● All non-primitive variables must be declared on

the heap (i.e., with new)● No pointers, practically everything is a pointer

Page 5: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

C++ Hello World Example (1/2)C++ Hello World Example (1/2)

File helloworld.h:

#ifndef __HELLO_H__#define __HELLO_H__#include <string>

using namespace std;

class HelloWorld {public: void SayHello(string s);}; #endif

Page 6: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

C++ Hello World Example (2/2)C++ Hello World Example (2/2)

File helloworld.cpp:

#include <iostream>#include "helloworld.h"

void HelloWorld::SayHello(string s) { cout << "Hello, " << s << "!" << endl;}

int main() { HelloWorld hw; hw.SayHello("Richard"); return 0;}

Output:Hello, Richard!

Page 7: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Hello World ExampleJava Hello World Example

File HelloWorld.java:

package helloworld;

public class HelloWorld { public void sayHello(String s) { System.out.println("Hello, " + s + "!"); } public static void main(String[] args) { HelloWorld hw = new HelloWorld(); hw.sayHello("Richard"); }}

Output:Hello, Richard!

Page 8: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Class Source FilesJava Class Source Files

● End with .java● Typically contain only one class

Can only have one public class, but may have multiple non-public classes

▴ Best practice is to use one class per file

● Named after the class contained inside e.g., class name = Stack, file name = Stack.java

● Convention is that class names start with a capital letter, method names start with lower case letter and use camel case

e.g., Class.myMethod()● Class source files are compiled into byte code

files with .class extension

Page 9: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Primitive TypesJava Primitive Types

● Primitive types include: byte, short, char, boolean, int, long,

float, double, void On the other hand, arrays are not primitive types, they

are special kinds of objects▴ e.g., they have the .length member

● Primitive types are not objects Can only be allocated on the stack Follow pass-by-copy semantics

▴ Arrays follow pass-by-reference semantics

● All primitive types have corresponding class definitions in java.lang

Byte, Short, Character, Boolean,Integer, Long, Float, Double, Void

Page 10: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Packages (1/2)Java Packages (1/2)

● Java class files are grouped into packages The package statement at beginning of source file

indicates to which package the class belongs▴ If no package specified, then class is in “default” package

But always specify a package!

Typically, all classes in a package will also be in the same directory on disk

Classes in a package can access each other's protected fields and methods

● Packages can be arranged in a hierarchy, but no special meaning in the parent/child relationship

Typically, packages are represented as hierarchical directories in the file system

Page 11: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Packages (2/2)Java Packages (2/2)

● A fully qualified class name is comprised of package and class name separated by periods

e.g., java.lang.String

● You can refer to classes by their full name or can import them to use only the class name

Similar to using namespace in C++ e.g., import foo.MyClass;

▴ Allows you to simply refer to MyClass in your code

e.g., import foo.*;▴ Allows you to refer to all classes in foo by only their name

The java.lang package is imported by default,so all classes in it can be referred to by their name

Page 12: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Class PathJava Class Path

● Like most platforms, Java defines a search order for locating class byte code

Similar to PATH and LD_LIBRARY_PATH for Windows and UNIX/Linux

● Nothing special Just a list of library archive files and/or directories to

search for compiled classes

● The default class path includes the built-in libraries

● Used for compiling and executing Java programs● Can be specified as an environment variable or

included on the command line

Page 13: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Compiling Java (1/2)Compiling Java (1/2)

● The javac command compiles Java classes

● Accepts numerous arguments, but the important ones are:

-d <directory> - where generated classes/packages are stored

-classpath <list> - list of archives and/or directories to be used as the class path

▴ The compiler will search this class path to resolve any dependencies on external class definitions

Page 14: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Compiling Java (2/2)Compiling Java (2/2)

● Assume the following project directory structure:src/ Source folder

stack/ Package folder

Stack.java Source files Main.java

classes/ Output folder

● Compile with:javac -d classes src/stack/*.java

● This will generate:classes/ Output folder

stack/ Package folder

Stack.class Class files Main.class

Page 15: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Executing Java (1/2)Executing Java (1/2)

● The java command starts the Java virtual machine to execute a Java program

Can execute any class with static main method, e.g.,public static void main(String[] args)

Your program can have many main methods, but you choose only one when you want to start

● Accepts numerous arguments, but the important one is:

-classpath or -cp - list of archives and/or directories to be used as the class path

▴ The virtual machine will search this class path to resolve all class definitions

Page 16: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Executing Java (2/2)Executing Java (2/2)

● Assume the following project directory structure:src/ Source folder

stack/ Package folder

Stack.java Source files Main.java

classes/ Output folder

stack/ Package folder

Stack.class Class files Main.class

● Execute with:java -cp classes stack.Main▴ Searches in classes for a class called stack.Main,

which is located in the stack directory and has a staticmain method

Page 17: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

C++ Stack Example (1/4)C++ Stack Example (1/4)

File stack.h:

#ifndef __STACK_H__#define __STACK_H__#define INC 2

class Stack{private: void ** stack; int capacity; int used;

public: Stack(); void Push(void *ptr); bool IsEmpty(); void * Pop(); void * Peek();};

#endif

Page 18: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

C++ Stack Example (2/4)C++ Stack Example (2/4)

File stack.cpp:

#include <iostream>#include "stack.h"using namespace std;

Stack::Stack() { stack = new void*[INC]; capacity = INC; used = 0;}

void Stack::Push(void *ptr) { if (used == capacity) { void ** newstack = new void *[capacity + INC]; for (int i = 0; i < used; i++) { newstack[i] = stack[i]; } stack = newstack; } stack[used++] = ptr;}

Page 19: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

C++ Stack Example (3/4)C++ Stack Example (3/4)

File stack.cpp (con't):

bool Stack::IsEmpty() { return (used == 0);}

void * Stack::Pop() { if (used > 0) { return stack[--used]; } return NULL;}

void * Stack::Peek() { if (used > 0) { return stack[used - 1]; } return NULL;}

Page 20: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

C++ Stack Example (4/4)C++ Stack Example (4/4)

File main.cpp:

#include <iostream>#include "stack.h"

using namespace std;

int main() { Stack stack; stack.Push((void *) "a"); stack.Push((void *) "b"); stack.Push((void *) "c"); stack.Push((void *) "d"); stack.Push((void *) "e"); cout << "peek " << *((char *) stack.Peek()) << endl; stack.Pop(); stack.Pop(); stack.Push((void *) "f"); while (!stack.IsEmpty()) { cout << "pop " << *((char *) stack.Pop()) << endl; }}

Page 21: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Stack Example (1/3)Java Stack Example (1/3)

File Stack.java:

package stack;

public class Stack { private final static int INC = 2; private Object[] stack; private int size; public Stack() { stack = new Object[INC]; size = 0; } public void push(Object o) { if (size == stack.length) { Object[] newstack = new Object[stack.length + INC]; for (int i = 0; i < size; i++) { newstack[i] = stack[i]; } stack = newstack; } stack[size++] = o; }

Page 22: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Stack Example (2/3)Java Stack Example (2/3)

File Stack.java (con't):

public boolean isEmpty() { return (size == 0); } public Object pop() { if (size > 0) { return stack[--size]; } return null; } public Object peek() { if (size > 0) { return stack[size - 1]; } return null; }}

Page 23: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Stack Example (3/3)Java Stack Example (3/3)

File Main.java:

package stack;

public class Main { public static void main(String[] args) { Stack stack = new Stack(); stack.push("a"); stack.push("b"); stack.push("c"); stack.push("d"); stack.push("e"); System.out.println("peek " + stack.peek()); stack.pop(); stack.pop(); stack.push("f"); while (!stack.isEmpty()) { System.out.println("pop " + stack.pop()); } }}

Page 24: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Interfaces (1/2)Interfaces (1/2)

● Java does not support multiple inheritance, instead it supports interfaces

Like an abstract class with only abstract public methods

Supports interface-based programming which allows us to decouple from specific implementations

● A class can extend only one base class (i.e., inherit from), but it can implement any number of interfaces

A class can be cast to its base class or to any interface that it implements

Page 25: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Interfaces (2/2)Interfaces (2/2)

public interface Shape { public void draw(Graphics g);}

public class Circle extends Base implements Shape { public void draw(Graphics g) { // Method details... }

// Class details...}

Circle inherits from Base and implements Shape, soit can be cast to either.

Page 26: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Generics (1/3)Generics (1/3)

● Generics are similar to C++ templates Allows you to define classes that are parameterized by

type Useful to ensure type safety Also helps you avoid having cast operations

throughout your code

Page 27: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Generics (2/3)Generics (2/3)

● Linked-list examplepublic class Node<T> { private T value; private Node next; public Node(T v) { value = v; } public T getValue() { return value; } public Node getNext() { return next; } public void setNext(Node n) { node = n; }}

Page 28: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Generics (3/3)Generics (3/3)

● Linked-list example (con't)

public static void main(String args) { Node<String> n = new Node<String>(“Richard”); n.setNext(new Node<String>(“Clement”)); do { // We can use String methods without // having to cast the value. System.out.println(n.getValue().length()); n = n.getNext(); }

while (n.getNext() != null);}

Page 29: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Nested Classes (1/3)Nested Classes (1/3)

● It is possible to define a class within another class

A nested class is a member of the enclosing class and has access to all of its members

● A nested class can be static or non-static Static nested classes are simply called nested

classes Non-static nested classes are called inner classes The difference between static and non-static nested

classes is that static nested classes cannot access instance data, while non-static can

Page 30: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Nested Classes (2/3)Nested Classes (2/3)

● Example of inner class

public class StringArray { private String[] data = { "Richard", "Clement" };

public Iterator getIterator() { return new Iterator(); }

public class Iterator { private int index = 0;

public String getNext() { if (index < data.length) { return data[index++]; } return null; } }}

Page 31: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Nested Classes (3/3)Nested Classes (3/3)

● Example of inner class (con't)

public class Main { public static void main(String[] args) { StringArray main = new StringArray(); Iterator i = main.getIterator();

for (String s = i.getNext(); s != null; s = i.getNext()) { System.out.println(s); } }}

Page 32: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Runtime Libraries (1/5)Java Runtime Libraries (1/5)

● Java comes with a large number of standard libraries

Provide platform/OS-neutral ways to handle nearly any task

▴ Console and file I/O▴ Utility data structures▴ Graphical user interface▴ Networking▴ Image creation and manipulation▴ Security▴ XML handling▴ etc.

Page 33: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Runtime Libraries (2/5)Java Runtime Libraries (2/5)

● The standard libraries are organized by packages They are automatically included on your class path

● Important standard packages include java.lang

▴ Contains the core class of the Java runtime

java.io▴ Contains the main classes related to I/O for data streams and

file systems

java.util▴ Contains various generic data structure implementations

Page 34: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Runtime Libraries (3/5)Java Runtime Libraries (3/5)

● Example of how to print using the static out field from java.lang.System

System.out.println(“Hello ” + name); System.out.print(“Hello ” + name);

▴ Most objects will be properly converted to a meaningful string representation (via Object.toString()) so that you can print them

▴ The + operator is used for string concatenation

Page 35: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Runtime Libraries (4/5)Java Runtime Libraries (4/5)

● List data structure ArrayList is an implementation of the List

interface based on an array as backing storage Example usage (assume that we have imported

java.util.List and java.util.ArrayList):

...List<String> list = new ArrayList<String>();list.add(“Richard”);list.add(“Clement”);for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).length());}...

Page 36: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Java Runtime Libraries (5/5)Java Runtime Libraries (5/5)

● Map data structure HashMap is an implementation of the Map interface

based on a hashing function Example usage (assume that we have imported

java.util.Map and java.util.HashMap):

...Map<String,String> map = new HashMap<String,String>();map.put(“Richard”, “Hall”);map.put(“Clement”, “Escoffier”);System.out.println(map.get(“Richard”).length());System.out.println(map.get(“Clement”).length());...

Page 37: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Programming Tools (1/3)Programming Tools (1/3)

● Need to download Java JDK Provides command-line tools Typically you will use the version available from Sun

Microsystems, but there are others

● Sufficient to start with JDK and a text editor Advanced programmer tools are freely available Whether you work from the command line or using an

IDE is up to you

Page 38: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Programming Tools (2/3)Programming Tools (2/3)

● NetBeans

Page 39: Lecture 6: Java for C++ ProgrammersGarbage collection in Java, no explicit delete No multiple inheritance Java also defaults to virtual methods No operator overloading No global scope

Programming Tools (3/3)Programming Tools (3/3)

● Eclipse