You are on page 1of 68

Computer Programming 2 1

COMPUTER
PROGRAMMING II
Computer Programming 2 2

TABLE OF CONTENTS

UNIT I…………………………………………………………………………3

(Arrays, Searching, Sorting)

UNIT II…………………………………………………………………………24

(Language-provided functions or Libraries (Pre-defined Functions),

Recursion, User-defined Functions (subprograms))

UNIT III…………………………………………………………………………48

(Fundamentals of Pointers, Pointer Declarations, Passing Pointer to

Function, Pointers and One-Dimensional Array)

UNIT IV…………………………………………………………………………52

(Structure within a Structure, Array within a Structure, Pointer Structures,

Linked List Structures Using Looping Constructs)

UNIT V…….……………………………………………………………….64

(Text File, Non-Text File)


Computer Programming 2 3

UNIT I
(Arrays, Searching, Sorting)

An array is a dynamically created object in the context of Java that serves as a

container for holding a constant number of values of the same type. Memory space is

allocated for values of a specific type by declaring an array. A subarray is known as an a

rray element that is also an array. The numerical index (a non-negative value)

corresponding to that element's position must be used to access an array element. The

first index value in the array is zero, so the four-value index is used to access the array's

fifth element. A subarray is defined as an array component that is also an array. Arrays

may have one or two dimensions.

Techopedia explains Array

Arrays have the following advantages:

 A particular element in a large group of elements may be accessed easily with the

array name and the element index.

 Arrays are useful when executing calculations within a loop.

One-dimensional array in Java programming is an array with a bunch of values having

been declared with a single index.

 First, you need to define the elements you want to be in the specified array

on, as you can see in the above example, and memory allocation for a one-

dimensional array in Java is as follows:

 Second, it is also necessary to specify the position of each element, as that is wher

e the elements will be stored.

 Thirdly, you need to declare the array accordingly.


Computer Programming 2 4

As it is visible, the three elements that have been listed simultaneously are as follows:

 10

 20

 30

The result is therefore written in single lines as 10 20 30 respectively, as it is a one-

dimensional set.

Consequently, the methods used in Java are as follows:

One Dimensional Array – Using Standard Method

Output:
Computer Programming 2 5

Using Scanner
1.) Read the array length as sc.nextInt() and store it in the variable len and

declare an array int[len].

2.) To store elements in to the array for i=0 to i<length of an array read the

element using sc.nextInt() and store the element at the index a[i].

3.) Display the elements of an array for loop iterates from i=0 to i<length of an

array print the array element a[i].

Output:
Computer Programming 2 6

Using For Loop – One Dimensional Array

Output:

Using String
1. We declared one-dimensional string array with the elements strings.

2. To print strings from the string array. for i=0 to i<length of the string print string

which is at the index str[i].


Computer Programming 2 7

Output:

Before learning multidimensional array, visit Java array article to learn about one-

dimensional array.

In that chapter, you learned to create and use array of primitive data types

(like: Double, int etc.), String array, and array of objects. It's also possible to create an

array of arrays known as multidimensional array. For example,

int[][] a = new int[3][4];

Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements of

type int.

Note, Java uses zero-based indexing, i.e. Java array indexing starts with 0 rather than 1.

Similarly, you can claim a set of three dimensions (3d). For example
Computer Programming 2 8

String[][][] personalInfo = new String[3][4][2];

Here, personalInfo is a 3d array that can hold maximum of 24 (3*4*2) elements of

type String.

How to initialize a 2d array in Java?

Here's an example to initialize a 2d array in Java.

int[][] a = {

{1, 2, 3},

{4, 5, 6, 9},

{7},

};

As mentioned above, each component of the array is in itself an array, and the length of

each row is also different.


Computer Programming 2 9

Let's write a program to prove it.

1. class MultidimensionalArray {

2. public static void main(String[] args) {

3.

4. int[][] a = {

5. {1, 2, 3},

6. {4, 5, 6, 9},

7. {7},

8. };

9.

10. System.out.println("Length of row 1: " + a[0].length);

11. System.out.println("Length of row 2: " + a[1].length);

12. System.out.println("Length of row 3: " + a[2].length);

13. }

14. }

When you run the program, the output will be:

Length of row 1: 3

Length of row 2: 4

Length of row 3: 1

Since each component of a multidimensional array is also an array

(a[0], a[1] and a[2] are also arrays), you can use length attribute to find the length of

each rows.

Example: Print all elements of 2d array Using Loop

1. class MultidimensionalArray {

2. public static void main(String[] args) {

3.

4. int[][] a = {

5. {1, -2, 3},

6. {-4, -5, 6, 9},


Computer Programming 2 10

7. {7},

8. };

9.

10. for (int i = 0; i < a.length; ++i) {

11. for(int j = 0; j < a[i].length; ++j) {

12. System.out.println(a[i][j]);

13. }

14. }

15. }

16. }

It's better to use for..each loop to iterate through arrays whenever possible. You can

perform the same task using for..each loop as:

1. class MultidimensionalArray {

2. public static void main(String[] args) {

3.

4. int[][] a = {

5. {1, -2, 3},

6. {-4, -5, 6, 9},

7. {7},

8. };

9.

10. for (int[] innerArray: a) {

11. for(int data: innerArray) {

12. System.out.println(data);

13. }

14. }

15. }

16. }
Computer Programming 2 11

When you run the program, the output will be:

-2

-4

-5

How to initialize a 3d array in Java?

You can initialize 3d array in similar way like a 2d array. Here's an example:

// test is a 3d array

int[][][] test = {

{1, -2, 3},

{2, 3, 4}

},

{-4, -5, 6, 9},

{1},

{2, 3}

};

Basically, 3d array is an array of 2d arrays.

Similar like 2d arrays, rows of 3d arrays can vary in length.


Computer Programming 2 12

Example: Program to print elements of 3d array using loop

1. class ThreeArray {

2. public static void main(String[] args) {

3.

4. // test is a 3d array

5. int[][][] test = {

6. {

7. {1, -2, 3},

8. {2, 3, 4}

9. },

10. {

11. {-4, -5, 6, 9},

12. {1},

13. {2, 3}

14. }

15. };

16.

17. // for..each loop to iterate through elements of 3d array

18. for (int[][] array2D: test) {

19. for (int[] array1D: array2D) {

20. for(int item: array1D) {

21. System.out.println(item);

22. }

23. }

24. }

25. }

26. }
Computer Programming 2 13

When you run the program, the output will be:

-2

-4

-5

SORTING AND SEARCHING

The problem of sorting is to

rearrange in ascending order a set of objects.

Two classical algorithms for sorting and

searching — binary search and mergesort —

will be discussed in depth in this section along

with several applications where their

efficiency plays a critical role.

Binary search. In the game of "twenty

questions", your task is to guess the value of a

secret number that is one of the n integers between 0 and n−1. For simplicity, we will

assume that n is a power of 2 and that the questions are of the form "is the number

greater than or equal to x?"


Computer Programming 2 14

An effective strategy is to have an interval containing the hidden number, guess the

number in the middle of the interval and then use the answer to halve the length of the

interval. This strategy is implemented by

Questions.java. It is an example of the general

method of problem-solving called binary search.

 Analysis of running time. Since the size of the

interval decreases by a factor of 2 at each iteration

(and the base case is reached when n = 1), the

running time of binary search is lg n.

 Linear–logarithm chasm. The alternative to

using binary search is to guess 0, then 1, then 2, then

3, and so forth, until hitting the secret number. We

refer to such an algorithm as a brute-force algorithm:

it seems to get the job done, but without much regard to the cost (which might

prevent it from actually getting the job done for large problems). In the worst

case, the running time can be as much as n.

 Binary representation. If you look back

to Binary.java, you will recognize that

binary search is nearly the same

