Java Exercise: Problems in Searching

Array is a fundamental data structure in Java programming language. It stores a fixed number of items, and we can use index to access each element.

The following 7 exercises are about searching and sorting an array.

Screen Shot 2018-04-17 at 20.26.36
Exercise 1

To find the occurrence of a number, I used a for loop to go through the array. Using the parameter key, I can use a if statement to check if the desired element is found and increment the integer variable “occurrence.”

Screen Shot 2018-04-17 at 20.27.17
Exercise 2

As the description suggests, we need to find the duplicate elements. Given an unsorted array, I used a inner loop, which starts from the index+1 of the outer loop. In the inner loop, is duplicate element is found once, the program will print the duplicate elements. This prevent the program to print the same duplicate element for more than one times (e.g. if 3 appears 2 times, the program won’t print two “3”s).

Screen Shot 2018-04-17 at 20.27.28
Exercise 3

To find the element which appears maximum times, I used an inner loop again to record the occurrence of each number. By comparing the temporary occurrence to the former maximum value, I can record that index and return it. Note that any time a number with the same max occurrence is found, the index will be overwritten.

Screen Shot 2018-04-17 at 20.27.38
Exercise 4

Since one element is missing in the sorted array, I just calculated the desired sum by incrementing a variable inside the loop. Then, I subtract the sum of the array elements from the desired sum (with the missing one), and the missing element is shown.

Screen Shot 2018-04-17 at 20.27.48
Exercise 5

For this exercise, I still used two loops with the second one starting from the index+1 of the first loop. In the inner loop, I used an if conditional statement: if the sum equals the desired value, the two elements are returned. I also found out that the flag “found” is useless because I print every pairs each time I checked them. Also, since the inner loop begins at i+1, there will be no duplicated pairs.

Screen Shot 2018-04-17 at 20.28.00
Exercise 6

To separate the even and odd numbers, I create a new array “separated,” which has the same length as the argument. The mechanism is that each time I find an even number, I put it from the beginning, and each time I find an odd number, I put it from the last spot. I use a and b to be the current available spot for even and odd number respectively. Also, I increment i to loop through the argument array. Since there are three indexes, I used a while loop to simplify the loop. For example, when a new odd number is inserted, I will count down the value of b.

Screen Shot 2018-04-17 at 20.28.19
Exercise 7

This question asks me to find the max and min value and return both the index and value. So I will first create the temporary max and min value, then loop through the array to compare the current max and min with the current value, then find out the actual max and min index. Then, I print them using the required format.

Screen Shot 2018-04-17 at 20.29.10
Output from the Testing Program

Here is a testing program I wrote in a main method. It shows that everything works fine. To conclude, when doing this kind of programming question, we need to know how many loops we are going to use and then identify how we will increment the index. We may also consider whether we should use flags or additional temporary arrays.

 

Application Software

mobile-apps-pile-ss-1920.jpg
Various application softwares, Retrieved from MediaIndia

Introduction:

Applications softwares are programs that are used to perform certain task for users. In the hierarchy of software, it is parallel with system softwares (The OS we talked about earlier). I will introduce three types of application softwares, the release and update strategies of application softwares, and GUI vs. GLI.

General-purpose software

This kind of softwares can perform a variety of tasks, and they are not constrained to a particular function. Here are a few common general purpose softwares:

Word processor

unnamed.png
An Example: Microsoft Word. Picture: GooglePlay

 

Word processor are used to manipulate user input text, format it, and output a printout. It can be used to achieve multiple purposes,

like making poster, taking notes, printing out documents, etc.

Spreadsheet

It’s a software that manipulate data in columns and rows. It can also be used to analyze data and draw graphs. It’s usually used by a single user.

Database Management Systems

DBMS-database-management-system.png
Source: TechTarget

It manages database and can be used by multiple users. Unlike spreadsheet, it accepts more different data associations.

Specific software

In contrast, specific softwares are designed to perform one particular function.

Email Clients: Used to access, manage, send emails.

Web Browsers: Used to access, present, and find information on the World Wide Web.

6-browser-icons2
Jonathan Hodgson

