Presentation is loading. Please wait.

Presentation is loading. Please wait.

Website: http://www.icarnegie.com SSD1 Unit 2 Intro to Java Presentation 2.3 Website: http://www.icarnegie.com.

Similar presentations


Presentation on theme: "Website: http://www.icarnegie.com SSD1 Unit 2 Intro to Java Presentation 2.3 Website: http://www.icarnegie.com."— Presentation transcript:

1 Website: http://www.icarnegie.com
SSD1 Unit 2 Intro to Java Presentation 2.3 Website:

2 Why Use Java? Simple - Java has thrown out many of the complex features of C++ and C resulting in a simpler language (no pointers, no unions, no enumerations) Object-oriented - Java is a single-root, single-inheritance object oriented language Multithreaded - Java has a built-in support for multithreading Distributed - Using Java RMI (remote method invocation) you can access objects on other machines almost as if they were local Portable - programs written in the Java language are platform independent

3 The Java execution environment
Like C and C++ programs, Java programs are compiled. Unlike C and C++ programs, Java programs are not compiled down to a platform-specific machine language. Instead, Java programs are compiled down to a platform-independent language called bytecode. Bytecode is similar to machine language, but bytecode is not designed to run on any real, physical computer. Instead, bytecode is designed to be run by a program, called a Java Virtual Machine (JVM), which simulates a real machine.

4 JVM – Java Virtual Machine
JVM is an interpreter that translates Java bytecode into real machine language instructions that are executed on the underlying, physical machine A Java program needs to be compiled down to bytecode only once; it can then run on any machine that has a JVM installed

5 JVM – Cont.

6 Running Java Programs // file HelloWorld.java
public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World !”); } } > javac HelloWorld.java The compilation phase: This command will produce the java bytecode file HelloWord.class > java HelloWorld The execution phase (on the JVM): This command will produce the output “Hello World!”

7 Java keywords are all lower case
Case Sensitivity Case sensitivity: String is not the same as string MAIN is not the same as main Java keywords are all lower case e.g. public class static void

8 Methods and variables start with a leading lowercase letter
Naming Conventions Methods and variables start with a leading lowercase letter next, push(), index, etc. Classes starts with a leading upper-case letter String, StringBuffer, Vector, Calculator, etc.

9 Naming Conventions – Cont.
Constants (final) are all upper-case : DEBUG, MAX_SCROLL_X, CAPACITY final double PI = ; Word separation in identifiers is done by capitalization (e.g maxValue), except for constants where underscore is used (e.g MAX_SCROLL_X)

10 Comments C++ Like: // comment .. /* this is a comment */ And Javadoc Comments: /** this is javadoc comment */

11 Flow control do/while switch if/else for It is like C/C++: int i=5;
// act1 i--; } while(i!=0); if/else char c=IN.getChar(); switch(c) { case ‘a’: case ‘b’: // act1 break; default: // act2 } if(x==4) { // act1 } else { // act2 } for int j; for(int i=0;i<=9;i++) { j+=i; }

12 Variables There are two types of variables in Java, primitive types (int, long, float etc.) and reference types (objects) In an assignment statement, the value of a primitive typed variable is copied In an assignment statement, the pointer of a reference typed variable is copied

13 16-bit unicode charecter
Primitive Types The Java programming language guarantees the size, range, and behavior of its primitive types Type Values boolean true,false char 16-bit unicode charecter byte 8-bit signed integers short 16-bit signed integers int 32-bit signed integers long 64-bit signed integers float double void - * The default value for primitive typed variables is zero bit pattern

14 Java provides Objects which wrap primitive types. Example:
Wrappers Java provides Objects which wrap primitive types. Example: Integer n = new Integer(“4”); int m = n.intValue();

15 Reference Types Reference types in Java are objects
An object has a set of data members (attributes) and a set of methods All reference typed variables are dynamically allocated from heap at runtime (and can’t be explicitly deallocated by the programmer) Referenced typed variables can’t be dereferenced (no reference * or derefernce & operators) The default value of reference typed variables is null

16 a=b Reference Types Java C++ MyObject x
MyObject *x ( not initialized !!!) N/A MyObject x(5) Since we’re handling pointers, the following is obvious : a 5 a 5 a=b b 9 b 9

