1 chapter 1 java –originally for intelligent consumer-electronic devices –then used for creating...
TRANSCRIPT
1
Chapter 1
• Java– Originally for intelligent consumer-electronic devices
– Then used for creating Web pages with dynamic content
– Now also used for:• Develop large-scale enterprise applications• Enhance WWW server functionality• Provide applications for consumer devices (cell phones, etc.)
2
PDA and Cell Phone
3
Java’s History• James Gosling and Sun Microsystems
• Oak
• Java, May 20, 1995, Sun World
• HotJava – The first Java-enabled Web browser
• Early History Website:– http://en.wikipedia.org/wiki/Java_(programming_language)– http://java.sun.com/features/1998/05/birthday.html
4
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
5
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-
Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Java is partially modeled on C++, but greatly simplified and improved. Some people refer to Java as "C++--" because it is like C++ but with more functionality and fewer negative aspects.
6
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-
Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Java is inherently object-oriented. Although many object-oriented languages began strictly as procedural languages, Java was designed from the start to be object-oriented. Object-oriented programming (OOP) is a popular programming approach that is replacing traditional procedural programming techniques.
One of the central issues in software development is how to reuse code. Object-oriented programming provides great flexibility, modularity, clarity, and reusability through encapsulation, inheritance, and polymorphism.
7
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-
Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Distributed computing involves several computers working together on a network. Java is designed to make distributed computing easy. Since networking capability is inherently integrated into Java, writing network programs is like sending and receiving data to and from a file.
8
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-
Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
You need an interpreter to run Java programs. The programs are compiled into the Java Virtual Machine code called bytecode. The bytecode is machine-independent and can run on any machine that has a Java interpreter, which is part of the Java Virtual Machine (JVM).
9
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-
Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Java compilers can detect many problems that would first show up at execution time in other languages.
Java has eliminated certain types of error-prone programming constructs found in other languages.
Java has a runtime exception-handling feature to provide programming support for robustness.
10
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-
Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Java implements several security mechanisms to protect your system against harm caused by stray programs.
11
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-
Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Write once, run anywhere
With a Java Virtual Machine (JVM), you can write one program that will run on any platform.
12
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-
Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Because Java is architecture neutral, Java programs are portable. They can be run on any platform without being recompiled.
13
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-
Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
14
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-
Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Multithread programming is smoothly integrated in Java, whereas in other languages you have to call procedures specific to the operating system to enable multithreading.
15
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-
Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Java was designed to adapt to an evolving environment. New code can be loaded on the fly without recompilation. There is no need for developers to create, and for users to install, major new software versions. New features can be incorporated transparently as needed.
16
JDK Versions• JDK 1.02 (1995)• JDK 1.1 (1996)• JDK 1.2 (1998)• JDK 1.3 (2000)• JDK 1.4 (2002)• JDK 1.5 (2004) a. k. a. JDK 5 or Java SE 5• JDK 1.6(2006) a. k. a. JDK 6 or Java SE 6
17
JDK Editions• Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone applications or applets.
• Java Enterprise Edition (J2EE)– J2EE can be used to develop server-side
applications such as Java servlets and Java ServerPages.
• Java Micro Edition (J2ME). – J2ME can be used to develop applications for mobile
devices such as cell phones.
This course uses J2SE to introduce Java programming.
18
Java IDE Tools
• Borland JBuilder
• NetBeans Open Source by Sun
• Sun ONE Studio by Sun MicroSystems
• Eclipse Open Source by IBM (preferred in this course)
19
Introduction to Classes and objects• Agenda
– What is an object oriented view of programming?
– What is a class?– How to define a class?– Creating and using an object
20
What is an object oriented view of programming
Suppose I want to invite my friends Tom, Liz and Rita to meet me for coffee at Tim Horton’s in the Devonshire Mall at 8PM today.
Approach 1:Give a complete and very detailed set of instructions on how to go from the University to Tim Horton’s. In this approach, every one exactly follows my instructions.
21
What is an object oriented view of programming
Approach 2:Simply tell my friends “ Pl meet me for coffee at 8 this evening at Tim Horton’s in the Devonshire Mall”
Here each person follows his/her own way of interpreting my message and reacting to it.I don’t know and I don’t care the specific mechanism used by each individual in response to my message.
22
A model for this approach
• Community of interacting agents called objects• Each object provides services• All action is initiated by a message to an object
23
Object oriented view
• Importance of information hiding • Service oriented view of the world
24
Notion of classes and objects
My Cookie cutter
• Every time I use the cookie cutter, I get a cookie ready for baking.•Each cookie looks exactly like the others•View my cookie cutter as a template
25
Class - a template for similar objects
Class definition• What are the properties of the class?• What are the capabilities of the class?
Worker class• How to characterise an object?
– name, age, place_working• What can an object do?
– change the place of work– describe the object as a string
26
Creating an object• First step is to define the class if needed• Use the class as a template to create objects• All objects of the same class has the same
set of properties and capabilities
27
Class Hierarchies and inheritance
Notion of superclass and subclasses
28
Defining a classpublic class worker { String Name; // Example of a variable int age; String placeWorking; public void ChangeJob(String NewPlace) // Method {placeWorking = NewPlace; } // Other methods as needed public worker(String WorkerName) // Constructor {Name = WorkerName; }}
29
How to use the services of a class• A service => a method • An object of the class must exist for nonstatic
methods
worker w;
w = new worker( “Jim”);//use of constructor
• Use service => invoke right method
w. ChangeJob(“Ford, Windsor”);
30
Thinking About Objects
• Objects– Reusable software components that model
real-world items– Look all around you
• People, animals, plants, cars, etc.
– Attributes• Size, shape, color, weight, etc.
– Behaviors• Babies cry, crawl, sleep, etc.
31
Java Class Libraries• Classes
– Include methods that perform tasks• Return information after task completion
– Include variables defining properties of class– Used to build Java programs
• Java contains class libraries– Known as Java APIs (Application Programming
Interfaces)– http://java.sun.com/j2se/1.5.0/docs/api/
32
Basics of a Typical Java Environment
• Java programs normally undergo five phases– Edit
• Programmer writes program (and stores program on disk)– Compile
• Compiler creates bytecodes from program– Load
• Class loader stores bytecodes in memory– Verify
• Verifier ensures bytecodes do not violate security requirements
– Execute• Interpreter translates bytecodes into machine language
33Typical Java environment.
PrimaryMemory
.
.
.
.
.
.
Disk
Disk
Disk
Editor
Compiler
Class Loader
Program is created in an editor and stored on disk in a file ending with .java.
Compiler creates bytecodes and stores them on disk in a file ending with .class.
Class loader reads .class files containing bytecodes from disk and puts those bytecodes in memory.
Phase 1
Phase 2
Phase 3
PrimaryMemory
.
.
.
.
.
.
Bytecode Verifier Bytecode verifier
confirms that all bytecodes are valid and do not violate Java’s security restrictions.
Phase 4
PrimaryMemory
.
.
.
.
.
.
InterpreterInterpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing data values as the program executes.
Phase 5
34
Compiling Java Source CodeYou can port a source program to any machine with appropriate compilers. The source program must be recompiled, however, because the object program can only run on a specific machine. Nowadays computers are networked to work together. Java was designed to run object programs on any platform. With Java, you write the program once, and compile the source program into a special type of object code, known as bytecode. The bytecode can then run on any computer with a Java Virtual Machine, as shown below. Java Virtual Machine is a software that interprets Java bytecode.
Java Bytecode
Java Virtual Machine
Any Computer
35
Thinking About Objects (60-322)
• Object-oriented design (OOD)– Models real-world objects– Models communication among objects– Encapsulates attributes and operations (behaviors)
• Information hiding• Communication through well-defined interfaces
• Object-oriented language– Programming in object oriented languages is called
object-oriented programming (OOP)– Java
36
Thinking About Objects
• Object-Oriented Analysis and Design (OOA/D)– Essential for large programs– Analyze program requirements, then develop
solution– UML
• Unified Modeling Language
37
• A First Program in Java: Printing a Line of Text
• Modifying Our First Java Program
• Displaying Text in a Dialog Box
•Another Java Application: Adding Integers
•Memory Concepts
•Arithmetic
•Decision Making: Equality and Relational Operators
38
A Simple Java Program
//This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); }}
Listing 1.1
39
Creating and Editing Using NotePadTo use NotePad, type
notepad Welcome.java from the DOS prompt.
40
Creating and Editing Using WordPad
To use WordPad, type write Welcome.java
from the DOS prompt.
41
Creating, Compiling, and Running Programs
Source Code
Create/Modify Source Code
Compile Source Code i.e., javac Welcome.java
Bytecode
Run Byteode i.e., java Welcome
Result
If compilation errors
If runtime errors or incorrect result
public class Welcome { public static void main(String[] args) { System.out.println("Welcome to Java!"); } }
… Method Welcome() 0 aload_0 … Method void main(java.lang.String[]) 0 getstatic #2 … 3 ldc #3 <String "Welcome to Java!"> 5 invokevirtual #4 … 8 return
Saved on the disk
stored on the disk
Source code (developed by the programmer)
Byte code (generated by the compiler for JVM to read and interpret, not for you to understand)
42
Comments
In Java, comments are preceded by two slashes (//) in a line, or enclosed between /* and */ in one or multiple lines. When the compiler sees //, it ignores all text after // in the same line. When it sees /*, it scans for the next */ and ignores any text between /* and */.
43
Discuss four small Java programs
Welcome1.java
Welcome2.java
Welcome3.java
Welcome4.java
44
Displaying Text in a Message Dialog Box
you can use the showMessageDialog method in the JOptionPane class. JOptionPane is one of the many predefined classes in the Java system, which can be reused rather than “reinventing the wheel.”
45
The showMessageDialog Method
JOptionPane.showMessageDialog(null, "Welcome to Java!", “Display Message", JOptionPane.INFORMATION_MESSAGE));
46
Two Ways to Invoke the MethodThere are several ways to use the showMessageDialog method. For the time being, all you need to know are two ways to invoke it.
One is to use a statement as shown in the example:JOptionPane.showMessageDialog(null, x,
y, JOptionPane.INFORMATION_MESSAGE));
where x is a string for the text to be displayed, and y is a string for the title of the message dialog box.
The other is to use a statement like this:JOptionPane.showMessageDialog(null, x);
where x is a string for the text to be displayed.
47
The exit Method
Prior to JDK 1.5, you have to invoke System.exit() to terminate the program if the program uses JOptionPane dialog boxes. Since JDK 1.5, it is not necessary.
48
Escape characters– Backslash ( \ )– Indicates special characters be outputEscape sequence
Description
\n Newline. Position the screen cursor at the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop. \r Carriage return. Position the screen cursor at the beginning of
the current line; do not advance to the next line. Any characters output after the carriage return overwrite the characters previously output on that line.
\\ Backslash. Used to print a backslash character. \" Double quote. Used to print a double-quote character. For
example, System.out.println( "\"in quotes\"" ); displays "in quotes"
Some common escape sequences.
49
Another Java Application: Adding IntegersAdditi
on.java
Message dialog type Icon Description
JOptionPane.ERROR_MESSAGE
Displays a dialog that indicates an error to the user.
JOptionPane.INFORMATION_MESSAGE
Displays a dialog with an informational message to the user. The user can simply dismiss the dialog.
JOptionPane.WARNING_MESSAGE
Displays a dialog that warns the user of a potential problem.
JOptionPane.QUESTION_MESSAGE
Displays a dialog that poses a question to the user. This dialog normally requires a response, such as clicking on a Yes or a No button.
JOptionPane.PLAIN_MESSAGE no icon Displays a dialog that simply contains a
message, with no icon. JOptionPane constants for message dialogs.
50
Memory Concepts
• Visual Representation– Sum = 0; number1 = 1; number2 = 2;
– Sum = number1 + number2; after execution of statement
sum 0
sum 3
51
Arithmetic• Arithmetic calculations used in most rograms
– Usage • * for multiplication • / for division• +, -• No operator for exponentiation (more in Chapter 5)
– Integer division truncates remainder7 / 5 evaluates to 1
– Remainder operator % returns the remainder 7 % 5 evaluates to 2
52
Arithmetic• Operator precedence
– Some arithmetic operators act before others (i.e., multiplication before addition)
• Use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3 • Use: ( a + b + c ) / 3
– Follows PEMDAS • Parentheses, Exponents, Multiplication, Division, Addition,
Subtraction
53
ArithmeticOperator(s) Operation(s) Order of evaluation (precedence) * /
%
Multiplication Division Remainder
Evaluated first. If there are several of this type of operator, they are evaluated from left to right.
+ -
Addition Subtraction
Evaluated next. If there are several of this type of operator, they are evaluated from left to right.
Precedence of arithmetic operators.
54
Decision Making: Equality and Relational Operators
Standard algebraic equality or relational operator
J ava equality or relational operator
Example of J ava condition
Meaning of J ava condition
Equality operators = == x == y x is equal to y != x != y x is not equal to y Relational operators > > x > y x is greater than y < < x < y x is less than y >= x >= y x is greater than or equal to y <= x <= y x is less than or equal to y
Equality and relational operators.
55
• Precedence of operators
Operators Associativity Type * / % left to right multiplicative + - left to right additive < <= > >= left to right relational == != left to right equality = right to left assignment Precedence and associativity of the operators discussed so far.