Have questions?
Tutoring center: Fridays from 11:00 to 13:00, @Sports Arena - Room #107
E-Mail: aahmadzadeh1[-at-]cs[-dot-]gsu[-dot-]edu
Office hours: Please email me to find an appropriate time slot.
LABS
LAB XIV
Final: Coding Test
Rules are simple:
Google all you want.
If you are using a code from the Internet, add the link to your code as a comment. (Otherwise, it is plagiarism.)
No communication via Facebook, E-Mail, IM, etc.
No collaboration with your classmates.
What to submit:
One main file (including all your methods and your main method).
When to submit:
Submission directory will be closed at 2:40 pm. Make sure you keep enough time for submission.
Do we know enough to:
> mine data
> pre-process it
> get some sort of knowledge out of it?
To run the given code, you need to have jsoup as the external library.
Download the jar file (jsoup-1.11.2.jar )
Add it to your project as an external library:
eclipse > project > properties > java build path > tab:libraries
Query the word "Java" for example:
MyGoogleSearch.getTitleResults("Java", 3);
The results would be somehow (not exactly) similar to this:
> [Download Free Java Software, java.com: Java + You, Oracle Technology Network for Java Developers | Oracle ...]
We are only interested in words for our task but as you see, there are a lot of other characters such as '+', ':', '...' , etc. and you should expect any other symbols too.
So, we need to process the input.
1. Clear up the Text
String[] getWords(String input);
Example input: This " IS \ + a baD 22 __E-xample
Example output: {this,is,a,bad,example}
List<String[]> getAllWords(String[] phrases);
Example input: { {This " IS \ + a baD __E-xample},{BAD & exAMPLE},{yeT 45 OnE #^ more bAd} }
Example output: [ {this,is,a,bad,example}, {bad,example} , {yet,one,more,bad} ]
2. Make It Simple
String[] meltList(List<String[]> inList);
Example input:[ {this,is,a,bad,example}, {bad,example} , {yet,one,more,bad} ]
Example output: { this,is,a,bad,example,bad,example,yet,one,more,bad }
3. Calculate the Frequency of the Words
Map<String, Integer> computeTF(String[] allWords);
Example input: { this,is,a,bad,example,bad,example,yet,one,more,bad }
Example output: { <this,1>, <is,1>, <a,1>, <bad,3>, <example,2>, <yet,1>, <one,1>, <more,1> }
4. Make 2 Maps comparable
void crossUpdate(Map<String, Integer> source, Map<String, Integer> another);
Example input:
map1 : { <this,1>, <is,1>, <a,1>, <bad,3> }
map2 : { <this,1>, <learn,2>, <is,2>, <example,1> }
Example output:
map1 : { <this,1>, <is,1>, <a,1>, <bad,3>, <learn,0>, <example,0> }
map2 : { <this,1>, <learn,2>, <is,2>, <example,1>, <a,0>, <bad,0> }
5. Get the Similarity of the Results (Method already implemented)
double cosineSimilarity(Map<String, Integer> map1, Map<String, Integer> map2)
Example output:
0.78 <- very similar
0.05 <- not similar
Warm-up
Write a simple method to sum the elements of a given array.
sum_Iterative: Write a simple method that for a given n sums up all the positive integers from 1 through n (inclusive).
sum_Recursive1: Re-write the previous function using recursion.
sum_Recursive2: Can we make it slightly faster?
Which of the above 3 implementations are faster? (Use the given code in Main.java to test them with different-size inputs.
int[] arr = new int[] {11,12,13,14,15,16,17,18,19}
> sum(arr) = 11 + 12 + 13 + ... + 19
---------------------------------------------------
int n = 10
sum(n) = 1 + 2 + ... + 10
---------------------------------------------------
int n = 3
sum(3) =
3 + sum(2)=
3 + 2 + sum(1) =
3 + 2 + 1 =
6
---------------------------------------------------
Resursion:
A recursive function always have:
The base case: "returns a value without making any subsequent recursive calls. It does this for one or more special input values for which the function can be evaluated without recursion." [here]
The recursive step: "is the central part of a recursive function. It relates the value of the function at one (or more) input values to the value of the function at one (or more) other input values. Furthermore, the sequence of input values values must converge to the base case." [here]
Factorial is an operation
(notation: ! )
n! = 1 X 2 X 3 X ... X n
Practice:
Implement a method that calculates factorial for a given integer in three versions:
factorial_Recursive1: Head recursive
factorial_Recursive2: Tail recursive.
factorial_Iterative: Iterative.
Compare their execution time for different inputs.
What is the largest input each of those functions can handle?
0: 1
1: 1
2: 2
3: 6
4: 24
5: 120
6: 720
7: 5040
8: 40320
9: 362880
10: 3628800
11: 3.99168E7
12: 4.790016E8
13: 6.2270208E9
14: 8.71782912E10
15: 1.307674368E12
16: 2.0922789888E13
17: 3.55687428096E14
18: 6.402373705728E15
19: 1.21645100408832E17
20: 2.43290200817664E18
Fibonacci sequence
fib(n) = fib(n-1) + fib(n-2)
"... the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two". [Wikipedia]
Practice: (at home)
Implement a method that calculates the n-th fibonacci number:
fibonacci_Recursive: Head recursive
fibonacci_Iterative: Tail recursive.
Compare their execution time for different inputs.
What is the largest input each of those functions can handle?
The rabbit jump problem:
Problem: A rabbit wants to go from point A to point B. Each move of the rabbit is a jump as long as half of the remaining distance. Can the rabbit ever get to the point B?
rabbitJump_Iterative: Write a method to calculate the sum of the jumps after n jumps.
rabbitJump_convergence: Is there something in Calculus that can help you improve this method?
Do you want to be exempt from the final lab exam?
You need to write a function that plots golden-ratio rectangles recursively.
No need to worry about graphics. They are all taken care of for you.
Try the method drawH in the class AnimatedRecursion as an example.
Implement drawGoldenRatio_Recursive and drawGoldenRatio_Recursive methods.
How to run the method draw() ?
AnimatedRecursion.init();
AnimatedRecursion.draw1(8, 500, 500, 700);
Why Swing?
The future of Java GUI is in JavaFX apparently, but learning AWT and Swing is a good practice to understand how different applications and the OS itself operate.
Application or Applet?
Desktop applications are not growing, to say the least. Today's apps are all running on cloud because they should be available across platforms and devices. Java applets run on browsers, nice, but unfortunately they are already outdated! Yet we try to learn these technologies because:
It is a good practice to start with simple things like a small applet or app. Newer technologies are rarely significantly different than the old ones.
Schools have never been the first to catch up with the latest technologies. So, educate yourself if you are passionate about a new technology.
All about Swing - By Oracle
All about Applets - By Oracle
A very comprehensive tutorial on programming GUI
First
Let's start an application from the scratch together. (Main architecture, a few buttons, a text-field, and a working panel.)
Second
Continue by adding the rest of the buttons, and their functionalities.
Thirds (Homework)
Add the following properties to your app:
Haven't added all the buttons?
All digits, 4 operators (+,-,*,/), and the equal sign (=) should be added and they must be working correctly.
Text size in the text-field is very small!
Use a larger font.
Buttons are ugly!
Change the color of the button.
User friendly calculator.
Keep the buttons in the order that it looks like a real calculator.
Doesn't look like your own app?
Add a small icon to the title-bar of your frame. Make it yours!
Easy to get an error?
User should not be able to start with an operator. (Erase if entered before the input.)
User should not be able to end with an operator. (Erase if entered at the end of the input.)
User should not be able to use more than one operator for each calculation. (Keep the first operation only.)
Preceding zeros should be erased.
Still user can get some error?
Create a small text area at the bottom of your app, and whenever the input is bad, show a message like "Bad Input!" and erase the user's input.
What to submit:
A runnable JAR file (that works across platforms: Linux/Windows/Mac)
How to create a runnable JAR file?
Visit this page.
LAB X
[Networking: Socket Programming]
Socket
"A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to." [Oracle Doc - Java 8]
Socket and ServerSocket are the classes we are going to use by importing java.net class. Each of these two classes implements one side of a two-way connection.
Usually one class is used on one machine to listen to the requests (server) and another class is used on all other machines (clients) that want to stablish a connection to that machine.
In this lab, we practice this by keeping both ends of the connection in one machine.
First, Analysis of the Code
CLIENT
Socket s = new Socket("localhost", 1111);
...
while (!str1.equals("*")) {
str1 = br.readLine();
dout.writeUTF(str1);
dout.flush();
str2 = din.readUTF();
System.out.println("SERVER: " + str2);
}
dout.close();
s.close();
SERVER
ServerSocket ss = new ServerSocket(1111);
Socket s = ss.accept();
...
while (!str1.contains("*")) {
str1 = din.readUTF();
System.out.println("CLIENT: " + str1);
str2 = br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
Second,
try to modify the code so that:
The message is not limited to one line. All the input will be sent over the socket only if it ends with "<" character.
The connection will be closed when "*" character is transmitted.
Make each side responsible for writing out their own title, "Server:" or "Client:".
Third,
Can you communicate between different machines?
Some tricks you may need to know:
Compile your java file: (this will compile and create a binary file from your code.)
javac MyCleint.java
Run your java program: (this will execute the main method of your program)
java MyClient
In case you need to terminate your running code forcefully:
Use Ctrl+c (send SIGINT) or Ctrl+z (send EOF)
Kill an orphan process to re-use the port:
kill -9 16543 (on Unix-base systems)
Taskkill /PID 16543 /F (on Windows)
MrWalker
is a small box that moves around when the user hits the arrow keys.
Talk:
Run the code that does everything at one place.
Make a Walker (abstract) and a SimpleWalker that does the same thing.
Let's improve the SimpleWalker, by adding an interface, called ICustomizable, that helps making a few things.
You only need to follow the UML (class) diagram on the right.

Interface: "... is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. -Oracle
Note: "Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces" -Oracle
Inheritance keywords:
MyClass extends AnotherClass
MyClass implements MyInterface
MyInterface extends AnotherInterface
Why interfaces?
A class CANNOT extend more than one class. But it can implements multiple interfaces.
Very often, objects do not share a lot (to provide superclass for them) but they may have similar behaviour. Interfaces, clarify what behaviours of objects are shared, although they way they are implemented could be unlike one another.
Using interfaces, we can put a set of methods in a bag, and let others use them as long as they implement how they work.
Using interfaces we can put a set of constants in a bag, and let others access them. (Any fields in an interface are automatically static and final.)
For large projects with many developers involved, very often an interface is provided for different teams, so that they all can agree to a "contract" that spells out how their software interact to keep all sides of the project in line with the documentation, without having the actual code written. (Knowing the signature is enough.)
and more ... !
Let's design a small application that simulates a small component of PAWS, where different courses can be created, students can add or drop several courses, and their GPA will be calculated. Similarly, perhaps we can expand our application to include instructors too. They can take some courses to teach, and be evaluated for what they did.
What is a Polymorphic object?
What is Polymorphism in OOP? (read more here.)
What do we mean by public in public class Shape ? How about private in private int age ? (Oracle ref.)
What is encapsulation?
Polymorphism:
"Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object."
"Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object."
- source: here.
Encapsulation:
"Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming."
- source: here.
LAB IV
[Object Oriented Programming: Classes]
In near future, we will learn about Objects, classes, Inheritance, Encapsulation, Interfaces, Abstraction, polymorphism.
Today:
Object: A java application is built by small pieces called objects. (e.g., in String name , 'name' is an object.)
Class: A blueprint from which an object may be created is a class. (e.g., in String name , 'String' is a class in Java.
Inheritance: Each class inherits the state and behaviour of their superclasses (parents).
Encapsulation: Lets us close any extra doors to our code (for security, maintenance, and coupling reasons.)
Steps:
Create a class for Shape , as shown on the right.
Construct an object of type Shape , once with the parameterless constructor, and once using the constructor with the parameter name = "circle" .
Create another class, Circle , which is a particular shape, so it inherits from Shape .
Note that without implementing the method display() , we can use it for Circle objects.
Can we adjust display() ? Let's use the annotation @Override .
Should we allow objects of type Shape be created? (Maybe no! But why and how?)
Can you create a new class, called Rectangle very similar to Circle ?
To see what we've practised during this lab click here.
Homework:
Find the code in
LAB III
[Basics: 2D Arrays]
Java naming conventions:
Class names: always begin with a capital letter. Ex: Main.java - String.java - MyClass.java
Variables: must start with lowercase. Ex: int i; - double salary; - String[] names;
If there are multiple words in the name, then you need to use Uppercase for starting letters for the words except for the starting word. This is called as lowerCamelCase. Ex: String myName - double salaryOfManagers;
Methods: same as lowerCamelCase.
Constants: All caps. Ex: static final double MAX_SALARY_2018;
Packages: (Let's try it.)
What are packages for?
How do they affect your project directories?
How do they affect your classes?
Please keep your code clean [ctrl + shift + f]
Today's practice -->
Download this -->
LAB II
[Basics: Arrays Manipulation]
Declaration only
int[] arr1;
Declaration + creation + initialization with zeros
int[] arr1 = new int[2];
Declaration + creation + initialization with 5 and 6
int[] arr3 = new int[]{5,6};
LAB I
[Review]
[1] Java VM: compile, interpret and run.
> .class, .java
> java -version, javac MyClass.java, java MyClass
A program has to be converted to a form the Java VM can understand so any computer with a Java VM can interpret and run the program. Compiling a Java program means taking the programmer-readable text in your program file (also called source code) and converting it to bytecodes, which are platform-independent instructions for the Java VM. (Source: Oracle)
[2] Java SDK, JDK, JRE
See the Oracle illustration for more details.
SDK: Software Development Kit.
JDK: Java Development Kit. This is actually the SDK for Java. It contains tools such as java, javac, javah, javadoc, jar, etc.
JRE: Java Runtime Environment. It provides the minimum requirements for executing a Java program. It contains: Java Virtual Machine, core classes,
[3] IDE
Integrated Development Environment
Text editors: Vim, Notepad, Notepad++, gedit, Word Office, Libre Office, etc.
Simple IDEs: Geany, Code::Blocks, DrJava,
Advanced IDEs: Eclipse, Netbeans, IntelliJ
[4] Java Documentation:
javadoc
Javadoc is a tool for generating API documentation in HTML format from doc comments in source code. It can be downloaded only as part of the Java 2 SDK. (Source: Oracle)
Why is this important?
Simple Example: Using javadoc tags
Example of Javadoc output: Oracle > LinkedList
[5] A good programming environment:
Some advices
As your code grows, it gets easier and easier to get lost between different classes, methods, and lines of the code. We need to be on top of our environment.
Use your OS wisely. Different workstations for different parts of our brain.
Use your IDE wisely. Different windows for different projects.
Use your entire screen.
[6] Some good programming habits:
Step by step programming. Divide the task into a set of extremely simple tasks and fight them one by one. Make sure one step is completely done before you move to the next step.
Comment your ideas. Having enumerated comments describing what should be coded can help you have the concentration you always wanted. (Remove them later or turn them into documentation.)
Do not be obsessed with "the right way". The hardest part is usually having "an idea". Better ideas usually come later. (//TODO)
Minimize the use of mouse/touch-pad. Learn the basic short-keys to speed up your performance.
[7] What have you learned about Java programming?
Let's review what you have learned in 1301, first.
(primitive) Data Types:
int, short, long, byte, float, double, boolean, char, ... .
Built-in Objects:
Integer, Double, String (API), Collections, ... .
Basic I/O operations: [java.util.*;]
System.out.print("What's up?");
String name = in.nextLine();
int age = int.nextInt();
Blocks and scopes:
{... {int k = 0; } ... }
Collections:
List {Vector, ArrayList, LinkedList},
Set {TreeSet, HashSet, LinkedHashSet},
Map {TreeMap, HashMap, LinkedHashMap}
Classes and Interfaces (<implements>)
Class inheritance (<extends>) and hierarchy
Access level modifiers (doc):
public, protected, <no modifier>, private
Abstract or Concrete classes, and final classes
static and non-static methods/variables