computation as converting a number to

binary! Each guess determines one bit of

the answer. For example, if the number is

77, the sequence of answers no yes yes no

no yes no immediately yields 1001101, the

binary representation of 77.

 Inverting an increasing function f(x). Given a

value y, our task is to find a value x such

that f(x) = y. We start with an interval (lo, hi) known to contain x and use the

following recursive strategy:

o Compute mid = lo + (hi − lo) / 2


Computer Programming 2 15

o Base case: If (hi − lo) is less than δ, then return mid as an estimate of x

o Recursive step: otherwise, test whether f(mid) > y. If so, look for x in

(lo, mid); if not look for x in (mid, hi).

The inverseCDF() method in Gaussian.java implements this strategy for the

Gaussian cumulative density function Φ. In this context, binary search is often

called bisection search.

 Binary search in a sorted array. One of the most important uses of binary search is

to find an item in a sorted array. To do so, look at the array element in the

middle. If it contains the item you are seeking, you are done; otherwise, you

eliminate either the subarray before or after the middle element from

consideration and repeat. BinarySearch.java is an implementation of this

algorithm.

Insertion sort.Insertion sort is a brute-force sorting algorithm based on a simple method

that is often used by people to organize play card hands: consider the cards one at a

time and insert them into their proper place among those already considered (keep

them sorted). In a Java method that sort strings in an array, the following code imitates

this process:

public static void sort(String[] a) {


int n = a.length;
for (int i = 1; i < n; i++) {
for (int j = i; j > 0; j--) {
if (a[j-1].compareTo(a[j]) > 0)
exch(a, j, j-1);
else break;
}
}
}
The first I elements in the array are sorted at the beginning of each iteration of the outer

loop; the inner loop moves a[i] to its correct position in the array by exchanging it with

each large value to its left, moving from right to left until it reaches its correct position.

Here's an example if I'm 6:


Computer Programming 2 16

This process executed first with i equal to 1, then 2, then 3, and so forth, as illustrated in

the following trace.

 Analysis of running time. The inner loop of the insertion sort code is within a

double nested for loop, which suggests that the running time is quadratic, but we

cannot immediately draw this conclusion because of the break.

o Best case. When the input array is already in sorted order, the total number

of compares in ~ n and the running time is linear.

o Worst case. When the input is reverse sorted, the number of compares is ~

1/2 n2 and the running time is quadratic.

o Average case. When the input is randomly ordered, the expected number of

compares is ~ 1/4 n2 and the running time is quadratic.

 Sorting other types of data. We want to be able to sort all types of data, not just

strings. For sorting objects in an array, we need only assume that we can

compare two elements to see whether the first is bigger than, smaller than, or

equal to the second. Java provides the Comparable interface for this

purpose. Insertion.java implements insertion sort so that it sorts arrays

of Comparable objects.
Computer Programming 2 17

 Empirical analysis. InsertionTest.java tests our hypothesis that insertion sort is

quadratic for randomly-ordered arrays.

Mergesort.

To develop a faster sorting method, we use a divide-and-conquer approach to algorithm

design that every programmer needs to understand. To mergesort an array, we divide it

into two halves, sort the two halves independently, and then merge the results to sort

the full array. To sort a[lo, hi), we use the following recursive strategy:

 Base case: If the subarray length is 0 or 1, it is already sorted.

 Reduction step: Otherwise, compute mid = lo + (hi - lo) / 2, recursively sort the two

subarrays a[lo, mid) and a[mid, hi), and merge them to produce a sorted result.

Merge.java is an implementation of this strategy. Here is a trace of the contents of the

array during a merge.


Computer Programming 2 18

 Analysis of running time. In the worst case, merge sort makes between ~

1/2 n lg n and ~ n lg n compares and the running time is linearithmic. See the

book for details.

 Quadratic–linearithmic chasm. The difference between n2 and n lg n makes a huge

difference in practical applications.

 Divide-and-conquer algorithms. The same basic approach is effective for many

important problems, as you will learn if you take a course on algorithm design.

 Reduction to sorting. A problem A reduces to a problem B if we can use a solution

to B to solve A. For example, consider the problem of determining whether the

elements in an array are all different. This problem reduces to sorting because we

can sort the array, the make a linear pass through the sorted array to check

whether any entry is equal to the next (if not, the elements are all different.)

Frequency counts.

FrequencyCount.java reads a sequence of strings from standard input and then prints a

table of the distinct values found and the number of times each was found, in

decreasing order of the frequencies. We accomplish this by two sorts.

 Computing the frequencies. Our first step is to sort the strings on standard input. In

this case, we are not so much interested in the fact that the strings are put into

sorted order, but in the fact that sorting brings equal strings together. If the input

is

to be or not to be to

then the result of the sort is

be not or to

with equal strings like the three occurrences of to brought together in the array.

Now, with equal strings all together in the array, we can make a single pass

through the array to compute all the frequencies. The Counter.java data type that

we considered in Section 3.3 is the perfect tool for the job.


Computer Programming 2 19

 Sorting the frequencies. Next, we sort the Counter objects. We can do so in client

code without any special arrangements because Counter implements

the Comparable interface.

 Zipf's law. The application highlighted in FrequencyCount.java is elementary

linguistic analysis: which words appear most frequently in a text? A

phenomenon known as Zipf's law says that the frequency of the ith most

frequent word in a text of m distinct words is proportional to 1/i.

Scientific example of sorting. Google display search results in descending order of

"importance", a spreadsheet displays columns sorted by a particular field, Matlab sorts

the real eigenvalues of a symmetric matrix in descending order. Sorting also arises as a

critical subroutine in many applications that appear to have nothing to do with sorting

at all including: data compression (see the Burrows-Wheeler programming assignment),

