In the Last Tutorial we discussed the concept of Inheritance. Today we are gonna touch another important concept called Encapsulation. I will start of by introducing the formal definition of Encapsulation as found here. Encapsulation is a way by which data and functions are combined into one structure or entity and treated as one. In older approaches of programming data and functions were kept independent of each other. This created problems for the programmers. As the size of the program grew so did its complexity. By combining the two into one entity programmers's job simplified :-
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Java Tutorial 2: Introduction to object oriented programming Inheritance
In our previous tutorial i.e. A programmer's Diary: Java Tutorial 1: Introduction to object oriented programming we touched the concept of objects and classes. In this tutorial we will try and grab the concept of inheritance. Ok so we established that classes are blueprints. But sometimes 1 blueprints is built on the foundation of the other blueprint. In this case we say that blueprint number 2 is derived from blueprint number 1. It has same features has blueprint number one and plus its own features.
Filed under:
java,
object oriented programming,
oops,
tutorial
Java Tutorial 1: Introduction to object oriented programming
Hi My name is Jasleen and I am gonna explain to you what exactly is object oriented programming in the most layman language possible. So what exactly is OBJECT ORIENTED PROGRAMMING? Sounds daunting right? But once you understand it you will realize it is NOT. You will discover its potential and it will change your perception towards how you see programming.
In object oriented programming we have only one job- Design Objects and put them into code. You must be thinking this girl is nuts and doesn't know anything. I am wasting my time. Trust me you are not.
In object oriented programming we have only one job- Design Objects and put them into code. You must be thinking this girl is nuts and doesn't know anything. I am wasting my time. Trust me you are not.
Topological Sort
In this post I will show the implementation of Topological sort using java. I have followed the algorithm from wikipedia. http://en.wikipedia.org/wiki/Topological_sorting#Algorithms.
Filed under:
algorithms,
graphs,
java,
topological sort
Red Black tree java code : Insertion , deletion
A red black tree is a binary tree that satisfies the following red-black properties
- Every node is either red or black
- The root is black
- Every leaf(NIL) is black
- If a node is red, then both its children are black
- For each node, all simple paths from the node to descendant leaves contains the same number of black nodes.
Filed under:
algorithms,
deletion,
insertion,
java,
red black tree
Binary Search Tree implementation java : Insertion, Deletion, Right Rotate, Left Rotate, Predecessor, Successor, Inorder
A binary search tree is a data structure having the following properties
- It has only one root node.
- Each node can have at most two children.
- The value of left child is always smaller than its parent.
- The value of right child is always greater than its parent.
- Every node has the following attributes :- parent, leftChild, rightChild and key.
Print Last n sentences from a file java
My version of program :- Print Last n sentences / lines from a file java
Open to a better solution. Just a trial
Open to a better solution. Just a trial
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PrintLastNSentences {
public void printLastNSentences(int n) {
try {
/*creating a simple file */
File file = new File("/home/jasleen/d.txt");
FileWriter fw = new FileWriter(file);
for (int i = 0; i < 100000; i++) {
fw.append("\nAs Macbeth takes a journey, so does his speech and its punctuation. Note the increasingly long sentences as Macbeth delves deeper into the horror and chaos of the contemplated deed. The first complete sentence is nearly five lines. The next sentence is over nine lines. And if, for the purpose of analyzing this speech, we consider the semicolons and colons to serve the same purpose as periods (which they could, depending on the actor), then we see even more clearly the escalation of sentence length. While Macbeth begins with a simple five-word phrase (\"He's here in double trust\") he culminates with a 36-word sentence (ending with \"drown the wind.\").");
}
fw.close();
/*Using a RandomAccessFile to seek the file*/
RandomAccessFile raf = new RandomAccessFile(file, "rw");
/*Retreiving the length of the file and subtracting by
1 to seek to the last character of the file*/
long pointer = file.length() - 1;
/*Using a StringBuilder to store the setence character by character.
Not used String because String is immutable*/
StringBuilder sb = new StringBuilder();
int linecount = 0;
/*Running the loop till we have reached a point where no more characters
are left to read or 10 lines have been processed*/
while (pointer != -1 && linecount < n) {
/*Seeking to the current poistion*/
raf.seek(pointer);
/*Reading the byte*/
int aByte = raf.read();
/*Checking to see if the current character is a new line character*/
if (((char) aByte) != '\n') {
sb.insert(0, (char) aByte); //here we are inserting the char at first position
} else {
if (sb.length() > 1)///This is a check to avoid blank sentences
///It can be removed if blank sentence are also allowed.
{
System.out.println(sb.toString());
sb.delete(0, sb.length()); //This is to empty the string builder
linecount++;
}
}
pointer--;
}
raf.close();//Closing the file after reading
} catch (FileNotFoundException ex) {
Logger.getLogger(PrintLastNSentences.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(PrintLastNSentences.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String args[]) {
new PrintLastNSentences().printLastNSentences(10);
}
}
Merge Sort implementation java
Merge sort is a sorting algorithm that splits the collection into two halves and sorts each half and then merging the two halves. Consider the following example.
JUnit test for MergeSort
Following is the java implementation of the algorithm in java.
public class MergeSort {
public MergeSort(Integer a[]) {
this.a = a;
}
Integer a[];
public void merge(int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
Integer L[] = new Integer[n1 + 1];
Integer R[] = new Integer[n2 + 1];
for (int i = 0; i < n1; i++) {
L[i] = a[p + i];
}
for (int j = 0; j < n2; j++) {
R[j] = a[q + j + 1];
}
L[n1] = Integer.MAX_VALUE;
R[n2] = Integer.MAX_VALUE;
int i = 0;
int j = 0;
for (int k = p; k <= r; k++) {
if (L[i] < R[j]) {
a[k] = L[i];
i = i + 1;
} else {
a[k] = R[j];
j = j + 1;
}
}
}
public void mergeSortPass(int p, int r) {
if (p < r) {
int q = (p + r) / 2;
mergeSortPass(p, q);
mergeSortPass(q + 1, r);
merge(p, q, r);
}
}
public void mergeSort() {
mergeSortPass(0, a.length - 1);
}
}
JUnit test for MergeSort
import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
import static org.junit.Assert.*;
public class MergeSortTest {
private Integer[] numbers;
private final static int SIZE = 7;
private final static int MAX = 20;
@Test
public void testMergeSort() {
for (int i = 0; i < 200; i++) {
numbers = new Integer[SIZE];
Random generator = new Random();
for (int a = 0; a < numbers.length; a++) {
numbers[a] = generator.nextInt(MAX);
}
Integer copy[]=new Integer[SIZE];
System.arraycopy(numbers, 0, copy, 0, numbers.length);
MergeSort ms=new MergeSort(numbers);
ms.mergeSort();
Arrays.sort(copy);
assertArrayEquals(copy, numbers);
}
}
}
Reference- Introduction To Algorithms
Subscribe to:
Posts (Atom)