Download presentation
Presentation is loading. Please wait.
1
Java for C++ Programmers
First Night
2
Overview First Night Second Night Basics Classes and Objects
Enumerations Exceptions Input/Output Templates vs. Generics STL vs. JavaSE API
3
First Night Agenda Basics – file structure, compilation & execution differences, standard out/err/in, primitive types, constants, functions, strings, reference types, arrays, passing variables, command line arguments, packages Discussion Lab exercises Break Classes & Objects – declaration, instantiation, access modifiers, members, methods, common methods, inheritance, interfaces, javadoc
4
C++ File Structure We typically have header files (*.h, *.H *.hpp) and a source file (*.c, *.C, *.cpp) There is no coloration between the name of the file and the classes (if any) defined within
5
C++ Example – factorial.H
#ifndef _FACTORIAL_H_ #define _FACTORIAL_H_ int factorial(int n); #endif
6
C++ Example – factorial.C
#include "factorial.H" int factorial(int n) { int result = 1; for(int i = n; i > 0; i--) { result *= i; } return result;
7
C++ Example – example1.C #include <iostream>
#include "factorial.H" using namespace std; int main(int argc, char** argv) { int n = 4; cout << "factorial(" << n << "): " << factorial(n) << endl; exit(0); }
8
Java File Structure No separate header file – all code is in a *.java file No duplication of method signature in declaration (*.H) and definition (*.C) to keep in sync No guarding of files to prevent against multiple includes A file must contain a class of the same name By convention files/classes start with a capital letter Enforced consistency No code lives outside of any class
9
Java Main Signature Main signature is a bit different No return value
Only 1 argument to main – a String array public static void main(String[] args)
10
Java Factorial Example
public class Factorial { public static void main(String[] args) { int n = 4; System.out.print("factorial("); System.out.print(n); System.out.print("): "); System.out.println(factorial(n)); } static int factorial(int n) { int result = 1; for(int i = n; i > 0; i--) { result *= i; return result;
11
g++ example1.o factorial.o
C++ Compilation To run: a.out a.out Compilation in C++ is done by compiling each of the *.C files, to produce *.o files The object files are then linked to create an executable which can be run directly g++ example1.o factorial.o example1.o factorial.o g++ -c example1.C g++ -c factorial.C example1.C factorial.H factorial.C
12
Java Compilation In Java, *.java files are compiled into *.class files
These *.class files contain what is known as “bytecode” Bytecode does not get run directly Bytecode is not linked to produce an executable Instead, this bytecode is interpreted and executed by another program known as the Java Virtual Machine (JVM) Bytecode can be run on any platform having a JVM
13
Java Compilation & Execution
*.java files are compiled using the javac command The class files are then executed using the java command Note no .class specified when running To run: java Factorial Factorial.class javac Factorial.java Factorial.java
14
Standard In/Out/Error
Like C++, Java automatically creates streams for stdout, stdin and stderr cout is equivalent to System.out cerr is equivalent to System.err cin is equivalent to System.in Unlike C++, no imports or includes need to be made to use these streams
15
Standard Out/Error Output is easily done using one of the print methods off of these objects System.out.print(arg) – prints the arg If you want a newline (what you would get by using endl), use the println variant of this function – System.out.println(arg) A detailed list of methods available on System.out or System.err can be found at:
16
Standard In Like C++, Java automatically creates a stream for stdin
cin is equivalent to System.in Unfortunately, reading a given type off of System.in is not as easy as using cin in C++ Typically another class is used in conjunction with System.in to more easily read values off of the stream
17
Primitive Types Like C++, Java has a built-in boolean type
C++ uses the keyword bool, whereas Java used the keyword boolean Both use the values true and false Unlike C++, you cannot assign non-boolean types into booleans boolean x = 1 results in a compiler error
18
Primitive Types Like C++, Java defines a character type
Just like C++, Java uses the char keyword to declare this type Character literals are defined using single quotes such as 'a'
19
Primitive Types Integer types are pretty much the same, both provide the following types A C++ short int is a Java short A C++ int is a Java int A C++ long int is a Java long There are no unsigned variants in Java Unlike C++, if you want to assign a higher precision number into a lower precision container you must explicitly down cast… int i = ; short s = (short)i;
20
Primitive Types Like C++, Java has both float and double types
The same down casting rules that applied with integer types applies to doubles and floats also So if you want to assign a double into a float you must cast it to be a float Additionally, Java assumes that floating point literals are doubles by default If you want to create a literal you can tack on an “f” to the literal to declare it of a float type float f = f;
21
Constants Constants in C++ are typically done in one of two ways…
A #define Or, a const declaration #define PI = ; const double PI = ;
22
Constants Java does not have a traditional pre-processor to do substitutions like C/C++ Thus it uses an approach similar to the const declaration Constants in Java are typically declared to be public static final Declared inside a class, outside all methods public static final double PI = ;
23
Functions C++ allows non-member functions
Java does not allow non-member functions All functions in Java are actually methods Methods may be made static, essentially making them equivalent to functions static int factorial(int n) { int result = 1; for(int i = n; i > 0; i--) { result *= i; } return result;
24
Strings Java provides a String class much like the string class in the C++ STL Similarities… Can create by simply using a double quoted string Concatenation is done using the + operator Length obtained by calling .length() method Some notable differences… No overloaded [i] operator, use the .charAt(i) method instead Strings in Java are immutable For more documentation on Java strings see:
25
Strings Since Strings are immutable a new String is created on all operations Need to be sure to assign result back into variable, otherwise result of operation is lost String s = "foo"; s = s + "bar" + "baz"; s = s.substring(3); System.out.println(s); s = s.replace("b", "B");
26
Reference Types The way Java handles reference (non-primitive) types in Java is very different from that of C++ A reference is kind of like a pointer in C++, but there are some notable differences All objects are stored in variables are actually references to objects No direct access to the underlying memory, including no pointer arithmetic References are strongly typed unlike C++, cannot assign a Date reference into a String reference Uninitialized references are set to null (lowercase)
27
Reference Types In C++ we can statically create an object like so…
Or, dynamically create an object like so (and need to remember to free it like so)… In Java, we create an object like so… Foo f(); Foo * fPtr = new Foo(); delete fPtr; Foo f = new Foo();
28
Reference Types If you’re using new, then it’s a reference
One of the biggest perks about Java’s approach to references deals with freeing objects You don’t! No more delete statements. Java uses a technique called “Garbage Collection” to automatically free memory which is no longer in use
29
Arrays Arrays are allocated using the new keyword
Primitives are initialized to zero The boolean type is initialized to false References are initialized to null Unlike C++, arrays in Java are objects The length of an array can be determined by looking at the array’s .length member (not a method!) Like C++, indexing is supported via square brackets – array[i]
30
Array Allocation // example declarations int[] intArray = new int[10];
boolean[] boolArray = new boolean[10]; // note [] may appear before of after, // before is the more popular Java convention String[] strArray1 = new String[10]; String strArray2[] = new String[10]; // may alternately use curly brace syntax String[] strArray3 = {"foo", "bar", "baz"};
31
Enhanced For Loop Java 5 introduced a number of new features to the language – one of those is an enhanced for loop This style for loop is known as a “foreach” loop Popular looping construct in many languages: PHP, JavaScript, Perl, Python, Ruby, shell, etc… C++ does not have a built in equivalent Typically a foreach loop is used in place of a traditional for loop when we do not care about the index as we are iterating over the collection
32
Enhanced For Loop The general format of this loop in Java is as follows… An example… for(Type item : Collection) { // do something with item } for(int i = 0; i < array.length; i++) { System.out.println(array[i]); } // becomes... for(String s : array) { System.out.println(s);
33
Passing Variables Everything in Java is passed by value
Yes, everything – no goofy & or * notation Does this mean passing an array of 1,000,000 items creates another huge array? No! In the case of an array or object, the variable represents a reference, so the reference is being passed by value So, when dealing with objects, we are always passing references (but by value)
34
Passing Variables public class Test {
public static void main(String[] args) { int[] array = new int[10]; for(int i = 0; i < array.length; i++) { array[i] = i; } zeroArray(array); // what is in array? static void zeroArray(int[] array) { array[i] = 0;
35
Passing Variables public class Test {
public static void main(String[] args) { int[] array = new int[10]; for(int i = 0; i < array.length; i++) { array[i] = i; } zeroArray(array); // what is in array? static void zeroArray(int[] array) { array = new int[array.length];
36
Command Line Arguments
Now that we know that how arrays are passed we can go back make use of command line arguments Remember main takes a String array, so we can access that like any other array… public static void main(String[] args) { for(String s : args) { System.out.println(s); }
37
Packages Like C++, Java provides a mechanism to organize code
Packages are similar to namespaces in C++ but have different syntax and conventions In Java classes need not be explicitly be under a package, in which case the default package will be used Though, this practice is discouraged
38
Namespaces in C++ namespace A { class Foo { // minimal class }; }
int main(int argc, char** argv){ A::Foo aFoo(); return 0;
39
Packages in Java To package a class…
The first line in the Java file should be a package declaration in the following format… The class file should be placed in a directory structure matching the package name… foo/bar/baz/Foo.java package foo.bar.baz;
40
Packaging Conventions
Typically package names consist of lowercase letters and/or numbers Multiple words are usually separated by periods In the real world most projects use something called reverse domain name notation edu.umbc.dhood2.proj1.ClassName Use this as another method to group your code into logical chunks
41
Using a Package Using a file in a package is very similar to that of C++ In C++ we might have something like… In Java, the syntax is different – we use the import keyword, drop the angle brackets, and the file extension #include <sys/socket.h> import java.util.Date;
42
Exercises Using Java, create, compile and run…
A simple “Hello World” program A program which takes a single string as a command line argument prints out whether or not the string is a palindrome Palindrome is a word that reads the same backwards as forwards A program which creates an array of 20 integers, fills it with the Fibonacci sequence and prints it out Fibonacci[0] = 1, Fibonacci[1] = 1 Fibonacci[n] = Fibonacci[n-2] + Fibonacci[n-1]
43
Break
44
C++ Class Declaration #ifndef _DATE_H_ #define _DATE_H_ class Date {
private: int m_month; int m_day; int m_year; public: Date(int month, int day, int year); int GetMonth() const; int GetDay() const; int GetYear() const; void SetMonth(int month); void SetDay(int day); void SetYear(int year); }; #endif
45
C++ Class Definition #include "Date.H" Date::Date(int month, int day,
int year) { this->m_month = month; this->m_day = day; this->m_year = year; } int Date::GetMonth() const { return this->m_month; int Date::GetDay() const { return this->m_day; int Date::GetYear() const { return this->m_year; } void Date::SetMonth(int month) { this->m_month = month; void Date::SetDay(int day) { this->m_month = day; void Date::SetYear(int year) { this->m_year = year;
46
Java Differences Since Java doesn’t split the declaration and implementation, all code is inline No semi-colon at the end of the class declaration Access explicitly attached to each method this is not a pointer, but a reference, so we use the this. instead of this-> notation
47
Java Naming Conventions
Class name are in UpperCamelCase Member names are lowerCamelCase Method names are lowerCamelCase
48
Java Class Declaration & Definition
public class Date { private int month; private int day; private int year; public Date(int month, int day, int year) { this.month = month; this.day = day; this.year = year; } public int getMonth() { return this.month; public int getDay() { return this.day; public int getYear() { return this.year; } public void setMonth(int month) { this.month = month; public void setDay(int day) { this.day = day; public void setYear(int year) { this.year = year;
49
C++ Method/Member Access
Private: Only accessible from within the class or by friends Protected: Accessible from within the class, and by derived classes Public: Accessible by any anyone
50
Java Access Modifiers Java member access is different from that of C++, some notable differences No friend classes Addition of 4th type, default (also known as package private) Modifier Within Same Class Within Same Package In a Subclass Everything Else public Y protected N default private
51
C++ Destructors In C++ you can create a destructor which gets invoked when the object goes out of scope or, if dynamically allocated when it is deleted Typically destructors free any dynamically allocated memory into the date structure Class::~Class() { // delete allocated memory }
52
Java “Destructor” Since Java does garbage collection, there typically is not a need to manually free allocated memory When the garbage collector runs, it will invoke a finalize method on classes it collects No guarantee that this is called when object goes out of scope – up to the garbage collector as to when it should get called This is seldom used in most Java applications
53
Operator Overloading Unlike C++, Java does not allow us to define overloaded operators for classes Notable exceptions being the built in String (+ operator) and array ([ ] operator) types There are, conventions to achieve the same effect in Java for common operations
54
Outputting an Object in C++
If we want to output an object in C++ many people will implement an operator<< // function ostream& operator << (ostream& os, const Date& d) { os << d.GetMonth() << "/" << d.GetDay() << "/" << d.GetYear(); return os; } // invocation Date d(1,20,2009); cout << d << endl;
55
Outputting an Object in Java
What happens if we try to print an object in Java? Output… This is not useful – where is it coming from? Date d = new Date(1,20,2009); System.out.println(d);
56
Outputting an Object in Java
As we’ll see shortly, all objects in Java inherit from a base object called Object When we call System.out.print() with any object a toString() method is getting called Object provides a toString() method, though it is pretty useless as is Frequently toString() is overridden to provide a meaningful String representation
57
Outputting an Object in Java
Example override for our Date object… Invocation… Output… public String toString() { return this.month + "/" + this.day + "/" + this.year; } Date d = new Date(1,20,2009); System.out.println(d); 1/20/2009
58
Comparing Objects in C++
In C++, we frequently override the operator== … // function bool Date::operator==(const Date& d) const { return (this->m_month == d.m_month) && (this->m_day == d.m_day) && (this->m_year == d.m_year); } // invocation Date d1(1,20,2009); Date d2(11,4,2008); if(d1 == d2) { cout << "same" << endl; } else { cout << "different" << endl;
59
Comparing Objects in Java
What happens if we try to compare 2 objects in Java… Outputs the following… why? Date d1 = new Date(1,20,2009); Date d2 = new Date(1,20,2009); if(d1 == d2) { System.out.println("same"); } else { System.out.println("different"); } different
60
Comparing Objects in Java
The == operator is checking to see if the references are the same (both point to same object) In order to check the members, we need to override the equals(Object) method inherited from the Object class… public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } Date otherDate = (Date) obj; return (this.month == otherDate.month) && (this.day == otherDate.day) && (this.year == otherDate.year);
61
Comparing Objects in Java
Invocation of equals method… Output… Date d1 = new Date(1,20,2009); Date d2 = new Date(1,20,2009); if(d1.equals(d2)) { System.out.println("same"); } else { System.out.println("different"); } same
62
Object Assignment in C++
To perform assignment in C++, we typically overload the operator= // definition Date& Date::operator=(const Date& rhs) { if(this != &rhs) { this->m_month = rhs.m_month; this->m_day = rhs.m_day; this->m_year = rhs.m_year; } return *this; // invocation Date d1(1,20,2009); Date d2 = d1;
63
Object Assignment in Java
Like comparison, the default behavior in Java is to deal with references So assigning one variable into another causes both to point to the same object (shallow copy) There is some debate in the Java community on how to handle this There is a clone() method and interface (we’ll talk about interfaces later), but it is not without oddities An alternate approach is to simply use a copy constructor…
64
Java Copy Constructor Definition… Invocation… public Date(Date d) {
this.month = d.month; this.day = d.day; this.year = d.year; } Date d1 = new Date(1,20,2009); Date d2 = new Date(d1);
65
C++ Inheritance In C++ we can extend a class, by specifying the superclasses using a “:” notation at the time of declaration
66
C++ Inheritance Base Vehicle class (header)… #ifndef _VEHICLE_H_
#define _VEHICLE_H_ #include <string> using namespace std; class Vehicle { private: string m_make; string m_model; public: Vehicle(string make, string model); string GetMake() const; string GetModel() const; }; #endif
67
C++ Inheritance Base Vehicle class (implementation)…
#include "Vehicle.H" #include <iostream> using namespace std; Vehicle::Vehicle(string make, string model) { this->m_make = make; this->m_model = model; } string Vehicle::GetMake() const { return this->m_make; string Vehicle::GetModel() const { return this->m_model;
68
C++ Inheritance A derived Car class (header)… #ifndef _CAR_H_
#define _CAR_H_ #include "Vehicle.H" #include <string> using namespace std; class Car : public Vehicle { private: bool m_fourWheelDrive; public: Car(string make, string model, bool fourWheelDrive); bool HasFourWheelDrive() const ; }; ostream& operator << (ostream& os, const Car& c); #endif
69
C++ Inheritance A derived Car class (implementation)… #include "Car.H"
#include <iostream> using namespace std; Car::Car(string make, string model, bool fourWheelDrive): Vehicle(make, model) { this->m_fourWheelDrive = fourWheelDrive; } bool Car::HasFourWheelDrive() const { return this->m_fourWheelDrive; ostream& operator << (ostream& os, const Car& c) { os << (c.HasFourWheelDrive() ? "4WD" : "2WD") << " " << c.GetMake() << " " << c.GetModel(); return os;
70
C++ Inheritance A derived Airplane class (header)…
#ifndef _AIRPLANE_H_ #define _AIRPLANE_H_ #include "Vehicle.H" #include <string> using namespace std; class Airplane : public Vehicle { private: string m_varient; public: Airplane(string make, string model, string varient); string GetVarient() const; }; ostream& operator << (ostream& os, const Airplane& a); #endif
71
C++ Inheritance A derived Airplane class (implementation)…
#include "Airplane.H" #include <iostream> using namespace std; Airplane::Airplane(string make,string model,string varient): Vehicle(make, model){ this->m_varient = varient; } string Airplane::GetVarient() const { return this->m_varient; ostream& operator << (ostream& os, const Airplane& a) { os << a.GetMake() << " " << a.GetModel() << " " << a.GetVarient(); return os;
72
Java Inheritance Uses the extend keyword instead of the “:” notation
See access table for visibility of members in base class Use super() to invoke base class constructor Use super.method() notation to invoke a method on the base class
73
Java Inheritance A Vehicle base class… public class Vehicle {
private String make; private String model; public Vehicle(String make, String model) { this.make = make; this.model = model; } public String getMake() { return make; public String getModel() { return model;
74
Java Inheritance A derived Car class…
public class Car extends Vehicle { private boolean fourWheelDrive; public Car(String make, String model, boolean fourWheelDrive) { super(make, model); this.fourWheelDrive = fourWheelDrive; } public boolean hasFourWheelDrive() { return this.fourWheelDrive; public String toString() { return (this.fourWheelDrive ? "4WD" : "2WD") + " " + this.getMake() + " " + this.getModel();
75
Java Inheritance A derived Airplane class…
public class Airplane extends Vehicle { private String varient; public Airplane(String make, String model, String varient) { super(make, model); this.varient = varient; } public String getVarient() { return this.varient; public String toString() { return this.getMake()+" "+this.getModel()+" "+ this.varient;
76
Java Inheritance Vehicle Java avoids the “diamond problem” by not permitting multiple inheritance Car Airplane AirplaneCar
77
Interfaces Java provides a construct known as an Interface
Similar to a pure virtual class in C++ Classes in Java “implement” may implement one or more interfaces Interfaces typically define a set of operations (method signatures) which the class must implement Interfaces my have static members
78
Interface Why use interfaces?
Interfaces are good for defining the set of operations a given type of structures should implement This is a good practice, as it allows you to swap out/in anything that implements that interface with minimal code changes Even more powerful when utilized in conjunction with Java’s version of templates
79
Java Interface Example
A simple Java Interface declaration… Note that this is of type interface, not class public interface Animal { public void talk(); }
80
Java Interface Example
A Cat class which implements this interface… public class Cat implements Animal { public void talk() { System.out.println("Meow"); }
81
Java Interface Example
A Cat class which implements this interface… public class Dog implements Animal { public void talk() { System.out.println("Arrrfff!"); }
82
Java Interface Example
The driver class… Note that we never have a handle on these animals as a Cat or Dog, just an animal As long as we call just the Animal interface methods, we can add as many Animal types as we want and not need to change any code public class Kennel { public static void main(String[] args) { Animal[] kennel = {new Cat(), new Dog()}; for(Animal a : kennel) { a.talk(); }
83
Comparable Interface In C++, we frequently overload one of the comparison operators so that we can sort objects Since we can’t define our own operators in Java, it provided an alternate mechanism There is a Comparable interface that you can choose to implement which allows many of the built in functions in the Java APIs to sort your custom objects
84
Comparable Interface Basically the Comparable interface requires that we implement the following method public int compareTo(Object other); The method compareTo must return A negative number if the calling object "comes before" the parameter other A zero if the calling object "equals" the parameter other A positive number if the calling object "comes after" the parameter other
85
Example Comparable Class
import java.util.Arrays; public class Date implements Comparable { private int month; private int day; private int year; public Date(int month, int day, int year) { this.month = month; this.day = day; this.year = year; } public String toString() { return this.month + "/" + this.day + "/" + this.year; // continued on next slide
86
Example Comparable Class
public int compareTo(Object obj) { if (obj == null || getClass() != obj.getClass()) { System.err.println("Whoops, aborthing"); System.exit(1); } Date date = (Date) obj; int yearDiff = this.year - date.year; int monthDiff = this.month - date.month; int dayDiff = this.day - date.day; if(yearDiff != 0) { return yearDiff; } else if (monthDiff != 0) { return monthDiff; } else { return dayDiff; // continued on next slide
87
Example Comparable Class
public static void main(String[] args) { Date[] dates = { new Date(10,7,2008), new Date(10,15,2008), new Date(9,26,2008), }; Arrays.sort(dates); for(Date d : dates) a{ System.out.println(d); }
88
Date Comparable When executed, we get the following output… 9/26/2008
10/7/2008 10/15/2008
89
Javadoc Comments Like C++, Java supports both C style (/* */) and C++ style end of line comments However, Java introduces another type of comment style know as a Javadoc comment These special can be analyzed by the javadoc tool and HTML documentation can be automatically generated /** * This is a javadoc comment */
90
Javadoc Tags The first sentence in the Javadoc comments is used to provide a high-level description of that member/method/class The rest of the paragraph will be shown in a more detailed section in the generated documentation Additionally, Javadoc supports tags which identify the attributes of the function such as… @param name description @return description See the following for more details about javadoc…
91
A Javadoc Example /** * This function takes in a Celsius temperature and * returns its Fahrenheit equivalent. * celsius degrees Celsius to be converted the Fahrenheit equivalent * of the Celsius temperature provided */ public double celsiusToFahrenheit(double celsius) { return 9.0 / 5 * celsius + 32; }
92
Javadoc Generation To generate the Javadoc generation you need to run the javadoc tool $ javadoc Test.java Loading source file Test.java... Constructing Javadoc information... Standard Doclet version 1.6.0_02 Building tree for all the packages and classes... Generating Test.html... Generating package-frame.html... Generating package-summary.html... Generating package-tree.html... Generating constant-values.html... Building index for all the packages and classes... Generating overview-tree.html... Generating index-all.html... Generating deprecated-list.html... Building index for all classes... Generating allclasses-frame.html... Generating allclasses-noframe.html... Generating index.html... Generating help-doc.html... Generating stylesheet.css... $
93
Generated HTML Documentation
Example method listed in method summary… Detailed method description…
94
Exercises Using Java, create, compile and run a program which creates and prints out several Employees (Employee class is derived from Person class) Person has an age, first name and last name An Employee is a Person, with an additional title and salary Once you have things compiling, comment your classes using javadoc comments, run the javadoc tool and view the results in a browser
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.