Download Lecture 1 Notes

Document related concepts
no text concepts found
Transcript
Scheme -> Java
Conversion Course 2001
Course Overview
• OOP Concepts
• Java Programming Structure & Style
• Methods and Classes
• APIs in JAVA and their applications
Course Timetable
• Today (Mon 10th Dec 2001)
- 2hr lecture, 10am - 12 noon, LT34
• Tomorrow (Tue 11th Dec 2001)
- 2hr lab, 10am - 12 noon, PL1, Linux Lab
• Day After Tomorrow (Wed 12th Dec 2001)
- 2hr lab, 10am - 12 noon, PL1, Linux Lab
Thanks to Aaron for helping us book the LT and the labs!
Recommended Resources
•
•
•
•
•
CS1101 Homepage :)
Online Java 1.3 API Docs
Your seniors :)
Your Javanese friends
Developing JAVA Software (Wiley)
- Russell Winders & Graham
• Computing Concepts with JAVA 2
Essentials
- Cay Horstman
Lesson
Proper
Why do we need to learn so many
programming styles and
languages?
Different problems, different
ways of solving - different tools
The tools are usually selected
based on their features
An example will be when the
programmer chooses between C
and Java, the crux lying in the
management of memory
Types of Programming Styles
Imperative
Functional
Logic
OOP
OOP
Object-Oriented Programming
What is it?
In OOP, everything is treated as an
object!
Every object has properties
(characteristics) and methods (actions),
just like our friends in PS10 :)
Properties :
Birthplace
Methods :
Eat
Troll
Person
Properties :
Name
Methods :
Look, Move
Classes
• A class is a template/blueprint
• An object/instance is the product based on
the blueprint
• Eg : A complete DNA profile lying in a
Biotech lab - not living, not in action, no
practical actions. But if you bring it to life
(make your product based on this blueprint)
- you get a living human, able to act.
Methods - Constructors, Accessors, Modifiers
• Constructor - method containing code on
how to create and initialize the object
• Accessor - to access (find out) the object’s
properties. Eg: Check the person’s name
• Modifier - to change the object’s properties.
Eg: Change the location of the person
Four Pillars of OOP
Data Hiding
Encapsulation
Polymorphism
Inheritance
Four Pillars of OOP
• Data Hiding - to hide data that is not
necessary for the user to know.
Eg. We do not care how the codes perform
sqrt(int x). We only need to use it.
• Encapsulation - the inclusion within a
program object of all the resources needed
for the object to function. A self-contained
atom
Four Pillars of OOP
• Polymorphism - characteristic of being able
to assign a different meaning to a particular
symbol or "operator" in different contexts.
eg. overloading methods, +, - operators...
• Inheritance - the concept that when a class
of objects is defined, any subclass that is
defined can inherit the definitions of one or
more general classes
Any Questions so
far?
A Brief History in Java
• Began from the “Green” project by Sun
Microsystems in 1990, headed by James Gosling aim: to develop software for use in consumer
electronics
• Gosling started writing software in C++ to be
embedded into electrical appliances. It soon
became apparent that it was the wrong tool.
• Burden of resource management in C++ was a
barrier to creating reliable, portable software..users
may have come to accept bugs in computer
software, but no one expects their toaster to crash...
A Brief History in Java
• Gosling’s solution - a new programming language
named Oak - incorporated memory management
and hardware independence. Oak code could be
ported to other similar systems without the need to
be rewritten
• Finally, in 1995, Oak was renamed Java (for
marketing purposes) and announced at SunWorld
95
• And now, it has become the industry standard for
Internet development
Why is JAVA so popular?
Main Reason : Platform independance
How does JAVA achieve this?
Ans : The Java Virtual Machine
Usual Compilers (eg: C) - Source code is
compiled into native machine code.
Java : Source code is run thru the Java
compiler and architecture-independent
bytecode is created. This bytecode can then be
used on any systems. When executed on a
machine, the JVM on that machine will then
interpret the bytecode and run the program.
Another way is JIT compilers - compiling the
bytecode to native machine code
Compilation to Virtual Machines
source code
translated to
virtual machine
code
sent to
virtual
machine
runs on
hardware
Okie….enough of all this theory…
now down to actual
Java programming… :)
Basic Java Structure
HelloWorld.java
import java.io.*;
class HelloWorld
{
public static void main(String [] args) throws Exception
{
String s = “Hello World!”;
System.out.println(s);
} // end method main
} /* end class main */
Data Types
int, float, double, short, long, byte, boolean, char, String
int, float, double, short and long used to represent numbers
byte is used for byte representation
char used to represent a single ASCII character
String used to represent a string of characters
boolean used to represent true and false.
JAVA is strictly typed
• variables in JAVA has to be of a certain type
• variables have to be declared before use
• Once declared, the type of a variable cannot
be changed
Typing of variables is not restricted to primitive
data types
Basically, a variable is used to store/represent
values. You can have a variable which
represents a numeric value, a String or even a
model/instance of a class you created
Just like in your PS10, you created beings
modelled on the classes (types of people) you
created. Eg:
(define Smurfy (make&install-troll ….))
Similarly, you can create the same variable in
Java like this (provided you have created a
Troll class) :
Troll Smurfy = new Troll(….);
Assignment
Type varname = expression
Example 1 : int x;
x=5+2;
Same as : int x = 7;
Point is : You must first declare what type the
variable belongs to. Only after that may you
assign a value to it, but the value must be of
the correct type. You can assign a value right
at the start when you create the variable…you
will also be able to change the value later on
Note and Remember!
JAVA is super case-sensitive!
X x
HelloWorld helloWorld
Decision Making - if
Syntax :
if condition
statement
else
statement
unlike Scheme, the condition must render
true or false.
Decision Making - if
Proper Eg :
if (5+2 = = 7)
System.out.println(“hi”);
else
System.out.println(“bye”);
Note that the else statement need not
always be included, especially if you
do not want to do anything if the
condition is false.
Decision Making - if
BAD Eg :
if (3-1)
System.out.println(“hi”);
else
System.out.println(“bye”);
In Scheme, false is denoted by an
empty list - everything else denotes
true. Not so in Java.
Decision – switch-case
Variable to be tested
switch ( dice-throw ) {
case 1: System.out.println(“One”);
break;
case 2: System.out.println(“Two”);
break;
case 3: System.out.println(“Three”);
break;
case 4: System.out.println(“Four”);
break;
case 5: System.out.println(“Five”);
break;
default: System.out.println(“Six”);
break;
}
Various actions to
be performed
Possible values that
the variable can take
Decision – switch-case
The if-else equivalent of the switch-case example just now
would be this :
if (dice-throw = = 1)
System.out.println(“One”);
else if (dice-throw = = 2)
System.out.println(“Two”);
else if (dice-throw = = 3)
System.out.println(“Three”);
else if (dice-throw = = 4)
System.out.println(“Four”);
else if (dice-throw = = 5)
System.out.println(“Five”);
else
System.out.println(“Six”);
Loops
In Scheme, whenever we want to do something
repeatedly (eg: adding from 1 to 10 or printing a
number 10 times), we would have to use recursion.
In Java, this is done using loops. There are 3 types
of loops in Java - the “for” loop, the “while” loop,
and the “do-while” loop
“for”
: for an known amount of time
“while”
: check first before doing
“do-while” : do first then check
Loops - “for” loop
Eg:
for (int cnt=1; cnt<=10; cnt++)
{
System.out.println(“hi”);
System.out.println(cnt);
}
cnt++ is
the same
as cnt=cnt+1
In the “for” loop, the counter is initialized and
incremented/decremented within the for
statement. Middle portion (in here, “cnt<=10”)
is the condition for continuing the loop
Loops - “while” loop
Eg :
int cnt=1;
while (cnt<=10)
{
System.out.println(“hi”);
System.out.println(cnt);
cnt++;
}
The “while” statement only carries the condition for
executing the loop. If you are using a counter to stop
the loop, you must remember to increment/decrement
it inside the loop body
Loops - “while” loop
Eg :
boolean flag=false;
int cnt=1;
while (!flag)
{
cnt++;
if (cnt>10)
flag=true;
}
Loops - “do-while” loop
Eg :
boolean flag=false;
int cnt=10;
do
{
System.out.println(“hi!”)
cnt++;
if (cnt>10)
flag=true;
} while (!flag)
The “do-while” loop
will at least execute
once, unlike the
previous two types
of loops
Sideline - operators :)
When we were discussing loops, we saw the use of
the NOT boolean operator..thought this will be a
good time to introduce you properly also to the
various arithmetic and boolean operators in JAVA :)
Arithmetic operators :
add : +
subtract : multiply : *
divide : /
remainder (mod) : %
Note for divide. If you try 1/2, you get 0,
but if you try 1.0/2 or 1/2.0, you get 0.5
Sideline - operators :)
Boolean operators :
equality : = = //eg. (3 = = 3)
Not equal : !=
NOT : !
// (!true) = = false
OR : ||
// eg. ( (x = = 5) || (y = = 2) )
AND : && // eg. ( (x = = 5) && (y = = 2) )
You probably would have noted by now that
the operations are infix, unlike the prefix
notation in Scheme. So, instead of (+ 3 4), you
do (3+4)
Recursion
Although loops are helpful in coding, they do have
their limitations. Recursive algorithms such as the
Fibonacci series are much more easily done using
recursion than using loops.
public int Fib (int n)
{
if ((n = = 0) || (n = = 1))
return 1;
else
return Fib(n-1) + Fib(n-2);
}
Recursion
Basically, the rules which you have learnt from
Scheme still applies - in recursion, there must always
be a base case…the whole execution must end at
some time.
After one semester in Scheme, you all should be
quite familiar with recursion now…so I guess no
problem regarding this :)
Arrays
Arrays are collections of objects of the same type.
int[ ] grades = new int[10];
grades
0
1
2
3
4
5
6
7
8
9
index
grades is an array of 10 integers
grades[0], grades[1], grades[2] … grades[9] are all integers
Arrays
Of course, as with variables, you can also create
arrays of the types you created, for example, an array
of trolls. If you have an array of 10 trolls, each index
slot will hold one troll
Arrays are usually used together with loops…an
example would be the storing of the marks of all the
students in an array and using a loop to print them all
out later. This is far better than creating a variable for
each student..what if there were 1000 students? Are
you going to have 1000 println( ) statements to print
each student’s marks?
Arrays
Let me prove my point :)
Let’s say we have 1000 students. Without using
arrays, this is how it looks like :
int student1, student2, …, student1000;
//Then someone enters the marks
System.out.println(student1);
System.out.println(student2);
….
….
System.out.println(student1000);
Arrays
Now let us use arrays :
int[ ] student = new int[1000] ;
//Then someone enters the marks
for (int cnt=0; cnt<1000; cnt++)
System.out.println(student[cnt]);
Now…that certainly beats writing out 1000
copies of the same thing, doesn’t it? ;-)
Sideline
Now, after going through one semester in
programming, you all should know the importance of
generic programming, ie. your code should be
general enough to handle a lot of cases.
Ok…what if your program (student marks) was
to be used by many different lecturers? It has to
be general enough - you can’t just hardcode
everything. With the use of arrays, you can just
ask the lecturer to key in a number n, and create
an array of that size accordingly.
int [ ] student = new int[n];
Methods
Basically, methods are the same as your lambda
procedures, except that in Java, there’s no such
thing as a nameless method - every method must
have a name.
return-type method-name (arguments)
{
body
}
Methods
return-type refers to the type of answer/result the
method will give back. For example, the method
sqrt( ) will return you a double. At the end of
your method, you must return the type which you
specified in return-type
The return type can be a primitive data type (int,
boolean, float, char..), or a class type (String,
Troll…) or void, if your method does not return
any value.
Methods
Some more on “void” …look at the 2 methods
below :
void square (int x)
{ System.out.println(x*x); }
int square (int x)
{ return x*x; }
One may ask, “Why don’t we just return void, cos we
just need the answer, right?” Not necessary. What if I
want to know square(222)+square(333) ? In this case,
the 2nd method makes more sense.
Methods
public static int myMethod1( )
{
int x = 2;
return x;
}
public static int myMethod2( )
{
boolean x = false;
return x;
}

