introduction to java for c/c++ programmers

55
Introduction to Java for C/C++ Programmers Note: Much of the following is taken from Professor Gary Shute's web page: http://www.d.umn.edu/~gshute/java/c 2java.html

Upload: jamil

Post on 18-Mar-2016

108 views

Category:

Documents


2 download

DESCRIPTION

Note: Much of the following is taken from Professor Gary Shute's web page: http://www.d.umn.edu/~gshute/java/c2java.html. Introduction to Java for C/C++ Programmers. General Similarities and Differences. Java similarity with C: simple data, expressions, and statements - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction to Java for C/C++ Programmers

Introduction to Java for C/C++ Programmers

Note: Much of the following is taken from Professor Gary Shute's web page:

http://www.d.umn.edu/~gshute/java/c2java.html

Page 2: Introduction to Java for C/C++ Programmers

General Similarities and Differences● Java similarity with C:

– simple data, expressions, and statements● Java similarity with C++:

– object orientation through classes– code commenting

● Unique to Java:– Dynamic memory management support (garbage collection)– GUI support– compile-once, run anywhere (Java Virtual Machine)– language support for interfaces (no multiple inheritance)

Page 3: Introduction to Java for C/C++ Programmers

Java Simple Data(Primitive Types)

Type Valueboolean true, falsechar unicode characterbyte 8 bit two's complementshort 16 bit two's complementint 32 bit two's complementlong 64 bit two's complementfloat 32 bit IEEE 754 floating pointdouble 64 bit IEEE 754 floating point

Page 4: Introduction to Java for C/C++ Programmers