computer graphics (convex hull, closest pair), computational biology (longest common

substring discussed below), supply chain management (schedule jobs to minimize

weighted sum of completion times), combinatorial optimization (Kruskal's algorithm),

social choice and voting (Kendall's tau distance), Historically, sorting was most

important for commercial applications, but sorting also plays a major role in the

scientific computing infrastructure.


Computer Programming 2 20

Java Examples - Array sort and search


Problem Description

How to sort an array and search an element inside it?

Solution

Following example shows how to use sort () and binarySearch () method to accomplish

the task. The user defined method printArray () is used to display the output:

import java.util.Arrays;

public class MainClass {


public static void main(String args[]) throws Exception {
int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
printArray("Sorted array", array);
int index = Arrays.binarySearch(array, 2);
System.out.println("Found 2 @ " + index);
}
private static void printArray(String message, int array[]) {
System.out.println(message + ": [length: " + array.length + "]");

for (int i = 0; i < array.length; i++) {


if(i != 0) {
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
}

Result

The above code sample will produce the following result.

Sorted array: [length: 10]

-9, -7, -3, -2, 0, 2, 4, 5, 6, 8

Found 2 @ 5
Computer Programming 2 21

Linear Search

Following example shows search array element with Linear Search.

public class HelloWorld {


public static void main(String[] args) {
int[] a = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
int target = 0;

for (int i = 0; i < a.length; i++) {


if (a[i] == target) {
System.out.println("Element found at index " + i);
break;
}
}
}
}

Result

The above code sample will produce the following result.

Element found at index 6

Bubble Sort

Following example shows sort array element with Bubble Sort.

public class HelloWorld {


static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i = 0; i < n; i++) {
for(int j=1; j < (n-i); j++) {
if(arr[j-1] > arr[j]) {
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args) {
int arr[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
System.out.println("Array Before Bubble Sort");

for(int i = 0; i < arr.length; i++) {


System.out.print(arr[i] + " ");
Computer Programming 2 22

}
System.out.println();
bubbleSort(arr);
System.out.println("Array After Bubble Sort");

for(int i = 0; i < arr.length; i++) {


System.out.print(arr[i] + " ");
}
}
}

Result

The above code sample will produce the following result.

Array Before Bubble Sort

2 5 -2 6 -3 8 0 -7 -9 4

Array After Bubble Sort

-9 -7 -3 -2 0 2 4 5 6 8
Computer Programming 2 23

UNIT II
(Language-provided functions or Libraries (Pre-defined Functions), Recursion,
User-defined Functions (subprograms))

Language-provided functions or Libraries (Pre-defined Functions)

These libraries provide many functions, whether the matter is related to events or

effects or AJAX. And if one of these libraries can’t do the job, a plug-in probably exists

that can.

1. Forms
wForms wForms is an open-source and unobtrusive library that simplifies the most

common JavaScript form functions. It offers ready-to-use form validation functions for

which can be applied by adding a class info to the form objects. Besides

these, wForms has powerful form synchronization (like “Check”/”Uncheck all”)

and conditional form capabilities (e.g. if x is checked, then show y).

Validanguage Validanguage is an unobtrusive JavaScript form validation framework.

It has an inheritance logic whose settings can be defined globally, per form or per

element. With the 2 APIs provided: and features like integrated AJAX support, caching

and callback functions, the framework provides a robust validation experience. It has a

HTML-like API inserted in comment tags and a JavaScript object-based API, for

advanced configuration.

LiveValidation LiveValidation is a lightweight library that equips you with set of

validation functions. Besides the classic validation methods, the library has a powerful
Computer Programming 2 24

live validation feature that controls the fields as you type. Ruby on Rails developers

will find it very easy to use because the naming conventions and parameters are very

similar. It is a stand-alone library but has a Prototype version, too.

yav A powerful, extensible and flexible form-validation library, yav has support for a

wide range of scenarios, from basic ones like date, email and integer, to advanced ones,

like masking and custom regular expressions. It has built-in AJAX support, and errors

displayed can be easily customized per object level.

qForms A complete solution for handling forms. It equips a developer with features

such as various validation rules, methods to prevent multi-submissions, ability to

lock/disable fields and more.

formreform Using multi-column layouts without tables is usually challenging. This tiny

library transforms a classic form into a stylish layout with one, two or four columns.

Forms are styled to fit any design automatically with formreform.

2. Animation
$fx()

$fx() is a lightweight library for animating HTML objects. Using it, you can alter any

CSS property within a given timeline. For complicated animations, you can combine

effects, group them to chains and run them in parallel. And you can set different

callbacks at every step to customize it further.

JSTweener A tweening library for JavaScript. Its API is similar to the famous

ActionScript tweening engine Tweener. You can mention the time of the animation,
Computer Programming 2 25

define the transition effects and delays. At almost any point (like onStart, onComplete,

onUpdate) you can fire new events.

Facebook Animation A powerful library for creating customizable CSS-based

animations. With a line or two in Facebook Animation, you can improve the UI. The

syntax is identical to the FBJS version (the library used in Facebook applications) and

once learned, it is an asset for creating Facebook applications.

FX A lightweight library, with a YUI-like syntax, FX can create a tween for almost any

CSS property. It supports color and scroll animations. Designing the “to” and “from”

values of any object/property is enough.

3. Visualization And Image Effects


JScharts

JS charts supports bar charts, pie charts and simple line graphs. It offers nice usability

by simply inserting the library onto Web pages and calling the data from an XML file or

a JavaScript array. Charts are created as PNG files and the library is compatible with all

the major browsers.

Canvas3DJSLibrary(C3DL)

C3DL makes writing 3D applications easy. It provides a set of math, scene and 3D

object classes to make the canvas more accessible to developers who want to develop

3D content in a browser but not have to deal in depth with the 3D math needed to make

it work.

Processing.js This is a JavaScript port to the Processing language (a language for

programming images, animation and interactions). The library is feature-rich for


Computer Programming 2 26

creating 2D outputs. It provides methods for shape/image drawing, color manipulation,

fonts, objects, math functions and more.

Raphaël An amazing library that simplifies working with vector graphics on the Web.

Raphaël uses SVG and VML for creating graphics that can be modified and event

handlers that can be attached to them. The library is feature-rich in functions, including

rotation, animation, scaling and drawing curves, rectangles and circles.

ImageFX This is a JavaScript library for adding effects to images, like blur, sharpen,

emboss, lighten and more. ImageFX uses canvas element for creating the effects. It is

compatible with all major browsers (there is a compatibility chart on the script’s page).

The library is so easy to use. Simply inserting the .js file in the Web page and calling a

one-line function is enough.

Pixastic Pixastic uses the HTML5 canvas element, which enables accessing raw pixel

data. The effects supported include desaturation and grayscale, inverting, flipping,

brightness and contrast adjustment, hue and saturation, embossing, blurring and much

more. Because the canvas element is relatively new, the library does not have equal

support in all browsers yet.

Reflection.js An unobtrusive JavaScript to auto-create reflection effects. The height and

opacity of the reflection can be defined. Using it is as easy as adding a “class” to the

images. It works in all major browsers and is smaller than 5 KB.


Computer Programming 2 27

4. Database
Taffy DB A JavaScript library that can be thought as an SQL database in the browser or

an advanced “array manager.” It works as a database layer within AJAX’ed Web

applications. You can create, read, edit and delete data, use loops, sort them and use

advanced queries.

ActiveRecord.js This library supports Google Gears and Chrome, Aptana Jaxer, Adobe

AIR, and any platform that supports W3C HTML5 SQL Specification (Webkit and

iPhone for now). It makes it easy to work with databases in JavaScript.

Using ActiveRecord.js, you can auto-create tables, validate and synchronize data and

more.

5. String And Math Functions


Date.js Working with dates are always tricky. So many dots, slashes and

formats. Datejs is a stunning library for simple to complex date functions. It can parse

dates like: “Next thursday”, “+2 years” and all formats like 2009.01.08, 12/6/2001 etc.

Sylvester This is a JavaScript library for doing vector and matrix math easily, without

using a lot of loops and getting lost between arrays. It includes classes for modelling

vectors and matrices in any number of dimensions and for modelling infinite lines and

planes in 3D space.

Pretty Date A smart JavaScript solution for displaying dates within the past month in a

prettier and more user-friendly way. It displays dates relative to the current time; for

example, “Yesterday,” “3 hours ago,” etc.


Computer Programming 2 28

XRegExp Regular expressions can be already used in JavaScript with the RegExp

object. XRegExp adds more power to RegExp with features that will be part of the

browsers of tomorrow (according to proposals for ECMAScript 4 - ES4). Using the

library, RegExp objects can be cached and reused, modifiers can be added to existing

RegExp objects and more.

JavaScript URL Library A library for handling and manipulating URLs more easily. It is

possible to reach every part of a URL as a string and modify it when needed. This URL

library is very new but already works as mentioned.

6. Fonts
typeface.js An unobtrusive library for using any font on a website. Unlike popular

solutions like sIFR or FLIR, typeface.js doesn’t require Flash and is 100% JavaScript. To

use any font, upload the TrueType font file to a Web-based generator, and download

the rendered JavaScript file and include it in your Web pages.

Cufón Very similar to typeface.js, Cufón enables you to use any TrueType font in a

website. Again, it converts the font to VML with a generator. After inserting the

generated .js file in your Web pages, you can use the font like any other.

7. Debugging And Logging

Blackbird Alert()s are widely used to create checkpoints in JavaScript

development. Blackbird offers a stylish console to log, view and filter messages in

JavaScript, which quickens the development process by eliminating the pause at every

alert and analyzing each better.


Computer Programming 2 29

NitobiBug A browser-based, cross-browser JavaScript object logging and inspection

utility. By inserting rules in your code (like which object to follow), you can have it

distinguish between simple types, like strings, booleans and numbers, and complex

objects, like error messages and objects.

Firebug Lite

Firebug, which sadly only works with Firefox, is one of the best debugging tools

around. To have a similar tool for all browsers, insert the Firebug Lite .js file into your

Web pages, and you get the functionality and interface you’re used to.

8. Other
swfobject

swfobject is the most popular and flexible method for embedding Flash movies. It is

unobtrusive, generates valid markup and can detect the version of a user’s Flash Player,

allowing you to display alternate content if the required Flash version is not loaded. A

nice article on “why swfobject should be used” can be found here.

sorttable and dragtable Tables, like them or not, are still one of the best ways to present

data. But they can be better: sorttable is a library that makes tabular data sortable, both
Computer Programming 2 30

ascending and descending. To do this, simply add class=”sortable” to the table. You can

also exclude certain columns from being sorted and make either ascending or

descending the default behavior. dragtable is another library that makes columns

draggable. After inserting the library in the Web page, add class=”dragtable” to the

table as above. Best of all, both libraries can be used together. Simply add

class=”sortable dragtable” to the table after including both libraries in the Web page.

DD_roundies and DD_belatedPNG

DD_roundies is a great JavaScript solutions for creating rounded corners without

using images. It is focused on IE and supports it through VML. Other browsers are

ignored because they support CSS’s border-radius property.

DD_belatedPNG is a library that provides a customizable fix for the notorious IE6 PNG

problem. Whether the PNG is used as “src” or “background-

image” DD_belatedPNG can fix it. Unlike other solutions, “background-position” and

“background-repeat” properties work as expected too.

Custom JavaScript Dialog Boxes A lightweight library (about 4.5 KB) for

creating custom dialog boxes. Four boxes can be displayed: alerts, warnings, prompts,

success. With a simple function, you can specify the title of the box, the content to be

shown and how many seconds to show it for.

GameJS

GameJS is a JavaScript-ported version of Microsoft’s XNA Game Framework that uses

“canvas” as the rendering device. JavaScript is not the best platform for creating games.

But for games with less FPS, and if you are a JavaScript developer, then why not? The

library includes handy classes for controlling the objects, drawing and keyboard

controls.
Computer Programming 2 31

Shortcuts.js Starting with Google Reader and Gmail, keyboard shortcuts in Web

applications have become popular because they improve usability so

much. Shorcuts.js provides functions to handle keyboard shortcuts more easily. Using

the library, it is possible to create hotkeys and run functions at the press of a button.

Mapstraction There are several mapping providers that provide different APIs. If you

need to switch providers (say from Google Maps to MapQuest), codes need to be

updated. That’s where Mapstraction comes in. It provides a common API that covers

most of the popular mapping providers. By simply updating a line of code, it is possible

to switch between them.

Amberjack A tiny JavaScript library (about 4 KB) that helps you add good-looking

website tours to your website. Once activated, a modal box guides users by displaying

any type of content. The steps in the tour can be hand-coded or generated online. Also,

tours can be made to match the look of the modal box, either via CSS or with a ready-to-

use theme.

JsLoad Remote loading API of JavaScript library. JsLoad is simple API that enables you

to import big JavaScript libraries from Google server. JsLoad load dependencies of any

version of the library automatically.


Computer Programming 2 32

JAVA PREDEFINED FUNCTIONAL INTERFACE

 The java.util.function package defines several predefined functional

interfaces that you can use when creating lambda expressions or method

references.

 They are widely used throughout the Java API.

Here are some of the most important:

Functional Abstract Function


Description
Interface Method descriptor

Consumer<T> accept(T t) T -> void Represents an operation that accepts a single

input argument and returns no result.

Function<T, R> apply(T t) T -> R Represents a function that accepts one

argument and produces a result.

Predicate<T> test(T t) T -> boolean Represents a predicate (boolean-valued

function) of one argument.

Supplier<T> get() () -> T Represents a supplier of results.

 Example using Consumer<T>:

public class ConsumerApp {

public static void main(String[] args) {


String[] players = {"Rafael Nadal", "Novak Djokovic",
"Stanislas Wawrinka", "David Ferrer",
"Roger Federer", "Andy Murray", "Tomas Berdych",
"Juan Martin Del Potro", "Richard Gasquet", "John Isner"};
// Show the list of players
System.out.print("Show the list of players:\n");
// void forEach(Consumer<? super T> action)
Arrays.asList(players).forEach((player) -> System.out.println(player));
}
}
Computer Programming 2 33

The result of this is:

Show the list of players:


Rafael Nadal
Novak Djokovic
Stanislas Wawrinka
David Ferrer
Roger Federer
Andy Murray
Tomas Berdych
Juan Martin Del Potro
Richard Gasquet
John Isner

You can download this example here (needed tools can be found in the right menu on

this page).

Example using Function<T, R>:

public class FunctionApp {


public static void main(String[] args) {
String[] players = {"Rafael Nadal", "Novak Djokovic",
"Stanislas Wawrinka", "David Ferrer",
"Roger Federer", "Andy Murray",
"Tomas Berdych", "Juan Martin Del Potro",
"Richard Gasquet", "John Isner"};
Function<String[],String> converter = (all)-> {
String names= "";
for (String n : all){
String forname=n.substring(0, n.indexOf(" "));
forname=n.substring(n.indexOf(" "))+" "+forname;
names+=forname+"\n";
}
return names;
};
System.out.println(converter.apply(players));
}
}
Computer Programming 2 34

The result of this is:

Nadal Rafael
Djokovic Novak
Wawrinka Stanislas
Ferrer David
Federer Roger
Murray Andy
Berdych Tomas
Martin Del Potro Juan
Gasquet Richard
Isner John

You can download this example here (needed tools can be found in the right menu on

this page)

Example using Predicate<T>:

public class PredicateApp {


private static List getBeginWith(List<String> list, Predicate<String> valid) {
List<String> selected = new ArrayList<>();
list.forEach(player -> {
if (valid.test(player)) {
selected.add(player);
}
});
return selected;
}

public static void main(String[] args) {


String[] players = {"Rafael Nadal", "Novak Djokovic",
"Stanislas Wawrinka", "David Ferrer",
"Roger Federer", "Andy Murray", "Tomas Berdych",
"Juan Martin Del Potro", "Richard Gasquet", "John Isner"};
List playerList = Arrays.asList(players);
System.out.println(getBeginWith(playerList,(s)->s.startsWith("R")));
System.out.println(getBeginWith(playerList,(s)->s.contains("D")));
System.out.println(getBeginWith(playerList,(s)->s.endsWith("er")));
}
}
The result of this is:
[Rafael Nadal, Roger Federer, Richard Gasquet]
[Novak Djokovic, David Ferrer, Juan Martin Del Potro]
[David Ferrer, Roger Federer, John Isner]
Computer Programming 2 35

You can download this example here (needed tools can be found in the right menu on

this page)

Example using Supplier<T>:

public class SupplierApp {


private static void printNames(Supplier<String> arg) {
System.out.println(arg.get());
}
private static void listBeginWith(List<String> list, Predicate<String> valid) {
printNames(()->"\nList of players:");
list.forEach(player -> {
if (valid.test(player)) {
printNames(()->player);
}
});
}
public static void main(String[] args) {
String[] players = {"Rafael Nadal", "Novak Djokovic",
"Stanislas Wawrinka", "David Ferrer",
"Roger Federer", "Andy Murray", "Tomas Berdych",
"Juan Martin Del Potro", "Richard Gasquet", "John Isner"};
List playerList = Arrays.asList(players);
// print which starts with 'R'
listBeginWith(playerList, (s) -> s.startsWith("R"));
listBeginWith(playerList, (s) -> s.contains("D"));
listBeginWith(playerList, (s) -> s.endsWith("er"));
}
}

The result of this is:

List of players:
Rafael Nadal
Roger Federer
Richard Gasquet

List of players:
Novak Djokovic
David Ferrer
Juan Martin Del Potro

List of players:
David Ferrer
Roger Federer
John Isner
Computer Programming 2 36

You can download this example here (needed tools can be found in the right menu on

this page)

 The API contains other predefined interfaces that can be used as functional

interface.

Here are some of them:

Functional Function
Abstract Method Description
Interface descriptor

Runnable run() () -> void When a Thread starts the Runnable

object, the method run() will bee

executed.

ActionListener actionPerformed ActionEvent This Listener receives action events

(ActionEvent) -> void and the method

actionPerformed(ActionEvent e)

execute.

Comparator<T> compare(T , T ) (T,T) -> int Compares its two arguments for

order. Returns a negative integer,

zero, or a positive integer as the first

argument is less than, equal to, or

greater than the second.

Observer Update (Observable, This method is called whenever the

(Observable, Object ) -> observed object is changed.

Object ) void
Computer Programming 2 37

Example using Runnable:

public class RunnableApp {


public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() +
" application : is running");
// Impementation without using lambda
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is running");
}
});
thread2.start();
// Using Lambda Runnable
Runnable task3 = () -> {
System.out.println(Thread.currentThread().getName() + " is running");
};
new Thread(task3).start();
// All in one statement using Lambda and Runnable interface
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " is running");
}).start();
}
}

