2.59k likes | 2.75k Vues
These notes are intended for use by students in CS0401 at the University of Pittsburgh and no one else These notes are provided free of charge and may not be sold in any shape or form Material from these notes is obtained from various sources, including, but not limited to, the following:
E N D
These notes are intended for use by students in CS0401 at the University of Pittsburgh and no one else • These notes are provided free of charge and may not be sold in any shape or form • Material from these notes is obtained from various sources, including, but not limited to, the following: • Starting Out with Java, From Control Structures through Objects, Third to Fifth Editions by Gaddis • Java Software Solutions, Fourth and Fifth Editions by Lewis and Loftus • Java By Dissection by Pohl and McDowell • The Java Tutorial(click for link) • The Java home page and its many sub-links: http://www.oracle.com/technetwork/java/index.html
Lecture 1: Prerequisites • Students taking CS401 should already have some programming background: • Previous experience with Java (ex: CS 0007) is recommended, but Python, C, C++ and VB are also acceptable • Concepts that you are expected to be familiar with include: • Basic program structure and syntax • How do we build programs and how do we get them to run • Primitive types and expressions • Numbers, characters, operators, precedence
Lecture 1: Prerequisites • Control Statements and Decisions • Boolean expressions • if and switch (or case) statements • Loops (for and while) • Methods (or functions) and parameters • Calling methods and flow of execution • Arguments and parameters • Arrays and their uses • One-dimensional only • If you do not have this background, you should consider taking CS 0007 before taking CS0401
Lecture 1: Goals of the Course • Goals for CS 0401 Course: • To (quickly) cover the basics of the Java language (including items mentioned in the previous slide) • These will be covered more from a Java implementa-tion point of view than from a conceptual point of view • You should already be familiar with (most of) the concepts, so learning the Java implementations should be fairly straightforward • Also will touch on the foundations of object-oriented programming • This includes Chapters 1-5 of the Gaddis text • Those who have had CS 0007 should consider this to be an extended review!
Lecture 1: Goals of Course • To learn the principles of object-oriented programming and to see Java from an object-oriented point of view • Objects, methods and instance variables • References and their implications • Creating new classes • Syntax and logic required • Inheritance and composition • Building new classes from old classes • Polymorphism and dynamic binding • Accessing different objects in a uniform way • Chapters 6, 8-10 of Gaddis • We will focus a lot of attention on these chapters
Lecture 1: Goals of Course • Note that we are covering OOP concepts using Java as our language • However, the general principles of object-oriented programming apply to any object-oriented language • Ex: C++, Objective-C, C#, Smalltalk, etc. • The more important goal here is to learn to program effectively in an object-oriented way • Understand why it is good and how to do it
Lecture 1: Goals of Course • To cover additional useful programming techniques and features of Java in order to become proficient programmers (using the Java language) • Array use and algorithms (sorting, searching) (Chapter 7) • Reading and Writing Files (Chapters 4, 11 + Notes) • Exception Handling (Chapter 11) • Graphical User Interfaces and Applications (Chapters 12, 13, 14) • Introduction to recursion (Chapter 15)
Lecture 2: Why Java? • Java • Java is an interpreted, platform-independent, object-oriented language • Interpreted, platform-independent: • Source .java code is compiled into intermediate (byte) code • Byte code is executed in software via another program called an interpreter • Benefits: • More safety features and run-time checks can be built into the language – discuss • Code can be platform-independent • As long as the correct interpreter is installed, the same byte code can be executed on any platform
Lecture 2: Why Java? JRE for Windows Java Source Code (.java) Java Byte Code (.class) JRE for Linux Java Compiler Program Execution JRE for Solaris The same .class file can execute on any platform, as long as the JRE is installed there JRE for Mac
Lecture 2: Why Java? • Drawback: • Interpreted code executes more slowly than regular compiled code • Since program is run in software rather than hardware, it cannot match the execution times of code that is compiled for specific hardware • Ex: C, C++ code • No language is best for every application • However, Java implementations can use JIT compilation of bytecode to execute faster • Object-oriented • Primary mode of execution is interaction of objects with each other • We will discuss object-oriented programming in much more detail soon
Lecture 2: Getting Started with Java • How do we execute Java programs? • First we must compile our source (.java) code into the intermediate (.class) code • We do this with the Java Compiler • javac program • Next we must interpret our .class code to see the result • We do this with the Java Interpreter, or Java Run-time Environment (JRE) • java program
Lecture 2: Getting Started with Java • Both programs come with the Software Development Kit (SDK) for Java • This is installed on all of the lab PCs and the Mac Minis • The most recent version (1.7) can be easily downloaded and installed from the Oracle Web site: • http://www.oracle.com/technetwork/java/index.html • It is free! • More on the basics of using the Java software development kit is shown in Lab 1 • Look for it online soon -- you will do it next week • But let’s look at an ex. and talk more about Java basics • See ex1.java – Carefully read the comments!
Lecture 2: Getting Started with Java • When you have a chance, try the following: • Download ex1.java from the Web site onto a PC that has the SDK installed (yours or a lab PC) • Open a terminal (command prompt) window • Change to the correct directory • Compile the program: javac ex1.java • Execute the program: java ex1 • Adding the .class extension is optional – it is assumed even if you don’t put it there • Show the directory to see that the .class file is now there • Also try the same thing from one of the Lab workstations during your first lab session
Lecture 2: Getting Started with Java • Note: Most developers use an IDE (integrated development environment) for program devel. • Here are two possibilities: • http://www.netbeans.org/ • http://www.eclipse.org/ • Both are available free • Eclipse is installed on the Mac Minis in the Java lab • These allow you to edit, compile and debug Java programs in an easy, integrated way • However, you should realize that the final program does NOT depend on the IDE, and you should be able to compile and run Java programs without the IDE • I will not be emphasizing these in lecture, but you are free to use one if you wish
Lecture 2: Java Basics • What fundamental entities / abilities do we need for any useful Java program? • A way to getdata into and out of our program • I/O • A way to create / name / variables and constants to store our data • Identifiers and variables • A way to manipulate / operate on the data • Statements and Expressions • A way to make decisions and control our flow of execution • Control structures
Lecture 2: Java Basics • Output(we will defer input until after we discuss variables) • Java has a predefined object called System.out • This object has the ability to output data to the standard output stream, which is usually the console (display) • This ability is via methods (procedures) • Ex: print, println • We pass information to the System.outobject through methods and parameters, and the information is then shown on the display • For example: System.out.println(“Hello Java Students!”);
Lecture 2: Java Basics • We can output strings, values of variables and expressions and other information using System.out • We will see more on this once we discuss variables • We will understand how System.out works more precisely after we have discussed classes and objects later in the term
Lecture 2: Java Basics • Lexical elements – groups of characters used in program code • These form all of the parts of the program code • Ex: keywords, identifiers, literals, delimiters • We will discuss some of these in the Java language • Keywords • Lexical elements that have a special, predefined meaning in the language • Cannot be redefined or used in any other way in a program • Ex: program, if, class, throws • See p. 10 in Gaddis for complete list
Lecture 2: Java Basics • Predefined Identifiers • Identifiers that were written as part of some class / package that are already integrated into the language • Ex: System, Applet, JFrame – class names • Ex: println, start, close – method names • Ex: E, PI – constant names • Programmers can use these within the context in which they are defined • In Java there are a LOT because Java has a large predefined class library
Lecture 2: Java Basics • Other Identifiers • Defined by programmer • used to represent names of variables, methods, classes, etc • Cannot be keywords • We could redefine predefined identifiers if we wanted to, but this is generally not a good idea • Java IDs must begin with a letter, followed by any num- ber of letters, digits, _ (underscore) or $ characters • Similar to identifier rules in most programming langs
Lecture 2: Java Basics • Important Note: • Java identifiers are case-sensitive – this means that upper and lower case letters are considered to be different – be careful to be consistent! • Ex: ThisVariable and thisvariable are NOT the same • Naming Convention: • Many Java programmers use the following conventions: • Classes: start with upper case, then start each word with an upper case letter • Ex: StringBuffer, BufferedInputStream, ArrayIndexOutOfBoundsException • Methods and variables: start with lower case, then start each word with an upper case letter • Ex: compareTo, lastIndexOf, mousePressed
Lecture 2: Java Basics • Literals • Values that are hard-coded into a program • They are literally in the code! • Different types have different rules for literal values • They are fairly intuitive and similar across most programming languages • Ex: Integer • An optional +/- followed by a sequence of digits • Ex: String • A sequence of characters contained within double quotes • See Section 2.3 for more details on literals
Lecture 2: Java Basics • Statements • Units of declaration or execution • A program execution can be broken down into execution of the program’s individual statements • Every Java statement must be terminated by a semicolon (;) • Ex: Variable declaration statement int var1, var2; • Ex: Assignment statement var1 = 100; • Ex: Method call System.out.println(“Answer is “ + var1); • We will see many more statements later
Lecture 2: Java Basics • Variables • Memory locations that are associated with identifiers • Values can change throughout the execution of a program • In Java, must be specified as a certain type or class • The type of a variable specifies its properties: the data it can store and the operations that can be performed on it • Ex: int type: discuss • Java is fairly strict about enforcing data type values • You will get a compilation error if you assign an incorrect type to a variable: Ex: int i = “hello”; incompatible types found: java.lang.String required: int int i = "hello"; ^
Lecture 2: Java Basics • Note: For numeric types, you even get an error if the value assigned will “lose precision” if placed into the variable • Generally speaking this means we can place “smaller” values into “larger” variables but we cannot place “larger” values into “smaller” variables • Ex: byte < int < long < float < double • Ex: int i = 3.5; • Ex: double x = 100; • This is ok possible loss of precision found : double required: int int i = 3.5; ^
Lecture 2: Java Basics • Floating point literals in Java are by default double • If you assign one to a float variable, you will get a “loss of precision error” as shown in the previous slide • If you want to assign a “more precise” value to a “less precise” variable, you must explicitly cast the value to that variable type int i = 5; int j = 4.5; float x = 3.5; float y = (float) 3.5; double z = 100; i = z; y = z; z = i; j = (long) y; j = (byte) y; Error check each of the statements in the box to the right
Lecture 3: Data and Expressions • In Java, variables fall into two categories: • Primitive Types • Simple types whose values are stored directly in the memory location associated with a variable • Ex: int var1 = 100; • There are 8 primitive types in Java: byte, short, int, long, float, double, char, boolean • See Section 2.4 and ex3.java for more details on the primitive numeric types var1 100
Lecture 3: Data and Expressions • Reference Types (or class types) • Types whose values are references to objects that are stored elsewhere in memory • Ex: String s = new String(“Hello There”); • There are many implications to using reference types, and we must use them with care • Different objects have different capabilities, based on their classes • We will discuss reference types in more detail later when we start looking at Objects s Hello There
Lecture 3: Data and Expressions • Rules for declaration and use • In Java, all variables must be declared before they can be used Ex: x = 5.0; • This will cause an error unless x has previously been declared as a double variable • Java variables can be initialized in the same statement in which they are declared • Ex: double x = 5.0; • However, keep in mind that two things are being done here – declaration AND initialization cannot resolve symbol symbol : variable x location : class classname x = 5.0; ^
Lecture 3: Data and Expressions • Multiple variables of the same type can be declared and initialized in a single statement, as long as they are separated by commas • Ex: int i = 10, j = 20, k = 45; • Multiple variables of different types cannot be declared within a single declaration statement • See ex2.java
Lecture 3: Data and Expressions • Operators and Expressions • Numeric operators in Java include +, –, *, /, % • These are typical across most languages • A couple points, however: • If both operands are integer, / will give integer division, always producing an integer result – discuss implications • The % operator was designed integer operands and gives the remainder of integer division • However, % can be used with floating point as well inti, j, k, m; i = 19; j = 7; k = i / j; // answer? m = i % j; // answer?
Lecture 3: Data and Expressions • Precedence and Associativity • What do these mean? • Recall that the precedence indicates the order in which operators are applied in an expression • See Table 2-8 • Recall that the associativity indicates the order in which operands are accessed given operators of the same precedence • General guidelines to remember for arithmetic operators: *, /, % same precedence, left to right associativity +, – same (lower) precedence, also L to R • See Table 2-9
Lecture 3: More Operators • Java has a number of convenience operators • Allow us to do operations with less typing • Ex: X = X + 1; X++; Y = Y – 5; Y –= 5; • See Section 2.6 for more details • One point that should be emphasized is the difference between the prefix and postfix versions of the unary operators • What is the difference between the statements: X++; ++X; • Discuss • See ex3.java
Lecture 4: Input and the Scanner Class • Input • Java has a predefined object called System.in • Analogous to System.out discussed previously • Allows data to be input from the standard input stream • Recall that System.outaccessed the standard output stream • By default this object allows us to read data from the console / keyboard
Lecture 4: Input and the Scanner Class • In JDK releases up to 1.4 • Console text input was fairly complicated to use • Objects had to be created and exceptions had to be handled • Made it difficult to show students learning Java simple input and output • Consequently, textbook authors often created their own classes to make console I/O easier • But they weren't standard Java, so students would not find them useful after their courses ended • In JDK 1.5, the Scanner class was added
Lecture 4: Input and the Scanner Class • Scanner is a class that reads data from the standard input stream and parses it into tokens based on a delimiter • A delimiter is a character or set of characters that distinguish one token from another • A token is all of the characters between delimiters • By default the Scanner class uses white space as the delimiter • The tokens can be read in either as Strings • next() • Or they can be read as primitive types • Ex: nextInt(), nextFloat(), nextDouble()
Lecture 4: Input and the Scanner Class • If read as primitive types, an error will occur if the actual token does not match what you are trying to read • Ex: Please enter an int: hello Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at ex3.main(ex3.java:39) • These types of errors are run-time errors and in Java are called exceptions • Java has many different exceptions • We'll look at exceptions in more detail later • Let's look at ex4.java
Lecture 4: Control Statements • Java Statements • We already discussed some Java statements • Declaration statement • Assignment statement • Method call • One of the most important types of statements in programming is the control statement • Allows 2 very important types of execution • Conditional execution • Statements may or may not execute • Iterative execution • Statements may execute more than one time
Lecture 4: Control Statements Linear Execution Conditional Execution Iterative Execution
Lecture 4: Boolean Expressions • Key to many control statements in Java are boolean expressions • Expressions whose result is true or false • true and false are predefined literals in Java • Can be created using one or more relational operators and logical operators • Relational operators • Used to compare (i.e. relate) two primitive values • Result is true or false based on values and the comparison that is asserted Ex: 6 < 10 -- true because 6 IS less than 10 7 != 7 -- false because 7 IS NOT not equal to 7
Lecture 4: Boolean Expressions • Java has 6 relational operators< <= > >= == != • Some boolean expressions are more complicated than just a simple relational operation • These expressions require logical operators • Operate on boolean values, generating a new boolean value as a result ! && || • Recall their values from a truth table
Lecture 4: Boolean Expressions • Let’s look at some examples int i = 10, j = 15, k = 20; double x = 10.0, y = 3.333333, z = 100.0; i < j || j < k && x <= y (i / 3) == y (x / 3) == y !(x != i)
Lecture 5: if statement • The if statement is very intuitive: if (booleanexpression) <true option>; else <false option>; • Each of <true option> and <false option> can be any Java statement, including a block • Java blocks are delimited by { } and can contain any number of statements • else + <false option> is optional • Note parens around booleanexpression - required
Lecture 5: if statement • Nested ifs • Since both <true option> and <false option> can be any Java statement, they can certainly be if statements • This allows us to create nested if statements • We can nest on <true option>, on <false option> or both • Show on board • Enables us to test multiple conditions and to have a different result for each possibility
Lecture 5: if statement • Dangling else • The structure of a Java if statement allows for an interesting special case: if (grade >= 95) if (extraCredit) System.out.println(“A+”); else System.out.println(“?”); • Question: is the <false option> for condition1 or condition2? • As shown above it will ALWAYS be for condition2 • Rule is that an else will always be associated with the “closest” unassociated, non-terminated if
Lecture 5: if statement • Thus, there is no problem for the computer • Problem is if the programmer does not understand the rule • Result is a LOGIC ERROR • Logic errors can be very problematic and difficult to correct • Unlike a syntax error, which prevents the program from being compiled, with a logic error the program may run and may seem fine • However, one or more errors in the programmer’s logic cause the result will be incorrect! • Compare on board: SYNTAX ERROR, RUN-TIME ERROR, LOGIC ERROR • Luckily, in this case the problem is easy to correct • How?
Lecture 5: while loop • The while loop is also intuitive while (booleanexpression) <loop body> • where <loop body> can be any Java statement • Logic of while loop: • Evaluate (booleanexpression) • If result is true, execute <loop body>, otherwise skip to next statement after loop • Repeat • while loop is called an entry loop, because a condition must be met to get IN to the loop body • Implications of this?
Lecture 5: Example • Let’s now use if and while in a simple program: • User will enter some scores and the program will calculate the average • Let’s do this together, trying to come up with a good solution • Consider some questions / issues: • What is the acceptable range for the scores? • What do we do if a score is unacceptable? • How many scores are there? • Do we even know this in advance? • What to do if we do not know this in advance?
Lecture 5: Example • Are there any special cases that we need to consider? • What variables will we need to use? • And what will be their types? • Once we have a solution, let’s look at two possible solutions • ex5a.java and ex5b.java • Note that for many programming problems, there are MANY possible solutions