Computer Aided Design (CAD): Programs that help users create, modify, analyze, or optimize their design.

Graphic Processing Software: Programs that help users create, present, edit, and analyze visual images.

Bespoke software

Bespoke softwares are tailor made for one particular user and purpose. Here are some examples:

For military: Bespoke software may include programs that control missiles, drones, or other military device.

For medical organization: Programs for medical equipment, or management of data inside the organization.

For financial institutions: Programs that analyze data in these institutions, control bank accounts, etc.

Management of Updates

It’s crucial for application software developers to further improve their products. There are several types of updates:

Patches – usually fix bugs of an existing software

Upgrades – include novel function and fix bug, usually paid

Updates – minor bug fix, usually free

Releases – final and working version, new (after α&β testing) or updated software

Automatic vs. Manual Update

prosconsautomanual.png

 

Graphical User Interface (GUI)

As a link between the hardware, system software, and application softwares, a Graphic User Interface provide ways of user interaction with the softwares. Common GUI features are provided in libraries as well as what happens when the window is moved or minimized. However, certain parts of interface vary according to the app.  It greatly improves usability.

Common Features of Apps (GUI elements)

Toolbars: An area include buttons, menus, and other input/output elements.

Menus: Display a list of command

Dialogue boxes: Used to communicate with user can let user choose from provided options.

GUI components (WIMP): windows, icons, menus, and pointers.

CLI vs. GUI

GUICLI.png

 

Operating System

maxresdefault.jpg
By OpenCanvas

Operating system is made up of a set of softwares which controls the resources of hardware and also provide services for applications. It is like the bridge between hardware and application softwares.

Major OS are MacOS, Windows, Linux, etc.

There are four main managers: memory manager, process manager, device manager, and file manager. In the following blog post I will explain each of them in detail.

Memory Manager

WX20171205-160952@2x.png
Dynamic partitions by OpenCanvas

It’s responsible for allocating and deallocating resources. There are three ways of managing memory.

Single user contiguous

The memory takes in one job, then process and clear, and then process the next job.

If the job’s size is larger than memory avaible, it will not be executed.

Disadvantage: impractical for complex system

Contiguous Partitions

Fixed partitions

More than a single job are stored in partition memory table to keep track of their usage. The partition is static unless re-boot.

dynamic partitions

Give memory requested, so memory is not wasted.

When memory is deallocated (cleared to make free), adjacent blocks are joined.

Allocation methods for contiguous partitions

– first fit allocation: use first eligible partition
– best fit allocation: look for the smallest: slower but more efficient.

Non-Contiguous Partitions

Instead of storing the whole program, we can split the job. In this case we use virtual memory.

There are 4 schemes:

Paged map allocation

Divide jobs to equal sized parts.

The sections of disk are called sectors/blocks; section of the main memory is call page frames.

preparation steps: 1. determine No. of pages in the program, 2. locate empty page frames.

Disadvantage: Since there is need to track the jobs, complexity is increased.

There are three tables:
1. Job table, which includes Job’s size & PMT
2. Page map table (PMT), includes page No. & page frame No.
3. Memory map table includes page frame&state.

Demand paging

Pages are loaded on demand; Page map table adds three columns: “status, modified, referenced.”

Page replacement policy determines how to replace page:
1. first in first out
2. least recently used
3. least frequently used
4. most recently used

Segmented memory allocation

Split to segments that reflect the nature and structure of the code.

Segment map table: segment No. & page pointer

Mixture of segmented memory allocation & demand paging memory allocation

It combines the logic of segmented memory allocation and the physical benefit of paging; It uses both segment map table and page map table plus the information of read, write, and execute. Disadvantage: Too complex for keeping track of all the information.

Why virtual memory good?

It uses back up memory, hard drive, to extend memory capacity.

Process Manager

Three factors that affect the processing: performance, speed, bandwidth.

CPU has its clock speed, and its bandwidth determines how much info can be processed in one instruction.

The processor’s memory is cache, which is 5/10 faster than RAM.

process scheduler

It includes job scheduler and process scheduler.

For each job, there may be multiple processes.