The result of this is:

main application : is running


Thread-0 is running
Thread-1 is running
Thread-2 is running

You can download this example here (needed tools can be found in the right menu on

this page)
Computer Programming 2 38

Example using ActionListener:

public class ListenerApp {


// static swing helper method
static private void setAppSize(JFrame frame, int width, int heigth) {
int widthExt = 20;
int heightExt = 50;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setBounds((screenSize.width - (width + widthExt)) / 2,
screenSize.height / 20, width + widthExt, heigth + heightExt);
}
public static void main(String[] args) {
JButton testButton = new JButton("Test Button");
// Without Lambda add listener as an anonymous object implementation
testButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Click Detected by anonymous object");
}
});
// add listener with lambda expression
testButton.addActionListener(
e -> System.out.println("Click Detected by Lambda Listner"));
// Swing stuff
JFrame frame = new JFrame("Listener APP");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setAppSize(frame, 300, 200);
frame.add(testButton, BorderLayout.CENTER);
frame.setVisible(true);
}
}

The result of this is:


Computer Programming 2 39

Pressing the button result in:

Click Detected by Lambda Listner

Click Detected by anonymous objec

You can download this example here (needed tools can be found in the right menu on

this page)

Example using Comparator<T>:

public class ComparatorApp {


public static void main(String[] args) {
List<Person> personList = Person.createShortList();
// Sort on persons surname with abstract inner class object implementation
Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return p1.getSurName().compareTo(p2.getSurName());
}
});
System.out.println("=== Sorted ascending Surname ===");
personList.forEach(p -> p.printName());
// Use Lambda and print all persons on ascending GivenName.
System.out.println("=== Sorted ascending Givenname ===");
Collections.sort(personList,
(Person p1, Person p2) -> p1.getGivenName().compareTo(p2.getGivenName()
));
personList.forEach(p -> p.printName());
// Use Lambda and print all persons on descending SurName
System.out.println("=== Sorted descending Surname ===");
Collections.sort(personList,
(p1, p2) -> p2.getSurName().compareTo(p1.getSurName()));
personList.forEach(p -> p.printName());
}
}
// Requuired Person.java file
public class Person {
private String givenName;
private String surName;
...
public static List<Person> createShortList(){
...
}
}
Computer Programming 2 40

