1 / 71

Java Overview CSE 422

Java Overview CSE 422. Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These materials are excerpted from a course created by Arthur Ryman of IBM Toronto, and used at the University of Toronto. Thanks!. Agenda. Introduction to Java (today)

mkitchen
Download Presentation

Java Overview CSE 422

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. Java OverviewCSE 422 Michigan State Universityprepared by Philip K. McKinleypresented by SeyedMasoud SadjadiThese materials are excerpted from a course created by Arthur Ryman of IBM Toronto, and used at the University of Toronto. Thanks!

  2. Agenda • Introduction to Java (today) • What is Java? • Tools Overview • Language Overview • Advanced Topics (next session) • Error Handling • Multithreading • Networking

  3. What is Java? • A concurrent, object-oriented programming language (OOPL) • A virtual machine (run-time environment) • can be embedded in web browsers (e.g. Netscape Navigator, Microsoft Internet Explorer and IBM WebExplorer) and operating systems. • Portable, Dynamic, and Extensible • A set of standardized packages (class libraries)

  4. Java, A Concurrent OOPL • Complete OOPL (not only structures into objects) • Characteristics of both C++ and Smalltalk • C++ • Same syntax for expressions, statements and control flow • Similar OO syntax (classes, access, constructors, methods, ... ) • Smalltalk • Similar object model (single-rooted inheritance hierarchy, access to objects via reference only) • Compiled to a byte-code (initially interpreted) • Dynamic loading • Garbage collection • Concurrency and synchronization (threads) • Objects can force mutual exclusion of threads running inside them

  5. Environment Java VM Java Virtual Machine • Java is complied to byte-codes whose target architecture is the Java Virtual Machine (JVM) • The virtual machine is embeddable within other environments, e.g. web browser & operating sys. • Uses a byte-code verifier when reading in byte-codes. • The Class Loader for classes loaded over the network (enhances security). javac Java Source Java Byte-code .java .class

  6. Portable, Dynamic, and Extensible • Java runtime based on architecturally neutral byte-codes (per class) .class files load interpret Java Runtime loaded classes (byte-codes) call Native.dll Native.dll

  7. Standard Set of Packages • Windowed GUIs • Full set of standard window-based GUI classes • Extremely easy to build GUI clients • Images and audio • Support for creating Image objects from .gif, .jpg, etc. • Provides Image processing “filters” • Applets can also play audio files • Networking • Library supports retrieving files, images, etc. via URL • Clean support for sockets providing access to Internet-based services • VM can dynamically load classes over the Internet

  8. Agenda • Introduction to Java (today) • What is Java? • Tools Overview • Language Overview • Advanced Topics (next session) • Error Handling • Multithreading • Networking

  9. JDK Tools • Java Developer’s Kit’s (JDK) three main tools are: • javac the Java compiler • java VM for running stand-alone Java applications • appletviewer a utility to view applets • Also included are: • javah Header file generator for interlanguage linking • javap A disassembler • javadoc HTML generator from Java source code • jdb a rudimentary Java debugger

  10. JIT Compiler • Although Java is interpreted, Just-In-Time compilers provide “client-side” compilation of byte-codes to machine code (native binary) • This provides: • Improved performance • Better match to specific hardware .class JVM running Applet or Application J.I.T.Compiler machine code

  11. Eclipse • jdt: java development tools subproject • Plug-ins for Java development

  12. Agenda • Introduction to Java (today) • What is Java? • Tools Overview • Language Overview • Advanced Topics (next session) • Error Handling • Multithreading • Networking

  13. Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++ Language Overview

  14. Java Programs • Two broad categories of program can be written • Applet • a Java program that runs inside a Java-enabled Web browser. • Application • a Java program run via the “java” command.

  15. A Simple Java Application • import java.io.*; • /** File: Count.java*/ • public class Count {` • public static void main (String[] s) throws IOException { • int count = 0; • while (System.in.read() != -1) • count++; • System.out.println("Input has "+count+" chars"); • } • } • Compile the .java file to generate the .class file • cmd>javac Count.java • Run the interpreter on the .class file • cmd> java Count • This is a test. • Input has 16 chars

  16. Analysis import java.io.*; /** File: Count.java*/ public class Count {` public static void main (String[] s) throws IOException { int count = 0; while (System.in.read() != -1) count++; System.out.println("Input has "+count+" chars"); } } • All Java code is contained within classes. • Java classes consist of fields (variables) and methods. • A Java source file contains at most one public class. • Applications must provide a method called main. To be recognized, the main method must have the correct method signature. • Java stores collections of classes in packages (class libraries). The import keyword selects the packages available.

  17. Comments • There are different types of comments // single line comment (until eol) /* single/multi-line comment (do not nest) */ /** multi-line documentation comment. Use immediately before class, method, and variable declaration. The javadoc utility will use this comment to automatically generate HTML. May also include HTML and use optional tags: <B> Here is a bolded comment <\B> @author Neil Bartlett @param d a number @return sqrt of the number*/

  18. Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++ Language Overview

  19. Variables and Identifiers • Variable may be a primitive data type or reference to an object • Unicode 1.1 character set used (16 bit international character set encoding). This applies to the char data type. • An identifier starts with: • a letter (from any language encoded by Unicode) • an underscore (_), or • a dollar sign($) • Subsequent characters may be letters or digits or both • Identifiers can be any length • Identifiers may not be a reserved word or a boolean literal (true, false)

  20. Data Types - Primitive Types • Primitive Type Precision Default Value • byte 8 bits 0 • short 16 bits 0 • int 32 bits 0 • long 64 bits 0 • char 16 bits '\u0000' • float 32 bits +0.0f • double 64 bits +0.0d • boolean - false • No variable can have an undefined value • Class variables are implicitly initialized to the default unless set explicitly • Local variables are not implicitly initialized to a default

  21. Scope of a Variable • Scope is the block of code in which a variable is accessible. • member variable. Declared within a class but not within a method. • local variable. Declared within a method or within a block. • method parameter. Values passed into method (more later) class MyClass { float myMethod( float f ) { float f1; { // define a block inside a method just for fun float f2 = 10F; f1 = f2; } float f3 = f1; return f*f3+i; } int i = 0; } i f f1 f2 f3

  22. Access Specifiers • Specifies who may access variables. Also applies to classes, constructors, and methods. • public • available everywhere • protected • available only to the current class and its subclasses • private • available only to the class in which it is declared. This is applied at the class not the object level. • package • If no access specifier is explicitly, available only within the current package

  23. Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++ Language Overview

  24. Flow of Control - Conditional if (condition) { statements; } else { statements; } switch (intVal) { case intVal1: statements; break; case intVal2: statements; return; default: statements; break; }

  25. Flow of Control - Looping for (initialize; test; increment){ statements; } while (condition) { statements; } do { statements; } while (condition); goto // reserved word that does nothing! break label; continue label; restart: for (int i = start; i < a.length ; ++i) { // mess with start if (a[i] == ';') continue restart; }

  26. Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++ Language Overview

  27. Creating Objects • Objects are instances of classes. • To declare an object, use the class name (the type) and a identifier, e.g. Date today; • A variables stores reference to an object. The declaration does not create an object. • Objects are created with the new reserved word. This will create the memory for the object and return a reference to the object today = new Date(); • Or, using one step Date today = new Date();

  28. The new operator • The new operator creates an object by allocating memory. • Takes one parameter - the class constructor. The class constructor is a special method declared in the class. It is responsible for initializing the object to a known state. Rectangle r = new Rectangle(0, 0, 100, 200); • Constructors have the same name as the class. A class can have more than one constructor, e.g. Rectangle r = new Rectangle(100, 200); • Constructors typically set up the object's variables and other initial state. They might also perform some initial behavior.

  29. MyClass Object o1 o2 Objects and References • A variable stores a reference to an object. There is no equivalent of C++ pointer. • Many objects references may refer to the same object MyClass o1 = new MyClass(); MyClass o2 = o1; • Both o1 and o2 now refer to the same object • Comparing variables that refer to objects just compares the references. It does not compare the objects. Integer i1 = new Integer(10); Integer i2 = new Integer(10); if (i1 == i2) { // not true }

  30. Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++ Language Overview

  31. Arrays • Arrays are objects in Java. Use new to create them. • Arrays are fixed length. Length cannot be changed once created. Indexes start at zero. Indexes are bounds checked. • Primitive Array byte[] bArray = new byte[5]; for (int i=0; i < bArray.length; i++) bArray[i] = 42; // value • Object Array Date dArray[] = new Date [5]; for (int i=0; i < dArray.length; i++) // Must now create the date objs dArray[i] = new Date (); //ref

  32. Multidimensional Arrays • Implemented as arrays of arrays int twoDArray[][] = new int[300][400]; • Declares a variable of type int[][] • Dynamically allocates an array of with 300 elements • Allocates arrays of 400 ints for each element of the 300 element array • Can provide partial sizing int threeDArray[][][] = new int[10][][]; Multidimentional arrays need not be rectangular int threeDArray[][][] = new int[10][][]; threeDArray[0] = new int[100][4]; threeDArray[1] = new int[3][5000];

  33. Initializing Arrays • Arrays may be initialized with static initializers int lookup_table[] = {1, 2, 3, 4, 5, 6, 7, 8}; • This is equivalent to int lookup_table[] = new int[8]; lookup_table[0] = 1; … • Similarly for multidimentional arrays String param_info[][] = {{"fps", "1-10", "frames per second"},{"repeat", "boolean", "repeat image loop"},{"imgs","url","images directory"} };

  34. Strings • Strings are objects, not primitives • Not null-terminated, not array of char • Rich set of string manipulation methods • Initializing • must construct a string object, String s does not create an object • String a = "abc" eqv. String a = new String("abc") • Concatenation operator, "abc"+"def" • String class is non-mutative • Use StringBuffer class for strings that change

  35. Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++ Language Overview

  36. Declaring Methods • Must declare the data type of the value it returns. If no value is returned, it must be declared as returning void. • Methods may take arguments. These are values that are passed into the method when it is called. Arguments are typed and named. If names conflict with the class level variables, the argument names will hide the class level variable names. • Methods are scoped for the whole class. No need for forward references. • Java is very strongly typed. No equivalent of C variable length argument list. • Cannot pass methods into methods. (Methods are not a type)

  37. Passing Arguments to Methods • Arguments are passed by value. Changing the value inside the method does not effect the value outside the method. This applies to both primitive types and object references. public class myClass { int x; void myMethod(myClass ac, int ay) { ay = 10; ac.x = 5; ac = null; } public static void main (String args[]) { myClass c = new myClass(); c.x = 1000; int y = 2000; c.myMethod(c, y); System.out.println("c:"+c+" c.x:"+c.x+" y:"+y); } }

  38. Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++ Language Overview

  39. Declaring Classes • A class is declared using the class keyword class myClass { // class body } • A class is by default accessible (e.g. can create objects of the class) from any other classes in the same package. • The public keyword can be used to create a class that is available anywhere.

  40. Constructors • Constructors are called by the new operator when a class is created. The constructor initializes the new object. class myClass { int x; String s; myClass() { x = 10; S = "Hello"; } } • Constructors have no return type, but they may take arguments. The argument types must match those provided by the new operator. myClass(int x, String s) { … } myClass c = new myClass(10, "Hello");

  41. Default Constructor • If no constructor is present a default constructor will be provided by the compiler. • The default constructor has no arguments and just calls the super class's constructor. class myClass { myClass() { super(); } } • Does not provide default constructor with arguments

  42. Class Variables and Methods • Problem: If all method calls need an object, how to we provide global constants and utility functions. Must we create an object just to use them? • Classes can provide variables and methods that may be used with out an object. There are called class variables and class methods. • To make a variable or method into a class variable, use the static keyword, e.g. static int count; • In contrast variables and methods of objects are called instance methods and instance variables. • Class methods may directly use other class methods and class variables. If they want to use an instance methods or variables, they must instantiate objects. • class method may not be overridden.

  43. Examples of Class Variables and Methods import java.util.*; public class ClassMethodExample { static String todaysDate() { Date d = new Date(); return d.toString(); } public static void main(String[] s) { System.out.println( "The square root of pi is "+ Math.sqrt( Math.PI )); System.out.println( "The date is "+todaysDate() ); } } • main method is a class method. It does not require an object. • Math and System are part of the core java packages. • They provide useful math and system functions and constants. These are implemented as class methods and class variables. • todaysDate is a user-defined class method. It constructs a Date object to do its job.

  44. Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++ Language Overview

  45. Inheritance • To inherit a class from another class use the extends keyword class SubClass extends SuperClass { ... } • The sub class inherits variables and methods from its super class. It also inherits variables and methods from the super class of the super class and so on up the inheritance tree. • Java has single inheritance. A class can only have one super class.

  46. The Object class • Every class you define has a super class. There is a special class called Object which is the implicit super class of any class which does not explicitly descend from a class, so class MyClass • is equivalent to class MyClass extends Object • Object is the root class of all classes. • The Object class provides generic methods for all objects. These include: • getClass. Returns an object that contains information about the class that the object was created from. • toString. Provides a generic string detailing the object. • clone. A placeholder method to allow copying of an object • equals. A method to compare objects.

  47. What's Inherited? • When one class extends from another, the sub class inherits those variables and methods that: • are declared with the public or protected access specifiers. • have no access specifier • But don't inherit those • with the same name a one in the sub class. • declared as private. class SuperClass { int x, y; int methodA() {…} int methodB() {} } class SubClass extends SuperClass { int y; // hides SuperClass.y int methodB() {} // overrides SuperClass.methodB }

  48. Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes Garbage Collection Reflection Packaging Java vs. C++ Language Overview

  49. Polymorphism - Method Hiding • A method with the same signature as a method in its super class hides or overrides the method in the super class. • An object of a sub class may be assigned to a reference of a super class. In this case, these overridden methods will be called class SuperClass { void aMethod() { … } } class SubClass { void aMethod() {…} } SuperClass s = new SubClass(); s.aMethod(); // calls SubClass's aMethod

  50. The final keyword • The final keyword is used to limit what can be changed when it is inherited It can be applied to: • classes. A final class cannot be extended from. Generally you do this for security reasons , e.g. the String class final class MyClass • methods. This stops a method from being overridden in a subclass. The method may still be called by the subclass. final double sqrt(double d) • variables. This declares a constant value. The value is available to the subclass but it may not change or shadow the value. final int useful_constant=10;

More Related