Methods
Arguments - what you pass into a method
Examples :
int square (int x) { }
int power (int x, int y) { }
String sayMyName(String myName)
{
System.out.println(“Your name is ”+myName);
}
Method-Overloading
Sometimes you want a method to be able to handle
different types or different number of arguments.
public static int add(int x, int y) {return x+y;}
public static int add(int x, int y, int z) {return x+y+z;}
public static int add(int x, int y, Num z){return x+y+Num.value( );}
• add(2,2);
- 1st method
• add(2,3,4);
- 2nd method
• add(2,3,4,5);
- compiler reject
• add(2,3,(new Num(2)));
- 3rd method
Exceptions
• an object that defines an erroneous situation
• thrown by program or runtime environment
• can be caught and handled
public static void myMethod( ) throws Exception
{
throw new Exception(“errrrrror”);
}
Exceptions
public static void myMethod() throws Exception
{
int x = 1 / 0;
}
Arithmetic Exception will be automatically thrown;
Try & catch statement
• used to catch exceptions that are thrown
• allow graceful exit or smooth flow
try {
statement-list1;
} catch (exception-class1 variable1) {
statement-list2; }
Try & catch statement
public static void myMethod( )
{
try
{
int x = 1 / 0;
} catch(Exception e1)
{System.out.println(“eh…dunno how to divide is it?”);}
System.out.println(“done”);
}