The result of this is:

=== Sorted ascending Surname ===


Name: Joe Bailey
Name: Bob Baker
Name: Jane Doe
Name: John Doe
Name: James Johnson
Name: Betty Jones
Name: Phil Smith
=== Sorted ascending Givenname ===
Name: Betty Jones
Name: Bob Baker
Name: James Johnson
Name: Jane Doe
Name: Joe Bailey
Name: John Doe
Name: Phil Smith
=== Sorted descending Surname ===
Name: Phil Smith
Name: Betty Jones
Name: James Johnson
Name: Jane Doe
Name: John Doe
Name: Bob Baker
Name: Joe Bailey

You can download this example here (needed tools can be found in the right menu on

this page)

Example using Observer:

public class ObserverApp extends Observable {

public void changeMessage(String message) {


setChanged();
notifyObservers(message);
}
public static void main(String[] args) {
ObserverApp board = new ObserverApp();
// add Observer objects
board.addObserver(new Student("Bob").getObserver());
board.addObserver(new Student("Joe").getObserver());
// create an event
board.changeMessage("More Homework!");
Computer Programming 2 41

}
}

class Student {
private String name;
// Lambda on observer
private Observer observer =
(o, arg) -> System.out.println(name + " got message: " + arg);
// this is the same as:
// private Observer observer = new Observer(){
// @Override
// public void update(Observable o, Object arg) {
// System.out.println(name+" got message: " + arg);
// }
// };
public Student(String name) {
this.name = name;
}
public Observer getObserver() {
return observer;
}
}

The result of this is:

Joe got message: More Homework!


Bob got message: More Homework!

Recursion, User-defined Functions (subprograms)

The process in which a function calls itself directly or indirectly is called recursion and

the corresponding function is called as recursive function. Using recursive algorithm,

certain problems can be solved quite easily. Examples of such problems are Towers of

Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph,

etc.Recursion is a common way to simplify a problem in the same form of subproblems.

This is called the technique of dividing and conquering. Factorial function is a basic

example of recursion.
Computer Programming 2 42

It is known as a recursive method that calls itself. And, this technique is called recursion

A practical representation of the universe would be to face up to two parallel mirrors. E


very point in between would be recursively mirrored.

How recursion works?


In the above

program, recurse() method is called

from inside the main method at first

(normal method call).

Also, recurse() method is called from

inside the same method, recurse().

This is a recursive call.

The recursion continues until some condition is met to prevent it from execution. If not,

infinite recursion occurs.

Hence, to prevent infinite recursion, if...else statement (or similar approach) can be used

where one branch makes the recursive call and other doesn't.

Example: Factorial of a Number Using Recursion


1. class Factorial {
2.
3. static int factorial( int n ) {
4. if (n != 0)
5. return n * factorial(n-1); // recursive call
6. else
7. return 1;
8. }
9.
10. public static void main(String[] args) {
11. int number = 4, result;
12. result = factorial(number);
13. System.out.println(number + " factorial = " + result);
14. }
15. }
When you run above program, the output will be:

4 factorial = 24
Computer Programming 2 43

Initially, factorial() is called from the main() method with number passed as an

argument.

Inside factorial() method, the value of n is 4 initially. During the next recursive call, 3 is

passed to the factorial() method. This process continues until n is equal to 0.

When n is equal to 0, if condition fails and the else part is executed which returns 1, and

accumulated result is passed to the main() method.

Advantages and Disadvantages of Recursion


When a recursive call is made, the stack will be allocated new storage location for

variables. As each recursive call returns, the stack eliminates the old variables and

parameters. Recursion thus requires more memory in general and is generally slow.

The recursive method, on the other hand, is much easier and takes less time to compose,

debug and maintain.

What is base condition in Recursion?

In the recursive program, the solution to the base case is provided and the solution of

the bigger problem is expressed in terms of smaller problems.

int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}

In the above example, base case for n < = 1 is defined and larger value of number can be

solved by converting to smaller one till base case is reached.

How a particular problem is solved using recursion?


The idea is to represent a problem in terms of one or more smaller problems, and add

one or more base conditions that stop the recursion. For example, we compute factorial
Computer Programming 2 44