5 states of processing:
hold: job schedule hold the process,
ready: and the process is into a ready state
run: the the job is processed. Concern the performance, it might go back to ready state. If there’s a process failure (it shows IO request page fault),
wait: then it will wait until it finds correct resource.
finish

Process control block: contain information about jobs, which are placed in queue.

Three limitations scheduling policy

  1. Finite number of resource
  2. Locked resources, meaning that they are not shared.
  3. Need the user to reassign jobs.

We don’t want resource hogging: a job make use of all resources, need to intervene.

Pre-emptive

The system is able to intervene the process, examples:

  1. Pre-emptive version of SJN: shortest remaining time(SJN);
  2. Round robin, there is predetermine time slice given to each job, called a time quantum. When the time expired, the job changes and waits in queue;
WX20171205-161143@2x.png
Round Robin, by OpenCanvas

Non pre-emptive

System need to wait for the each process to complete, examples:

  1. First come first serve (FCFS), response time is not efficient; unpredictable;
  2. SJN: short job next. It needs accurate run-time estimate;
  3. Priority scheduling: administrator first, user’s basic process later.

Multiple level queue: multi priority, variable time quantums, aging queue.

Three problems of scheduling:

Deadlock: all resources are locked.
Livelock: some resources are released but put back to locked state.
Starvation: one process always gets resource, others always wait.

Device Manager

It controls the external devices in coordination with the internal system.

4 responsibilities

1. status of each device
2. enforce policies
3. allocation
4. diallocation

3 types of devices

  1. dedicated device: one at a time, like printers
  2. shared device: assigned to multiple processes,
  3. virtual devices: spooler, which controlled by program. Put job in queue and take them one at a time. Good spooler can cancel or reorder the jobs.

Direct access storage

  1. Fix head magnetic disk storage: The circles on the disk are called tracks. It has fixed r/w heads.
  2. Movable head magnetic disk (hard disk): It has 1 read-write head. Adv: more space for data, reduced cost; Dis: constrained by the speed of the moving head.
  3. Optical disk storage: It moves at constant angular velocity. It uses laser to access the data. Blue ray disk can store data in thinner layers, thus increasing storage.
  4. Flash memory: It is electrical erasable programmable (EEP) read-only memory. It was used to boot-up (ROM), but now it is used in more scenarios like Solid State Drives.

File Manager

It is related to the managing of data, program, compiler, installed applications, and set permissions of access, etc.

It is in charge of physical component, information resources, and policies.

Its 4 tasks

  1. Keep track of where each file is store,
  2. Use a policy to determine how the file should be store,
  3. Allocate each file when the user has been cleared for access.
  4. Deallocate the file when it is returned to storage.

Network manager

It provides a way for users to share hardware and software resources while controlling users access.

GUI

OS has to provide a link between the user and the computer hardware, and GUI is the solution

Types of user interfaces

Linux_command-line._Bash._GNOME_Terminal._screenshot.png
CLI. From Wiki

Graphical User Interfaces (GUIs);
Command Line Interfaces (CLIs);
Natural Language Interface (NLIs);
Menu Based Interface (MBIs);

The MacOS and Windows are both GUIs. Linux might have CLIs when there is no GUI.

Conclusion:

Operating system is the foundation of all the application softwares. As the hierarchy of software shows, software includes system softwares and applications softwares. System softwares connect the hardware to provide crucial service to applications. Therefore, it’s important to know how the OS works in order to better understand computers.

 

 

MIT Deep Learning & Autonomous Cars

Cars as autonomous agents

This simple diagram perfect depicts an autonomous agent (e.g. Autonomous car). It lives in the environment, perceive by sensors, do action by effectors.

There are 3 types of tasks

* Formal tasks

* Expert tasks

* Mundane tasks

They are arranged from the easiest to the most difficult for AI. In order to know which task driving is, we need to analyze how autonomous cars work.

Using these sensors, an autonomous car need to be able to the following tasks. The first one is localization and mapping. It essential means that cars need to know where themselves are as regard to the environment. The second one is scene understanding: What is the environment like? Is there a tree or a dog in front of the car? Thirdly, a car need to do movement planning, meaning that it needs to know how to travel from point A to point B. The last one is driver state, which is the understanding of the driver’s action.

