scheme -> java conversion course 2001. course overview oop concepts java programming structure...
DESCRIPTION
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!TRANSCRIPT
Scheme -> JavaConversion Course
2001
Course OverviewCourse Overview
• OOP Concepts
• Java Programming Structure & Style
• Methods and Classes
• APIs in JAVA and their applications
Course TimetableCourse 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 ResourcesRecommended 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
LessonLessonProperProper
Why do we need to learn so Why do we need to learn so many programming styles and many programming styles and
languages?languages?
Different problems, different Different problems, different ways of solving - different toolsways of solving - different tools
The tools are usually selected The tools are usually selected based on their featuresbased on their features
An example will be when the An example will be when the programmer chooses between programmer chooses between C and Java, the crux lying in C and Java, the crux lying in the management of memorythe management of memory
Types of Programming StylesTypes of Programming Styles
Imperative Functional
Logic OOP
OOPOOP
Object-Oriented ProgrammingObject-Oriented Programming
What is it?What is it?
In OOP, everything is treated as an In OOP, everything is treated as an object!object!
Every object has properties Every object has properties (characteristics) and methods (characteristics) and methods
(actions), just like our friends in PS10 :)(actions), just like our friends in PS10 :)
PersonTroll
Properties : NameMethods :Look, Move
Properties : BirthplaceMethods :Eat
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 HidingEncapsulation
PolymorphismInheritance
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
virtual machine code
virtualmachine
hardware
runs on
sent to
source code
translated to
Okie….enough of all this theory…now down to actual
Java programming… :)
Basic Java StructureHelloWorld.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 Typesint, 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(….);
AssignmentType 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 xHelloWorld helloWorld
Decision Making - ifSyntax : if condition statementelse statement
unlike Scheme, the condition must render true or false.
Decision Making - ifProper 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
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;}
Possible values that the variable can take
Various actions to be performed
Variable to be tested
Decision – switch-caseThe 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” loopEg: for (int cnt=1; cnt<=10; cnt++){ System.out.println(“hi”); System.out.println(cnt);}
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
cnt++ isthe sameas cnt=cnt+1
Loops - “while” loopEg : 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” loopEg : boolean flag=false;int cnt=1;while (!flag){ cnt++; if (cnt>10) flag=true;}
Loops - “do-while” loopEg : 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) = = falseOR : || // 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)
RecursionAlthough 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);}
RecursionBasically, 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 is an array of 10 integers
grades[0], grades[1], grades[2] … grades[9] are all integers
0 1 2 3 4 5 6 7 8 9grades
index
ArraysOf 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?
ArraysLet 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 marksSystem.out.println(student1);System.out.println(student2);….….System.out.println(student1000);
ArraysNow let us use arrays :
Now…that certainly beats writing out 1000 copies of the same thing, doesn’t it? ;-)
int[ ] student = new int[1000] ;//Then someone enters the marks
for (int cnt=0; cnt<1000; cnt++) System.out.println(student[cnt]);
SidelineNow, 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];
MethodsBasically, 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}
Methodsreturn-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.
MethodsSome 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;
}
MethodsArguments - 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-OverloadingSometimes 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 {statement-list1;
} catch (exception-class1 variable1) {statement-list2; }
Try & catch statement
• used to catch exceptions that are thrown
• allow graceful exit or smooth flow
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”);
}