n if we know factorial of (n-1). The base case for factorial would be n = 0. We return 1

when n = 0.

Why Stack Overflow error occurs in recursion?

If the base case is not reached or not defined, then the stack overflow problem may

arise. Let us take an example to understand this.

int fact(int n)
{
// wrong base case (it may cause
// stack overflow).
if (n == 100)
return 1;

else
return n*fact(n-1);
}

If fact(10) is called, it will call fact(9), fact(8), fact(7) and so on but the number will never

reach 100. So, the base case is not reached. If the memory is exhausted by these

functions on the stack, it will cause a stack overflow error.

What is the difference between direct and indirect recursion?


A function fun is called direct recursive if it calls the same function fun. A function fun

is called indirect recursive if it calls another function say fun_new and fun_new calls

fun directly or indirectly. Difference between direct and indirect recursion has been

illustrated in Table 1.
 Direct recursion:
void directRecFun()
{
// Some code....

directRecFun();

// Some code...
}
 Indirect recursion:
void indirectRecFun1()
{
Computer Programming 2 45

// Some code...

indirectRecFun2();

// Some code...
}

void indirectRecFun2()
{
// Some code...

indirectRecFun1();

// Some code...
}

What is difference between tailed and non-tailed recursion?


A recursive function is tail recursive when recursive call is the last thing executed by the

function. Please refer tail recursion article for details.

How memory is allocated to different function calls in recursion?


When any function is called from main(), the memory is allocated to it on the stack. A

recursive function calls itself, the memory for the called function is allocated on top of

memory allocated to calling function and different copy of local variables is created for

each function call. When the base case is reached, the function returns its value to the

function by whom it is called and memory is de-allocated and the process continues.

Let us take the example of how recursion works by taking a simple function.
Computer Programming 2 46

Output:
3 2 1 1 2 3

When printFun(3) is called from main(), memory is allocated to printFun(3) and a local

variable test is initialized to 3 and statement 1 to 4 are pushed on the stack as shown in

below diagram. It first prints ‘3’. In statement 2, printFun(2) is called and memory is

allocated to printFun(2) and a local variable test is initialized to 2 and statement 1 to 4

are pushed in the stack.

Similarly, printFun(2) calls printFun(1) and printFun(1) calls printFun(0). printFun(0)

goes to if statement and it return to printFun(1). Remaining statements

of printFun(1) are executed and it returns to printFun(2) and so on. In the output, value

from 3 to 1 are printed and then 1 to 3 are printed. The memory stack has been shown in

below diagram.
Computer Programming 2 47

What are the disadvantages of recursive programming over iterative

programming?

Note that both recursive and iterative programs have the same problem-solving

powers, i.e., every recursive program can be written iteratively and vice versa is also

true. The recursive program has greater space requirements than iterative program as

all functions will remain in the stack until the base case is reached. It also has greater

time requirements because of function calls and returns overhead.

What are the advantages of recursive programming over iterative

programming?
Recursion provides a clean and simple way to write code. Some problems are

inherently recursive like tree traversals, Tower of Hanoi, etc. For such problems, it is

preferred to write recursive code. We can write such codes also iteratively with the help

of a stack data structure.


Computer Programming 2 48

UNIT III
(Fundamentals of Pointers, Pointer Declarations, Passing Pointer to Function,
Pointers and One-Dimensional Array)

What are the fundamental rules of pointers?


A pointer is a programming language object that stores the memory address of

another value located in computer memory. A pointer references a location in memory,

and obtaining the value stored at that location is known as dereferencing the pointer. As

an analogy, a page number in a book's index could be considered a pointer to the

corresponding page; dereferencing such a pointer would be done by flipping to the

page with the given page number and reading the text found on that page. The actual

format and content of a pointer variable is dependent on the underlying computer

architecture.

Using pointers significantly improves performance for repetitive operations like

traversing iterable data structures, e.g. strings, lookup tables, control

tables and tree structures. In particular, it is often much cheaper in time and space to

copy and dereferences pointers than it is to copy and access the data to which the

pointers point.

Pointers are also used to hold the addresses of entry points for called subroutines

in procedural programming and for run-time linking to dynamic link libraries (DLLs).

In object-oriented programming, pointers to functions are used for binding methods,

often using what are called virtual method tables.

Java

Unlike C, C++, or Pascal, there is no explicit representation of pointers in Java.

Instead, more complex data structures like objects and arrays are implemented

using references. The language does not provide any explicit pointer manipulation

operators. It is still possible for code to attempt to dereference a null reference (null

pointer), however, which results in a run-time exception being thrown. The space

occupied by unreferenced memory objects is recovered automatically by garbage

collection at run-time.
Computer Programming 2 49

Because Java has no data types for the pointer, it is not possible to use Java pointers. Eve

n the few experts are not going to be able to use java pointers. Java has no C-

like pointers, but it allows you to create new objects on the heap that are "referenced" by

variables

All objects in Java are references and you can use them like pointers.

abstract class Animal


{...
}

class Lion extends Animal


{...
}

class Tiger extends Animal


{
public Tiger() {...}
public void growl(){...}
}

Tiger first = null;


Tiger second = new Tiger();
Tiger third;
Dereferencing a null:

first.growl(); // ERROR, first is null.


third.growl(); // ERROR, third has not been initialized.
Aliasing Problem:

third = new Tiger();


first = third;
Losing Cells:

second = third; // Possible ERROR. The old value of second is lost.


You can make this safe by first assuring that there is no further need of the old value of
second or assigning another pointer the value of second.

first = second;
second = third; //OK
Note that giving second a value in other ways (NULL, new...) is just as much a potential
error and may result in losing the object that it points to.

The Java system will throw an exception (OutOfMemoryError) when you call new and
the allocator cannot allocate the requested cell. This is very rare and usually results
from run-away recursion.
Note that, from a language point of view, abandoning objects to the garbage collector
are not errors at all. It is just something that the programmer needs to be aware of. The
same variable can point to different objects at different times and old values will be
Computer Programming 2 50

reclaimed when no pointer references them. But if the logic of the program requires
maintaining at least one reference to the object, It will cause an error.

Novices often make the following error.

Tiger tony = new Tiger();


tony = third; // Error, the new object allocated above is reclaimed.
What you probably meant to say was:

Tiger tony = null;


tony = third; // OK.
Improper Casting:

Lion leo = new Lion();


Tiger tony = (Tiger)leo; // Always illegal and caught by compiler.

Animal whatever = new Lion(); // Legal.


Tiger tony = (Tiger)whatever; // Illegal, just as in previous example.
Lion leo = (Lion)whatever; // Legal, object whatever really is a Lion.

Function Pointers in Java

Java does not provide function pointers in the same way C/C++ does.

Instead of passing a function pointer f, you create an object with an instance

method f and pass the object instead. With lambdas and method refernecs the

syntactical overhead for doing this is close to zero.

Using a method reference

class Example {
// Method that takes a "method" as argument
static void exampleMethod(Runnable toRun) {
toRun.run();
}

// Method to pass
static void sayHello() {
System.out.println("Hello");
}

public static void main(String[] args) {


exampleMethod(Example::sayHello); // prints "Hello"
}
}

Using a lambda

You may also invoke the exampleMethod above as follows:


Computer Programming 2 51

exampleMethod(() -> System.out.println("Hello"));

For similar examples with different method signatures, see the Lambda Cheat Sheet.

Using ordinary objects

The above examples requires Java 8. Here's how to do it in Java 7:

exampleMethod(new Runnable() {
@Override
public void run() {
System.out.println("Hello");
}
});

Using reflection

You can use reflection to pass actual Method objects and Method.invoke to invoke the
method. This is not recommended and often seen as a hack / last resort.

import java.lang.reflect.Method;

