1 / 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/c2java.html. Introduction to Java for C/C++ Programmers. General Similarities and Differences. Java similarity with C: simple data, expressions, and statements

jamil
Download Presentation

Introduction to Java for C/C++ Programmers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 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)

  3. Java Simple Data(Primitive Types) TypeValue boolean true, false char unicode character byte 8 bit two's complement short 16 bit two's complement int 32 bit two's complement long 64 bit two's complement float 32 bit IEEE 754 floating point double 64 bit IEEE 754 floating point

  4. 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) { ... }

  5. 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

  6. Defining Java Classes In its simplest form, a Java class definition has the following structure: • 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 public class A { <method, variable, and constant definitions> } // terminating semicolon not required!

  7. Class Example public 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; } }

  8. 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)

  9. 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

  10. Example public 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 = 3 b = 3 Changing a to 4 a = 4 b = 3

  11. 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

  12. 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.

  13. Another Example 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()); } } Output: c = 3 d = 3 Changing c to 4 c = 4 d = 4

  14. 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

  15. 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

  16. Example System.out.println(x.getClass().getName()); • 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

  17. 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; }

  18. 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

  19. 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

  20. 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

  21. 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 } }

  22. 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);

  23. 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;

  24. 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)

  25. 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

  26. 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);

  27. 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> }

  28. 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> }

  29. 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 are used

  30. 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> }

  31. 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

  32. 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)

  33. 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);

  34. 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

  35. 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

  36. 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

  37. 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())

  38. Compiling Java Classes • One way: combine class definitions into one file. File: example.java 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; } }

  39. 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

  40. 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

  41. 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

  42. 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

  43. 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

  44. 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

  45. 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>

  46. Example File foo/MyInt.java: 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; } } Note: no import statements are used in this example

  47. Example (cont'd) File foo/test.java: 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()); } }

  48. 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

  49. 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

  50. 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

More Related