Java Simple Data (cont'd)● Similarity with C/C++:

– syntax for literals and expressions exactly the same except for Unicode escape sequences for chars and strings

● Differences:– Java does not have pointers (or structs, or unions)– Java does not automatically coerce between the

integral types, the boolean type, and the character type. For example, if x is an int, the following is illegal:

while (x) { ... }

Page 5: Introduction to Java for C/C++ Programmers

Java Objects

● An object is an encapsulation of data along with methods for manipulating the data

● Java objects are grouped into classes● Classes are regarded as a special kind of object● Many Java classes are defined in the standard

class library● Programmers may also define their own classes

Page 6: Introduction to Java for C/C++ Programmers

Defining Java Classes

● Unlike C, Java does not require that class members be defined before their use

● The Java compiler works like an assembler, performing multiple passes

● Trade-off: syntax error handling is complicated, resulting in some errors not being reported till later compiles

In its simplest form, a Java class definition has thefollowing structure:

public class A { <method, variable, and constant definitions>

} // terminating semicolon not required!

Page 7: Introduction to Java for C/C++ Programmers

Class Examplepublic class MyInt { // an object of this class // simply holds an int value

private int value; // instance variable

public MyInt(int v) { // constructor value = v; }

public void setValue(int newv) { // setter value = newv;

}

public int getValue() { // getter return value;

}

}

Page 8: Introduction to Java for C/C++ Programmers

Java Variables● Other than literal values, all Java data is accessed

through variables:– instance variables (class level)– parameters and local variables (method level)

● All variables are typed as either:– simple (primitive) data– class object– interface object (like a class object whose methods

have been declared but not defined)

Page 9: Introduction to Java for C/C++ Programmers

Variable Values: Simple Types

● Java variables with simple or primitive types contain value copies:– Although two variables may contain the same value,

they will have two distinct copies– If one of the variables is changed, it has no effect on

the other

Page 10: Introduction to Java for C/C++ Programmers

Examplepublic class test {

public static void main(String[] args) { int a = 3; int b = a; System.out.println("a = " + a + "\nb = " + b); System.out.println("Changing a to 4"); a = 4; System.out.println("a = " + a + "\nb = " + b); }}

Output: a = 3b = 3Changing a to 4a = 4b = 3

Page 11: Introduction to Java for C/C++ Programmers

Notes on the Example

● Every Java application must have a main method, defined in a class

● println is a method in a builtin output stream class for writing to standard output

● The ``+'' operator for strings is defined to be concatenation

● The value of b is not affected because it is a primitive type, and therefore a copy

Page 12: Introduction to Java for C/C++ Programmers

Variable Values: Object Types

● Java object variables, on the other hand, are references to objects

● Two object variables may refer to the same object. If the object is modified then the change can be seen through both variables.

Page 13: Introduction to Java for C/C++ Programmers

Another Examplepublic class test { public static void main(String[] args) { MyInt c = new MyInt(3); MyInt d = c; System.out.println("c = " + c.getValue() + "\nd = " + d.getValue()); System.out.println("Changing c to 4"); c.setValue(4); System.out.println("c = " + c.getValue() + "\nd = " + d.getValue()); }}

Output:c = 3d = 3Changing c to 4c = 4d = 4

Page 14: Introduction to Java for C/C++ Programmers

What You Can Do With Object Variables

● Assign it the value of a new object– example: MyInt d = c;

● Give it no value at all– example: d = null;– Note: null is not a special object!

● Send it a message– example: System.out.println("c = "+c.getValue()+ ...);

Object Method String parameter

Page 15: Introduction to Java for C/C++ Programmers

Java Messages● Two forms:

– <receiver>.<method-name>(<parameter list>)– <receiver>.<variable-name>

● <receiver> can be:– a variable: c.setValue(4)– indexed array expression: myArray[i].setValue(4) – any expression that evaluates to an object: System.out.println("...")

– a class name: BorderLayout.NORTH – the last usage is usually in connection with static class

variables

Page 16: Introduction to Java for C/C++ Programmers

Example

● System is a builtin class● out is a variable in the System class of type PrintStream, another builtin class

● out is like stdout in C● getClass is a method in the builtin Object class,

the supertype of all objects, including x's class● getName is a method in the builtin Class class● so this statement prints the name of x's class

System.out.println(x.getClass().getName());

Page 17: Introduction to Java for C/C++ Programmers

Creating Java Objects● Most Java objects are created using the keyword new with a call to a constructor method:– new MyInt(3);

● A class also provides a default parameterless constructor that is inherited from the Object class

● Most constructors are declared public:

public <class-name>(<typed parameter list>) { <object initialization code> }

public MyInt(int v) { // constructor value = v; }

Page 18: Introduction to Java for C/C++ Programmers

Multiple Class Constructors● Often, a class has one "primary" constructor that

accepts a full set of parameters and perhaps several others that accept fewer parameters

● Those constructors with fewer parameters can call the primary constructor with suitable default values for the missing parameters

● The primary constructor can be accessed within any the other constructors using the this form

Page 19: Introduction to Java for C/C++ Programmers

Multiple Class Constructor Example

public class SomeClass {

private String name = null; private String prefix = null; private String identifier = null;

public SomeClass(String n, String pre, String id) { name = n; prefix = pre; identifier = id; }

public SomeClass(String n, String pre) { this(n, pre, n); // calls the 3-arg constructor } // with id defaulting to n

public SomeClass(String n) { this(n, ""); // calls the 2-arg constructor } // with pre defaulting to empty} // string

Page 20: Introduction to Java for C/C++ Programmers

Defining Subclasses

● Unlike C++, which allows multiple inheritance, a Java class can only inherit from a single parent class, which is called its superclass

● If a class inherits from a superclass, all the public and protected members of the superclass are automatically defined for it

● Defining subclasses is accomplished with the extends clause on the class definition

● If the extends clause is not used in a class definition then its superclass is the class called Object

Page 21: Introduction to Java for C/C++ Programmers

Defining Subclasses (cont'd)● Suppose SomeOtherClass is to be a subclass

of SomeClass and use its constructors– Use the extends clause– Use the super keyword to call the superclass's

constructor:

public class SomeOtherClass extends SomeClass {

public SomeOtherClass(String n, String id) { super(n, "", id); // super must be first } // in body if used

public SomeOtherClass(String n) { super(n); // more code can follow }}

Page 22: Introduction to Java for C/C++ Programmers

Instance and Class Members● Any member (variable, method, or constant) of a

class that is not declared static is an instance member:– They are associated with individual objects– In a message, the receiver is specified by a variable or

expression that evaluates to an object● Any member declared static is a class

member, shared by all objects of the class:– In a message, the receiver is specified by a class name– Example: BorderLayout.NORTH– Example: JOptionPane.showInputDialog(msg);

Page 23: Introduction to Java for C/C++ Programmers

Constants: final Variables

● Unlike C, Java uses the keyword final to declare constants

● Most constants are usually class variables, so they are declared like:

static final int taxRate;

Page 24: Introduction to Java for C/C++ Programmers

Identifier Scopes● The identifier scoping rules for methods and

control structures are the same as for C++:– The scope of an identifier is the method or innermost

block in which it is declared● There are two additional scopes in Java:

– Class scope: an entire class definition– Package scope: an entire directory of Java source

code files (covered later)

Page 25: Introduction to Java for C/C++ Programmers

Limiting Access for Class Members● Each class member can have an access keyword

of public, private, protected, or no keyword at all

● public and private access is similar to that for C++

● protected members can be accessed anywhere in the class and in any subclass and within the package scope– so, protected instance variables are a bad idea

● Members without any access keyword are given package scope by default

Page 26: Introduction to Java for C/C++ Programmers

Abstract Classes

● An abstract class is one that can have no instances● Abstract classes often declare methods that are left

undefined until the class is extended● In C++, these were called pure virtual methods● In Java, these are given the abstract keyword, for

example:– public abstract boolean func(int n);

Page 27: Introduction to Java for C/C++ Programmers

Abstract Classes (cont'd)

● The existence of an abstract method within it also makes the class itself abstract:

public abstract class A {

<member definitions> public abstract boolean func(int n);

<more member definitions>

}

Page 28: Introduction to Java for C/C++ Programmers

Concrete Subclasses

● Subclasses that define all of the abstract methods are called concrete subclasses

public class B extends A {

<new member definitions> public boolean func(int n) { <implementation code> }

<more new member definitions>

}

Page 29: Introduction to Java for C/C++ Programmers

Java Interfaces● A Java interface is like an abstract class all of

whose methods are abstract● Also, the only variables allowed in an interface

are final

public interface C {

public boolean func(int n);

<more method declarations>

}Since it's an interface, no abstract keywords areused

Page 30: Introduction to Java for C/C++ Programmers

Implementing Interfaces● An abstract class expects to be extended; an

interface expects to be implemented ● While a Java class can extend only one

superclass, it can implement any number of interfaces

public class E extends A implements C, D {

<definitions of members declared in A, C, and D>

<new member definitions> }

Page 31: Introduction to Java for C/C++ Programmers

Interfaces vs. Abstract Classes● Abstract classes are classes that cannot have

instances; Interfaces are not even classes● The reason for using an abstract class is to force

other programmers to create subclasses● The reasons for using an interface include:

– making classes more reusable– simulating multiple inheritance– taking advantage of pure polymorphism

● Knowing how and when to use abstract classes and interfaces comes with experience

Page 32: Introduction to Java for C/C++ Programmers

Java Arrays and Strings● In Java arrays and strings are objects● Thus, you can create new ones with new:

– int[] A = new int[5];– int A[] = new int[5]; // also allowed– String s = new String(); // empty

● Initializing syntax is also allowed:– double readings[] = {3.01, -44.2, 0.0012};– String myString = "A brand new string";

● Java allows familiar syntax to access array elements, for example: A[i]

● But not for strings: myString.charAt(i)

Page 33: Introduction to Java for C/C++ Programmers

More About Strings● There is a toString() method that is defined

for all objects● It is a standard practice for standard and

programmer-defined subclasses to redefine toString() to return a string appropriate for the class's type

● In expressions in which a string is expected but not found Java will automatically call the appropriate class's toString() method:

System.out.println("a = " + a + "\nb = " + b);

Page 34: Introduction to Java for C/C++ Programmers

Java Type Checking

● In a Java assignment statement, the type of the variable on the left hand side must be "wider" than the type of the expression on the right

● Suppose d is of type double, i is of type int, super is a class variable of type SuperClass, and sub is a class variable of type SubClass where SubClass extends SuperClass:– d = i; // OK– i = d; // NO– super = sub; // OK– sub = super; // NO

Page 35: Introduction to Java for C/C++ Programmers

Java Coercion (Casting)● For primitive types, casting can be done only when it

makes sense to do so:– d = (double)true; //NO-incompatible types– i = (int)d; // OK-but info loss possible

● For class types, casting can be done only when it is "down" the class hierarchy. Suppose OtherClass is not a direct or indirect subclass of SuperClass:– super = (SuperClass)(new OtherClass()); // NO - incompatible types

– sub = (Subclass)super; // OK

Page 36: Introduction to Java for C/C++ Programmers

Java Generic Data Structures and Coercion

● The Java standard class library contains a few useful generic data structure classes and interfaces, such as:– Hashtable– Vector– Stack– Enumeration

● These classes and interfaces are designed to deal with collections of objects

● To be generally useful, they are declared to work generically on objects of type Object

Page 37: Introduction to Java for C/C++ Programmers

Java Generic Data Structures and Coercion (cont'd)

● Ramifications:– You cannot directly assign an element of one of these

collections to a variable unless it is declared to have type Object

– Most likely you will want to coerce the returned value to a more appropriate specific type

● For example, if s is an object of type Stack that holds strings then when you pop this stack you will want to coerce the result to String:– (String)(s.pop())

Page 38: Introduction to Java for C/C++ Programmers

Compiling Java Classes● One way: combine class definitions into one file.

public class test {

public static void main(String[] args) { ...<makes use of MyInt class>... }}

public class MyInt { private int value;

public MyInt(int v) { value = v; } public void setValue(int newv) { value = newv; } public int getValue() { return value; }}

File: example.java

Page 39: Introduction to Java for C/C++ Programmers

Compiling Java Classes (cont'd)● Java source code files must have the .java

extension● Files are compiled using the javac command.

Example:– 3% javac example.java

● For each class in the file, a separate object file (interpreted bytecode) with a .class extension is created. In the example:– MyInt.class– test.class

Page 40: Introduction to Java for C/C++ Programmers

Executing Java Object Code● Java object code (the content of .class files)

contains instructions for the Java Virtual Machine (JVM)

● Java object code can be run on any machine that has an interpreter for the JVM

● To execute object code, use the java command– Argument must be the name of a class– The class must have a main method defined– Do not include the .class extension. Example:

● 4% java test

Page 41: Introduction to Java for C/C++ Programmers

Separate Compilation in Java● Good software engineering practice advises that

each Java class have its own source file● If the class name is A, then the source file name

should be A.java. In our example:– MyInt.java– test.java

● This allows classes to be separately compiled:– 5% javac MyInt.java – This creates the object file MyInt.class

Page 42: Introduction to Java for C/C++ Programmers

External References and the CLASSPATH Variable

● The preceding example worked because the class MyInt does not have any references to symbols external to its file

● However, if you now try:– 6% javac test.java– you will get an error saying that MyInt cannot be

resolved; the compiler does not know where to look● To use separate compilation, you must tell the

compiler where to look for external symbols by setting the CLASSPATH environment variable

Page 43: Introduction to Java for C/C++ Programmers

External References and the CLASSPATH Variable (cont'd)

● The CLASSPATH variable specifies directories the java compiler should search for external classes

● The simplest use of CLASSPATH:– 7% setenv CLASSPATH . – This sets the class path to the list containing the current

directory● Now if you do:

– 8% javac test.java– the object file test.class will be created– Note that MyInt.java is automatically recompiled if it

has changed since test.class was last created

Page 44: Introduction to Java for C/C++ Programmers

Java Packages

● Classes that are in the same directory should be grouped into a package. Why?– To allow classes in a different directory to

conveniently import them, and– To avoid name clashes

● For example, the test and MyInt classes could be grouped into a package called foo– If so, a directory called foo should contain the files test.java and MyInt.java

Page 45: Introduction to Java for C/C++ Programmers

Java Packages and Source Code Files● Each source file making up a package should

start with a package statement of the form:– package <package-name>;

● The structure of a source file should be:

<package statement>

<import statements>

<class definition>

Page 46: Introduction to Java for C/C++ Programmers

Example

package foo;

public class MyInt { private int value;

public MyInt(int v) { value = v; }

public void setValue(int newv) { value = newv; }

public int getValue() { return value; }}

File foo/MyInt.java:

Note: no import statements are used in this example

Page 47: Introduction to Java for C/C++ Programmers

Example (cont'd)

package foo;

public class test { public static void main(String[] args) { MyInt c = new MyInt(3); MyInt d = c; System.out.println("c = " + c.getValue() + "\nd = " + d.getValue()); System.out.println("Changing c to 4"); c.setValue(4); System.out.println("c = " + c.getValue() + "\nd = " + d.getValue()); }}

File foo/test.java:

Page 48: Introduction to Java for C/C++ Programmers

Packages and the Java Interpreter

● When packages are used, class names can be fully qualified by prefixing the package name, separated by a dot (.):– foo.MyInt– foo.test

● The Java interpreter java requires a fully qualified class name:– 9% java foo.test

● Note: java test worked before because test was in the default package (see next) and thus test was a fully qualified class name

Page 49: Introduction to Java for C/C++ Programmers

Packages and the CLASSPATH Variable

● The class path is actually a list of directories in which to look for packages in which classes reside

● When a source file does not have a package statement, its class goes into an unnamed default package, which is always searched

● When a source file has a package statement, then the class path must have the directory containing the directory representing the package

Page 50: Introduction to Java for C/C++ Programmers

Packages and the CLASSPATH Variable (cont'd)

● Suppose the unix path for foo is ~/java/foo. Then:– 10% setenv CLASSPATH ~/java

● More than one directory can be added to the class path by separating them with colons (:)– 11% setenv CLASSPATH ~/java:.– Adding the current directory (.) insures that files in the

current directory without a package specification will be searched

Page 51: Introduction to Java for C/C++ Programmers

Multiple Packages

● Frequently, a class will need to make use of a class from another package

● Suppose that we leave test in the foo package but move MyInt to the bar package:

package bar;

public class MyInt { private int value; public MyInt(int v) { value = v; } public void setValue(int newv) { value = newv; } public int getValue() { return value; }}

File bar/MyInt.java:

Note

Page 52: Introduction to Java for C/C++ Programmers

Multiple Packages and the import Statement

● When a file makes use of classes from an outside package, they must be imported:– import <package>.<class> – import <package>.* // imports all classes

package foo;

import bar.MyInt;

public class test {

public static void main(String[] args) { ...<makes use of MyInt class>... }}

foo/test.java

Page 53: Introduction to Java for C/C++ Programmers

Java Standard Classes and Packages● Java standard library classes, like Stack and

various GUI classes, are grouped into many packages. Some important ones:– java.lang Language support (e.g., String)– java.util Utilities (Stack)– java.io Input and output (PrintStream)– java.awt Abstract Window Toolkit (Color)– java.applet Applets (Applet)– java.net Networking (Socket)– java.sql Database Access (ResultSet)– javax.swing Extended GUI (JButton)

Page 54: Introduction to Java for C/C++ Programmers

Using Java Standard Classes● To use a class from the Java Standard Library,

you must import it:– import java.util.Stack;

● Often, you need more than one class from a package. For example, instead of importing each of:– javax.swing.JButton, – javax.swing.JPanel, and– javax.swing.JFileChooser

● you can just do:– import javax.swing.*;

Page 55: Introduction to Java for C/C++ Programmers

The Best Java Documentation● http://java.sun.com/apis.html● This brings you to Sun's API (applications

programming interface) documentation● Go to the Java 2 Platform, Standard Edition, and

choose the version that is compatible with your platform– CS Department Suns: version 1.4.0– ub: version 1.2.2– bulldog: version 1.4.0(beta)

● Professor Gary Shute has a local copy of the 1.2.2 API documentation at: http://www.d.umn.edu/~gshute/java