Java Programming II


CSc - 1302

Spring - 2018

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.

Student Evaluation of This Lab >



Final: Coding Test

Rules are simple:

  1. Google all you want.

  2. If you are using a code from the Internet, add the link to your code as a comment. (Otherwise, it is plagiarism.)

  3. No communication via Facebook, E-Mail, IM, etc.

  4. 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.



Review: Text Manipulation

Starting point -->

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.

  1. Download the jar file (jsoup-1.11.2.jar )

  2. 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 + 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


Algorithms: Back to Basics



  • 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 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 =




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


  • Implement a method that calculates factorial for a given integer in three versions:

    1. factorial_Recursive1: Head recursive

    2. factorial_Recursive2: Tail recursive.

    3. 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:

    1. fibonacci_Recursive: Head recursive

    2. 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.draw1(8, 500, 500, 700);


[GUI: Graphical User Interface]

Starting point -->

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:

  1. 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.

  2. 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


Let's start an application from the scratch together. (Main architecture, a few buttons, a text-field, and a working panel.)


Continue by adding the rest of the buttons, and their functionalities.


Thirds (Homework)

Add the following properties to your app:

  1. Haven't added all the buttons?

      • All digits, 4 operators (+,-,*,/), and the equal sign (=) should be added and they must be working correctly.

  2. Text size in the text-field is very small!

      • Use a larger font.

  3. Buttons are ugly!

      • Change the color of the button.

  4. User friendly calculator.

      • Keep the buttons in the order that it looks like a real calculator.

  5. Doesn't look like your own app?

      • Add a small icon to the title-bar of your frame. Make it yours!

  6. 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?


[Networking: Socket Programming]


"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 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.

Create TWO projects, with NO packages (use default), and create ONE class in each project; and

Copy the code from my repository (on the right) into your classes.

First, Analysis of the Code


Socket s = new Socket("localhost", 1111);


while (!str1.equals("*")) {

str1 = br.readLine();



str2 = din.readUTF();

System.out.println("SERVER: " + str2);





ServerSocket ss = new ServerSocket(1111);

Socket s = ss.accept();


while (!str1.contains("*")) {

str1 = din.readUTF();

System.out.println("CLIENT: " + str1);

str2 = br.readLine();








try to modify the code so that:

  1. The message is not limited to one line. All the input will be sent over the socket only if it ends with "<" character.

  2. The connection will be closed when "*" character is transmitted.

  3. Make each side responsible for writing out their own title, "Server:" or "Client:".


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

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)


[OOP: Review]

Solution: will be available after the due date.


is a small box that moves around when the user hits the arrow keys.


  • 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.


Start from here -->


[OOP: Interfaces]


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

Want to see different perspectives?

  • A great explanation for understanding interfaces: [Here @ Quora]

  • Another good discussion [Here @ Stack Exchange]

  • A not-very-impressive article about interfaces: [Here @ Oracle]

Why interfaces?

  1. A class CANNOT extend more than one class. But it can implements multiple interfaces.

  2. 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.

  3. 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.

  4. 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.)

  5. 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.)

  6. and more ... !



[OOP: customize objects' properties!]

Solution (Lab 7)-->


A closer look at polymorphism

Let's review the idea of polymorphism with a simple example. Suppose we have a class Landrover that extends SUV.

What is the difference between the two lines below?

  • Landrover myLR = new Landrover();

  • SUV mySUV = new Landrover();



[OOP: more on Polymorphism!]

Solution (Lab 6) -->

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.



[OOP: Inheritance, Encapsulation, Polymorphism]


  • 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 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.


"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.

Polymorphic Objects


Let's create a project that manages orders of a pizzeria.

The details of the requirements are shown in the right.


Complete Bucket and ChickenWings in the same way we practiced on Pizza and PepperoniPizza.

Due: Thursday, Feb 15 2018, by midnight.



[Object Oriented Programming: Classes]

HW (Due: (04-Feb)) -->

Practice: Shapes -->

  • In near future, we will learn about Objects, classes, Inheritance, Encapsulation, Interfaces, Abstraction, polymorphism.


  • 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.)


  1. Create a class for Shape , as shown on the right.

  2. Construct an object of type Shape , once with the parameterless constructor, and once using the constructor with the parameter name = "circle" .

  3. Create another class, Circle , which is a particular shape, so it inherits from Shape .

  4. Note that without implementing the method display() , we can use it for Circle objects.

  5. Can we adjust display() ? Let's use the annotation @Override .

  6. Should we allow objects of type Shape be created? (Maybe no! But why and how?)

  7. Can you create a new class, called Rectangle very similar to Circle ?

What does it mean?

To see what we've practised during this lab click here.


  1. Find the code in


[Basics: 2D Arrays]

  • Java naming conventions:

    1. Class names: always begin with a capital letter. Ex: - -

    2. Variables: must start with lowercase. Ex: int i; - double salary; - String[] names;

    3. 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;

    4. Methods: same as lowerCamelCase.

    5. 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 -->


[Basics: Arrays Manipulation]

[1] How arrays work?

Oracle: Arrays | Geeksforgeeks: Arrays |

  • 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};

[2] Let's practice slightly more complex tasks.

Today's practice -->



[1] Java VM: compile, interpret and run.

> .class, .java

> java -version, javac, 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

  1. Text editors: Vim, Notepad, Notepad++, gedit, Word Office, Libre Office, etc.

  2. Simple IDEs: Geany, Code::Blocks, DrJava,

  3. Advanced IDEs: Eclipse, Netbeans, IntelliJ

[4] Java Documentation:


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)

[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

[] Why Java? (1)(2)(3)(4)
[] Install Java on Ubuntu [Here][] Install Java on Windows | Mac | Linux | Solaris. [Here][] Install Eclipse IDE (Oxygen) on Ubuntu. [Video]
[] Add the drag-and-drop Window Builder to Eclipse [Here] [Video]