Lectures
Microsoft Office (Powerpoint) is required for opening these files. Please let me know if you don't have Microsoft Office on your computer.
Lecture 01: Basics of Programming, Using text editors and compilers.
Code:
HelloWorld.java.
Lecture 02: Revisiting the Command line, Anatomy of a Java Program, Types of Program Errors.
Lecture 03: Binary number system, Values, Data types and Variables.
Code:
VariablesValues.java.
A web based
decimal to binary converter.
Take a look at this
ASCII table showing all the characters corresponding to the 256 values of a byte.
Lecture 04: Expressions, Type casting, Operators, if-else and the while loop.
Code:
ArithmeticOperators.java
,
Assignment.java
,
LogicOperators.java
,
IfElse.java
,
WhileLoop.java
,
TypeCasting.java
Lecture 05: switch statement, for loop, break and continue statements, Variable scoping, Strings and static methods
Code:
BreakContinue.java
,
ForLoop.java
,
Switch.java
,
StaticMethod.java
,
Digits.java
,
Digits2.java
,
StringsDemo.java
,
VariableScope.java
Lecture 06: Revisiting Static Methods, Recursion.
Code:
DigitsRecursion.java
,
Fibonacci.java
,
StaticMethod.java
Lecture 07: Revisiting Recursion, Large Programming Example.
Code:
InfiniteRecursion.java
,
LoopConvert.java
,
Power.java
,
MultiplyDigits.java
,
MultiplyDigits2.java
,
MultiplyDigits3.java
,
MultiplyDigits4.java
Lecture 08: Revisiting Debuggers, Introduction to object oriented programming, references and aliasing.
Code:
Rectangle.java
,
RectangleDemo.java
Lecutre 09: OOP Recap, methods, Constructors
Code:
Classroom.java
,
ClassroomDemo.java
,
Rectangle.java
,
RectangleDemo.java
,
RectangleDemo2.java
Lecture 10: Arrays
Code:
Scores.java
,
Scores2.java
,
Histogram.java
,
Chessboard.java
,
Chessboard2.java
Lecture 11: The slides just have the Assignment 1 questions
Code:
LogicalOpTable.java
Lecture 12: Strings, Integer and Double parsing, Program Arguments
Code:
Concat.java
,
StringMisc.java
,
ProgramArgs.java
,
Palindrome.java
Lecture 13: Inheritance, The "Object" class
Code:
Parallelogram.java
,
Rectangle.java
,
Parallelogram2.java
,
Parallelogram3.java
Lecture 14: Midterm Review. The slides only have questions.
Lecture 15: Assignment 2 Review. The slides only have questions.
Lecture 16: OOP Mega Recap. Classes, objects, methods and inheritance
Lecture 17: Polymorphism. "is-a" using class inheritance and interfaces. Abstract methods and classes.
Code:
A.java
,
AbstractDemo.java
,
AbstractShape.java
,
NewCircle.java
,
NewRectangle.java
,
Parallelogram3.java
,
Rectangle.java
,
RectanglePoly.java
,
Shape.java
,
ShapeDemo.java
Lecture 18: Recap of Arrays. Solutions to Practice Problem 1.
Lecture 19: Recap of Strings. Solution to Practice Problem 2.
Lecture 20: Assignment 3 solutions. The slides just have the questions.
Lecture 03 onwards in Office 2003 format:
03
,
04
,
05
,
06
,
07
,
08
,
09
,
10
,
11
,
12
,
13
,
14
,
15
,
16
,
17
,
18
,
19
,
20
Assignments
All students should abide by the honor code policy documented
here.
Discussion on general topics and assignment questions is encouraged. However, students must work individually on their writeup.
Homework Assignment 1 (due Friday, May 23rd)
[To complete this assignment, you may consult the lecture slides and use a computer for programming. Please don't look for answers on the internet.]
Question 1 (3 points):
What are the kinds of errors that can be detected by a program during compile time?
Question 2 (3 points):
Write a program to print the numbers 1 to n and their squares side by side where n is an integer initialized at the beginning of the program. The output should be something like:
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
...
Run it to see if the output is correct.
Copy the code in your answersheet and also submit the java source code separately.
Question 3 (4 points):
Write a program to print the first n fibonacci numbers for a given n.
Fibonacci numbers are defined as f(n) = f(n-1) + f(n-2).
The initial part of the fibonacci series looks like 0, 1, 1, 2, 3, 5, 8, ...
Run it to see if the output is correct.
Copy the code in your answersheet and also submit the java source code separately.
[Please use loops (and not recursion) to solve this problem. We will look at recursion in detail in a later class.]
Homework Assignment 2 (due Monday, June 2nd)
For a given integer n, Write a program to print a triangle like the following with n lines. The figure below shows the result with n=10. Note that the last line should have (only) n *'s.
*
**
***
****
*****
******
*******
********
*********
**********
Run it to see if the output is correct.
Copy the code in your answersheet and also submit the java source code separately.
------------------------------------------------------
Question 2 (4 points):
Convert the following while loop into a recursion.
int z;
int x = 7309;
int num_bits = 0;
z = x;
while(z != 0){
num_bits++;
z /= 2;
}
System.out.println("The number of bits in "+x+" is "+num_bits);
Note that this is not very different from the finding the number of digits in Digits2.java. This again goes to reinforce that decimal digits and binary digits are very similar.
Run it to see if the output is correct. You may use the binary to decimal converter present at http://acc6.its.brooklyn.cuny.edu/~gurwitz/core5/nav2tool.html to verify correctness.
Copy the code in your answersheet and also submit the java source code separately.
------------------------------------------------------
[ The following programming assignment can get longer than 10-15 lines of code because of large if-else-if ladders or large switch-case statement blocks to print strings like "twelve ". However, only a moderate change in the core code logic is required.]
Question 3 (8 points):
a)Use the Digits2.java and DigitsRecursion code snippets discussed in class and modify it so that instead of printing something like "The digits for 7309 are seven three zero nine ."
it prints the following:
"7309 = seven thousand three hundred nine" or
"576 = five hundred seventy six" or
"700 = seven hundred" or
"7012 = seven thousand twelve" or
"6002 = six thousand two" or
Assume that the number supplied is less than 9999.
Run it to see if the output is correct.
Copy the code in your answersheet and also submit the java source code separately.
[You can start with either Digits2.java or DigitsRecursion.java (the modifications to both are similar in complexity). You get 5 points for cracking any one of them successfully and 3 points for cracking the other].
Homework Assignment 3 (due Wednesday, June 11th)
Question 1 (2 points):
Briefly explain the difference between classes and objects.
Question 2 (2 points):
What is main motivation behind "inheritance" in OOP?
Question 3 (3 + 2 points):
The MyInt class given below encapsulates an int. The main method is coded up to take two program arguments,
interpret them as integers and print the result of their addition. Go through the program and notice the use of MyInt objects.
Compile and run the program MyInt (run it using "...java MyInt 5 6" or any two numbers of your choice). Notice that it prints the
correct addition of the integers supplied at the command line.
a) Comment out the 2nd line and uncomment the 3rd line in static method add. Recompile and run the program
as above. Notice the difference in results. Clearly explain the reason for this difference in results.
b) Take a look at the program in MyInt2.java which is similar to MyInt.java. Compile and run it as above.
Explain why its results are errorneous. What's the similarity between the logical errors seen in a) above
and b)?
MyInt.java
class MyInt
{
int data;
MyInt(int x){
data = x;
}
public String toString(){
return "MyInt: "+data;
}
static void add(MyInt i1, MyInt i2){
//Comment one of the two statements below.
i1.data = i1.data + i2.data;
//i1 = new MyInt(i1.data + i2.data);
}
public static void main(String args[]){
MyInt i, j;
i = new MyInt(Integer.parseInt(args[0]));
j = new MyInt(Integer.parseInt(args[1]));
System.out.println(i);
System.out.println(j);
add(i, j);
System.out.println(i);
}
}
MyInt2.java
class MyInt2
{
static void add(int i1, int i2){
i1 += i2;
}
public static void main(String args[]){
int i, j;
i = Integer.parseInt(args[0]);
j = Integer.parseInt(args[1]);
System.out.println(i);
System.out.println(j);
add(i, j);
System.out.println(i);
}
}
Assignment 4 (due Saturday, June 14th)
Question 1 (3 + 3 points):
Take a look at the given program Mean.java. Currently, it takes a single argument (either 'arithmetic', 'geometric' or 'harmonic'). It first creates a double array of size 5 and and initializes the array with randomly selected numbers between 0 and 1. It then prints all the numbers.
Mean.java
class Mean
{
public static void main(String args[]){
double[] numbers;
numbers = new double[5];
// Math.random() returns a random double from 0.0 to 1.0
for(int i = 0; i < numbers.length; i++)
numbers[i] = Math.random();
// Print the numbers
for(int i = 0; i < numbers.length; i++)
System.out.println(i+":\t"+numbers[i]);
System.out.print("Mean: "+mean(numbers, args[0]));
}
static double mean(double[] nums, String which_mean){
if(which_mean.equals("arithmetic"))
return arithmeticMean(nums);
else if(which_mean.equals("geometric"))
return geometricMean(nums);
else
return harmonicMean(nums);
}
static double arithmeticMean(double[] nums){
// TODO: write code to calculate the arithmetic mean
// of the numbers in nums and return the result.
return 1.0;
}
static double geometricMean(double[] nums){
// TODO: write code to calculate the geometric mean
// of the numbers in nums and return the result.
return 2.0;
}
static double harmonicMean(double[] nums){
// TODO: write code to calculate the harmonic mean
// of the numbers in nums and return the result.
return 3.0;
}
}
To display the mean, the program calls a static method depending on the program argument to calculate the specified mean of the numbers.
a) Write the code to calculate and return the arithmetic, geometric and harmonic means of the given array in their place holders.
Arithmetic mean of x1, x2, x3,... = (x1 + x2 + x3 +...)/n
Geometric mean of x1, x2, x3,... = (x1*x2*x3...) raised to the power (1/n)
Harmonic mean of x1, x2, x3,... = n/(1/x1 + 1/x2 + 1/x3 +...)
Use the static method
double Math.pow(double a, double b)
to calculate a raised to the power b.
Run to program and see if different values of the means are printed with the different program arguments.
Trivia: Note that harmonic mean <= geometric mean <= arithmetic mean in all cases.
b) Put the three mean calculating methods as non-static methods in three different classes. Name the classes Arithmetic, Geometric and Harmonic. Change static method mean() such that it directly accepts an object of one of the above types as the second argument and uses it to calculate the appropriate mean. In main() use args[0] to appropriately construct an object of one of the above classes to pass to mean(). In some sense, this object is your "calculator" object which specifies 'how' should the mean be calculated.
At the end, the effect should be the same as the original program.
Trivia: The above technique of using polymorphism with classes containing no member variables is also known as "delegation". It has been promoted extensively by Microsoft's C# programming language which is a language similar to Java.
Submit Mean.java, Arithmetic.java, Geometric.java and Harmonic.java via e-mail. Mean.java should have a comment at the top showing your name and email address. No other documents need to be submitted.
Assignment Solutions (code only)
Assignment 1:
Squares.java,
Fibonacci.java
Assignment 2:
Triangle.java,
WhileLoopConvert.java,
ImprovedDigits2.java,
ImprovedDigitsRecursion.java
Assignment 4:
Mean.java,
Arithmetic.java,
Geometric.java,
Harmonic.java
Assignments are due
8:00pm on the due date. You get 50% credit if you submit by 8:00pm next day, 25% credit if you submit by 8:00pm next to next day and 0% credit afterwards. Please meet me (or send me e-mail) if you face problems with the assignments.
Midterm Exam with Solutions
[
Office 2007 |
Office 2003 ]
Final Exam with Solutions
[
Office 2007 |
Office 2003 ]
Practice Problem 1
Consider a class List. An object of class List is a "container" and can contain as many integers as you want.
List should support the following methods:
void add(int x) => should add x to the list
boolean contains(int x) => should return true if x is in the list
void remove(int x) => if x is present in the list then remove x from the list.
Use arrays to implement this class. Since creating an array fixes its limit, make a List constructor which takes as parameter the maximum number of ints you will ever store in the List.
List(int size) => construct a list with maximum size
Hint: Use a boolean array to keep track of which slots are free and which slots are occupied in the int array.
The above should give you a practice in basic usage of classes, member variables and methods. Note how you were able to ENCAPSULATE the arrays in a List class giving it more meaning than its contents.
Using List create a child-class Set which doesn't keep duplicate integers.
Thus, the add() method now adds an integer to the Set only if its not already present in the Set, otherwise it just ignores it.
The semantics of the contains() and remove() methods remain the same as above.
Note how INHERITANCE helps you reuse the List class to its fullest. Compare the number of lines of code in the two classes. Also compare the conceptual complexity of the Set class given that you have the understanding of the behavior of the List "encapsulation".
Practice Problem 2
Copy paste your List and Set implementations from Practice Problem 1 into another folder. We will buildup from these.
The objective is to make List and Set general enough that they can store _any_ object and not just integers. Thus, modify the code so that the methods supported by List and Set are
void add(Object o)
boolean contains(Object o)
void remove(Object o)
To check for equality in contains() use Object's method equals(Object). The equals() implementation in Object returns true if the provided alias points to the same object.
Make two classes Animal and Plant both of which encapsulate a string containing the name of the Animal or Plant.
Override the method toString() (inherited from Object) of Animal and Plant to differentiate their behavior in some way.
add a method in class List called
void printAll()
which prints all the objects present in the List. Note that a System.out.println(o) where o is the object will invoke the toString() method on the object and print out the returned string.
In a seperate main(), create instances of Animal and Plant objects with different names and add them to your List or Set. Call printAll() on the List to see it automatically using the correct implementation of toString() from the Animal and Plant classes. This demonstrates polymorphism using an Inheritance based "is-a" relationship (Animal and Plant inherit from Object).
Practise Problem Solutions
Practise Problem 1:
List.java,
Set.java
Practise Problem 2:
List.java,
Set.java,
Animal.java,
Plant.java,
Rectangle.java
May 19th:
We have moved to blackboard for all course content, announcements and calendar. I have also created a discussion group for us to discuss topics on blackboard.
June 10th:
I have posted another practice problem for you on polymorphism. We will take up a solution to this problem in class on Thursday or Friday in a Programming Spree session.
Give it a try (its optional and not graded).
June 9th:
You can find Pactice Problem 1 with the assignments. Its non-trivial in complexity but a really thorough exercise in the OOP concepts we have covered so far.
Give it try (its optional). We will take a look at its solution on Wednesday in a Programming Spree session.
Assignment 3 is up. Its due on June 11th.
June 6th:
Assignment 2 is graded. You should be able to see your grade on blackboard.
June 5th:
Your midterm has been graded. You should be able to see your grade on blackboard.
June 2nd:
Lecture 13 slides and demo code are up. Please let me know if you are having problems with understanding parts of OOP. We have quite a few lectures available... we can revisit some topics.
May 30th:
Lecture 12 slides and demo code are up.
Mid-term Exam: The syllabus for the mid-term exam is all the stuff covered before object oriented programming. Don't panic... study the lecture slides, example code and go through the book modules once.
Make a list of all the doubts you face while you are studying and we should be able to take them up in class.
Update on Assignment 2
In question 2, the "Run to see if the output is correct." part involves trying some numbers with your program and looking at the website link given to check if the number of binary digits match. The verification part is for your satisfaction only. I will grade you on your program alone (and not the verification you do as instructed above).
Please consider using the methods given below for Question 3. It is not compulsory to use these methods. I have given them to you to give you an idea of the approx. number of lines of code expected. Please don't write 99 case statements. Note that besides these methods, you only need about 10 lines of changes per program. You may modify the methods supplied below but please don't increase the number of lines significantly. On the other hand, I will really be interested if somebody significantly shortens the number of lines :).
static void printTeens(int x){
if(x < 10){
printDigit(x);
return;
}
switch(x){
case 10:
System.out.print("ten ");
break;
case 11:
System.out.print("eleven ");
break;
case 12:
System.out.print("twelve ");
break;
case 13:
System.out.print("thirteen ");
break;
case 14:
System.out.print("fourteen ");
break;
case 15:
System.out.print("fifteen ");
break;
case 16:
System.out.print("sixteen ");
break;
case 17:
System.out.print("seventeen ");
break;
case 18:
System.out.print("eighteen ");
break;
case 19:
System.out.print("nineteen ");
break;
default:
System.out.print("* ");
}
}
static void printSecond(int x){
switch(x){
case 0:
//System.out.print("zero ");
break;
case 1:
System.out.print("* ");
break;
case 2:
System.out.print("twenty ");
break;
case 3:
System.out.print("thirty ");
break;
case 4:
System.out.print("forty ");
break;
case 5:
System.out.print("fifty ");
break;
case 6:
System.out.print("sixty ");
break;
case 7:
System.out.print("seventy ");
break;
case 8:
System.out.print("eighty ");
break;
case 9:
System.out.print("ninety ");
break;
default:
System.out.print("* ");
}
}
static void printDigit(int x){
switch(x){
case 0:
//System.out.print("zero ");
break;
case 1:
System.out.print("one ");
break;
case 2:
System.out.print("two ");
break;
case 3:
System.out.print("three ");
break;
case 4:
System.out.print("four ");
break;
case 5:
System.out.print("five ");
break;
case 6:
System.out.print("six ");
break;
case 7:
System.out.print("seven ");
break;
case 8:
System.out.print("eight ");
break;
case 9:
System.out.print("nine ");
break;
default:
System.out.print("* ");
}
}
May 29th:
Lecture 11 slides and demo code are up. The slides contain the Assignment 1 questions only... its of use only if you are working on making a collection :).
The demo code contains only LogicalOpTable.java. Running the example programs with a debugger will greatly improve your understanding of the control flow of the program, esp. recursion.
May 28th:
Lecture 10 slides and demo code are up. Please keep a note of snippets of code that you have doubts on and we will discuss that in class. You can also email me about your doubts... we should be able to formulate a problem out of it which we can discuss in class.
Assignment 1 graded. You should be able to see your score on blackboard. I will return your answer sheets in class tomorrow and discuss the assignment. We will also take a look at the performance of the class as a whole and your relative scores.
May 27th:
Lecture 9 slides and demo code are up.
Homework Assignment 2 is up. Due by 8:00pm, June 2nd.
50% credit if submitted by 8:00pm, June 3rd.
25% credit if submitted by 8:00pm, June 4th.
0% credit if submitted after 8:00pm, June 4th
May 23th:
Lecture 8 slides and demo code are up. Please go through the concepts discussed (esp. aliasing) thoroughly. If you have problems in specific areas let me know after class.
May 22nd:
Lecture 7 slides and demo code are up. The example code that we saw today in class is possibly the most complex piece of code we will be looking at in this class. It is basically for you to carefully observe the use of variables with loops and recursion to obtain a desired outcome. Also take a look at the changes made to the existing program to obtain a desired result.
Study that example well. However, I assure you that you will not be asked to produce programs of such complexity.
Reading Assignment 3: Read Module 3; you may skip the break with labels part of the module. Content in Module 3 (excluding stuff not directly related to what we have covered in class) is eligible for exams and assignments.
Note on Assignment 1: Please make sure you read the question once more once you have finished writing the solution. Make sure that you have followed instructions properly.
If I have asked a variable to be initialized in the beginning of a program, just initialize it to some reasonable value. Also, please don't submit infinite loops :).
As discussed in class, we will have a mid-term exam in class on June 4th. Also, we will have our final exams at 8:00am (3 hours) on June 16th. It seems that I don't enjoy the flexibility of shifting this one around... so I guess we have to live with this :(.
May 21st:
Please note that I am not looking for anything more than 10-15 lines of code in the assignments.
I don't need you to comment every thing in code. However, I do want you to be practical and in practice people generally comment just the stuff which is not directly intuitive.
You are free to use your own naming conventions.
There are no penalties for bad commenting, bad variable naming or bad indentation. These things come with time, everybody generally develops their own style first and then learns to shift from one style to another in a practical environment. For now, I am not concerned about programming style.
Lecture 6 slides and demo code are up.
May 20th:
Lecture 5 slides and demo code are up.
We will take a look at static methods again. Please go through the demo code examples along with Digits and Digits2 examples. They are good examples to learn about how to solve a problem first, create an algorithm and then use Java to create a program.
Homework Assignment 1 is up. The due date is 8:00pm on Friday, May 23rd.
You get 50% credit if you submit by 8:00pm on Saturday, May 24th.
You get 25% credit if you submit by 8:00pm on Sunday, May 25th.
There is no credit for submissions after 8:00pm Sunday.
May 19th:
Lecture 4 slides and demo code are up.
Some of you faced problems opening Lecture 3 slides. That's because your Office software version is older (2003) whereas those files were created using Office 2007. I have uploaded links to both formats so that you can choose depending the Office software you have.
You may be able to get the most recent Office software for free (or a very low price) from UNC ITS.
May 16th:
Lecture 3 slides and the demo code are up for download.
Notes on usage of command line:
- You can place the java/class files you are working on anywhere on the system. Just make sure that you go the same folder by the command line and the file manager before starting to work on the files.
- Please make sure that the file that you are editing is the same file you are compiling at the command line. One way to make sure is to use the command 'type' on windows cmd.exe. 'type (filename)' will print the contents of the text file on your computer. (The equivalent command on the mac is 'cat (filename)'. So try 'type HelloWorld.java' where you have been running 'C:\Program Files\.....\javac HelloWorld.java'. Make sure that this is the same file that you are editing and saving.
- Make sure that you get the case (uppercase, lowercase alphabets) correct when you are trying to match the java filename to the classname. Unless otherwise specified, computers in general are case sensitive.
May 14th:
Lecture 2 slides are up for download.
There is no class on May 15th. Classes resume on May 16th.
Homework Exercise (not an assignment; will not be graded): Read Module 1 of the text book over the next 3 days.
May 13th:
I have 12 (different) books on Introductory Java Programming in my office. If you want one for free you can come and get one during office hours. It will be nice if you can share the books among your self for the purpose of the course. After the course, they are yours to keep.
Lecture 1 is up for download.
May 9th:
Hi! The website is slowly beginning to take shape. I will be adding content and updating you as it progresses.