1 / 34

What’s in ICS.H22

2. Java Useful because commonly used Great example of an object-oriented language Object-oriented languages encourage code reuse and good code design => Code tends to be more reliable Java is also “strongly typed” so it’s harder to make mistakes

Download Presentation

What’s in ICS.H22

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. 2. Java Useful because commonly used Great example of an object-oriented language Object-oriented languages encourage code reuse and good code design => Code tends to be more reliable Java is also “strongly typed” so it’s harder to make mistakes Learning how computers work: how programs are compiled and executed. 1. Algorithms and Data Structures From simple to more complex All very fundamental and useful You practice algorithmtic thinking… What’s in ICS.H22 1+2: Learning algorithms in practice: Coding and executing them in java

  2. Why Java ? • Java is an elegant, powerful programming language • simpler than other object-oriented languages [e.g., C++] • Java is the basis of other modern programming languages [e.g., C#] • Java is platform independent --- write once run everywhere • Java supports multiple platforms (Unix, Windows, Mac), multiple types of devices (desktops, PDAs, phones, embedded devices) • Java has good support • good multimedia, graphics packages • good client-server and network support (applet, serverlet) • good, free Integrated Development Environments (IDE)

  3. Bill Joy BSD Unix guy from Berkeley founded Sun Microsystems (early 80s) “the network is the computer” (a little ahead of its time) target workstation market missed the boat on PC revolution, retreated to Aspen, Colorado James Gosling early fame as the author of “Gosling Emacs” (killed by GNU) then onto Sun’s “NeWS” window system (killed by X) lesson: keeping things proprietary is kiss of death Java Programming Language: Designers

  4. Java Programming Language: History • Joy and Gosling joined force, Sun subsidiary, FirstPerson, Inc. (1992) • target consumer electronics: PDAs, appliances, phones, all with cheap infra-red kinds of networks • need a language that’s small, robust, safe, secure, wired • started working on C++-- • soon gave up hope, decided to start from scratch • Bad luck (again) • bad luck: a little ahead of time • PDAs died with the demise of Apple Newton • switched to interactive TV (ITV) • the resulting language was called “Oak” • then ITV died too • good luck (finally) • the net exploded in 1993 • Oak became Java, rest is history!

  5. Learning Java • just like learning any new language • syntax: “new words” • grammar: how to put them together • programming: telling a coherent story • library: use plots already written • initially needs efforts, but pays off in the end !

  6. Machine Languages • The “brain” of a computer is its Central Processing Unit (CPU) • A CPU can understand only very basic instructions, - e.g., store a given value at a memory location, do some arithmetic operations, compare two values, start to execute the instruction at another location • The set of instructions of a CPU form the machine language of the CPU Intel Pentium IBM PowerPC 750 for iMac

  7. Machine Languages • Machine languages, or the instructions understood by computers, are represented by numbers • for example, for Intel x86 (which includes Pentium), the numbers10110000 01100001give the instruction: copy number 97 to the processor register storage named ah. • Each type of CPU has its own specific machine language (why?) • Early programmers wrote programs using machine languages - the first programmer is Ada Byron (Lady Lovelace)

  8. Higher-Level Programming Languages • Other levels of programming languages were created to satisfy different objectives, e.g., make it easier for a human being to read/write programs: • assembly languages • intermediate languages • high-level languages

  9. movl (%edx,%eax), %ecx movl 12(%ebp), %eax leal 0(,%eax,4), %edx movl $nodes, %eax movl (%edx,%eax), %eax fldl (%ecx) fsubl (%eax) movl 8(%ebp), %eax leal 0(,%eax,4), %edx movl $nodes, %eax movl (%edx,%eax), Assembly language or simply assembly is a human-readable notation for the machine language it’s much easier to remember: movl %al, 97 than 10110000 01100001 Assembly Languages Example assembly code fragment

  10. int celsiusTemp = 32; double fahrenheitTemp; fahrenheitTemp = celsiusTemp * 9.0 / 5.0 + 32; if (fahrenheitTemp > 100) System.out.println (“Hot !”); else System.out.println (“OK !”); A high-level programming language enables a programmer to specify, in a high level (close to natural language), what data a computer will act upon, how these data will be stored, and what actions to take under various circumstances A high-level language is independent of CPU High-Level Programming Languages Example Java Code fragment

  11. Programming Languages • A program written in a high-level language must be translated into machine language before it can be executed on a particular type of CPU • A compiler is a software tool which translates source code into a specific target language • typically, that target language is the machine language for a particular CPU type compiler source code machine code e.g., c, c++ intel x86 gcc HelloWorld.c HelloWorld.exe

  12. Java Translation • To be platform independent, Java cannot use the previous approach • Java introduces an intermediate language called bytecode • Java bytecode is not the machine language for any traditional CPU, but a virtual machine • the Java compiler translates Java source code (.java files) into bytecode (in .class files) • therefore the Java compiler is not tied to any particular machine • Java is thus considered to be architecture-neutral

  13. Java Execution • To execute a Java program, another piece of software called an interpreter , translates between bytecode and the machine language • an interpreter is specific to a specific machine language • the interpreter understands java bytecode, and then issues instructions in the machine language for which it is written • we also say that an interpreter provides a java virtual machine (JVM) • Another approach is to have a “just in time” (JIT) compiler which translates from bytecode to machine code on the fly, while interpreting it

  14. Java Translation and Execution Java source code Java compiler Java bytecode Java interpreter for Windows Java interpreter for Mac JIT compiler Machine code

  15. Related Topic: Programming Errors… A program can have three types of errors • The compiler will find problems with syntax and other basic issues (compile-time errors) • If compile-time errors exist, an executable version of the program is not created • A problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally (run-time errors) • A program may run, but produce incorrect results (logical errors)

  16. Java Programming: The Edit/Compile/Run Loop • Programming in Java consists of three tasks • edit java source code (.java files) • compile java source code to generate bytecode (.class files) • execute/run/test bytecode using an interpreter

  17. An Sample Java Program //========================================================== // // HelloWorld.java // // Author: Richard Yang // // Class: HelloWorld // // --------------------------------------------------------- // This program prints a string called "Hello World!” // //========================================================== public class HelloWorld { public static voidmain(String[] args) { System.out.println("Hello World!"); } // end of method main } // end of class

  18. Comments • Two types of comments in Java • single-line comments use //… // this comment runs to the end of the line • multi-lines comments use /* … */ /* this comment runs to the terminating symbol, even across line breaks */ • Comments are ignored by the compiler: • used only for human readers (i.e., inline documentation) • they should be included to explain the purpose of the program and describe processing steps

  19. Identifiers • Identifiers are the words that a programmer uses in a program • An identifier can be made up of letters, digits, the underscore character (_), and the dollar sign ($) • An identifier cannot begin with a digit (why?) • Java is case sensitive, therefore Total and total are different identifiers

  20. Three Types of Identifiers 1. Identifiers chosen by ourselves when writing a program (such as HelloWorld) 2. Identifiers chosen by another programmer, so we use the identifiers that they chose (e.g., System, out, println, main) • public class HelloWorld • { • public static void main(String[] args) • { • System.out.println(“Hello World!”); • } • }

  21. Identifiers: Reserved Words 3. Special identifiers called reserved words that already have a predefined meaning in the Java language - a reserved word cannot be used in any other way abstract boolean break byte byvalue case cast catch char class const continue default do double else extends false final finally float for future generic goto if implements import inner instanceof int interface long native new null operator outer package private protected public rest return short static super switch synchronized this throw throws transient true try var void volatile while Java revered words: they are all lowercase!

  22. Java Program Structure • In the Java programming language: • a program is made up of one or more classes • a class contains one or more methods • Java application must always contain a method called main • a method contains program statements

  23. Java Program Structure: Class // comments about the class class name is anidentifier; conventionwe follow: capitalize each English word public class HelloWorld { } class header class body starts with a left brace { and ends with a right brace } comments can be added almost anywhere

  24. Structure of a Java Class public class Classroom { } // instance variables int min_capacity = 0; int max_capacity = 100; int chairs = 30; … // methods public int addStudents (int students) { … } public int addChairs (int chairs) { … } … public static void main (String[] args) { … }

  25. Java Method and Statements • Methods • building blocks of a class • each method name is an identifier, e.g. “addStudents” • convention we follow: a method name starts lower case, with each additional English word capitalized (e.g., main, doMyJob ) • the main method • each Java application must have one • all programs start by executing the main method • braces are used to start ({) and end (}) a method • Statements • every statement must end in a semicolon ;

  26. Classes and Methods • Methods and classes are language constructs to help organize a program • a method “organizes” a sequence of statements • thus we can use a single method to refer to a bunch of statements • a class “organizes” a collection of methods (and data) • Division of tasks into classes and methods supports object-oriented programming and creates good abstraction boundaries between different tasks and objects

  27. Classes and Methods Provide Abstraction • In the jargon of program design, they are structures which provide abstraction • The objective of abstraction is to help programmers to hide (or ignore) the right details at the right time • Why abstraction • a human being can only manage seven (plus or minus 2) pieces of information at one time • if we group information into chunks, for example, by organizing complex software carefully into methods and classes, we can write more complex software

  28. Methods and Classes • A method provides an abstraction for a sequence of statements • initially, a method helps a programmer to refer to a a sequence of statements which she may reuse • more generally, a method defines a service • a method takes input (parameters), performs some actions, and (sometime) returns a value • we invoke a method (call its service) and specify input/parameters • A class provides an abstraction for objects with some common behaviors/services which we can tell them to perform for us • the services/behaviors provided by an object are defined by the methods in the class that defines the object • we create objects from its class definition: class serves as a blueprint

  29. System.out.println ("Whatever you are, be a good one."); Object created from PrintStream class method dot Information provided to the method (parameters) Example • System.out is an object created from the PrintStream class • Example: invoking the println method of the System.out object:

  30. Declaring Object Reference Variables • In the general case, we need to first create objects • pre-created objects such as System.out are rare • To “keep track” of created objects, we need variablesto refer to the created objects • variables are identifiers • A variable can be used to refer to different objects • To avoid mixing different types of objects, we should specify the type of objects that a variable can refer to; thus we need to specify the type of a variable: <Type> <variableName>;

  31. Declaring Object Reference Variables • Example: String title; where String is a predefined class in Java; we also call title an object reference variable • No object has been created with the above declaration of a variable • The object itself must be created separately

  32. Explicitly Creating Objects • We use the new operator to create an object title = new String (“Java Software Solutions"); This calls the constructor method of class String, which is a special method that sets up the object (every class must have a constructor method) • Now the variable title refers to an instance of String object title “Java Software Solutions"

  33. Explicitly Creating Objects title = new String (“Java Software Solutions"); • “new” operator in general: <varName> = new <className> ([<params>]); This calls the constructor method of class <className> which (optionally) takes some parameters <params> • Now the variable <varName> refers to an object which is an instance of class <className> Object of class <className>, constructed using parameters <params> <varName>

  34. Use Methods of Objects title = new String (“Java Software Solutions"); • Once an object has been instantiated, we can use the dot operator to invoke its methods, e.g., count = title.length(); • This procedure call invokes method “length” of class String, because “title” is a variable which refers to an object which is an instance of class String. • Saying it another way: “title” is a variable of “type” String • Methods (e.g. method “length” of class String) can return values (Here the return value is assigned to variable “count”) title “Java Software Solutions"

More Related