Professional Documents
Culture Documents
COMPUTER
PROGRAMMING II
Computer Programming 2 2
TABLE OF CONTENTS
UNIT I…………………………………………………………………………3
UNIT II…………………………………………………………………………24
UNIT III…………………………………………………………………………48
UNIT IV…………………………………………………………………………52
UNIT V…….……………………………………………………………….64
UNIT I
(Arrays, Searching, Sorting)
container for holding a constant number of values of the same type. Memory space is
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
A particular element in a large group of elements may be accessed easily with the
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-
Second, it is also necessary to specify the position of each element, as that is wher
As it is visible, the three elements that have been listed simultaneously are as follows:
10
20
30
dimensional set.
Output:
Computer Programming 2 5
Using Scanner
1.) Read the array length as sc.nextInt() and store it in the variable len and
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
Output:
Computer Programming 2 6
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
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
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
type String.
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
1. class MultidimensionalArray {
3.
4. int[][] a = {
5. {1, 2, 3},
6. {4, 5, 6, 9},
7. {7},
8. };
9.
13. }
14. }
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
(a[0], a[1] and a[2] are also arrays), you can use length attribute to find the length of
each rows.
1. class MultidimensionalArray {
3.
4. int[][] a = {
7. {7},
8. };
9.
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
1. class MultidimensionalArray {
3.
4. int[][] a = {
7. {7},
8. };
9.
12. System.out.println(data);
13. }
14. }
15. }
16. }
Computer Programming 2 11
-2
-4
-5
You can initialize 3d array in similar way like a 2d array. Here's an example:
// test is a 3d array
int[][][] test = {
{2, 3, 4}
},
{1},
{2, 3}
};
1. class ThreeArray {
3.
4. // test is a 3d array
5. int[][][] test = {
6. {
8. {2, 3, 4}
9. },
10. {
12. {1},
13. {2, 3}
14. }
15. };
16.
21. System.out.println(item);
22. }
23. }
24. }
25. }
26. }
Computer Programming 2 13
-2
-4
-5
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
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
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
that f(x) = y. We start with an interval (lo, hi) known to contain x and use the
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
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
algorithm.
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:
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.
This process executed first with i equal to 1, then 2, then 3, and so forth, as illustrated in
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
o Best case. When the input array is already in sorted order, the total number
o Worst case. When the input is reverse sorted, the number of compares is ~
o Average case. When the input is randomly ordered, the expected number of
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
of Comparable objects.
Computer Programming 2 17
Mergesort.
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:
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.
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
important problems, as you will learn if you take a course on algorithm design.
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
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
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
Sorting the frequencies. Next, we sort the Counter objects. We can do so in client
phenomenon known as Zipf's law says that the frequency of the ith most
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
computer graphics (convex hull, closest pair), computational biology (longest common
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
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;
Result
Found 2 @ 5
Computer Programming 2 21
Linear Search
Result
Bubble Sort
}
System.out.println();
bubbleSort(arr);
System.out.println("Array After Bubble Sort");
Result
2 5 -2 6 -3 8 0 -7 -9 4
-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))
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
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.
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
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
qForms A complete solution for handling forms. It equips a developer with features
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.
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
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,
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
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”
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
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.
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
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
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
opacity of the reflection can be defined. Using it is as easy as adding a “class” to the
4. Database
Taffy DB A JavaScript library that can be thought as an SQL database in the browser or
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
Using ActiveRecord.js, you can auto-create tables, validate and synchronize data and
more.
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
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
library, RegExp objects can be cached and reused, modifiers can be added to existing
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
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
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.
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
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
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
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.
using images. It is focused on IE and supports it through VML. Other browsers are
DD_belatedPNG is a library that provides a customizable fix for the notorious IE6 PNG
image” DD_belatedPNG can fix it. Unlike other solutions, “background-position” and
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
GameJS
“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
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
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
interfaces that you can use when creating lambda expressions or method
references.
You can download this example here (needed tools can be found in the right menu on
this page).
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)
You can download this example here (needed tools can be found in the right menu on
this page)
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.
Functional Function
Abstract Method Description
Interface descriptor
executed.
actionPerformed(ActionEvent e)
execute.
Comparator<T> compare(T , T ) (T,T) -> int Compares its two arguments for
Object ) void
Computer Programming 2 37
You can download this example here (needed tools can be found in the right menu on
this page)
Computer Programming 2 38
You can download this example here (needed tools can be found in the right menu on
this page)
You can download this example here (needed tools can be found in the right menu on
this page)
}
}
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 process in which a function calls itself directly or indirectly is called recursion and
certain problems can be solved quite easily. Examples of such problems are Towers of
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
The recursion continues until some condition is met to prevent it from execution. If not,
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.
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
When n is equal to 0, if condition fails and the else part is executed which returns 1, and
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,
In the recursive program, the solution to the base case is provided and the solution of
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
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.
If the base case is not reached or not defined, then the stack overflow problem may
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
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...
}
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
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
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
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
UNIT III
(Fundamentals of Pointers, Pointer Declarations, Passing Pointer to Function,
Pointers and One-Dimensional Array)
and obtaining the value stored at that location is known as dereferencing the pointer. As
page with the given page number and reading the text found on that page. The actual
architecture.
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).
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
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.
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.
Java does not provide function pointers in the same way C/C++ does.
method f and pass the object instead. With lambdas and method refernecs the
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");
}
Using a lambda
For similar examples with different method signatures, see the Lambda Cheat Sheet.
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 {
UNIT IV
(Structure within a Structure, Array within a Structure, Pointer Structures,
Linked List Structures Using Looping Constructs)
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
Documentation Section
Package Statement
Import Statement
Interface Section
Class Definition
Documentation Section
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
The compiler ignores these comments during the time of execution and is solely meant
Multi-line Comment
Documentation Comment
Let’s take a look at an example to understand how we can use the above-mentioned
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
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
We can import a specific class or classes in an import statement. Take a look at the
2 import java.applet.*; //imports all the classes from the java applet package
Interface Section
1 interface stack{
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.
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
4 System.out.println("hello world");
5 }
}
6
Let’s analyze the above program line by line to understand how it works.
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
Braces
The curly brackets are used to group all the commands together. To make sure that the
When the main method is declared public, it means that it can be used outside of
The word static means that we want to access a method without making its
The word void indicates that it does not return any value. The main is declared
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.
item = 0;
next = null;
Node(int n) {
item = n;
next = null;
Node(int n, Node p) {
item = n;
next = p;
};
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.item = 5;
head.next = null; // not actually necessary, since pointers are initialized to null
by default
we could write
head.item = 5;
head.next = list;
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
We can add a new node containing 5 after p (i.e., between the node p and the
q.item = 5;
q.next = p.next;
p.next = q;
which produces:
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
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
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) {
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
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() {
head = head.next;
return temp;
You should have recognized the previous two methods as identical to push and pop on
a stack!!
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:
Node p = head;
while (p != null) {
p = p.next;
}
Computer Programming 2 62
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
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
void printList() {
System.out.print("head -> ");
for(Node p = head; p!=null; p = p.next) {
System.out.print(p.item + " -> ");
}
System.out.println(".");
}
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:
return s + ".";
Another simple example would be finding the length of a list, which can be done by
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
character.
in this section.
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.
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
"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
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
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
Additional text editors for macOS include BBEdit and TextMate. Linux users can also
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
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
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
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
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
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
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
REFERENCES:
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.