(1) How to compile and run code in Java
- Compile: javac <SourceFile1> <SourceFile2> <SourceFile3> ... <SourceFileN>
- Run: java <ClassName>
SHOW EXAMPLE 1
(2) Basic Differences:
- In C++, we write: int main(int argc, char** argv) {
In Java, we write: public static void main(String[] args) {
- In C++, we write: cout << "Hello World!" << endl;
In Java, we write: System.out.println("Hello World!");
- In C++, we write: #include "linkedList.h"
In Java, we write: import java.util.LinkedList;
- In C++, we write: class Apple : public Fruit {
In Java, we write: public class Apple extends Fruit {
- In C++, we write:
template <typename T, typename U>
class Pair {
In Java, we write: public class Pair<T,U> {
- In C++, we write:
private:
int width = 5;
In Java, we write: private int width = 5;
- In C++, we write: string* myAddress = nullptr;
In Java, we write: String myAddress = null;
SHOW EXAMPLE 2
(3) Fundamental Differences:
- In C++, there are header files (.h) and source files (.cpp)
In Java, there are source files (.java), compiled files (.class), but no header files.
- In Java, every function needs to be the method of some class.
- In Java, there are no pointers. (at least for our purposes)
Instead, there are references.
- In Java, all arrays know their own length.
For example, we can do the following:
int[] myArray = new int[5];
System.out.println(myArray.length); // This prints the number 5
- In Java, there are no virtual methods or pure virtual methods.
Child class objects just inherit parent class methods.
... unless the child defines its own method with the same signature.
- In Java, when you use the keyword "new", you don't need to later call "delete".
The Garbage Collector automatically cleans up data that goes out of scope.