17 How can I store groups of objects?
It is possible to store a group of objects in Java by using Vectors and Arrays to collect the objects – thus are known as “collections”. Collections allow programs to add objects to them and making them available for later use or processing. This can be done as many times as needed. What is a Vector? It is a class of the java.util package that allows collections of objects that will easily add new objects, remove objects, and go through collection processing of the objects (traversing the vector). A vector has synchronized threading and also can dynamically grow or shrink without having a specified size initially declared. What is an Array? It is not a Class! A primitive programming language feature that is built into Java that uses indexing to support collections of data. It uses only the field “length” to provide information on the number of elements in the array. An array can also store primitive values. Please refer to pp in the book

18 Ex: objvar1 variable1 = (difvar1) variable2;
Casting The changing of an object or primitive variable from one declared state to another. Ex: objvar1 variable1 = (difvar1) variable2; Ex: Animal myDog= new Dog (); Dog spot = (Dog) myDog; long x, y, z; //64 bits, from 9 to -9 quintillion int j, k; // 32 bits, from 2 to -2 billion y = 55; // is this ok? k = 22; // is this ok? j = y; // is this ok? k = 32L // is this ok? j = (int) y; // is this ok?

19 Iteration through a Vector
Calling a vector: Vector vec = new Vector () Adding an object to a vector: vec.add(object) Traversing vectors with for loops: for (i=0; i < size of collection; i++) { process element number(i) } Looking for an AlgaeColony? Vector neighbors = simulation.getNeighbors(row, col, 0); int index; for (index = 0; index < neighbors.size(); index++) { if (neighbors.get(index) instanceof AlgaeColony) { return true; } else { return false;

20 Java arrays are objects, so they are declared using the new operator
The size of the array is fixed Animal[] arr; // nothing yet … arr = new Animal[4]; // only array of pointers for(int i=0 ; i < arr.length ; i++) { arr[i] = new Animal(); // now we have a complete array

21 Garbage Collection In C++ we use the ‘delete’ operator to release allocated memory. ( Not using it means : memory leaks ) In Java there is no ‘delete’ and there are no memory leaks. Objects are freed automatically by the garbage collector when it is clear that the program cannot access them any longer.  Thus, there is no "dangling reference" problem in Java.

22 Classes in Java In a Java program, everything must be in a class.
There are no global functions or global data Classes have fields (data members) and methods (functions) Fields and methods are defined to be one-per-object, or one-per-class (static) Access modifiers (private, protected, public) are placed on each definition for each member (not blocks of declarations like C++)

23 Class Example data members constructors a method package example;
public class Rectangle { public int width = 0; public int height = 0; public Point origin; public Rectangle() { origin = new Point(0, 0); } public Rectangle(int w, int h) { this(new Point(0, 0), w, h); public Rectangle(Point p, int w, int h) { origin = p; width = w; height = h; public void setWidth(int width) { this.width = width; data members constructors a method

24 Examples of Finding Specific Objects
Dynamic typing means the declared type (called the apparent type) and the actual type (called the dynamic type) can vary over the lifetime of a variable Java comes with some mechanisms for testing the type of an object Instanceof operator Variable instanceof ClassName if ( tape instanceof Movie ){…} Returns true if the variable holds reference to an instance of the class (or any descendent class) getClass() method Class getClass() if(tape.getClass().equals(Movie.class)) {…} Returns dynamic type of the object

25 Packages A package physically and logically bundles a group of classes
Classes are easier to find and use (bundled together) Avoid naming conflicts Control access to classes Unrestricted access between classes of the same package Restricted access for classes outside the package

26 Creating a Package place a package statement at the top of the source file in which the class or the interface is defined. If you do not use a package statement, your class or interface ends up in the default package, which is a package that has no name The scope of the package statement is the entire source file. C1.java package p1; public class C1 {...} class C2 {...}

27 Using Package Members Only public package members are accessible outside the package in which they are defined. Refer to a member by its long (qualified) name A qualified name of a class includes the package that contains the class Good for one-shot uses Import the package member When only a few members of a package are used Import the entire package May lead to name ambiguity

28 Using Package Members - Examples
Refer to a package member by its qualified name: p1.C1 myObj = new p1.C1(); Importing a package member Place an import statement at the beginning of the file, after the package statement: import p1.C1; ... C1 myObj = new C1();

29 Questions?


Download ppt "Website: http://www.icarnegie.com SSD1 Unit 2 Intro to Java Presentation 2.3 Website: http://www.icarnegie.com."

Similar presentations


Ads by Google