Introduction to Java for C/C++ Programmers
Kevin SquireDepartment of Computer Science
Naval Postgraduate School
2
Homework
Download and install Java 6.0 Eclipse
I’ll introduce Eclipse sometime this week
3
The First Program
class Hello {
// main: generate some simple output
public static void main (String[] args) {
System.out.println ("Hello, world.");
}
}
// Save as Hello.java
// Compile with “javac Hello.java”
// Run with “java Hello”
4
The First Program
class CLASSNAME {
public static void main (String[] args) {
STATEMENTS
}
}
5
Variables and Types
Some types are the same as C
int hour, minute;
float temperature;
Some (e.g., Strings) are (somewhat) new:
String firstName;
String lastName;
6
Printing Variables
class Hello {
public static void main (String[] args) {
String firstLine;
firstLine = "Hello, again!";
System.out.println (firstLine);
}
}
7
Operators
Mostly the same
int hour, minute;
hour = 11;
minute = 59;
System.out.print ("Number of minutes since midnight: ");
System.out.println (hour*60 + minute);
System.out.print ("Fraction of the hour that has passed: ");
System.out.println (minute/60);
8
Operators for Strings
Some new:int i = 5;
String hello = "" + i + " Hello, " + "world.";
puts the following string in the variable hello "5 Hello, world."
9
Math Methods (Functions)
import static java.lang.Math.sqrt;
double root = sqrt (17.0);
double angle = 1.5;
double height = Math.sin (angle);
double degrees = 90;
double angle = degrees * 2 * Math.PI / 360.0;
int x = (int)Math.round (Math.PI * 20.0);
double x = Math.exp (Math.log (10.0));
10
static keyword
In addition to (instance) members, a Java class can include static members that are attached to the class rather than instances of the class.
Equivalent to C/C++ functions which are not class methods
Since they are not attached to objects, they do not have access to any particular object’s data members
All Math functions (Math.sin, Math.sqrt, etc.) are static member functions of the Math class.
11
Defining New Static Methods
Form:public static void NAME ( LIST OF PARAMETERS ) {
STATEMENTS
}
Examplepublic static void newLine () {
System.out.println ("");
}
12
Class With Only static Methods
class NewLine {
public static void newLine () {
System.out.println ("");
}
public static void threeLine () {
newLine (); newLine (); newLine ();
}
public static void main (String[] args) {
System.out.println ("First line.");
threeLine ();
System.out.println ("Second line.");
}
}
13
String Objects
Java has two kinds of variables: primitive types objects
Strings are the only object type we've talked about so far
Questions we might ask: “What is the data contained in a String object?” “What are the methods we can invoke on String objects?”
14
Aside: Java Documentation
All Java documentation is downloadable or available online.
Try: search Google for “java 5.0 String”
15
Reminder: chars
char fred = ’c’;
if (fred == ’c’) {
System.out.println (fred);
}
16
String charAt method
The following code:String fruit = "banana";
char letter = fruit.charAt(1);
System.out.println (letter);
yieldsa
Why?
17
String charAt method
The following code:String fruit = "banana";
char letter = fruit.charAt(1);
System.out.println (letter);
yieldsa
Why? To get the first letter, use
char letter = fruit.charAt(0);
18
Length
What's wrong with the statements below?
int length = fruit.length();
char last = fruit.charAt (length);
19
Length
What's wrong with the statements below?
int length = fruit.length();
char last = fruit.charAt (length); Correct version:
int length = fruit.length();
char last = fruit.charAt (length-1);
20
Indices
String fruit = "banana";
int index = fruit.indexOf(’a’);
int index = fruit.indexOf(’a’, 2); // start at
// position 2
21
Other Notes on Strings
Strings are immutable Strings are not comparable with ==, >, etc.
22
Comparing Strings
String name1 = "Alan Turing";
String name2 = "Ada Lovelace";
if (name1.equals (name2)) {
System.out.println ("The names are the same.");
}
int flag = name1.compareTo (name2);
if (flag == 0) {
System.out.println ("The names are the same.");
} else if (flag < 0) {
System.out.println ("name1 comes before name2.");
} else if (flag > 0) {
System.out.println ("name2 comes before name1.");
}
23
Interesting Objects
Packages Contain built-in Java classes java.lang is available by default (includes all of the
basic parts of the language) Must be imported, e.g.
import java.awt.*;
imports all classes in the java.awt package.
24
Point Objects
import java.awt.*; // goes at top of file, outside main()
...
Point blank;
blank = new Point (3, 4);
Rectangle box = new Rectangle (0, 0, 100, 200);
// Access coordinate of blank
int x = blank.x;
System.out.println (blank.x + ", " + blank.y);
int distance = blank.x * blank.x + blank.y * blank.y;
25
Objects as Parameters
public static void printPoint (Point p) {
System.out.println ("(" + p.x + ", " + p.y + ")");
}
// System.out.println(blank) gives: java.awt.Point[x=3,y=4]
public static double distance (Point p1, Point p2) {
double dx = (double)(p2.x - p1.x);
double dy = (double)(p2.y - p1.y);
return Math.sqrt (dx*dx + dy*dy);
}
26
Objects as Return Types
public static Point findCenter (Rectangle box) {
int x = box.x + box.width/2;
int y = box.y + box.height/2;
return new Point (x, y);
}
27
Objects are Mutable
public static void moveRect (Rectangle box, int dx, int dy) {
box.x = box.x + dx;
box.y = box.y + dy;
}
...
Rectangle box = new Rectangle (0, 0, 100, 200);
moveRect (box, 50, 100);
System.out.println (box);
// yields java.awt.Rectangle[x=50,y=100,width=100,height=200]
28
Aliasing/References
Rectangle box1 = new Rectangle (0, 0, 100, 200);
Rectangle box2 = box1;
box1 and box2 both refer to the same Rectangle.
Alternatively, we can say that the given Rectangle has two aliases (box1 and box2)
29
null
When you create an object variable, remember that you are creating a reference to an object. Until you make the variable point to an object, the value of the variable is null. null is a special value in Java (and a Java keyword) that is used to mean “no object.”
The declaration Point blank; is equivalent to the initialization
Point blank = null;
30
Null Pointer Exceptions
Point blank = null;
int x = blank.x; // NullPointerException
blank.translate (50, 50); // NullPointerException
31
Garbage Collection
Create a new Point:
Point blank = new Point (3, 4);
Set blank to null:
blank = null;
In C, this would cause a memory leak; the memory allocated in the first statement would be lost until the program exits.
In contrast, Java keeps track of the memory allocated to the object, and reclaims it (deallocates it) when there are no more references to the object
There is therefore no need for “delete” in Java (and it doesn’t exist).
32
Creating Your Own Classes
Defining classes in Java is slightly different than in C++ By convention, class names (and hence object types) always begin
with a capital letter, which helps distinguish them from primitive types and variable names.
You usually put one class definition in each file, and the name of the file must be the same as the name of the class, with the suffix .java. For example, the Time class is defined in the file named Time.java.
In any program, one class is designated as the startup class. The startup class must contain a method named main, which is where the execution of the program begins. Other classes may have a method named main, but it will not be executed.
Basic differences between Java and C++ class definition are highlighted on the following slides.
33
C++/Java Class Definition
C++:
class CRectangle {
int width, height;
public:
CRectangle (int, int);
int area () {
return (width*height);
}
};
CRectangle::CRectangle (int a,
int b) {
width = a;
height = b;
}
Java:
public class CRectangle {
private int width, height;
public CRectangle (int a, int b) {
width = a;
height = b;
}
public int area () {
return (width*height);
}
}
34
C++/Java Class Definition
C++:
class CRectangle {
int width, height;
public:
CRectangle (int, int);
int area () {
return (width*height);
}
}; // Note: ";" required here
CRectangle::CRectangle (int a,
int b) {
width = a;
height = b;
}
Java:
public class CRectangle {
private int width, height;
public CRectangle (int a, int b) {
width = a;
height = b;
}
public int area () {
return (width*height);
}
} // Note: no ";" required here
35
C++/Java Class Definition
C++:
class CRectangle {
int width, height;
public:
CRectangle (int, int);
int area () {
return (width*height);
}
};
CRectangle::CRectangle (int a,
int b) {
width = a;
height = b;
}
Java:
public class CRectangle {
private int width, height;
public CRectangle (int a, int b) {
width = a;
height = b;
}
public int area () {
return (width*height);
}
}
36
C++/Java Class Definition
C++:
class CRectangle {
int width, height;
public:
CRectangle (int, int);
int area () {
return (width*height);
}
};
CRectangle::CRectangle (int a,
int b) {
width = a;
height = b;
}
Java:
public class CRectangle {
private int width, height;
public CRectangle (int a, int b) {
width = a;
height = b;
}
public int area () {
return (width*height);
}
}
37
C++/Java Class Definition
C++:
int main () {
CRectangle rectA (3,4); CRectangle rectB (5,6);
cout << "rectA area: " << rectA.area() << endl; cout << "rectB area: " << rectB.area() << endl;
return 0;}
Java: public class CRectangle { ...
public static void main(String [] args) {
CRectangle rectA = new CRectangle (3,4); CRectangle rectB = new CRectangle (5,6);
System.out.println( "rectA area: " + rectA.area()); System.out.println( "rectB area: " + rectB.area()); }}
38
C++/Java Class Definition
C++:
int main () {
CRectangle rectA (3,4); CRectangle rectB (5,6);
cout << "rectA area: " << rectA.area() << endl; cout << "rectB area: " << rectB.area() << endl;
return 0;}
Java: public class CRectangle { // main is ... // inside a class def.
public static void main(String [] args) {
CRectangle rectA = new CRectangle (3,4); CRectangle rectB = new CRectangle (5,6);
System.out.println( "rectA area: " + rectA.area()); System.out.println( "rectB area: " + rectB.area()); }}
39
C++/Java Class Definition
C++:
int main () {
CRectangle rectA (3,4); CRectangle rectB (5,6);
cout << "rectA area: " << rectA.area() << endl; cout << "rectB area: " << rectB.area() << endl;
return 0;}
Java: public class CRectangle { ... // main()’s type is different public static void main(String [] args) {
CRectangle rectA = new CRectangle (3,4); CRectangle rectB = new CRectangle (5,6);
System.out.println( "rectA area: " + rectA.area()); System.out.println( "rectB area: " + rectB.area()); }}
40
C++/Java Class Definition
Function overloading is the same as C++ Destructors are the same (~ClassName()), but
are not needed as frequently (why?)
41
Inheritance and Polymorphism
Inheritance and Polymorphism are very similar in Java and C++
To derive a subclass, the notation is class SUBCLASS extends SUPERCLASS {…
The constructor of the superclass is accessed via a call to the function super().
Note that all methods are virtual by default So, if a subclass overrides a method of a parent class, the
“right method” will always be called
42
Code Example
#include <iostream>using namespace std;
class CPolygon {protected: int width, height;public: CPolygon(int a, int b) { width=a; height=b;} virtual int area() {return 0};
�
};
class CRectangle: public CPolygon {public: CRectangle(int a, int b): CPolygon(a,b) {}
int area () { return (width * height); }};
In file Polygon.java:
public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b;} public int area() {return 0};}
In file Rectangle.java:
public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); }
public int area () { return (width * height); }}
C++: Java:
43
Code Example
#include <iostream>using namespace std;
class CPolygon {protected: int width, height;public: CPolygon(int a, int b) { width=a; height=b;} virtual int area() {return 0};
�
};
class CRectangle: public CPolygon {public: CRectangle(int a, int b): CPolygon(a,b) {}
int area () { return (width * height); }};
In file Polygon.java:
public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b;} public int area() {return 0};}
In file Rectangle.java:
public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); }
public int area () { return (width * height); }}
C++: Java:
44
Code Example
#include <iostream>using namespace std;
class CPolygon {protected: int width, height;public: CPolygon(int a, int b) { width=a; height=b;} virtual int area() {return 0};
�
};
class CRectangle: public CPolygon {public: CRectangle(int a, int b): CPolygon(a,b) {}
int area () { return (width * height); }};
In file Polygon.java:
public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b;} public int area() {return 0};}
In file Rectangle.java:
public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); }
public int area () { return (width * height); }}
C++: Java:
45
Code Example
#include <iostream>using namespace std;
class CPolygon {protected: int width, height;public: CPolygon(int a, int b) { width=a; height=b;} virtual int area() {return 0};
�
};
class CRectangle: public CPolygon {public: CRectangle(int a, int b): CPolygon(a,b) {}
int area () { return (width * height); }};
In file Polygon.java:
public class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b;} public int area() {return 0};}
In file Rectangle.java:
public class Rectangle extends Polygon{ public Rectangle(int a, int b) { super(a,b); }
public int area () { return (width * height); }}
C++: Java:
46
Code Example (cont.)
In file Triangle.java:
public class Triangle extends Polygon {
public Triangle(int a, int b) {
super(a,b);
}
public int area () {
return (width * height / 2);
}
}
In file PolyTest.java:public class PolyTest {
public static void int main () {
Rectangle rect = new Rectangle(4,5);
Triangle trgl = new Triangle(4,5);
System.out.println(rect.area());
System.out.println(trgl.area());
}
}
class CTriangle: public CPolygon {public: CTriangle(int a, int b): CPolygon(a,b) {} int area () { return (width * height / 2); }};
int main () { CRectangle rect(4,5); CTriangle trgl(4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0;}
C++: Java:
47
Code Example (cont.)
In file Triangle.java:
public class Triangle extends Polygon {
public Triangle(int a, int b) {
super(a,b);
}
public int area () {
return (width * height / 2);
}
}
In file PolyTest.java:public class PolyTest {
public static void int main () {
Rectangle rect = new Rectangle(4,5);
Triangle trgl = new Triangle(4,5);
System.out.println(rect.area());
System.out.println(trgl.area());
}
}
class CTriangle: public CPolygon {public: CTriangle(int a, int b): CPolygon(a,b) {} int area () { return (width * height / 2); }};
int main () { CRectangle rect(4,5); CTriangle trgl(4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0;}
C++: Java:
48
Code Example (cont.)
In file Triangle.java:
public class Triangle extends Polygon {
public Triangle(int a, int b) {
super(a,b);
}
public int area () {
return (width * height / 2);
}
}
In file PolyTest.java:public class PolyTest {
public static void int main () {
Rectangle rect = new Rectangle(4,5);
Triangle trgl = new Triangle(4,5);
System.out.println(rect.area());
System.out.println(trgl.area());
}
}
class CTriangle: public CPolygon {public: CTriangle(int a, int b): CPolygon(a,b) {} int area () { return (width * height / 2); }};
int main () { CRectangle rect(4,5); CTriangle trgl(4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0;}
C++: Java:
49
Polymorphism Example (cont.)
In file Triangle.java:
public class Triangle extends Polygon {
public Triangle(int a, int b) {
super(a,b);
}
public int area () {
return (width * height / 2);
}
}
In file PolyTest.java:public class PolyTest {
public static void int main () {
Polygon rect = new Rectangle(4,5);
Polygon trgl = new Triangle(4,5);
System.out.println(rect.area());
System.out.println(trgl.area());
}
}
class CTriangle: public CPolygon {public: CTriangle(int a, int b): CPolygon(a,b) {} int area () { return (width * height / 2); }};
int main () { CPolygon *rect = new CRectangle(4,5); CPolygon *trgl = new CTriangle(4,5); cout << rect->area() << endl; cout << trgl->area() << endl; return 0;}
C++: Java:
50
C++ Pure Virtual Classes = Java Abstract Classes
#include <iostream>using namespace std;
class CPolygon {protected: int width, height;public: CPolygon(int a, int b) { width=a; height=b;} virtual int area() = 0;
�
};...int main () { CPolygon *rect = new CRectangle(4,5); CPolygon *trgl = new CTriangle(4,5);// illegal//CPolygon *poly = new CPolygon(4,5); cout << rect->area() << endl; cout << trgl->area() << endl;//cout << poly->area() << endl; return 0;}
In file Polygon.java:
public abstract class Polygon { protected int width, height; public Polygon(int a, int b) { width=a; height=b;} public abstract int area();}...In file PolyTest.java:
public class PolyTest {
public static void int main () {
Polygon rect = new Rectangle(4,5);
Polygon trgl = new Triangle(4,5);
// illegal
// Polygon poly = new Polygon(4,5);
System.out.println(rect.area());
System.out.println(trgl.area());
// System.out.println(poly.area());
}
}
C++: Java:
51
Class Object
In Java, all classes (built-in and user-defined) are subclasses or descendents of class Object.
You’ll notice this fact when using the online Java documentation
Because of this, every class inherits a number of useful standard methods from class Object, including:
toString(), equal(), hashCode()
It is often useful or necessary to override these methods.
52
Numerical Object Types
• For each primitive type in Java, there is a corresponding Object type
• Sometimes Object types are required when using built-in classes (e.g., ArrayList)
• Easy to convert between the two (just assign one to the other)
• Note on 8-bit types– char is a character type in Java– byte is an 8-bit numerical type in
Java– These are not equivalent
Booleanboolean
Characterchar
Doubledouble
Floatfloat
Longlong
Shortshort
Integerint
Bytebyte
Object TypePrimitive Type
53
Additional Type Notes
All Java types are signed The following are illegal in Java:
unsigned long bigLong; // not legal in Java
unsigned double salary; // not legal in Java
The boolean type in Java is called boolean (cf. bool in C++)
true and false are NOT equal to 1 and 0, as they are in C++
Casting between boolean and int types is not allowed:
boolean aBool = false; // not legal in Java
int anInt = (int)aBool; // not legal in Java
54
Java Interfaces An interface in Java is a collection of method
declarations and constants, with no data and no bodies.
We say that a class implements an interface if it implements all of the methods declared in the interface.
In general, interfaces define behaviors we desire in a wide variety of possibly unrelated classes.
55
Interface Example As an example, consider an interface for objects
that can be sold:
public interface Sellable {
public String description(); public int listPrice(); public int lowestPrice();}
Any class which implements this interface must define these three functions.
56
Interface Example Here's a class which implements Sellable:
public class Photograph implements Sellable { private String descript; private int price; private boolean color;
public Photograph(String desc, int p, boolean c) { descript = desc; price = p; color = c; }
public String description() { return descript; } public int listPrice() { return price; } public int lowestPrice() { return price/2; } public boolean isColor() { return color; }}
57
Interface Example Suppose we had another interface, Transportable:
public interface Transportable { /** weight in grams */ public int weight(); /** whether the object is hazardous */ public boolean isHazardous();}
Note that, as before, the interface defines no code, only function prototypes.
58
Multiple Inheritance We can then create a class which implements both
interfaces. This is called multiple inheritance.
public class BoxedItem implements Sellable, Transportable {
... public String description() { return descript; } public int listPrice() { return price; } public int lowestPrice() { return price/2; } public int weight() { return weight; } public boolean isHazardous() { return haz; } public int insuredValue() { return price*2; } ...}
59
Using Interfaces When using objects which define interfaces, we
can treat them very much like classes:
Sellable[] itemsForSale = new Sellable[10];
...itemsForSale[0] = new Photograph(“Monterey Bay”, 100, true);itemsForSale[1] = new BoxedItem(“TV”,...);...
System.out.println(itemsForSale[0].description() + “: $” + itemsForSale[0].listPrice() + + “, sale price: ” + itemsForSale[0].lowestPrice();
60
Pre-defined Java Interfaces
Java has a large number of useful interfaces pre-defined, many of which we'll see throughout the quarter
Some of them include Comparable: allows objects of an implementing
class to be compared and sorted Runnable: used in threads programming Java Collections Framework interfaces, including
List: list of items Queue: FIFO list Map: collection of <key,value> pairs Set: collection of objects Collection: any of the above, and more
Interfaces used in GUI programming
61
Inheritance versus Interface
The Java interface is used to share common behavior (only method headers) among the instances of different classes.
Inheritance is used to share common code (including both data members and methods) among the instances of related classes.
In your program designs, remember to use the Java interface to share common behavior. Use inheritance to share common code.
If an entity A is a specialized form of another entity B, then model them by using inheritance. Declare A as a subclass of B.
62
C++ Templates ≈ Java Generics
Java includes a generics framework, similar to C++ Templates, which allows us to define a class in terms of formal type parameters.
public class Pair<K,V> { ...
We instantiate a class using actual type parameters.
Pair<String,Integer> pair1 =
new Pair<String,Integer>();
63
public class Pair<K, V> {
private K key;
private V value;
public void set(K k, V v) {
key = k;
value = v;
}
public K getKey() { return key; }
public V getValue() { return value; }
public String toString() {
return "[" + getKey() + ", " + getValue() + "]";
}
Generics Example
64
public static void main (String[] args) {
// Create a String-Integer Pair
Pair<String,Integer> pair1 = new Pair<String,Integer>();
pair1.set(new String("height"), new Integer(36));
System.out.println(pair1);
// Create a Student-Double Pair
Pair<Student,Double> pair2 = new Pair<Student,Double>();
pair2.set(new Student("A5976","Sue",19), new Double(9.5));
System.out.println(pair2);
}
}
Generics Example
65
In the previous example, K and V could be instantiated as arbitrary types. We can also restrict their types:
public class Pair2<K extends Person,
V extends Number> {
private K key;
private V value;
...
Generics will be useful for further discussion on lists and other abstract data types (ADTs).
Generics Example
66
Eclipse First Run Checklist
First run:
1. Select/create a workspace directory (when eclipse starts)
67
Eclipse First Run Checklist
1. Change formatting to NOT use tab characters Preferences -> Java -> Code Style -> Formatter
For active profile, select “Java Conventions [built-in]”
68
Eclipse First Run Checklist
Best: edit this profile, rename it to “Java Conventions [spaces only]” and select “Spaces Only” as the Tab policy.
69
Eclipse First Run Checklist
Make sure JRE is selected Preferences -> Java -> Installed JREs Add a new JRE if necessary
70
Eclipse First Run Checklist
Make sure JRE is selected Preferences -> Java -> Installed JREs Add a new JRE if necessary
71
Eclipse Project Checklist
Create a new Java project
72
Eclipse Project Checklist Type <Your_Last_Name>_Prog_<x>_<Name> for the project name
Select “Use project folder as root for sources and class files. Click Finish.
73
Eclipse Project Checklist
Right click on the new project, and create a new class
74
Eclipse Project Checklist
• For the new class, fill in a package name (same as Project, but first letter should be lower case), class name, and select appropriate options at the bottom. Click Finish.
75
Eclipse Project Checklist
Your project should look like this. Finish it up and turn it in!