Java Lecture 1
Java Lecture 1
Expected Background
A one-semester college course in programming. (MISM admissions policy) I assume you can write a program in some language, understand variables, control structures, functions/subroutines. If in doubt, lets talk.
Course Outline
Week 1: Background, basics of O-O, first Java program, programming environments Week 2: Raw materials: types, variables, operators, program control Week 3: Classes: declarations, constructors, cleanup & garbage collection Week 4: Packages, access specifiers, finals, class loading
Week 5: Polymorphism, abstract classes, design patterns Week 6: Interfaces & extends, inner classes, callbacks via inner classes Week 7: Midterm exam
Week 8: Arrays, container classes, iterators Week 9: More on collections, collections of references, choosing between types Week 10: Exception handling Week 11: Java I/O Week 12: Applets, applications, Swing Week 13: JDBC, threads
Administrative Details
Professor: Stephen F. Roehrig Office: Hamburg Hall, 2101A Business hours: 10 am to 10 pm Office hours by appointment Email: [email protected] Course Web site: https://blackboard9.andrew.cmu.edu Blackboard has the syllabus and course slides, and is used for grades and a discussion board.
12 weeks, plus exams Two 80-minute lectures per week, usually Tuesdays and Thursdays, 3:30 PM Course notes in PowerPoint, available on Blackboard Course notes available (usually) the Sunday before class Send course questions to Blackboards Discussion Group, personal questions to me.
Grading:
Homework: 50% Midterm exam 20% Final exam: 30% I give exactly one A+ per section.
Homework usually weekly. Submission instructions with each assignment, usually submit code (.java) and compiled code (.class) to Blackboard. If you have a question about how your homework was graded, first see the TA who graded the homework. If you are still unsatisfied, see me. You have one week after a homework is returned to dispute a grade. Printing slides? Three to a page, at least. Save a tree! Remove the PowerPoint background before printing. Save toner!
Recommended text: Horstmann & Cornell, Core Java 2, Volume 1 - Fundamentals, 7th edition, Sun Microsystems Press. Other books are OK as well. Our teaching assistants are
Attendance is not required, but you are responsible for everything said in class. I encourage you to ask questions in class. This is Americayou are supposed to ask questions. Dont guess, ask a question!
My Policy on Cheating
Cheating means submitting, without proper attribution, any computer code that is directly traceable to the computer code written by another person. I give students a failing course grade for any cheating. Expulsion is also possible. This doesnt help your job prospects. We will use MOSS in cases of suspected cheating.
My Policy on Cheating
You may discuss homework problems with classmates, after you have made a serious effort in trying the homework on your own. You can use ideas from the literature (with proper citation). You can use anything from the textbook/notes. The code you submit must be written completely by you.
In addition to any penalties imposed by the instructor, including failing the course, all cheating and plagiarism infractions will be reported in writing to the Associate Dean for the program, the Associate Dean of Faculty, the Dean of Student Affairs, and the Dean. They will review and determine if expulsion should be recommended. The report will become part of the students permanent record.
Course Etiquette
Etiquette is conduct in polite society No cell phones No random comings and goings If you are sleepy, go home No open notebook computers in class. If you want to read email or surf the Web, please do it elsewhere. I am very old-fashioned. I get insulted if students dont pay attention.
Recording
No student may record or tape any classroom activity without my express written consent. If a student believes that he/she is disabled and needs to record or tape classroom activities, he/she should contact the Office of Disability Resources to request an appropriate accommodation.
Machine language Assembler 3rd generation (COBOL, FORTRAN, C) Specialized (Lisp, Prolog, APL) 4th generation (SQL, GAMS, spreadsheets, Mathematica) 5th generation (example, anyone?)
Bring the language closer to the problem. But 4GLs are typically focused on specialized domains (e.g., relational databases). We want a language that is general purpose, yet can easily be tailored to any domain. An inspiration from an odd place
Simula
Designed to simulate job shops, banks, etc. To code, you create classes (like milling machines) and instances (machine #1, etc.). All milling machines have properties (how much time to make Part #1). All milling machines have abilities (mill to depth n, move part to position x). Job shop operations simulated by making the machines, and moving material through them.
Very close to the problem; domain experts can pitch in easily. Its possible to make new types of machines (e.g., drill press). Description of the shop floor is transparent:
millingMachine#1. millPart (part#3, depth 2mm) drillPress#2. idleUntil (Poisson(0.2))
Programming = Simulation?
Object-Oriented Languages
Smalltalk, C++, Java, etc You can make any kind of objects you want How different from procedural languages?
No different at all: Every (reasonable) language is Turing complete Very different: Make expression easier, less error-prone
Everything is an object. A program is a bunch of objects telling each other what to do, by sending messages. Each object has its own memory, and is made up of other objects. Every object has a type (class). All objects of the same type can receive the same messages.
It's easy as pie to write procedural code in Java. It takes some discipline (an attitude) to think O-O. It's worthwhile to do it.
Objects
An object has an interface, determined by its class. A class is an abstract data type, or userdefined type. Designing a class means defining its interface.
Built-In Types
Think of an int What is its interface? How do you send it messages? How do you make one? Where does it go when youre done with it? In solving a computational problem, the goal is to Dream up useful classes, and Endow them with appropriate characteristics.
Example
This is legal, but just makes a reference variable named myBeer This variable can refer to any BottleOfBeer object, but currently refers to nothing The operator new actually causes an object to be created, so we tell it what kind we want
Example (cont.)
But this only declares a reference to a (nonexistant) array. To actually create the bottles, I need to say
ninetyNineBottlesOfBeer = new BottleOfBeer[99]; // and a for loop to create the 99 bottles
The interface is the critical part, but the details (implementation) are important too.
BottleOfBeer -topOn:Boolean
Users use the interface (the public part); the implementation is hidden by access control.
C libraries are like this, sort of: The library designer invents a useful struct. Then she provides some useful functions for it. The user creates an instance of the struct, then applies library functions to it. One big difference is that anyone can change any part of the struct. (Booo, hsss!) Another difference is in initialization.
Composition: One class has another as a part (indicated by the diamond aggregation symbol).
CaseOfBeer Tavern
BottleOfBeer
Patron
Inheritance: One class is a specialized version of another (indicated by the triangle inheritance symbol).
BottleOfRollingRock -topOn:Boolean -lowCal:Boolean +open():void +lift(height:int):void +tilt(angle:int):void +isLowCal():Boolean
Polymorphism
Different subclasses respond to the same message, possibly with different Patron actions.
+beerPlease():Polite
Am e ricanPatron
BritishPatron
Ge rm anPatron
+beerPlease():Rude
+beerPlease():InGerman
Creating Objects
We usually assume this is free; with built-in types like int or char, we just say int i; char c; With user-defined types (the ones we make), we need to be explicit about what we want: using one or more constructor functions This is a very important issue!
Destroying Objects
If an object goes out of scope, it can no longer be used (its name is no longer known). In C++, we might need to write an explicit function to free memory allocated to an object. Java uses references and garbage collection.
What happens to lect? The LectureNotes object still exists, but the reference lect disappears (its out of scope after return). Eventually, the garbage collector removes the actual LectureNotes object.
0x1234
memory
When you speak of the variable lect, you are referring to the actual LectureNotes object. When lect goes out of scope it is automatically destroyed. The LectureNotes object lives on, but nobody can use itunless there are other references to it
Wrapper Types
Variables of primitive types are automatic, i.e., they are stored on the stack. They are automatically deleted when they go out of scope. What if you want an object holding a primitive type? Example:
char c = x; Character C = new Character(x);
BigInteger, BigDecimal
These are arbitrary precision, as big as they need to be. You cant use the usual operators (+*/) since they are objects. But there are methods (functions) to do these things. How might these be implemented?
Class Members
Fields (a.k.a. member variables, data members) Methods (a.k.a. member functions)
class MyClass { int a; YourClass b; double memberFunction(int x, double f) { return 0; } }
Editing
Use any text editor you like (not a word processor!); save as HelloDate.java
Compiling
From a DOS or UNIX command line, type > javac HelloDate.java This should produce the file HelloDate.class Again from the command prompt, type > java HelloDate
Running
Notes on DoubleSpace
We use the class Scanner, which comes from the Java I/O library. It could throw an exception if the user enters a bad file name, so this has to be trapped (with the try/catch stuff). DoubleSpace just prints the file, with a blank line after every existing line in the file.
Download a recent version of Eclipse http://www.eclipse.org/downloads/ Install it in some convenient place Run it!
System.out.println(Hello);
Saving the file causes the compiler to be invoked Now run the program