[Read more…] about Insert Element in Linked List Java Example
Deleting Desire Element of Linked List Java Example
Deleting Last Element of Linked List Java Example
Deleting First Element of Linked List Java Example
Insertion and deletion at the beginning of a linked list are very fast. They involve changing only one or two references, which takes 0(1) time. Finding, deleting, or insertion next to a specific item requires searching through, on the average, half the items in the list. This requires O(n) comparisons. An array is also O(n) for these operations, but the linked list is nevertheless faster because nothing needs to be moved when an item is inserted or deleted.
Of course, another important advantage of linked lists over arrays is that the linked list uses exactly as much memory as it needs, and can expand to fill all of the available memory. The size of an array is fixed when it’s created; this usually leads to inefficiency because the array is too large, or to running out of room because the array is too small Vectors, which are expandable arrays, may solve this problem to some extent, but they usually expand in fixed-sized increments (such as doubling the size of the array whenever it’s about to overflow). This is still not as efficient a use of memory as a linked list.
import java.io.*;
class node
{
public int v;
public node nxt;
public node(int x)
{
v=x;
}
public void dispval1()
{
System.out.println(v);
}
}
class LinkList
{
private node first,p,q;
public LinkList()
{
first=null;
}
public void insertval(int x)
{
node p=new node(x);
p.nxt=null;
if(first==null)
{
first=p;
q=p;
}
else
{
q.nxt=p;
q=p;
}
}
public void delfirst()
{
q=first;
first=first.nxt;
q=null;
}
public void displayList()
{
node r= first;
while(r !=null)
{
r.dispval1();
r=r.nxt;
}
}
}
class DeletingFirstElement
{
public static void main(String args[]) throws IOException
{
LinkList k=new LinkList();
int i;
for(i=1;i<=5;i++)
{
k.insertval(i);
}
System.out.println("Data in linked list is");
k.displayList();
k.delfirst();
System.out.println("Data in linked list after deleting first element is");
k.displayList();
}
}
Singly Linked List in Java Example
A linked list refers to a collection of nodes connected to each other with the help of a link. Each link object contains a reference usually called next to the next link in the list. Although an array is a common way of storing data elements, but inserting an element in between an array or deleting an element from an array requires a lot of shuffling of other array elements.
So, the better way is keep the data in terms of nodes linked to each other with the help of links. A link of one node can be set to point at another node without any reshuffling. Hence inserting or deleting an element from linked list is quite an easy task (just changing the link locations will do the job).
import java.io.*;
class node
{
public int v;
public node nxt;
public node(int x)
{
v=x;
}
public void dispval()
{
System.out.println(v);
}
}
class LinkList
{
private node first,p,q;
public LinkList()
{
first=null;
}
public void insertval(int x)
{
node p = new node(x);
p.nxt=null;
if(first==null)
{
first=p;
q=p;
}
else
{
q.nxt=p;
q=p;
}
}
public void delfirst()
{
q=first;
first=first.nxt;
q=null;
}
public void displayList()
{
node r=first;
while(r !=null)
{
r.dispval();
r=r.nxt;
}
}
}
class SinglyLinkedList
{
public static void main(String args[]) throws IOException
{
LinkList k= new LinkList();
BufferedReader b= new BufferedReader(new InputStreamReader(System.in));
String h;
int n,i,m;
System.out.println("How many numbers you want to insert in link list");
h=b.readLine();
n=Integer.parseInt(h);
System.out.println("Enter numerical in linked list");
for(i=1;i<=n;i++)
{
h=b.readLine();
m=Integer.parseInt(h);
k.insertval(m);
}
k.displayList();
}
}
Random File Handling in Java Example
Java RandomAccessFile Read Example
RandomAccessFile in Java Example
The RandomAccessFile class provides a multitude of methods for reading and writing to and from files.
Although we can certainly use FileInputStream and FileOutputStream for file I/O,
RandomAccessFile provides many more features and options.
Constructors:
RandomAccessFile(String name, String mode)
RandomAccessFile(File file, String mode)
The first constructor takes a String parameter specifying the name of the file to access, along with a String parameter specifying the type of mode (read or write). The mode type can be either “r” for read mode or “rw” for read/write mode. The second constructor takes a File object as the first parameter, which specifies the file to access. The second parameter is a mode string, which works exactly the same as it does in the first constructor.
getFilePointer() method
getFilePointer() returns the current position of the file pointer as a long value. The file pointer indicates the location in the file where data will next be read from or written to.
Seek() method
seekO method sets the file pointer to the absolute position specified by the long parameter pos.
import java.io.*;
public class RandomAccessFileJavaExample
{
int i;
public static void main(String args[])
{
try
{
RandomAccessFileJavaExample RAFileExample = new RandomAccessFileJavaExample();
RAFileExample.creation();
}
catch(IOException e)
{
System.out.println(e);
}
}
void creation() throws IOException
{
File dt= new File("java.dat");
RandomAccessFile fp=new RandomAccessFile(dt,"rw");
for(i=1;i<=5;i++)
{
fp.writeInt(i);
}
fp.close();
}
}
Copying Contents after Converting Each Character in Capital in a File Java Example
Counting Uppercase, LowerCase, Digits in a File Java Example
Counting Lines,words,Char in a File Java Example
FileReader in Java Example
Copying Contents After Removing Vowels in Java Example
Copying Contents of One File to Another Java example
Reading File in Java using FileInputStream Example
A Java application can accept any number of arguments from the command line. Command-line arguments allow the user to affect the operation of an application.
The user enters command line arguments when invoking the application and specifies them after the name of the class to run. For example, suppose our Java application name is ReadingFileFileInputStream which displays the contents of a file. To display the contents of the file ecomputernotes.bat, we execute the program as :
java ReadingFileFileInputStreamecomputernotes.bat
In the Java language, when we invoke an application, the runtime system passes the command line arguments to the application’s main method via an array of Strings: args. Each element in this string array args contains one of the command line arguments sent through command line. We can find out the number of command line arguments with the array’s length attribute:
n = args.length;
In Java, name of the application is already known as it is the name of the class in which the main method is defined. So the Java runtime system does not pass the class name to the main method. Rather, it passes only the items on the command line that appear after the class name.
import java.io.*;
class ReadingFileFileInputStream
{
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fp;
try
{
fp=new FileInputStream(args[0]);
}
catch(FileNotFoundException e)
{
System.out.println("File cannot be found");
return;
}
do
{
i=fp.read();
if(i !=-1)
System.out.print((char)i);
}while(i !=-1);
fp.close();
}
}
FileInputStream in Java Example
We use FilelnputStream class for reading from the file as it creates an input byte stream for reading from the file. To read the contents from the file ecomputernotes.bat, we first make an object by name say fp of FileOutputStream class and specify the file name ecomputernotes.bat as an argument to the constructor:
fp=new FilelnputStream(ecomputernotes.bat “);
If the file is not found or some error occurs in the disk, then the exception FileNotFoundException is thrown. If the file is found and everything is well, the matter is read from the file and is displayed on the screen after casting it into characters (because data in file is in byte form). When file is over, it is closed by fp.close() method.
import java.io.*;
class FileInputStreamJavaExample
{
public static void main(String args[]) throws IOException
{
int i;
FileInputStream fp;
try
{
fp=new FileInputStream("ecomputernotes.bat");
}
catch(FileNotFoundException e)
{
System.out.println("File Cannot be Found");
return;
}
System.out.println("Data in File is");
do
{
i=fp.read();
if(i !=-1)
System.out.print((char)i);
}while(i !=-1);
fp.close();
}
}
FileOutputStream in Java Example
The FileOutputStream class is used for creating or writing into the file. For more advanced file output, we use the RandomAccessFile class. A FileOutputStream object can be created using one of the following constructors:
• FileOutputStream(String name)
• FileOutputStream(File file)
• FileOutputStream(FileDescriptor fd)
The first constructor takes a String parameter, which specifies the name of the file to be used for output. The second constructor takes a File object parameter, which specifies the output file. The third constructor takes a FileDescriptor object as its only parameter.
import java.io.*;
class FileOutputStreamJavaExample
{
public static void main(String args[]) throws IOException
{
int i;
BufferedReader vv=new BufferedReader(new InputStreamReader(System.in));
FileOutputStream hh;
try
{
hh=new FileOutputStream("ecomputernotes.bat");
}
catch(IOException e)
{
System.out.println("File can not be created");
return;
}
try
{
System.out.println("Enter lines of text, # to quit");
do
{
i=vv.read();
hh.write(i);
}while(i !='#');
}
catch(FileNotFoundException e)
{
System.out.println("File error");
}
hh.close();
}
}
Split Function in Java with Example
In Split Function Java Example, the string t is split into pieces (wherever space has occurred in it) with the help of split() method and all its pieces are then stored in the string array h. Then, the length of the string h is computed by length() function and the loop is invoked in reverse to display the tokens stored in string array h in reverse order.
import java.io.*;
class SplitFunction
{
public static void main(String args[]) throws IOException
{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
String t;
int i,n;
System.out.println("Enter a line of text");
t=bf.readLine();
String[] h = t.split(" ");
System.out.println("the words in reverse order are");
n=h.length;
for(i=n-1;i>=0;i--)
{
System.out.println(h[i]);
}
}
}
Properties in Java Example
Properties is a subclass of Hashtable. It uses a list of values in which key and value is a String. many other Java classes use Properties.
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Enumeration;
class PropertiesJavaExample
{
public static void main(String args[])
{
Properties k = new Properties();
String s,a;
k.put("Rajsthan","Jaipur");
k.put("Tamilnadu","Chennai");
k.put("MP","Bhopal");
k.put("Gujrat","Gandhinagar");
try
{
s=args[0];
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("The Command Line Argument Missing");
return;
}
a=k.getProperty(s);
if(a != null)
System.out.println("Capital of "+s+" is "+a);
else
System.out.println("The State Specified is not Available");
}
}
Java StringTokenizer example
java.util.StringTokenizer class split String into different token by “space” and “comma” delimiter.
import java.util.StringTokenizer;
import java.io.*;
class JavaStringTokenizerExample
{
public static void main(String args[]) throws IOException
{
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
int n;
do
{
System.out.println("Enter a string,Enter to quit");
StringTokenizer h = new StringTokenizer(k.readLine());
n = h.countTokens();
System.out.println("There are "+n+" tokens");
while (h.hasMoreTokens())
System.out.println(h.nextToken());
} while(n !=0);
}
}
StringTokenizer in Java Example
The StringTokenizer class is used to create a parser for String objects. It parses strings according to a set of delimiter characters. It implements the Enumeration interface in order to provide access to the tokens contained within a string. StringTokenizer provides three constructors:
StringTokenizer(String s)
StringTokenizer(String s, String d)
StringTokenizer(String s, String d, boolean t)
s is the input string, d is a set of delimiters to be used in the string parsing and t is a boolean value used to specify whether the delimiter characters should be returned as tokens or not. The default delimiter considered are : space, tab, newline, and carriage-return characters.
The access methods provided by StringTokenizer include the Enumeration methods, hasMoreElements() and nextElement(), hasMoreTokens() and nextToken(), and countTokens()· The countTokens() method returns the number of tokens in the string being parsed.
import java.util.StringTokenizer;
class StringTokenizerJavaExample
{
public static void main(String args[])
{
String t="Welcome to India";
StringTokenizer h = new StringTokenizer(t," ");
while (h.hasMoreTokens())
{
String m = h.nextToken();
System.out.println(m);
}
}
}
Hashtable in Java Example
The Hashtable class implements a hash table data structure. A hash table indexes and stores objects in a dictionary using hash codes as the objects keys. Hash codes are integer values that identify objects. All different objects are assigned different hash values and therefore different dictionary keys.
The Object class implements the hashCode() method. This method allows the hash code of an arbitrary Java object to be calculated. All Java classes and objects inherit this method from Object. The hashCode() method is used to compute the hash code key for storing objects within a hash table. Object also implements the equals() method which is used to determine whether two objects with the same hash code are equal.
The Java Hashtable class is very similar to the Dictionary class from which it is derived. Objects are added to a hash table as key-value pairs. The object used as the key is hashed, using its hashCode() method, and the hash code is used as the actual key for the value object. When an object is to be retrieved from a hash table, using a key, the key’s hash code is computed and used to find the object.
Hashtable class provides following constructors.
Hashtable()
Hashtable(int s)
Hashtable(int s, float If)
Hashtable(Map m)
The first constructor creates a hash table of default size and with default load factor. The second constructor creates a hash table of specified size but with default load factor. The third constructor allows a hash table to be created with a specific initial capacity and load factor. The load factor is a float value between 0.0 and 1.0 which specifies the percentage of hash table which if full, hash table will be resized. For example, suppose a hash table is created with a capacity of 100 entries and a 0.70 load factor. When the hash table is 70 percent full, anew, larger hash table will be created. The default load factor is 0.75
The fourth constructor creates a hash table that is initialised with the element m and the capacity of the hash table is set to twice the number of elements in m. The access methods defined for the Hashtable class allow key-value pairs to be added to and removed from a hash table, search the hash table for a particular key or object value, create an enumeration of the table’s keys and values, determine the size of the hash table, and recalculate the hash table, as needed. Many of these methods are inherited or overridden from the Dictionary class.
import java.lang.System;
import java.util.Hashtable;
import java.util.Enumeration;
public class HashtableJavaExample
{
public static void main(String args[])
{
Hashtable h= new Hashtable();
h.put("Rajsthan","Jaipur");
h.put("Tamilnadu","Chennai");
h.put("MP","Bhopal");
h.put("Gujrat","Gandhinagar");
System.out.println("h: "+h);
Enumeration e = h.keys();
System.out.print("keys: ");
while (e.hasMoreElements())
System.out.print(e.nextElement()+”, “);
System.out.print(“\nElements: “);
e = h.elements();
while (e.hasMoreElements())
System.out.print(e.nextElement()+”, “);
System.out.println( );
System.out.println(“Capital of Tamilnadu is “+h.get(“Tamilnadu”));
System.out.println(“Capital of MP is “+h.get(“MP”));
System.out.println(“Capital of Gujrat is “+h.get(“Gujrat”));
}
}
BitSet in Java Example
The BitSet class is used to create objects that maintain a set of bits. The bits are maintained as a growable set. The capacity of the bit set is increased as needed. Bit sets are used to maintain a list of flags that indicate the state of each element of a set of conditions. Flags are boolean values that are used to represent the state of an object. It is used for representing a set of true and false values.
Two BitSetconstructors are provided.
BitSet()
BitSet(int size)
The first constructor initializes a BitSet to a default size and second constructor initialises the bitset to the given size.
import java.util.BitSet;
public class BitSetJavaExample
{
public static void main(String args[])
{
int n=8;
BitSet p = new BitSet(n);
for(int i=0;i<n;i++)
p.set(i);
System.out.print("Bits of p are set as : ");
for(int i=0;i<n;i++)
System.out.print(p.get(i)+" ");
BitSet q = (BitSet) p.clone();
System.out.print("\nBits of q are set as : ");
for(int i=0;i<n;i++)
System.out.print(q.get(i)+" ");
for(int i=0;i<3;i++)
p.clear(i);
System.out.print("\nBits of p are now set as : ");
for(int i=0;i<n;i++)
System.out.print(p.get(i)+" ");
System.out.print("\nBits of p which are true : "+p);
System.out.print("The Bits of q which are true : "+q);
BitSet r= (BitSet) p.clone();
p.xor(q);
System.out.println("Output of p xor q= "+p);
p = (BitSet) r.clone();
p.and(q);
System.out.println("Output of p and q = "+p);
p = (BitSet) r.clone();
p.or(q);
System.out.println("Output of p or q = "+p);
}
}
Stack in Java Example
The Stack class provides the capability to create and use stacks within the Java programs. Stacks are· storage objects that store information by pushing it onto a stack and remove and retrieve information by popping it off the stack. Stacks implement a last-in-first-out storage capability: The last object pushed on a stack is the first object that can be retrieved from the stack. The Stack class extends the Vector class.
The Stack class provides a single default constructor, Stack(), that is used to create an empty stack.
Objects are placed on the stack using the push() method and retrieved from the stack using the pop() method.
Search() It allows us to search through a stack to see if a particular object is contained on the stack.
Peek() It returns the top element of the stack without popping it off.
Empty() It is used to determine whether a stack is empty.
The pop() and peek() methods both throw the EmptyStackException if the stack is empty. Use of the empty() method can help to avoid the generation of this exception.
import java.util.Stack;
import java.util.EmptyStackException;
class StackJavaExample
{
public static void main(String args[])
{
Stack Stk = new Stack();
int m,s;
Stk.push(new Integer(20));
Stk.push(new Integer(30));
System.out.println("Value Popped from Stack is : "+ Stk.pop());
Stk.push(new Integer(30));
s=0;
while(!Stk.empty())
{
m=((Integer)Stk.pop()).intValue();
s=s+m;
}
System.out.println("Sum of the Values Left in Stack is : "+ s);
}
}
Stack implementation in Java Example
import java.util.Stack;
import java.util.EmptyStackException;
class StackImpJavaExample
{
public static void main(String args[])
{
Stack Stk = new Stack();
Stk.push("Blue Demon");
Stk.push("Orchids");
Stk.push("Ganga");
System.out.println("Element Popped From Stack is : "+Stk.pop());
Stk.push("Ganga");
System.out.println("Element at the Top of the Stack is : "+Stk.peek());
while (!Stk.empty())
System.out.println("Elements Popped from Stack is : "+Stk.pop());
}
}
Vector elementAt() Java example
The elements() method of the Vector class is used to retrieve an enumeration of the elements that were added to the vector. A while loop is then used to cycle through and print the elements contained in the enumeration. The hasMoreElements() method is used to determine whether the enumeration contains more elements. If it does, the nextElement() method is used to retrieve the object for printing.
The removeElement() of the Vector class is used to remove the vector element The for loop indexes each element in the vector using the elementAt() method.
import java.util.Vector;
import java.util.Enumeration;
class elementAtJavaExample
{
public static void main(String args[])
{
Vector vector = new Vector(4);
int n,i;
vector.addElement("Blue Demon");
vector.addElement("Doble Cola");
vector.addElement("Ganga");
vector.addElement("Orchids");
vector.addElement("Duke's Mangola");
System.out.println("Capacity of vector is :" + vector.capacity());
System.out.println("First element is :" + vector.firstElement());
System.out.println("Last element is :" + vector.lastElement());
System.out.println("Third element is :" + vector.elementAt(3));
System.out.println("Orchids is at position: " + vector.indexOf("Orchids",0));
vector.insertElementAt("Vanilla",2);
vector.removeElementAt(0);
n=vector.size();
String arr[]=new String[n];
vector.copyInto(arr);
for(i=0;i<=n-1;i++)
{
System.out.println(arr[i]);
}
}
}
Vector Java Example
The Vector class provides the capability to implement a growable array. The array grows larger as more elements are added to it. The array may also be reduced in size, after some of its elements have been deleted. This is accomplished using the trimToSize() method.
Vector operates by creating an initial storage capacity and then adding to this capacity as needed. It grows by an increment defined by the increment variable. The initial storage capacity and increment can be specified in Vector’s constructor. There
are three types of constructors:
Vector()
Vector(int size)
Vector(int size, int increment)
The increment specifies the number of elements to allocate each time the vector is filled up to its capacity. In default constructor we don’t specify the initial capacity nor the increment so, it creates a default vector of initial size of 10.
All the vectors are created with an initial storage capacity and objects are added to them. When the initial capacity is filled and we attempt to store more objects in the vector, the vector allocates the space equal to that specified by increment. The increment is so selected that it allocates space to the new objects and still has some extra space. Specifying more space reduces the overhead of allocating space every time. If we don’t specify the increment, the vector size is doubled every time its capacity is filled
import java.util.Vector;
import java.util.Enumeration;
class VectorsJavaExample
{
public static void main(String args[])
{
Vector vector = new Vector(3,2);
vector.addElement(new Integer(15));
vector.addElement(new Integer(12));
vector.addElement(new Integer(25));
vector.addElement(new Integer(25));
vector.addElement(new Integer(10));
System.out.println("First Element is: " + (Integer)vector.firstElement());
System.out.println("Last Element is: " + (Integer)vector.lastElement());
Enumeration Enum = vector.elements();
System.out.print("Total Elements in Vector are : ");
while(Enum.hasMoreElements())
System.out.print(Enum.nextElement() + " ");
}
}
Creating Own Exception in Java Example
Java.lang.Exception Class is the superclass for all exceptions in Java. To creating our own extensions, we simply extend this class. [Read more…] about Creating Own Exception in Java Example
ArrayStoreException in Java Example
ArrayStoreException is thrown when ever we storing something in an array. If we store wrong type object into an array then this will be thrown. Here is the Java example which explains this. [Read more…] about ArrayStoreException in Java Example
What is Bytecode?
Bytecode: The intermediate code produced by certain semi-compiled programming languages, in particular SMALLTALK and JAVA, So called because each instruction is one byte long. Source programs are com piled into bytecode, which is then executed by a bytecode INTERPRETER or VIRTUAL MACHINE that forms part of the language RUN-TIME SYSTEM. In such languages, programs may be distributed either in SOURCE CODE or in bytecode form.
What are Apache?
A very popular WEB SERVER developed and distributed free of charge as OPEN SOURCE software by an Internet-based community of unpaid volunteers. Apache’s great strengths lie in the availability of its source code and its well-defined interface for writing add-on modules: many large and profitable e-commerce sites run on modified versions of Apache. The name is a wince-making pun on the phrase ‘a patchy server’, bestowed because of the numerous software PATCHES released for it in its early days.