class Example {

static void exampleMethod(Method toInvoke) throws Exception {


// null as callee for static methods
toInvoke.invoke(null);
}

public static void sayHello() {


System.out.println("Hello");
}

public static void main(String[] args) throws Exception {


// prints "Hello"
exampleMethod(Example.class.getMethod("sayHello"));
}
}
Computer Programming 2 52

UNIT IV
(Structure within a Structure, Array within a Structure, Pointer Structures,
Linked List Structures Using Looping Constructs)

Java programming language is platform-independent and a secure programming

language. With a wide variety of applications, Java programming language has been in

demand for the last two decades. The out-of-the-box features help java stand apart. In

this article, we will understand the structure of a java program in detail. Following are

the topics discussed in this blog:

 Documentation Section

 Package Statement

 Import Statement

 Interface Section

 Class Definition

 Main Method Class

Documentation Section

It is used to improve the readability of the program. It consists of comments in

Java which include basic information such as the method’s usage or functionality to

make it easier for the programmer to understand it while reviewing or debugging the

code. A Java comment is not necessarily limited to a confined space, it can appear

anywhere in the code.


Computer Programming 2 53

The compiler ignores these comments during the time of execution and is solely meant

for improving the readability of the Java program.

There are three types of comments that Java supports

 Single line Comment

 Multi-line Comment

 Documentation Comment

Let’s take a look at an example to understand how we can use the above-mentioned

1 // a single line comment is declared like this

2 /* a multi-line comment is declared like this

3 and can have multiple lines as a comment */

4 /** a documentation comment starts with a delimiter and ends with */

comments in a Java program.

Package Statement

There is a provision in Java that allows you to declare your classes in a collection

called package. There can be only one package statement in a Java program and it has to

be at the beginning of the code before any class or interface declaration. This statement

is optional, for example, take a look at the statement below.

1 package student;

This statement declares that all the classes and interfaces defined in this source file are a

part of the student package. And only one package can be declared in the source file.

Import Statement

Many predefined classes are stored in packages in Java, an import statement is used to

refer to the classes stored in other packages. An import statement is always written after

the package statement but it has to be before any class declaration.

We can import a specific class or classes in an import statement. Take a look at the

example to understand how import statement works in Java.


Computer Programming 2 54

1 import java.util.Date; //imports the date class

2 import java.applet.*; //imports all the classes from the java applet package

Interface Section

This section is used to specify an interface in Java. It is an optional section which is

mainly used to implement multiple inheritance in Java. An interface is a lot similar to a

class in Java but it contains only constants and method declarations.

An interface cannot be instantiated but it can be implemented by classes or extended by

1 interface stack{

2 void push(int item);

3 void pop();

4 }

other interfaces.

Class Definition

A Java program may contain several class definitions, classes are an essential part of

any Java program. It defines the information about the user-defined classes in a

program.

A class is a collection of variables and methods that operate on the fields. Every

program in Java will have at least one class with the main method.

Main Method Class

The main method is from where the execution actually starts and follows the order

specified for the following statements. Let’s take a look at a sample program to

understand how it is structured.


Computer Programming 2 55

1 public class Example{

2 //main method declaration

3 public static void main(String[] args){

4 System.out.println("hello world");

5 }

}
6

Let’s analyze the above program line by line to understand how it works.

public class Example

This creates a class called Example. You should make sure that the class name starts

with a capital letter, and the public word means it is accessible from any other classes.

Comments

To improve the readability, we can use comments to define a specific note or

functionality of methods, etc for the programmer.

Braces

The curly brackets are used to group all the commands together. To make sure that the

commands belong to a class or a method.

public static void main

 When the main method is declared public, it means that it can be used outside of

this class as well.

 The word static means that we want to access a method without making its

objects. As we call the main method without creating any objects.

 The word void indicates that it does not return any value. The main is declared

as void because it does not return any value.

 Main is the method, which is an essential part of any Java program.

String[] args

It is an array where each element is a string, which is named as args. If you run the Java

code through a console, you can pass the input parameter. The main() takes it as an

input.
Computer Programming 2 56

System.out.println();

The statement is used to print the output on the screen where the system is a predefined

class, out is an object of the PrintWriter class. The method println prints the text on the

screen with a new line. All Java statements end with a semicolon.

Basic Principles of Linked Lists

Basic data declarations

All the code below assumes the following declaration:

