Java An Introduction Outline The Java Virtual Machine Java essential language features data types operators References: Internet Course notes by E.Burris Computing Fundamentals with Java, by Rick Mercer Beginning Java Objects - From Concepts to Code by Jacquie Barker Object-Oriented Design & Patterns, Cay Horstmann Introduction to Java Programming, David Eck Sun white papers on Java 9/1/2010 1 9/1/2010 2 Java Virtual Machine Java uses combination of compilation and interpretation You compile a Java source file (.java) into intermediate byte code (.class file) machine language for a computer that doesn't really exist. The byte codes are interpreted at runtime by the Java Virtual Machine (JVM). Java program can run on any computer that has an interpreter for Java bytecode The interpreter simulates the JVM like Virtual PC simulates a PC same compiled program running on many different types of computers. 9/1/2010 3
Java Virtual Machine It's called a virtual machine because most implementations of the virtual machine will be in software on top of another hardware machine platform. The JVM runs under the OS and the Java program runs under the JVM. Java Structure Java language Java JVM APIs & Libraries Java can be used as a stand-alone language. Using VM: you write java code and VM translates code into machine language needed. Combination of Java and Java bytecode is platform independent. 9/1/2010 5 9/1/2010 6 Java Objects & Methods Java is an object-oriented language Except for simple, native data types, all data in Java are objects All GUI building blocks (windows, buttons, etc) are objects All functions are called methods The main program is a main method that is contained within a class - not stand alone 9/1/2010 7 Structure of a Java Program /** FirstProgram.java A trivial program to illustrate Java programming elements. */ Class wrapper public class FirstProgram{ Main method signature Introductory Comments public static void main(string[] args) { System.out.println( Hello World! ); 9/1/2010 8
Java doesn't have any implementation-dependent behaviors. All primitive types are guaranteed to be a specific size. For example, in C++ an int may be 16-bits or 32-bits. In Java an int is always 32-bits. C++ allows stand-alone or global functions. In Java all functions must be the member of some class. Static member functions don't require the instance of a class to execute. 9/1/2010 9 9/1/2010 10 In C++ you have to declare a function (provide a prototype) before you can use it. Not necessary in Java because compiler makes multiple passes. In C++ objects can be created at compile time or at run time. In Java all objects are allocated dynamically from the heap (i.e. at run time). In Java cannot directly manipulate memory locations by address. No pointer arithmetic with arrays 9/1/2010 11 Pointers vs Object References Java always uses pointers. They re called references An object variable is a reference to an object -- a value that describes the location of the object. Java C++ C++ Bank b; Bank *b; (dynamic) Bank b; (static) b = new Bank(); b = new Bank(); In Java, only the dot operator is used for dereference (no arrows or *s). Java C++ C++ b.setbalance(100); b->setbalance(100); b.setbalance(100); (*b).setbalance(100); 9/1/2010 12
Object References Multiple variables can store references to the same object. For example, after the following statements: Bank bank = new Bank(); Bank anotherbank = bank; both object variables (bank and anotherbank) refer to the same object Java References Pointers in Java are safe You cannot create invalid pointers The garbage collector automatically reclaims unused objects -- you can't have a memory leak. 9/1/2010 13 9/1/2010 14 Implicit Parameter this this refers to the object on which the method was invoked. Assume class Bank has the method public void setname (String name) { this.name = name; then bank.setname( First National ) sets the name field of the Bank object to the value of the explicit parameter which is also called name. Use of this resolves ambiguity between the name field and name parameter 9/1/2010 15 Java super Method In Java the keyword super refers to the superclass or parent class of a class. super is a reference you can use in a subclass to call a method in the parent class. public void paintcomponent(graphics g) { super.paintcomponent(g); Call to super must be the first statement in method 9/1/2010 16
Java super Method The reference super is also used to call a specific constructor in a parent class. public class TypeSafeVector extends Vector { This Class s Constructor TypeSafeVector(int size, Object elementtype) { super(size);... Vector class constructor In C++ the integer 0 can be exchanged for the bool value false and any non-zero integer can be exchanged for the value true. In Java you can't interchange integer and boolean values. In Java both primitive types and reference types are passed by value. There is no pass by reference (&). 9/1/2010 17 9/1/2010 18 Java objects don't have destructors. Java doesn't have a pre-processor. Java has no typedefs, #defines or structs There is no goto statement in Java. (goto is a reserved word, but it isn't used.) But you can add a label to a loop and use that label as an argument on a break or continue statement. 9/1/2010 19 Java has no arithmetic operator overloading. Effects of operator overloading can be achieved by declaring a class, appropriate instance variables, and appropriate methods to manipulate those variables. 9/1/2010 20
: Exceptions Exception handling is optional in C++; it is mandatory in Java. If you do something that causes ( throws ) an exception, then the program must handle ( catch ) it. More on exceptions later No multiple inheritance. Java uses interfaces to implement multiple inheritance. An interface is a definition of a set of methods that one or more classes will implement. An important issue of interfaces is that they declare only methods and constants. Variables may not be defined in interfaces. (Sun) 9/1/2010 21 9/1/2010 22 Java Data Types & Operators 9/1/2010 23 Data Types Two categories of data types in Java: 1. primitive 2. reference A primitive data type represents a single value of a certain type and size recognizable by the compiler. For example, int i = 5; defines a 4-byte storage area that will hold integer values in the two's complement data format. A reference data type represents a reference to an instance of a class. 9/1/2010 24
Data Types Data Types There are 8 primitive data types in Java: Integers Data type Length byte 1 byte -128.. 128 short 2 bytes -32,768.. 32,767 int 4 bytes -2,147,483,648.. 2,147,483,647 long 8 bytes -9,223,372,036,854,775,808.. 9,223,372,036,854,775,807 9/1/2010 25 Floating Point Data type Length Format float 4 bytes IEEE 754 double 8 bytes IEEE 754 Other Data type Length Format char 2 bytes Unicode boolean N/A true/false Note: no unsigned int type 9/1/2010 26 Char Data Types // Character type // Characters are represented in Unicode -- 16-bit encoding standard char c; // 2 byte Unicode // boolean -- note, this is different from C++(bool) boolean bl; // can be true or false b = 128; // this an error in Java // boolean and int are not interchangeable Type Conversions Automatic type conversions are done only if no precision will be lost in the conversion (C++ will convert and truncate if necessary) int x; double y = 3.5; x = y; //in Java, will be an error Explicit type conversion can be done with a cast to override this decision: x = (int) y; //cast the double to an int 9/1/2010 27 9/1/2010 28
Constants Decimal constants (such as 1.2) are by default of type double. You can't directly assign or convert a double to a float because there might be a loss of data. You specify a decimal constant of type float by following the value with an F. For example: 1.2F. Initializing Variables Default values: boolean answer = false; //note spelling int i=0; double rate = 0.0; char ch = ; //blank space String name = null; 9/1/2010 29 9/1/2010 30 Naming conventions Variable names are lowercase if one word. If compound words, the first letter of second (third ) word is capitalized. item productnumber nameofthiscustomer A long name is preferable to a confusing short one! Constants The key word final denotes a constant: final int MAX_VALUE = 3; You can assign a value to a final variable only once. You don't have to assign a value in the definition, but it's good programming style. Final variables are ALL CAPS. 9/1/2010 31 9/1/2010 32
Other Operators Dot operator (.) The only operator used to access the methods or member data of an object. instanceof operator Tests whether a reference is of a particular type or is to a class that implements a particular interface Object obj = e.nextelement(); if (obj instanceof Shape) { Shape s = (Shape) obj; cast operator (type). Converts from one type to another. The example here casts a reference to an Object to a reference to a Shape. Shape s = (Shape) e.nextelement(); 9/1/2010 33