Transcript Slide 1

APCS-AB: Java Intro
Introduction to Java, Classes &
Objects
October 4, 2005
week5
1
The Java Programming
language
• Section 1.4 of your book has a history of Java as
•
•
a programming language
Developed in the early 90s by James Gosling at
Sun Microsystems
The Java Platform has three major groups:
 Java 2 Platform, Standard Edition (J2SE)
• We focus on this one
 Java 2 Platform, Enterprise Edition (J2EE)
 Java 2 Platform, Micro Edition (J2ME)
week5
2
A simple Java Program
// HelloWorld.java
// Author: Ms.K
// Demonstrates a simple java program
public class HelloWorld{
public void sayHello(){
System.out.println(“Hello”);
}
/* This is an example of a multi-line comment
in the book it talks about the main method:
public static void main(String [ ] args)
we won’t be programming main until later */
}
week5
3
How Java works
public class myProgram{
Compiler
(javac)
sayHello();
}
Program in the Java
language
Checks for errors,
makes sure your
code will run
Output (code)
Java bytecode
.class file
Hello
Class!
week5
Java Virtual Machine (JVM)
Translates the bytecode to something the underlying
platform (computer) understands, and runs your program
4
Programming Languages
• Languages can be:
 High level or low level
 Platform dependent or independent
 Procedural, functional, logic, or object-oriented
week5
5
Java is…
• A high-level,
• Object-oriented,
• Platform independent
Programming Language
• What does that mean?
week5
6
Java as a Language
• High-level – More like a real language, can be read by a
•
human and understood, made more for ease of use for
people than for the computer
Object-oriented – think about problems from the things
(objects) that are in the problem and what those objects
can do (methods)
 This allows you to be able to:
• design code in a natural way
• easily add new capabilities without retesting all the code
• Platform independent – code that you write on one
computer can be transported and run on another
computer without re-compiling
week5
7
OO vs. Functional
Programming
• Scheme is a functional programming language
 Programs are written using only operations to be
performed on inputs, without using any temporary
variables to store intermediate results
• (definition from www.jsoftware.com/books/help/jforc/glossary.htm)
• Java is an object-oriented programming
language
 Programs are written to model objects in the world, the
focus is on what objects are part of the problem, what
those objects encapsulate and how they are
manipulated, instead of on the procedures or functions
used
week5
8
OO Programming as Modeling
• The parts of the model are objects in the problem
domain
• What are the properties of objects?
 Objects can be organized into categories
• We will talk later about inheritance & polymorphism
 Objects do things
• They have methods to accomplish tasks or to communicate
with other objects
 Objects know things
• They have internal state, variables that hold information about
themselves
week5
9
Classes
• A class describes (abstractly) a category of
objects
 Think of a class as a blueprint for an object – it describes the
boundaries of what an object can know or can do
• Instantiation is the process of creating the
object instance from the class
 An object must be instantiated before we can use it
week5
10
What does this all mean?
• What kinds of problems is Scheme geared
to help us with?
• What kinds of problems is Java geared to
help us with?
• What does this all tell us about the relative
power of these two different languages?
 Remember, programming languages are tools.