Here is the block diagram for the autonomous cars as atonomous agents.

Neural Network

Neural network has the same meaning as deep learning.

It is inspired by neuron, the building block for the brain. And the corresponding thing in deep learning is a perceptron. It has three steps of processing data:

1. weigh

2. sum up

3. activate

In a neural network, many perceptrons are linked together to form a network. Sometimes, there are one hidden layer between the input and output, and sometimes there are multiple layers if the problem is very complex. More layers require more calculation power, so it is usually a hard question for people to manually set the number of perceptron and the amount of layers of them.

There are many different types of neural networks, including deep neural network (DNN), recurrent neural networks (RNN), and convolutional neural network (CNN).

Retrieved from sohu.com

CNN is usually used for image analysis, because it is good to analyze two dimensional data set and it is very efficient in finding the features of the image. The most useful application of CNN maybe object detection. By extracting the features of a certain image, the algorithm can identify the possibility that something belongs to a certain object.

Deep Learning & Autonomous Cars

Google’s Way. Retrieved from waymo.com

Thanks to the advanced machine learning algorithm, autonomous cars can perceives the environment better.

As an autonomous agent, a car must perceive the environment accurately and know where it is. The image got by the sensors can be analyzed in the micro-processor, which is equipped with deep learning algorithms like CNN. Then, as the objects near the car are detected, the car can then calculate the path to avoid crash.

However, there are some disadvantage of using machine learning algorithms. Firstly, it requires tons of data, which is time consuming. Also, if it is a self-learning algorithm, like reinforcement learning, human might not understand the logic behind the cars’ decisions, thus being unable to avoid errors. Moreover, object detection algorithm is easily fooled. For example, in the video, the algorithm mistakenly identifies some unrecognizable pictures as other objects because of the noise added to the picture.

Retrieved from a blog from OpenAI

This might lead to safety issues if the car mistakenly categorized the objects beside it. Also, people may attach the AI by using an adversarial input. Therefore, to conclude, autonomous car should still improve its algorithm and try to avoid safety issue before it can be used in every life.

Abstract and Polymorphism

Abstract Class and Methods

Abstract classes are classes that have at least one abstract method. An abstract method is a method that is not implemented.

Here is an example of an abstract method:

public void draw(Graphics g);

In this method, you should not write the {} after the method’s signature.

In an abstract class, there must be at least one abstract method. Reversely, if there is an abstract method in a class, the class is also abstract.

Here is an picture of the class card of an abstract class.

Remember the title should be italic.

In addition, because the class is not complete implemented, it cannot instantiate objects. Also, if a class inherits from an abstract class, it must implement all the abstract methods in the super class.

In conclusion, an abstract class is used as a “template” for subclasses. Since the subclasses are forced to implement the abstract methods, the proper functions that a subclass must have are ensured.

Polymorphism

Polymorphism used to be an very abstract term for me. It means the state of having multiple forms. After having CS class, I know that this concept is truly abstract: Subclasses can have some unique functionalities while sharing the same functions with the parent class.

http://www.byte-notes.com/sites/default/files/field/image/plymorphism-in-C%2B%2B.jpg

The advantages are as follows:

* we can treat the objects of the subclass as the objects of the same parent class. For example, the draw methods that draw different shapes can exist in different subclasses. The different objects can all call the draw method.

* the method names are the same. So it’s easier to memorize and use.

* subclass has their own variations by overriding.

* Reusability of code is achieved.

Overriding & Overloading

http://www.javatpoint.com/method-overloading-in-java

This diagram shows the difference between overriding and overloading. Overloading is to add a method of the same name but different parameters and implementation. An example will be add(){i+1;} and add(int n){i+n;}.

Overriding means that, in the subclass, a new method with the same name but different implementation is written. Therefore, when this method is called, the old method implementation is replaced by the new one, like add(){i+1;} and add(){i+2;}. Both overriding and overloading provide variations and flexibility to the program.

Programming Activity

In this activity, we used our knowledge about inheritance and polymorphism to finish writing a problem that can draw tortoise and rabbits and let them compete.

