1 / 40

Chapter 1 - Introduction to Java Programming

Chapter 1 - Introduction to Java Programming. Outline Introduction to Java Thinking About Objects Java’s Object Memory Model The applications in Java : Applications and Applets Java Input /Output Java elements: Arithmetic, Equality and Relational Operators, Primitive types, ….

fawzi
Télécharger la présentation

Chapter 1 - Introduction to Java Programming

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. Chapter 1 - Introduction to Java Programming Outline Introduction to Java Thinking About Objects Java’s Object Memory Model The applications in Java : Applications and Applets Java Input /Output Java elements: Arithmetic, Equality and Relational Operators, Primitive types, …

  2. 1.1 Introduction to Java • Java • Object oriented • Similar to C/C++ , so Friendly • Simple and more security (no pointers, no multiple inheritance) • Dynamic Web • Platform independent • Standard • In Java there are three kinds of applications • Standalone Application (Application) • Applets (mini application) • Application and Applets

  3. Primary Memory Primary Memory Primary Memory Program is created in an editor and stored on disk in a file ending with .java. Editor Phase 1 Disk Compiler creates bytecodes and stores them on disk in a file ending with .class. Compiler Phase 2 Disk Class Loader Phase 3 Class loader reads .class files containing bytecodes from disk and puts those bytecodes in memory. Disk Bytecode Verifier Phase 4 Bytecode verifier confirms that all bytecodes are valid and do not violate Java’s security restrictions. Interpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing data values as the program executes. Interpreter Phase 5 . . . . . . . . . . . . . . . . . . Fig. 1.1 Typical Java environment. Develop Java programs by 5 phases

  4. Egxample:

  5. 1.2 Thinking About Objects • 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

  6. 1.2 Thinking About Objects (cont.) • Object-Oriented Analysis and Design (OOA/D) • Essential for large programs • Analyze program requirements, then develop solution • UML • Unified Modeling Language • History of the UML • Need developed for process with which to approach OOA/D • Brainchild of Booch, Rumbaugh and Jacobson • Object Management Group (OMG) supervised • Version 1.4 is current version • Version 2.0 scheduled tentatively for release in 2003

  7. 1.3 The applications in Java

  8. 1.3 The applications in Java

  9. 1.3 The applications in Java 1.3.1 Buildingapplications • An application is created from classes. • A class is similar to a struct in C/C++, but is different that a class also defines the methods to work on the data. • In order to create a application in Java, the programmer must defines a class with a special method called main(). • The code in the main() executes first when the program starts.

  10. Welcome1.javaProgram Output 1 // Fig. 1.1: Welcome1.java 2 // Text-printing program. 3 4 public class Welcome1 { 5 6 // main method begins execution of Java application 7 public static void main( String args[] ) 8 { 9 System.out.println( "Welcome to Java Programming!" ); 10 11 } // end method main 12 13 } // end class Welcome1 First program Tools Editor: Any Text Editor: TextPad, Jcreator, Eclipe (Open Source), NetBean, v.v. JDK 1.5 (java.sun.com/j2se) Welcome to Java Programming!

  11. 1.4 Java's Object Memory Model • Variables • Every variable has a name, a type, a size and a value • Name corresponds to location in memory • When new value is placed into a variable, replaces (writes and destroys) previous value • Reading variables from memory does not change them While accessing variables within your programs via this, super, and directly, it helps to understand where all this data is stored.

  12. 1.4 Java's Object Memory Model The dynamically changing part of program memory can be divided into two areas: • Stack memory This area of program memory is used to store local variables declared in methods or code blocks. Stack memory always grows in one direction and shrinks in the opposite direction. • Heap memory This area of program memory is used to store memory for objects. • References to objects can be put in the stack area. • A heap is a huge table of memory cells. • Small blocks are reserved or allocated from time to time when the new statement creates new objects. • And whenever a block of memory cells is no longer referred to by any existing variables, the unused cells can be freed or garbage-collected.

  13. 1.4 Java's Object Memory Model (Cont.) To demonstrate usage of the memory types, let's assume that you have two methods defined as in the following code segment. void m1() { int v1 = 1; TextField t1; // checkpoint #1 t1 = new TextField("Hi", 3); // checkpoint #2 m2(v1, t1); v1 = 8; // checkpoint #5 } void m2(int v2, TextField t2) { int v3 = 4; TextField t3; // checkpoint #3 t3 = new TextField("Ho", 6); v2 = 7; // checkpoint #4 } When method m1() is called and its local variable declaration is executed-that is, when checkpoint #1 is reached-the two local variables v1 and t1 will be in stack memory and have the values 1 and null, respectively.

  14. 1.4 Java's Object Memory Model (Cont.) A new object of TextField type is then created at checkpoint #2. The newly created object is put in the heap memory area, and a reference to the object is stored in local variable t1 on the stack. The memory model at this point is shown in A new object of TextField type is then created at

  15. 1.4 Java's Object Memory Model (Cont.) • Method m2() is called with two arguments. Java provides call-by-value semantics for method arguments of primitive datatypes and reference types. In the case of reference types, the value of the reference is passed. • Therefore, the argument variable t2 refers to the same object as the local variable t1 of method t1(). • At checkpoint #3, where the local variables v3 and t3 are declared, the memory model after the declaration looks like

  16. 1.4 Java's Object Memory Model (Cont.) + Next, a new object is created by a new statement and assigned to local variable t3. + Then the argument variable v2 is assigned a new value. + Since it is call-by-value, the value of the local variable v1 of method m1() is not affected.

  17. 1.4 Java's Object Memory Model (Cont.) • The Meanings of Names • Identifiers give names to a range of things within our programs types, variables, fields, methods, and so forth. • Name management is achieved with two mechanisms. • First, the namespace is partitioned to give different namespaces for different kinds of names. • Second, scoping is used to control the visibility of names declared in one part of a program to other parts. • Different namespaces allow you to give the same name to a method and a field (not that we recommend doing this), and scoping allows you to use the same name for all your for loop counters. •   There are six different namespaces: • package names, • type, class names, • field names, • method names, • local variable names (including parameters), and • labels • When a name is used in a program, its context helps determine what kind of name it is.

  18. 1.4 Java's Object Memory Model (Cont.) • The use of separate namespaces gives you greater flexibility when writing code (especially when combining code from different sources) but can be abused. Consider this pathological, but perfectly valid, piece of code: package Reuse; class Reuse { Reuse Reuse(Reuse Reuse) { Reuse: for (;;) { if (Reuse.Reuse(Reuse) == Reuse) break Reuse; } return Reuse; } }

  19. 1.5 Arithmetic Calculations • Arithmetic calculations used in most programs • Usage • * for multiplication • / for division • +, - addition, subtraction • No operator for exponentiation • Integer division truncates remainder 7 / 5 evaluates to 1 7.0 / 5 evaluates to 1.2 • Remainder operator % returns the remainder 7 % 5 evaluates to 2 11.5 % 2.5 evaluates to 1.5

  20. x y x/y x%y Finite ±0.0 ± INF NaN ±0.0 Finite ±0.0 ±0.0 ±0.0 ±0.0 NaN NaN 1.5 Arithmetic Calculations(Cont.) Floating-point division and remainder can produce infinities or NaN but never throw an exception. This table shows the results of the various combinations:

  21. 1.6 Decision Making: Equality and Relational Operators • ifcontrolstatement • Simple version in this section, more detail later • If a condition is true, then the body of the if statement executed • 0 interpreted as false, non-zero is true (in C) • Control always resumes after the if structure • Conditions for if statements can be formed using equality or relational operators if ( condition ) statement executed if condition true; • No semicolon needed after condition • Else conditional task not performed

  22. 1.6 Decision Making: Equality and Relational Operators • Upcoming program uses if statements • Discussion afterwards

  23. Comparison.java1. import2. Class Comparison2.1 main2.2 Declarations2.3 Input data (showInputDialog)2.4 parseInt2.5 Initialize result 1 // Fig. 1.20: Comparison.java 2 // Compare integers using if statements, relational operators 3 // and equality operators. 4 5 // Java packages 6 import javax.swing.JOptionPane; 7 8 public class Comparison { 9 10 // main method begins execution of Java application 11 public static void main( String args[] ) 12 { 13 String firstNumber; // first string entered by user 14 String secondNumber; // second string entered by user 15 String result; // a string containing the output 16 17 int number1; // first number to compare 18 int number2; // second number to compare 19 20 // read first number from user as a string 21 firstNumber = JOptionPane.showInputDialog( "Enter first integer:" ); 22 23 // read second number from user as a string 24 secondNumber = 25 JOptionPane.showInputDialog( "Enter second integer:" ); 26 27 // convert numbers from type String to type int 28 number1 = Integer.parseInt( firstNumber ); 29 number2 = Integer.parseInt( secondNumber ); 30 31 // initialize result to empty String 32 result = ""; 33

  24. Comparison.java3. if statements4. showMessageDialog Test for equality, create new string, assign to result. Notice use of JOptionPane.INFORMATION_MESSAGE 34 if ( number1 == number2 ) 35 result = result + number1 + " == " + number2; 36 37 if ( number1 != number2 ) 38 result = result + number1 + " != " + number2; 39 40 if ( number1 < number2 ) 41 result = result + "\n" + number1 + " < " + number2; 42 43 if ( number1 > number2 ) 44 result = result + "\n" + number1 + " > " + number2; 45 46 if ( number1 <= number2 ) 47 result = result + "\n" + number1 + " <= " + number2; 48 49 if ( number1 >= number2 ) 50 result = result + "\n" + number1 + " >= " + number2; 51 52 // Display results 53 JOptionPane.showMessageDialog( null, result, "Comparison Results", 54 JOptionPane.INFORMATION_MESSAGE ); 55 56 System.exit( 0 ); // terminate application 57 58 } // end method main 59 60 } // end class Comparison

  25. Program Output

  26. 1.7. Reading Input

  27. 1.7. Reading Input

  28. 1.7. Reading Input

  29. Reading Input

  30. 1.8. Introduction to Java Applet • Applet • Program that runs in • appletviewer (test utility for applets) • Web browser (IE, Communicator, Opera, FireFox, Chrome, …) • Executes when HTML (Hypertext Markup Language) document containing applet is opened and downloaded • Applications run in command windows

  31. Sample Applets from the Java 2 Software Development Kit • You start as player "X" Fig. 3.2 Sample execution of applet TicTacToe.

  32. Sample Applets from the Java 2 Software Development Kit • Demonstrates 2D drawing capabilities built into Java2 Try changing the options to see their effect on the demonstration. Click a tab to select a two-dimensional graphics demo.

  33. Simple Java Applet: Drawing a String • Now, create applets of our own • Take a while before we can write applets like in the demos • Cover many of same techniques • Upcoming program • Create an applet to display "Welcome to Java Programming!" • Show applet and HTML file, then discuss them line by line

  34. Java appletProgram Output import allows us to use predefined classes (allowing us to use applets and graphics, in this case). extends allows us to inherit the capabilities of class JApplet. Method paint is guaranteed to be called in all applets. Its first line must be defined as above. 1 // Fig. 3.6: WelcomeApplet.java 2 // A first applet in Java. 3 4 // Java packages 5 import java.awt.Graphics; // import class Graphics 6 import javax.swing.JApplet; // import class JApplet 7 8 public class WelcomeApplet extends JApplet { 9 10 // draw text on applet’s background 11 public void paint( Graphics g ) 12 { 13 // call superclass version of method paint 14 super.paint( g ); 15 16 // draw a String at x-coordinate 25 and y-coordinate 25 17 g.drawString( "Welcome to Java Programming!", 25, 25 ); 18 19 } // end method paint 20 21 } // end class WelcomeApplet

  35. Simple Java Applet: Drawing a String (Cont.) • Running the applet • Compile • javac WelcomeApplet.java • If no errors, bytecodes stored in WelcomeApplet.class • Create an HTML file • Loads the applet into appletviewer or a browser • Ends in .htm or .html • To execute an applet • Create an HTML file indicating which applet the browser (or appletviewer) should load and execute

  36. 1 <html> 2 <applet code = "WelcomeApplet.class"width = "300" height = "45"> 3 </applet> 4 </html> Simple Java Applet: Drawing a String (Cont.) • appletviewer only understands <applet> tags • Ignores everything else • Minimal browser • Executing the applet • appletviewer WelcomeApplet.html • Perform in directory containing .class file

  37. WelcomeApplet2.java1. import2. Class WelcomeApplet2 (extendsJApplet)3.paint3.1 drawString3.2 drawStringon same x coordinate, but 15 pixels down The two drawString statements simulate a newline. In fact, the concept of lines of text does not exist when drawing strings. 1 // Fig. 3.9: WelcomeApplet2.java 2 // Displaying multiple strings in an applet. 3 4 // Java packages 5 import java.awt.Graphics; // import class Graphics 6 import javax.swing.JApplet; // import class JApplet 7 8 public class WelcomeApplet2 extends JApplet { 9 10 // draw text on applet’s background 11 public void paint( Graphics g ) 12 { 13 // call superclass version of method paint 14 super.paint( g ); 15 16 // draw two Strings at different locations 17 g.drawString( "Welcome to", 25, 25 ); 18 g.drawString( "Java Programming!", 25, 40 ); 19 20 } // end method paint 21 22 } // end class WelcomeApplet2

  38. HTML fileProgram Output 1 <html> 2 <applet code = "WelcomeApplet2.class" width = "300" height = "60"> 3 </applet> </html>

More Related