week5
11
Lewis & Loftus: Chapter One
• Read/Skim it at your leisure - it is an overview of a lot of the ideas
that we will cover (or a basic intro to some of the things that we may
not have time to really discuss much)
 1.1 Computer Processing (overview, binary, analog/digital)
 1.2 Hardware Components (architecture, I/O devices, memory, cpu)
 1.3 Networks (connections, local-area & wide-area networks, Internet,
World Wide Web, urls)
 1.4 Java Programming Language (Sample program, comments,
identifiers & reserved words, white space)
 1.5 Program Development (language levels, editors, compilers &
interpreters, development environments, syntax & semantics, errors)
 1.6 Object-Oriented Programming (Problem-Solving, OO Software
Principles)
week5
12
Role Play
• Class Activity: Bamboozler, Acrobat &
Calculator
 (from http://web.sbu.edu/cs/dlevine/RolePlay/roleplay.html)
week5
13
APCS-AB: Java Intro
Introduction to Java & BlueJ
October 5, 2005
week5
14
Java for Modeling
• As we mentioned yesterday, one of the
primary uses of Java (or any OOP
language) is to model objects in the real
world
• So let’s try to model something simple, a
dog
week5
15
Creating a Dog class in Java
public class Dog {
This is the start of a one-line comment
// This is a comment, used to describe code
CODE GOES HERE: what the Dog knows and what it does
}
Curly brace to end the class
week5
16
Object/Instance
• A specific description, an instance of a class
 A specific dog that we are modeling
• An object knows things and does things
 Also called attributes and behaviors
• Things an object knows are variables
 Data that is unique for an object of a given type
• Things an object does are methods
• Variables and methods are defined as part of the
class
 Variable values are set only for a specific instance
week5
17
Dog Class
public class Dog{
String breed;
String name;
int size;
These are variables.
Variables have a
data type and a name
public void bark(){ }
}
week5
This is a method.
Right now it doesn’t
do anything
A dog object would have individual values
for each of these variables
18
My Dog Instance
Breed: Bulldog
Name: Bully
Size: 24
Color: Purple
This dog can bark (invoke the method)
week5
19
What’s a Method?
• Things an object does
void bark() {
System.out.println(“Ruff! Ruff”);
}
This is a statement; this tells the computer
what you want to do in this method
week5
20
What’s a Statement?
• A line of code that gives a specific instruction
• Must end with a semicolon
int x; /* a declaration is a type of statement */
x = 5; // an assignment statement
System.out.println(“Ruff! Ruff”); /* a print
statement */
week5
21
What if you want to teach your
dog to bark differently?
• Make the dog say “Grrruffff”, “Bow-wow”,
or “Ruff Ruff”
 Could change the Dog program each time and
recompile like we did yesterday
 Or we could have the method take a
parameter (a String)
• {{ Explore this together in BlueJ }}
week5
22
BlueJ
week5
23
How BlueJ works
• BlueJ is a freely available program
 An interactive development environment (IDE) designed to help
students learn to program
 Makes it easy to sit down, write, and compile a program
• we’ll see later that it’s not always easy in other environments where
you have to deal with classpaths, file systems, DOS commands, etc
 Has visualization of class structure (very helpful for beginning and
advanced programmers)
 Can directly create objects and then interact with their methods
week5
24
Starting in BlueJ
BlueJ has a template that
gives you some starting code
It automatically creates:
•An instance variable
•A constructor
•An example method, with
example javadoc comments
week5
25
Homework
• Installing Java and BlueJ at home (handout)
• Mid-quarter comments (for the teacher)
 How is this class going for you?
week5
26
Lab 1:
Introduction to Java and BlueJ
•
•
•
•
•
Open BlueJ (and make shortcut on desktop)
Make new project called “Eyes”
Add class from file (“JavaEyes.java”)
Compile it
Run it
 Call Methods on it
• Look at the code (open editor)
week5
27
APCS-AB: Java
Assignments & Syntax
October 6, 2005
week5
28
Syntax
• Syntax is…
 The rules governing the structure of a language
 The rules that the compiler understands
 Defines meaning of the various symbols used in a language
• In Java if you get the syntax wrong, the compiler won’t
know what you are trying to do
• So it won’t do anything (it gives you an error)
week5
29
Concatenation
• Joining together or appending one string to
the end of another
• String literals cannot extend across
multiple lines in your program
 You must use the plus sign to concatenate two
string literals together
System.out.println(“This is a bad program
because it extends across multiple lines
without concatenating the strings together.
This will not compile.”);
week5
System.out.println(“This is a good program”
+ “ because it uses the + sign to extend”
+ “ the program across multiple lines.”);
30
Variables
• A variable is a name for a location in memory that stores
•
data
When you declare a variable, you tell the compiler to
reserve a certain size piece of memory to store data in
(based on the type of data)
 We will talk more about the types of data tomorrow
• Example:
 String name;
 int number;
week5
31
Variables
• Variables need a data type and a identifier.
• Think of a variable as a cup. A container. It
holds something.
 The data type tells Java the size of the container.
 The identifier is there so you know which container is
yours.
name
week5
number
32
Assignments
• When you declare a variable, you just set aside
•
the memory - but that space is “blank”
To actually place something in the variable, you
need to assign a value to it:
 name = “Henry”;
 number = 123;
“Henry”
name
week5
number
33
Assignment Statements
• More examples:
 String anotherName = “Andrew Udovic”;
 int num = 5 + 4*23;
• In Java, here are the basic rules:
 On the left side is always the variable name, the “container” in
which we are going to store data
 On the right side could be a single piece of data, or an expression
that has to be evaluated
• The single piece of data, or the result of whatever is evaluated is
then “assigned” to the variable (ie - placed into the memory location)
 You always end each statement with a semi-colon
week5
34
A program example
public class Example {
String name;
int number; //make the containers
public void doAssignment(){
name = “Nick”;
number = 123;
printStuff();
}
private void printStuff(){
System.out.println(“The name in this program is: “ + name);
System.out.println(“The number is” + number);
}
}
week5
35
Additional assignments
• If we reassign a value to a variable, the new value is written to
memory.. What happens to the old value?
int myVar = 123;
myVar = 34343435345;
• If we just reference (use) a variable, the value is not changed
System.out.print( “myVar is: “ + myVar);
// after this call, myVar still has 34343435345 stored in it
week5
36
Strongly Typed
• Java doesn’t let us store the wrong kind of data in our variables
 The compiler will cause an error if you try to use the wrong kind of data
for a variable.
• If we declare a variable of type String:
String s;
• Then we can’t put an integer into that String
s = 1232;
//Compile error: incompatible types - found int but expected java.lang.String
week5
37
Constants
• Sometimes we want to store a piece of data that will never change
 For example, we may want to say that a table at lunch can hold no more than 12
people. If we just use the number 12 in our program, people looking at our code
may not know where it came from
• So we give it a name like MAX_PEOPLE to help explain what the piece of
•
data is doing in a program
Also, lets say that we suddenly get new lunch tables that have a maximum of
15 people…
 We only have to change the data in one place, instead of trying to find all the
places that the number 12 was used in our program
• Constants are not variables (the value can never change)
 they hold one value for the durations of the program
week5
38
Constants in Java
• To declare a constant in Java, you use the reserved word final
• By convention, we use uppercase letters to name constants so that
we can tell them about from regular variables
final int MAX_PEOPLE = 12;
• The compiler will then prevent anybody from changing the value
once it has been set to the initial value
week5
39
Naming Practices in
Programming
• Class names start with a capital letter
 public class Dog { }
• Object names start with a lowercase letter
 Dog fido = new Dog();
• Method names and variables start with lowercase, but use capital
letters for subsequent words
 public void changeMyOil() {}
 int myAge;
• Constants use all caps
 MAX_INT_SIZE
week5
40
Arithmetic Operators
• What if we want to have a counter variable?
 Something that starts at 0 and then counts up, one-by-one
depending on what else we may be doing in a program
• int x = 0;
• So we could do:
• x = x + 1;
 So what would x equal? How does this all work?
• We do this a lot in programming, so there’s shortcut for
this (called the increment operator)
 x++;
week5
// is the same as x = x+1;
41
Other Arithmetic Operators
• Minus
 x = x -1;
• Multiplication
 x = x * 5;
• Division:
 x = x/2;
• What do you think will happen if we try to divide by zero?
• Modulo
 x = 5%2;
• You have the special operator for increment, do you think
there are any similar operators for these functions?
week5
42