Here is the class diagram of it.

We can see that there is a abstract method called racer. Then, there are two variations, which are the two animals. The hollow triangular arrow represents the relationship “is a,” which is inheritance. Also, the other arrows represent association, which is a “use a” relationship.

From this picture we can see that there are two abstract methods: move() and draw(Graphics g); In the subclasses, they are implemented:

For example, this is the Hare class. The Hare moves in a random speed according to this move method. Also, the draw method actually draws a grey rabbit. In contrast, in the Tortoise class, these two methods are different:

This is exactly how polymorphism works!

Also, I am asked to finish the code in the controller method “RacePoly.”

Here are the codes:

This is the first question, which asks me to write a switch statement to do user interaction.

The second one is to call the move and draw method in all objects of the subclasses. This is an implementation of polymorphism because the same method “move” and “draw” exist in both subclasses.

This one is similar to the previous one. However, this draws the racers first before the race starts.

Then, the final product will be like this!

Interesting, isn’t it?

To conclude, from this programming activity, I practiced to use the concept of polymorphism in real java code. Also, it reminds me of Arraylist and switch statement, which I nearly forgot before I did this activity. Polymorphism is really useful in real life programming. Whenever we need to use different subclasses of the same parent at the same time, we can use what we learned about polymorphism to make the program more efficient.

Searching and Sorting an Array

In programming, we often need to handle a large amount of data. To find or change something in the dataset, there are several algorithms to achieve that.

Searching Algorithms

sequential Search

Sequential search, or linear search, is the algorithm that goes through all items in a collection and tries to find the desired item. If the item is found, this algorithm may return that item; if not, it will return -1.

The pseudocode is shown below:

set POSITION  to 0
set FOUND to false
loop while(POSITION < LENGTH AND NOT FOUND)
    if (numbers [position] equals searchitem) then
        set FOUND  to true
    else
        set POSITION to POSITION + 1
end loop

my java program

This is the static method that I wrote to search an item in a given array.


This is an interactive program that requires the user to type in the search item and also verify if the item is an integer.

Sorting an Array

when the array is very long and the elements are random, sequential search needs to go through all items in the array, which is very inefficient, So we sort the array so that we can then use other searching methods that are more efficient.
Among the algorithms, the complexity or the amount of computation can be represented by the big O notation. For example, the linear search algorithm big O notation is O(n), which shows a linear relationship between the amount of data and calculating power required.

Sorting Algorithms

Sorting is to arrange the items in a collection in a certain order. Here are two sorting algorithms that I will talk about:

  • Bubble sort
  • Selection sort

Bubble Sort

Bubble sort is one of the most basic sorting algorithms. It will compare the first two consecutive items, and switch them if they are not in correct order. Then, it will continue to compare the second and third item, and third and fourth, and so on.
During the process, the collection can be divided into two groups: Sorted an unsorted. This is because once an iteration is finished, an item is past to the end and its position is fixed.
The big O notation for bubble sort is O(n2), which growth exponentially as n increases.

pseudocode:

set firstUnsorted to 0
set SWAP to true
while (firstUnsorted < LENGTH - 1 AND SWAP) //first while loop
    set SWAP to false
    //start of “Bubble up” function
    set INDEX to LENGTH - 1
    while (INDEX > firstUnsorted) //second while loop
        if (DATA[INDEX]) < DATA(INDEX -1)
            swap DATA[INDEX] and DATA[INDEX - 1] 
            set SWAP to true
        set INDEX to INDEX - 1 
    end while
    //end of “Bubble up” function
    set firstUnsorted to firstUnsorted + 1 
end while

my java program

Here is the code inside of the main method:

The output:

Selection Sort

Selection sort is another sorting algorithm that is inefficient for a large set of data, as has a big O notation of O(n2). It divides the data into two groups, sorted and unsorted. At first, all data are in the unsorted list, then the program go through the data, find the smallest item and switch it with the left most data, then this item is categorized as sorted data.

pseudocode

my java program

Then, according to the sudocode, I developed a program that can sort a given array. This time, I make the program interactive so that it can let user input and then sort the inputted array.
Here is my code of the sorting method.

