Basic concepts Web Programming course Web Programming Course
Basic concepts Web Programming course Web Programming Course Winter '06 1
Outline n Java introduction ¨ What is Java ¨ Some Java tools Basic Java programming n Objects and classes n Java Inheritance n Web Programming Course Winter '06 2
What is Java? n A programming language. ¨ Syntax n and constructs are nearly similar to C++ A virtual platform ¨ Java Virtual Machine is a software “machine” ¨ Since it’s “virtual”, it can be implemented on any hardware n A class library ¨ Standard APIs for GUI, data storage, processing, I/O, and networking. Web Programming Course Winter '06 3
Compiling and running Java source code is compiled into a platformindependent bytecode which is executed on a platformdependent virtual machine Hello. javac Hello. java compile source code run java Hello. class bytecode Web Programming Course Winter '06 4
Java Development Kit n n JDK is the standard development tool for Java Some JDK Tools ¨ javac – The Java compiler. Compiles java applications and applets into bytecode ¨ java – The Java interpreter used to run java programs ¨ appletviewer – Allows the running of applets without requiring a Web browser ¨ javadoc – Generates API documentation in HTML format from Java source code ¨ jdb – The Java debugger Web Programming Course Winter '06 5
Getting started n Download the Java SDK http: //java. sun. com/j 2 se/1. 5. 0/download. jsp n Download a Java IDE http: //www. jcreator. com http: //www. eclipse. org/downloads/index. php http: //www. bluej. org/download. html (there are many more…) Web Programming Course Winter '06 6
Outline n n Java introduction Basic Java programming ¨ Data types ¨ Basic Syntax – definition, assignments and control statements ¨ Arrays n n Objects and classes Java Inheritance Web Programming Course Winter '06 7
Java Data Types n Primitive Data Types: ¨ boolean true or false ¨ char unicode (16 bits) ¨ byte signed 8 bit integer ¨ short signed 16 bit integer ¨ int signed 32 bit integer ¨ long signed 64 bit integer ¨ float, double IEEE 754 floating point Web Programming Course Winter '06 8
Other Data Types n Reference types (composite) ¨ classes ¨ arrays strings are supported by a built-in class named String n string literals are supported by the language (as a special case). n Web Programming Course Winter '06 9
Variables n n n In Java culture a variable starts with a small letter. A variable is a location in the memory which is assigned a value and a type. Java does not have “global” variables. long info. Count; double. Precision; float x, y; //declaring 2 float variables int iteration; Web Programming Course Winter '06 10
Assignment and Initialization n n Assignment: setting a value to a variable Initialization: creating a variable with a primary value int i 1; i 1 = 88; // assignment i 2 = 128 ; // initialization char ch =‘A’ ; double x = 77. 88; x = i 1; // legitimate conversion Web Programming Course Winter '06 11
JAVA ARITHMETIC OPERATORS Operator Meaning Example + Addition 5+9 - Subtraction 6– 3 * Multiplication 2*4 / Division 10 / 2 % Modulo 53 % 10 += Incrementing the LHS value by the RHS value i += 5 -= Subtraction of the LHS variable by the RHS value i -= 8 Web Programming Course Winter '06 12
JAVA ARITHMETIC OPERATORS Operator Meaning example /= Division of LHS variable by the RHS value i /= 4 *= Multiplication of the LHS variable by the RHS value i *= 2 ++ Increment the variable by 1. Increment and return value (pre-increment) Return value and then increment (postincrement) -- Decrement the variable by 1. Pre decrement Post decrement Web Programming Course Winter '06 ++i i++ --i i-13
COMPARISON OPERATORS Operator Meaning Example == != Equals. Not equal. a==b a != b < Less than. a<b > Greater than. a>b <= Less than or equal to. a <= b >= Greater than or equal to. a >= b Web Programming Course Winter '06 14
LOGICAL OPERATORS Operator Meaning Example && Logical AND. if(a>0 && a<10) || Logical OR. if(a = = 4 || a = = 6) ! Negate. if(!(a = = 4 || a = = 6)) Q: What is the returned type for these operators? Web Programming Course Winter '06 15
Control Flow: IF/ELSE if (a > b) { System. out. println (a + “ is bigger”) ; } else { System. out. println (a + “ is not bigger”) ; Web Programming Course Winter '06 16
Control Flow : LOOPS Three kinds of loops in Java: while loop, for loop, do loop n Simple while loop n int a = 1, sum = 0; while (a < 10 ) { sum += a; a *= 2; } Web Programming Course Winter '06 17
Control Flow : LOOPS n Simple for loop for (int i=0; i<10; i ++) { System. out. println (i* i) ; } Web Programming Course Winter '06 18
Control Flow : LOOPS n Simple do loop char ch; do { ch = System. in. read ( ) ; // read 1 char System. out. println(ch) ; } while (ch != ‘e’) ; Web Programming Course Winter '06 19
Control Flow : SWITCH switch (a) { case 0: case 1: ++c 1; case 2: ++c 2; break; default: System. out. println (“a is: “ + a); break; } What happens if the value of a is 1 ? What if a is 2? Web Programming Course Winter '06 20
Control Flow : Break int[ ] a 1 = { 2, 4, 6, 8, 10, 12, 4 }; int[ ] a 2 = { 1, 10, 40, 10, 4, 40 }; for (int i=0; i<a 1. length; i++) { for (int j<a 2. length; j++) { if (a 1[ i ] = = a 2 [ j ] ) break; } } System. out. println (i + “ “ + j) ; What is the output of this code ? Web Programming Course Winter '06 21
Outline Java introduction n Basic Java programming n Objects and classes n ¨ Objects classes and OO design ¨ Java class issues ¨ Exception handling n Java Inheritance Web Programming Course Winter '06 22
Object and Class o o Date is a class. d 1 and d 2 are references (pointers) to objects of class Date. Object is an instance of a class. The keyword new is used to create an instance (object) of a certain class reference (pointer) Date d 1; d 1 = new Date ( ); Date d 2 = new Date ( ) ; Web Programming Course Winter '06 object (instance) 23
Fields The fields are the data of the object/class n The object’s state is the current values of its fields n Class My. Date { int day, month, year=2005; } My. Date d=new My. Date(); d. day = 31; d. month =1; Web Programming Course Winter '06 24
Messages and Methods n n n Objects communicate by sending messages When an object receives a message it executes a method A method may: ¨ Change the object’s state ¨ Return a value ¨ Send messages to other objects An Object = State + Methods Web Programming Course Winter '06 25
Messages and Methods 1. 2. class My. Date { int day; month, year; 3. void set (int d, int m, int y) { day=d; month=m; year=y; 4. 5. 6. } 7. void inc. Days (int n. Days) {. . . } int get. Week. Day ( ) {. . . } 8. 9. 10. } Web Programming Course Winter '06 Why do we need this method? 26
Messages and Methods 11. 12. 13. 14. 15. My. Date d = new My. Date ( ); / / sending messages to object d d. set (31, 1, 2000) ; d. inc. Days (3) ; int week. Day = d. get. Week. Day ( ) ; Web Programming Course Winter '06 27
Encapsulation (information hiding) means that the object hides its internal structure. n The “Black-Box” Paradigm: objects communicate by sending messages. An object should not access another object’s internals n Web Programming Course Winter '06 28
Encapsulation class My. Date { private int day, month, year; public void set (int d, int m, int y){…} public void inc. Days(int n. Days) {…} public int get. Week. Day(){…} } class Other. Class { void any. Method { My. Date d = new My. Date () ; d. set (31, 1, 2000) ; d. month = 2; // COMPILATION ERROR !!! } } Web Programming Course Winter '06 29
Overloading n Overloading: Several methods may have the same name, but different parameters. My. Date d 1 = new My. Date (31, 1, 2000) ; My. Date d 2 = new My. Date (“ 21 -mar-1685”) ; Constructor overloading is common. Web Programming Course Winter '06 30
Overloading class My. Date { int day, month, year; void set (int d, int m, int y) {. . . ) void set (stribg str) {. . . } My. Date (int d, int m, int y) {. . . } My. Date (String str) {. . . } My. Date ( ) {. . . } //default constructor } Web Programming Course Winter '06 31
Packages Classes are organized in packages n The keyword import tells the compiler that we want to use a certain class from a certain package To use all classes from a package: n import java. util. * ; But not: import java. *. * Web Programming Course Winter '06 32
Using class from the standard library 1. 2. 3. 4. 5. 6. § § § public class Test. Date { public static void main (String[ ] args) { java. util. Date now = new java. util. Date ( ) ; System. out. println (now) ; } } java. util. Date is a class from the standard Java library. java. util is a name of a package. The object at line 3 is created with the default constructor. Web Programming Course Winter '06 33
Standard Library Packages Here are some packages from the standard libray: q java. lang Package that contains essential Java classes; including numerics, strings, objects, compiler, runtime, security, and threads. This is the only package that is automatically imported into every Java program. Classes in package: String, System, Thread, . . . Web Programming Course Winter '06 34
Standard Library Packages java. io Package that provides classes to manage input and output streams, to read data from and write data to files, strings, and other sources. q Classes in package: Output. Stream, File. Reader, File. Writer. . . Web Programming Course Winter '06 35
Standard Library Packages java. util Package that contains miscellaneous utility classes, including generic data structures, bit sets, time, date, string manipulation random number generation, system properties, notification, and enumeration of data structures. n Classes in package: Vector, Hashtable, Bit. Set, Calendar, Date. Web Programming Course Winter '06 36
Standard Library Packages java. net Package that provides classes for network support, including URLs, TCP sockets, UDP sockets, IP addresses, and a binary to-text converter. q Classes in package: inet. Address, Socket, Server. Socket, URL. Web Programming Course Winter '06 37
Putting a class into a package class A { class B { } } package pack; class C { class D { } } Class A and B are in the same package – the default package Class C and D are in the same package – package Web Programming Course Winter '06 38
Access Control n Each method and variable has access permission which is one of the following: ¨private ¨package (this is the default) ¨public ¨protected n Class may have package or public access permission Web Programming Course Winter '06 39
Access Modifiers Access Levels Specifier Class Package Subclass World private protected Y Y Y N N N public Y Y no specifier Web Programming Course Winter '06 40
Class members n We saw that an object may have: Variables ¨ Methods ¨ n A class, too, may have: Variables ¨ Methods ¨ The keyword static in a declaration of method or variable makes it a class method or a class variable. n Web Programming Course Winter '06 41
Class variables and methods static method is invoked directly on the class. It does not need an object n static method may not access non-static variable, and may not call non-static method. (why? ) n static method is also the Java version of the “global function” in C++ and other programming languages n Web Programming Course Winter '06 42
Class variables and methods class My. Date { int day, month, year; static private int lowest. Year; static int maximum. Days. In. Month = 31; static void set. Lowest. Year (int n) { lowest. Year = n; } static int get. Days. In. Month (int month) {} My. Date ( ) {. . . } void set (int d, int m, int y){} void inc. Days (int n. Days) {} Web Programming Course Winter '06 43
Class variables and methods //accessing static members class Any. Class { void any. Method ( ) { My. Date. set. Lowest. Year (1900) ; int n = My. Date. get. Days. In. Month (4) ; int m = My. Date. maximum. Days. In. Month; } } Web Programming Course Winter '06 44
What is it good for? public class Singleton { private static Singleton _instance=null; private Singleton(){…} public static get. Instance(){ if(_instance==null) _instance = new Singleton(); return _instance; } } Web Programming Course Winter '06 45
Constants q The keyword final in a variable declaration makes it a constant. class Math { public static final double PI = 3. 14159; } Web Programming Course Winter '06 46
Primitive and Reference Types n Objects and Arrays are reference types ¨ Primitive types are stored as values. ¨ Reference type variables are stored as references Hello hi=new Hello(); Hello Shalom=hi; A single instance of Hello int x =1; int y=x; Two values stored in memory Web Programming Course Winter '06 47
Wrapper Classes q q q Sometimes we need to refer to a primitive type as an object. (e. g. passing primitives by reference) This is done by using the Wrapper Classes. The java. lang package includes a wrapper class for each primitive type. Primitive Type Wrapper Class byte short int long float double boolean char Byte Short Integer Long Float Double Boolean Character Web Programming Course Winter '06 48
Exceptions n Terminology: ¨ throw an exception: signal that some condition (possibly an error) has occurred. ¨ catch an exception: deal with the error (or whatever). In Java, exception handling is necessary (forced by the compiler)! Web Programming Course Winter '06 49
Exception Handling n Syntax try{ dangerous code here. . } catch(Exception e) { error handling code here. . } finally { this code is always executed. . } Web Programming Course Winter '06 But there a lot of different errors that require different error handling! You can catch different exception types! (getting there…) 50
Exception Example public class Hello {. . . java. lang. Array. Index. Out. Of. Bounds. Exception inherits from public static void main(String[] args) { Exception System. out. print("Hello "+args[0]+" If you catch(Array. Index. Out. Of. Bounds. Exception e) "+args[1]); } then you will only catch that type exception; however if you } Java Hello Yossi catch(Exception e) you will catch all Exception types E (but you won’t know what you caught) th xce ro pt w io n n is Exception in thread "main" java. lang. Array. Index. Out. Of. Bounds. Exception: 1 at Hello. main(Hello. java: 9) Web Programming Course Winter '06 51
Example 2 n Write a java program that prints “Hello <first name > <last name>” where <name> is a command line argument and handles cases of missing input Web Programming Course Winter '06 52
Example 2 public class Hello {. . . public static void main(String [] args) { try{ System. out. print("Hello"+args[0]+“ "+args[1]); } catch(Exception e) { System. out. println("Missing input"); } } } Web Programming Course Winter '06 53
Exception Example public class Hello {. . . public static void main(String[] args){ try{ System. out. print("Hello"+args[0]+“ "+args[1]); } catch(Exception e){ System. out. println("Missing input"); } } Ex Java Hello ce ro pt w io n n th is s i n io Missing Input Web Programming Course Winter '06 pt e c x E ght u ca 54
Outline Java introduction n Basic Java programming n Objects and classes n Java Inheritance n ¨ Inheritance and implementation Web Programming Course Winter '06 55
Basic Java OO concepts n Java inheritance mechanism uses two key concepts – ¨ Class inheritance (single class inheritance) ¨ Interface implementation (multiple implementation allowed) Web Programming Course Winter '06 56
Class Inheritance class Hi. There extends Hello { private int counter; public Hi. There(){ counter = 0 ; } } Parent’s constructor is called Web Programming Course Winter '06 57
Interface Implementation “An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy “ [the Java tutorial] Polymorphism can be implemented using interfaces! Web Programming Course Winter '06 58
Interface Implementation interface Hello. Sayer{ interface Bye. Sayer{ public void say. Hello(); } public void say. Bye(); } class Polite implements Hello. Sayer, Bye. Sayer { public void say. Hello{ System. out. println(“Hello”); } public void say. Bye{ System. out. println(“Bye”); } Web Programming Course Winter '06 . . Bye. Sayer b=new Polite(); b. say. Bye(); //will not work. . b. say. Hello(); 59
Abstract classes and methods n n An abstract class is a type of class which we are unable to instantiate. An abstract class is created for the purpose of inheriting from it An abstract method is a method in a superclass, that is declared but not implemented. class with one or more abstract methods must be an abstract class Web Programming Course Winter '06 60
The Keyword Super n n The keyword super refers to the class super class The keyword is usually used inorder to – ¨ invoke the constructor of the superclass ¨ invoke an (overriden) method of the superclass Class. A method. A() Class. B method. A() … super. method. A() Web Programming Course Winter '06 61
Class java. lang. Object n java. lang. object is the superclass for all classes n If we declare a class Our. Class but we do not declare: class Class. A extends Class. B then Class. A is a direct subclass of java. lang. Object Class. A Web Programming Course Winter '06 62
Casting- convert a variable from one type to another. n Down Casting - convert from a superclass to one of its subclasses n Object O = new String(“aaaaa”); ((String)O). index. Of(‘a’); Web Programming Course Winter '06 63
Class Diagram introduction The unified Modeling Language (UML) is a design language for building computer applications n The UML standard uses diagrams to describes system design and interaction n We shall focus on the Class Diagram, expressing static relations between classes n Web Programming Course Winter '06 64
Class Diagram n Class relations ¨ Picture uses a Screen ¨ Picture has N Shapes ¨ Shape has a “center” of class point ¨ Line is a shape ¨ Circle also is a Shape ¨ Picture has size ¨ Picture can draw and resize Web Programming Course Winter '06 65
Class Relations Containment (“has-a”) Engine Association (“uses-a”) Course Class. Room Car Seat Inheritance (“is-a”) abs Gui. Component Checkbox Web Programming Course Winter '06 Scrollbar 66
Class relations n Association - Class C 1 uses class C 2 if: Methods of C 1 send messages to objects of class C 2, or ¨ Methods of C 1 create, receive or return objects of class C 2. ¨ Web Programming Course Winter '06 67
Summary n n Java and c++ differ in? what is a virtual machine? What does the class-library supplies us? How is it different from windows MFC for example? What is the difference between a class and an object? And between a reference and a primitive type? What is an interface? Why is it needed? Web Programming Course Winter '06 68
Questions? Web Programming Course Winter '06 69
- Slides: 69