public class Node {

public int item;

public Node next;

Node() { // this would be the default, put here for reference

item = 0;

next = null;

Node(int n) {

item = n;

next = null;

Node(int n, Node p) {

item = n;

next = p;

};

Node head = null; // pointer to the head of a list


Computer Programming 2 57

These constructors will simplify a number of the algorithms below. For example, to

create a list with one element containing the item 5, we could write:

head = new Node();

head.item = 5;

head.next = null; // not actually necessary, since pointers are initialized to null

by default

or we can simply use the constructor:

head = new Node(5);

Either will produce:

To add a node containing a 5 to the front of an existing list

we could write

head = new Node();

head.item = 5;

head.next = list;

or use the constructor:

head = new Node(5, list);

either of which produces the follow data structure:


Computer Programming 2 58

We can also "splice" a node into the middle of an existing list, as long as we have a

pointer to the node right before the splice; suppose we have a list and a pointer p to a

node in the list:

We can add a new node containing 5 after p (i.e., between the node p and the

node p.next) by writing:

Node q = new Node();

q.item = 5;

q.next = p.next;

p.next = q;

which produces:

Or we can use the constructor:

p.next = new Node(5, p.next);

which produces the same list but without the temporary variable q:
Computer Programming 2 59

Note that it can also be used to create simple linked lists in a single Java statement. For

example, the list just created by splicing could alternately have been created by the

following single statement.

Node list = new Node(6, new Node(2, new Node(5, new Node(1))));

Basic Paradigms for Manipulating a Linked List with a Global Head Pointer

In many cases, you have one or more linked lists stored in an ADT object, and you need

to manipulate them using ADT methods, and everything is private inside the object.

This is the case, for example, in the stack and queue ADT examples of linked lists we

studied in lecture. The head pointer, and all the method are private members of the

class, for example, here is an object D with an internal linked list and associated

methods:

We will assume for the present that we are manipulating a single linked list in this

fashion.
Computer Programming 2 60

Adding to front of a list

The declarations above create an empty list:

Node head = null;

To add to the front of the list, just use the constructor as shown above, changing the

pointer head to put a new node between it and the node it points to:

void addToFront(int n) {

head = new Node(n, head);

So, here is the result of three calls to addToFront, starting from an empty list:

addToFront(1, head);

addToFront(2, head);

addToFront(6, head);
Computer Programming 2 61

Removing the first node in a list

Do the reverse of the previous method is also a simple example of list manipulation;

here we will remove the first element and return the number in the node removed

int removeFront() {

int temp = head.item; // does no error checking for empty lists!

head = head.next;

return temp;

You should have recognized the previous two methods as identical to push and pop on

a stack!!

Basic chaining to access each element of a list

The basic thing you do with a list is to "chain along" the list, setting a pointer p to each

node in turn and performing some operation at each node (such as printing out the list).

This is done with a simple for loop that initializes a reference to the first node and stops

when it reaches null. At each iteration of the loop, p will point to each node in the list in

turn:

for(Node p = head; p != null; p = p.next ) {

// Do something with each node, such as print out the item

OR use a while loop:

Node p = head;

while (p != null) {

// Do something with each node, such as print out the item

p = p.next;

}
Computer Programming 2 62

This produces the following at each successive iteration of the loop:

At the last iteration, p chains along one more time to point to null, and the for loop

ends:

Note we are guaranteed by the loop condition that p is not null inside the loop, so we

can refer to p.item or p.next anytime we want inside the loop without worrying

about NullPointerExceptions.
Computer Programming 2 63

Printing Out A List

We can then put this code inside a method to do something specific to each member of

the list, such as printing it out. Remember that these methods exist inside an object with

a global field head pointing to a linked list.

void printList() {
System.out.print("head -> ");
for(Node p = head; p!=null; p = p.next) {
System.out.print(p.item + " -> ");
}
System.out.println(".");
}

Producing a String representation of the list

If we want to produce a String representation for the toString() method the ADT, we

can do the same thing but collect the results and return them:

public String toString() {

String s = "head -> ";

for(Node p = head; p!=null; p = p.next) {

s += (p.item + " -> ");

return s + ".";

Finding the Length of a List

Another simple example would be finding the length of a list, which can be done by

simply keeping a running count inside the for loop:

int length() {
int count = 0;
for(Node p = head; p != null; p = p.next ) {
++count;
}
return count;
}
Computer Programming 2 64

UNIT V
(Text File, Non-Text File)

Every method that deals with reading text files needs one of these. Java will throw any

errors up the line, and they will be caught in

our main method. To read characters from

a text file, the FileReader is used. This reads

bytes from a text file, and each byte is a single

character.

Manipulating text files is an ability in your

programming career that will serve you well.

You'll learn how to open and write to a text file

in this section.

A binary file is a computer file that

is not a text file. The term "binary file" is often

used as a term meaning "non-text file".

A text file is a computer file that only contains text and has no special formatting such

as bold text, italic text, images, etc. With Microsoft Windows computers text files are

identified with the . txt file extension, as shown in the example picture.

An example of a text file and ASCII art can be seen in Kirk text file. You can click this

link to open the .txt file in your browser or right-click the file to save the text file to your

computer.

Types of Text Files

In the general sense, a text file refers to any file that has only text and is void of images

and other non-text characters. These sometimes use the TXT file extension but don't

necessarily need to. For example, a Word document that is an essay containing just text

can be in the DOCX file format but still be called a text file.

Another kind of text file is the 'plain text' file. This is a file that contains zero formatting

(unlike RTF files), meaning nothing is bold, italic, underlined, colored, using a special

font, etc. Several examples of plain text file formats include ones that end
Computer Programming 2 65

in XML, REG, BAT, PLS, M3U, M3U8, SRT, IES, AIR, STP, XSPF, DIZ, SFM, THEME,

and TORRENT.

Of course, files with the .TXT file extension are text files too and are commonly used to

store things that can be easily opened with any text editor or written to with a simple

script. Examples might include storing step-by-step instructions for how to use

something, a place to hold temporary information, or logs generated by a program

(though those are usually stored in a LOG file).

"Plaintext," or cleartext files, are different than "plain text" files (with a space). If file

storage encryption or file transfer encryption is not used, the data can be said to exist in

plaintext or be transferred over plaintext. This can be applied to anything that should be

secured but isn't, be it emails, messages, plain text files, passwords, etc., but it's usually

used in reference to cryptography.

How to Open a Text File

All text editors should be able to open any text file, especially if there isn't any special

formatting being used. For example, TXT files can be opened with the built-in Notepad

program in Windows by right-clicking the file and choosing Edit. Similar for TextEdit

on a Mac.

Another free program that can open any text file is Notepad++. Once installed, you can

right-click the file and choose Edit with Notepad++.

Most web browsers and mobile devices can open text files too. However, since most of

them are not built to load text files using the various extensions you mind them using,

you might need to first rename the file extension to .TXT if you want to use those

applications to read the file.

Some other text editors and viewers include Microsoft

Word, TextPad, Notepad2, Geany, and Microsoft WordPad.

Additional text editors for macOS include BBEdit and TextMate. Linux users can also

try the Leafpad, gedit, and KWrite text openers/editors.


Computer Programming 2 66

Open Any File as a Text Document

Something else to understand here is that any file can be opened as a text document

even if it doesn't contain readable text. Doing this is useful when you're not sure what

file format it's really in, like if it's missing a file extension or you think it's been

identified with an incorrect file extension.

For example, you can open an MP3 audio file as a text file by plugging it into a text

editor like Notepad++. You can't play the MP3 this way but you can see what it's made

up of in text form since the text editor is only able to render the data as text.

With MP3s in particular, the very first line should include "ID3" to indicate that it's a

metadata container that might store information like an artist, album, track number, etc.

Another example is the PDF file format; every file starts off with the "%PDF" text on the

first line, even though it'll be completely unreadable.

How to Convert Text Files

The only real purpose for converting text files is to save them into another text-based

format like CSV, PDF, XML, HTML, XLSX, etc. You can do this with most advanced text

editors but not the simpler ones since they generally only support basic export formats

like TXT, CSV, and RTF.

For example, the Notepad++ program mentioned above is capable of saving to a huge

number of file formats, like HTML, TXT, NFO, PHP, PS, ASM, AU3, SH, BAT, SQL,

TEX, VGS, CSS, CMD, REG, URL, HEX, VHD, PLIST, JAVA, XML, and KML.

Other programs that export to a text format can probably save to a few different kinds,

typically TXT, RTF, CSV, and XML. So if you need a file from a specific program to be

in a new text format, consider returning to the application that made the original text

file, and export it to something else.

All that said, text is text so long as it's plain text, so simply renaming the file, swapping

one extension for another, might be all you need to do to "convert" the file.
Computer Programming 2 67

Also, see our list of Free Document Converter Software Programs for some additional

file converters that work with various types of text files.

Is Your File Still Not Opening?

Are you seeing jumbled text when you open your file? Maybe most of it, or all of it, is

completely unreadable. The most likely reason for this is that the file is not plain text.

Like we mentioned above, you can open any file with Notepad++, but like with the MP3

example, it doesn't mean that you can actually use the file there. If you try your file in a

text editor and it's not rendering like you think it should rethink how it should open; it's

probably not in a file format that can be explained in human-readable text.

If you have no idea how your file should open, consider trying some popular programs

that work with a wide variety of formats. For example, while Notepad++ is great for

seeing the text version of a file, try dragging your file into VLC media player to check if

it's a media file that contains video or sound data.


Computer Programming 2 68

REFERENCES:

Java Multidimensional Arrays. (n.d.). Retrieved from https://www.programiz.com/java-


programming/multidimensional-array.

Binary search. (n.d.). Retrieved from https://introcs.cs.princeton.edu/java/42sort/.

kartikgoel1999Check out this Author's contributed articles., kartikgoel1999, & Check


out this Author's contributed articles. (2019, April 23). Recursion in Java. Retrieved from
https://www.geeksforgeeks.org/recursion-in-java/.

About The AuthorUmut Muhaddisoglu is a Web designer/developer. He runs


WebResourcesDepot, & Author, A. T. (2009, March 3). 40 Useful JavaScript Libraries.
Retrieved from https://www.smashingmagazine.com/2009/03/40-stand-alone-javascript-
libraries-for-specific-purposes/.

Finnesand, K. (2019). Java Predefined Functional Interface. [online] W3processing.com.


Available at:
http://www.w3processing.com/index.php?subMenuLoad=java/oop/PredefinedFunction
al.php [Accessed 30 Nov. 2019].

Pointer (computer programming). (2019, November 20). Retrieved from


https://en.wikipedia.org/wiki/Pointer_(computer_programming)#Java.

Function Pointers in Java. (n.d.). Retrieved from


https://programming.guide/java/function-pointers-in-java.html.

Linked Lists and Iterative Algorithms. (n.d.). Retrieved from


http://www.cs.bu.edu/~snyder/cs112/CourseMaterials/LinkedListNotes.Iteration.html.

Fisher, T. (2019, September 26). What's a Text File & How Do You Open One? Retrieved from
https://www.lifewire.com/txt-text-file-4150707.

You might also like