Here is the output:

Conclusion

As we want to find something in a collection, we may just go through all the items one by one. However, if we first sort them into a certain order, either from the largest to the smallest or the opposite, we can then use more efficient algorithm to search the collection. In real life, there are many applications related to data analysis, etc. In the future, I may learn about other more efficient algorithms.

One Dimensional Array

In this blog post I will share my answer to the programming activity in Chapter 8 of Java Illuminated Fourth Edition.

0

This is the class diagram of the program. The BarChart class mainly focus on the graphics and presentation of the array. The ArrayPractice1 class includes the exercises, and it also uses the BarChart object. Here are the exercises.

Exercise #1

Prints the array to the console with elements separated by a space. The instance variable arr is the integer array to be printed.

Answer:

public void printArray( )
{
    for ( int i = 0;i < arr.length; i++ )
    {
        System.out.print (arr[i] + ” “);
        animate( i );
    }
}

Explanation:

According to the question, I need to print every element in the array. The only way that we can go through the elements in the array is by using index. I used a for loop and use “i” as the index. I print out the element of index “i” and add a space after it. After that, i is incremented so that the next element will be printed.

Output:

Picture1

Exercise #2

Sets all the elements in the array to parameter value. The instance variable arr is the integer array to be processed.

Answer:

for ( int i = 0;i < arr.length; i++ )
{
    arr[i] = value;
    animate( i );
}

Explanation:

Using another for loop, I assign the integer “value” to every element in the array. If, in the future, we need to assign different value to the array, we can use the index “i” the differentiate the values.

Output:

2

Exercise #3

Counts number of elements equal to parameter value. The instance variable arr is the integer array to be processed.

Answer:

int fre = 0;
for (int i = 0; i< arr.length ; i++){
    if (arr[i] == value){
        fre ++;
    }
    animate( i , fre );
}
return fre;

Explanation:

To count the frequency, we need to declare an integer variable outside the for loop so that when the loop ends the value will not be deleted. Then, for each time the element equals the value, the frequency variable increments.

Output:

3

Exercise #4

Finds and returns the minimum value in arr. The instance variable arr is the integer array to be processed.

Answer:

int min = arr[0];
for (int i = 0; i < arr.length ; i++){
    if (arr[i] <= min){
        min = arr[i];
    }
animate( i, min );
}
return min;

Explanation:

To find the minimum value, we need to first declare a variable that holds the min value. Then, in the for loop, overtime we find a value smaller than the min value, we update the min variable by assigning the value of that element into it. The for loop will go through the array and compare every value with the current minimum one.

Output:

4

Conclusion: Real Life Implication

The array is very useful since we often need to analyse data and present data in a organised way. These exercises help me to familiarise myself with one dimensional array and the methods related to it. In real life, we can use one dimensional array in statistic, and use this program to present the statistic. Also, we can use array to search in a big bunch of data, and also to present a large amount of data efficiently. We can also incorporate array in GUI, which enables us to present the array visually.

 

Inheritance – Programming Activity

After we learned inheritance in class, we were assigned an programming activity which is in 10.4 of the textbook Java Illuminated Fourth Edition.

Generally, this programming activity is to use inheritance to create a subclass of the BankAccount class which we coded earlier. Also, we will create a client of the SavingAccount class which will show how it works.

Exercise

The textbook asks me to copy the source file, and add more to the class according to the instructions.

Exercise 1 & 2 – inheritance/instance variable

Question:

  • indicate that SavingAccount inherits from BankAccount
  • define the private interestRate instance variable (a double, annual rate)
public class SavingsAccount extends BankAccount
{
 public final double DEFAULT_RATE = .03;
 private double interestRate;
...

To inherit from a super class, I need to use the keyword “extends” plus superclass name.

Although now this class is a subclass of BankAccount class, we can add more instance variables, which is called specialisation. Therefore, I directly add a private double variable here. It is private so that its subclass will not be able to directly access it.

Exercise 3 -default constructor

  • write the default constructor (explicitly call the BankAccount Default constructor, set interestRate to default value DEFAULT_RATE, print a message indicating that the constructor is called.)
public SavingsAccount(){
  super();
  //This is explicit, 
  //while implicit means 
  //even if you do not call it, 
  //the default constructor 
  //will be called.
  interestRate = DEFAULT_RATE;
  System.out.println("Default Constructor is called.");
 }

To explicit call the constructor of the super class, BankAccount, I used “super()” which calls the constructor of super class that has not argument. To indicate the constructor is called, I let the system print out a message.

The output will be:

1

This will show up when I create a new object of the subclass using the explicit call of the super class’s default constructor.

Exercise 4 – overloaded constructor

public SavingsAccount(double startBalance, double startInterestRate){
    super(startBalance);
    setInterestRate(startInterestRate);
    System.out.println("Overloaded constructor is called.");
 }

This time I called the overloaded constructor of the super class. This constructor has arguments, so that when you call the super class’s overloaded constructor, you need to include the correct arguments.

2

The output will be like this:

3

The message helps me to make sure which constructor is called.

Exercise 5 – mutator method

This asks me to write a void-return-type method that can implement the interest rate.  It will call the deposit method and pass a month’s worth of interest.

public void applyInterest(){
     deposit(getBalance()*interestRate);
}

Since the interest rate is for a month, I used an accessor method to get the balance and multiplies the monthly interest rate. Then I called the deposit method, which is inherited from the super class.

Exercise 6 – toString method

  • This is returns formatted balance and interestRate.
  • invokes superclass toString to format balance
  • formats interestRate as percent using a NumberFormat object
  • also use the gerPercentInstance method in the NumberFormat class.
public String toString(){
    //return formatted balance and interestRate
    return (super.toString() +
    " Interest rate is " + 
    NumberFormat.getPercentInstance().format(interestRate));
}

In this method I used “super.” notation to call the toString method in the super class. Then I actually override the toString method by adding a formatted interest rate using number format.

The output will be:

4

Conclusion

In this program, I practiced writing a subclass using inheritance. I distinguished between overload and override. I may use what I learned in these exercise into my future programs. I also found out that inheritance is a very efficient way of writing codes because it save codes and make it easier to write similar classes and also to make classes to be specialised.

Reading Assignment

This assignment is to read through chapter 3.15, 12.7 and 12.9 of the book Java Illuminated (sixth edition). From these chapters, I learned about wrapper class, as well as radio button, checkboxes, and drop-down list (combo box). I will mainly talk about wrapper class and some examples of it.

Picture1
From Java Illuminated. These are corresponding wrapper class for the primitive data types.

The Integer, Double, and Other Wrapper Classes

The reason for the name Wrapper class is that this class “wrap” the primitive data type into objects. This class provides methods to convert between objects and primitive data types.

To convert a primitive data type variable into a object, we can instantiate a new object, passing the primitive variable as an argument:

int a = 1;
Integer integerObject = new Integer(a);

As we can see here, the name of the wrapper class is similar to the name of the primitive data type. Specifically, the names of the wrapper classes starts with capital letter, and they are complete words. (ie. char is Character)

If I write the previous code like this:

int a = 1;
Integer integerObject = a;

This is called autoboxing, because the class automatically does the conversion for us.

If we use Integer object in an arithmetic expression, like:

sum = a + integerObject;

The program will add the two int variables together. This is called unboxing. Here the class convert the object to primitive type automatically.

Parse Method

Inside the wrapper classes, there are static methods that can be used to convert String to different objects or primitive data type.

For example, if we have a String “12.0”, and we want to use it as a double, we can use dot notation to use the method in the Double wrapper class:

double doublePrimitiveType = Double.parseDouble("12.0");

Then the variable doublePrimitiveType will be assigned the double 12.0. Similarly, if we want to get the double object, we can write like this:

Double doubleObject = Double.valueOf("12.0");

Then the double object is assigned to the variable doubleObject.

As this is an example for Double class, we can just replace the part of word after “parse__” to convert other types of data and objects.

Conclusion

The wrapper class is necessary because there needs to be a way of converting between different primitive data types. Also, when the conversion is lossy, we need to consider what is omitted and what is left.

Website Built with WordPress.com.

Up ↑