• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Java Stream

PrintStream Class in Java

By Dinesh Thakur

When a program is executed, the input is read from the various sources and the output is sent to different destinations. Generally, keyboard and monitor screen are used as standard input and output device, respectively.

 

The data fed by the user is supplied to the program using input streams and the output of the program is supplied to the output device using output streams. This output is displayed to the user using Java PrintStream class. So far the two methods, print () and println (),that have been used for displaying the primitive data type, object, etc. on an output device are defined by the PrintStream class. This is a byte stream class which is derived from the Output Stream class. Unlike other output streams, the PrintStream class does not throw an IOException even if an exceptional event occurs.

PrintStream class can be connected to the underlying output stream such as

FileOutputStream, ByteArrayOutputStream, BufferedOutputStream, etc

Print Stream class defines following type of constructor.

PrintStream(OutputStream os)

This constructor creates a print stream and connects it to the output stream os.

In addition to print () and println () methods, the PrintStream class defines some Other methods which are listed in Table

                                        Table PrintStream Class Methods

Method

Description

PrintStream append (char c)

Appends the character c to the output stream

PrintStream append (CharSequence cs)

Appends the character sequence c to the output stream

boolean checkError ()

Checks the error state of the stream

protected void setError ()

Sets the error state to true

 

Character Stream Classes in Java

By Dinesh Thakur

One of the limitations of byte stream classes is that it can handle only 8-bit bytes and cannot work directly with Unicode characters. To overcome this limitation, character stream classes have been introduced in java.io package to match the byte stream classes. The character stream classes support 16-bit Unicode characters, performing operations on characters, character arrays, or strings, reading or writing buffer at a time. Character stream classes are divided into two stream classes namely, Reader class and Writer class.

Reader Classes

Reader classes are used to read 16-bit unicode characters from the input stream. The Reader class is the superclass for all character-oriented input stream classes. All the methods of this class throw an IOException. Being an abstract class, the Reader class cannot be instantiated hence its subclasses are used. Some of these are listed in Table

                                                                Table Reader Classes

Class

Description

BufferedReader

contains methods to read characters from the buffer

CharArrayReader

contains methods to read characters from a character array

FileReader

contains methods to read from a file

FilterReader

contains methods to read from underlying character-input stream

InputStreamReader

contains methods to convert bytes to characters

PipedReader

contains methods to read from the connected piped output stream

StringReader

contains methods to read from a string

The Reader class defines various methods to perform reading operations on data of an input stream. Some of these methods along with their description are listed in Table.

                                                                Table Reader Class Methods

Method

Description

int read()

returns the integral representation of the next available character of input. It returns -1 when end of file is encountered

int read (char buffer [])

attempts to read buffer. length characters into the buffer and returns the total number of characters successfully read. It returns -I when end of file is encountered

int read (char buffer [], int loc, int nChars)

attempts to read ‘nChars’ characters into the buffer starting at buffer [loc] and returns the total number of characters successfully read. It returns -1 when end of file is encountered

void mark(int nChars)

marks the current position in the input stream until ‘nChars’ characters are read

void reset ()

resets the input pointer to the previously set mark

long skip (long nChars)

skips ‘nChars’ characters of the input stream and returns the number of actually skipped characters

boolean ready ()

returns true if the next request of the input will not have to wait, else it returns false

void close ()

closes the input source. If an attempt is made to read even after closing the stream then it generates IOException

Using Buffered.Reader Class

The BufferedReader class creates a buffered character stream between the input device and the program. It defines the methods to read the data from the buffer in the form of characters.

The BufferedReader object can be created using one of the following two constructors.

BufferedReader(Reader inpStream) //first

BufferedReader(Reader inpStream, int nChars) //second

The first constructor creates a buffered character stream of default buffer size. The second constructor creates a buffered character stream that uses an input buffer of size nChars.

Besides the methods provided by the Reader class, the BufferedReader class contains some other methods which are discussed as follows.

• String readLine ():It reads a line of the input text.

• boolean ready () : It checks whether or not the stream is ready to be read.

A program to demonstrate the use of BufferedReader class

import java.io.*;
class BufferedReaderExample {
       publicstaticvoid main(String args[])throwsIOException{
             String s=“This program is skipping first character of each word in the string”;
             StringReader sr = newStringReader(s);
             System.out.println(“The input string is: “+s);
             /*Creating an instance of BufferedReader using StringReader*/
             BufferedReader br = newBufferedReader(sr);
             //Reading from the underlying StringReader
             System.out.print (“The output string is: “);
             br.skip(1);
             /*skipping the first character of the first word of the input string*/
             //reading the remaining string
             int i=0;
             while((i=br.read())!=–1){
                   System.out.print((char)i);
                   if((char)i==‘ ‘)
                       //checking for white spaces
                       {
                               br.skip(1);
                               /*skipping first character of each word*/
                        }
             }
     }
}

The output of the program is

The input string is: This program is skipping first character of each word in the string

The output string is: his rogram s kipping irst haracter f ach ord n he tring In this program, skip () method is used to skip the first character of each word of the input string.

Writer Classes

Writer classes are used to write 16-bit Unicode characters onto an outputstream. The Writer class is the superclass for all character-oriented output stream classes .All the methods of this class throw an IOException. Being an abstract class, the Writer class cannot be instantiated hence, its subclasses are used. Some of these are listed in Table.

                                                            Table Writer Classes

Class

Description

BufferedWriter

Contains methods to write characters to a buffer

FileWriter

Contains methods to write to a file

FilterWriter

Contains methods to write characters to underlying output stream

CharArrayWriter

Contains methods to write characters to a character array

OutputStreamWriter

Contains methods to convert from bytes to character

PipedWriter

Contains methods to write to the connected piped input stream

StringWriter

Contains methods to write to a string

The Writer class defines various methods to perform writing operations on output stream. These methods along with their description are listed in Table.

                                                      Table Writer Class Methods

Method

Description

void write ()

writes data to the output stream

void write (int i)

Writes a single character to the output stream

void write (char buffer [] )

writes an array of characters to the output stream

void write(char buffer [],int loc, int nChars)

writes ‘n’ characters from the buffer starting at buffer [loc] to the output stream

void close ()

closes the output stream. If an attempt is made to perform writing operation even after closing the stream then it generates IOException

void flush ()

flushes the output stream and writes the waiting buffered output characters

Using BufferedWriter Class

The BufferedWriter class, an output counterpart of the BufferedReader, is used to write characters onto the character-output stream.

The BufferedWriter object can be created using one of the following two constructors.

BufferedWriter(Writer outStream) //first

BufferedWriter(Writer outStream, int nChars) //second

The first constructor creates a buffered character stream of default buffer size. The second constructor creates a buffered character stream that uses an input buffer of size nChars. Besides the methods provided by the Writer class, the BufferedWriter class contains the newLine () method which writes a new line.

//A program to demonstrate the use of BufferedWriter class

The output of the program is

This is an example of BufferedWriter

import java.io.*;
class BufferedWriterExample {
        public static void main(String args[]) throws IOException {
               String s = “This is an example of BufferedWriter”;
               StringWriter sw = new StringWriter();
               //creating an instance of BufferedWriter class
               BufferedWriter bw = new BufferedWriter(sw);
               bw.write(s,0,5);
               bw.newLine();
               bw.write(s,5,s.length()–5);
               /*writes the substring starting from index 5*/
               bw.flush() ;
              //flushes the stream
               System.out.println(sw.getBuffer());
               sw.close();
               //closing the stream
               bw.close();
               //closing the stream
       }
}

In this example the BufferedWriter class is used to write data to character-output stream (instance of StringWriter class). The getBuffer () method of the StringWriter class returns a buffer of String type.

Byte Stream Classes in java

By Dinesh Thakur

Byte stream classes are used to perform reading and writing of 8-bit bytes. Streams being unidirectional in nature can transfer bytes in one direction only, that is, either reading data from the source into a program or writing data from a program to the destination. Therefore, Java further divides byte stream classes into two classes, namely, InputStream class and OutputStrearn class. The subclasses of InputStrearn class contain methods to support input and the subclasses of OutputStrearn class contain output related methods.

Input Stream Classes

Java’s input stream classes are used to read 8-bit bytes from the stream. The InputStrearn class is the superclass for all byte-oriented input stream classes. All the methods of this class throw an IOException. Being an abstract class, the InputStrearn class cannot be instantiated hence, its subclasses are used. Some of these are listed in Table

                                                          Table Input Stream Classes

Class

Description

BufferedInputStream

contains methods to read bytes from the buffer (memory area)

ByteArrayInputStream

contains methods to read bytes from a byte array

DataInputStream

contains methods to read Java primitive data types

FileInputStream

contains methods to read bytes from a file

FilterInputStream

contains methods to read bytes from other input streams which it uses as its basic source of data

ObjectInputStream

contains methods to read objects

PipedInputStream

contains methods to read from a piped output stream. A piped input stream must be connected to a piped output stream

SequenceInputStream

contains methods to concatenate multiple input streams and then read from the combined stream

The Input Stream class defines various methods to perform reading operations on data of an input stream. Some of these methods along with their description are listed in Table

                                            Table InputStream Class Methods

Method

Description

int read()

returns the integral representation of the next available byte of input. It returns -1 when end of file is encountered

int read (byte buffer [])

attempts to read buffer. length bytes into the buffer and returns the total number of bytes successfully read. It returns -1 when end of file is encountered

int read (byte buffer [], int loc, int nBytes)

attempts to read ‘nBytes’ bytes into the buffer starting at buffer [loc] and returns the total number of bytes successfully read. It returns -1 when end of file is encountered

int available ()

returns the number of bytes of the input available for reading

Void mark(int nBytes)

marks the current position in the input stream until ‘nBytes’ bytes are read

void reset ()

Resets the input pointer to the previously set mark

long skip (long nBytes)

skips ‘nBytes’ bytes of the input stream and returns the number of actually skippedbyte

void close ()

closes the input source. If an attempt is made to read even after closing the

stream then it generates IOException

Using ByteArrayinputStream Class

The ByteArrayinputStream class opens an input stream to read bytes from a byte array. It contains an internal buffer that holds bytes that are read from the stream. It should be noted that closing the stream does not have any consequences. That is, methods of this class can be invoked even after closing the stream without generating any IOException.

The ByteArrayinputstream object can be created using one of the following constructors.

ByteArrayinputStream(byte[] buffer) //first

ByteArrayinputStream(byte[] buffer, int loc, int nBytes)

//second

The first constructor creates a ByteArrayinputStream which uses a byte array buffer as its input source. The second constructor creates a ByteArrayinputStream which uses a subset of byte array buffer as its input source. The reading begins from the index specified by loc and continues until nBytes are read.

// A Program to demonstrate the use of ByteArrayInputStream class

import java.io.*;

class ByteArrayInputStreamExample

{

      public static void main(String args[]) throws IOException

      {

           byte b[]=”this is my first program”.getBytes();

           ByteArrayInputStream inp =new ByteArrayInputStream(b);

           int n=inp.available();

           System.out.println(“Number of available bytes: “+n);

           long s=inp.skip(11); //skipping 11 bytes

           System.out.println(“Number of skipped bytes: “+s);

           int i;

           System.out.print(“String after skipping s bytes: “);

           while((i=inp.read()) != -1)

                  {

                         System.out.print((char)i);

                   }

           inp.reset(); /*reset the pointer to the beginning of the stream*/

           System.out.println(); //new line

           int j;

           System.out.print(“String in uppercase: “);

           while((j=inp.read()) != -1)

                  {

                      System.out.print(Character.toUpperCase((char) j));

                  }

      }

}

The output of the program is

Number of available bytes: 24

Number of skipped bytes: 11

String after skipping s bytes: first program

String in uppercase: THIS IS MY FIRST PROGRAM

In this example, the getBytes () method is used to convert string into bytes. The use of available () and skip () methods is demonstrated here. Once the entire stream is read, reset () method is invoked to set the pointer at the start of the stream.

Output Stream classes

Java’s output stream classes are used to write 8-bit bytes to a stream. The OutputStream class is the superclass for all byte-oriented output stream classes. All the methods of this class throw an IOException. Being an abstract class, the OutputStream class cannot be instantiated hence, its subclasses are used. Some of these are listed in Table

                                                           Table Output Stream Classes

Class

Description

BufferedOutputStream

Contains methods to write bytes into the buffer

ByteArrayOutputStream

Contains methods to write bytes into a byte array

DataOutputStream

Contains methods to write Java primitive data types

FileOutputStream

Contains methods to write bytes to a file

FilterOutputStream

Contains methods to write to other output streams

ObjectOutputStream

Contains methods to write objects

PipedOutputStream

Contains methods to write to a piped output stream

PrintStream

Contains methods to print Java primitive data types

The OutputStream class defines methods to perform writing operations. These methods are discussed in Table

                                           TableOutputStream Class Methods

.Method

Description

void write (int i)

writes a single byte to the output stream

void write (byte buffer [] )

writes an array of bytes to the output stream

Void write(bytes buffer[],int loc, int nBytes)

writes ‘nBytes’ bytes to the output stream from the buffer b starting at buffer [loc]

void flush ()

Flushes the output stream and writes the waiting buffered output bytes

void close ()

closes the output stream. If an attempt is made to write even after closing the stream then it generates IOException

Using ByteArrayOutputStream Class

TheByteArrayOutputStreamclass,anoutputcounterpartoftheByteArrayinputStream, writes streams of bytes to the buffer. Similar to ByteArrayinputStream, closing this stream has no effect. That is, methods of this class can be invoked even after closing the stream without generating any IOException.

The ByteArrayOutputStream object can be created using one of the following constructors.

ByteArrayOutputStream () I /first

ByteArrayOutputStream(int nBytes) //second

The first constructor creates a buffer of 32 bytes. The second constructor creates a buffer of size equal to nBytes. The size of the buffer increases as bytes are written to it.

// A Program to demonstrate the use of ByteArrayOutputStream class

import java.io.*;

class ByteArrayOutputStreamExample

{

     public static void main(String args[]) throws IOException

     {

        ByteArrayOutputStream out=new ByteArrayOutputStream();

        byte b[]=”Today is a bright sunny day”.getBytes();

        out.write(b);

        System.out.println(out.toString() ); /*converting byte array to String*/

        out.close(); //closing the stream

     }

}

The output of the program is

Today is a bright sunny day

In this example, the getBytes () method is used to convert string into bytes. Once the entire stream is written, the to String ( ) method is invoked to convert the contents (bytes) of the buffer into a string.

Filter Streams

By Dinesh Thakur

The java.io package provides a set of abstract classes that define and partially implement Filter streams. A Filter stream filters data as it is being read from or written to the stream. The two filter streams for reading and writing data are Filter input Stream and Filter Output Stream ,respectively.

 

A filter stream is constructed on another stream. That is, every filtered stream must be attaché to another stream. This can be achieved by passing an instance of Input Stream or Output Stream to a constructor. This implies that filter streams are chained. Multiple filters can be added by chaining them to a stream of bytes. The read method in a readable filter stream reads input from the underlying stream, filters it and passes on the filtered data to the caller. The write method in a writable filter stream filters the data and then writes it to the underlying stream. The filtering done by the streams depends on the stream. Some streams buffer the data, some count data as they go by and others convert data from the original form to a different one. Most filter streams provided by the java.io package are sub-classes of Filter input Stream and Filter Output Stream, and are listed below:

   • Data input Stream and Data Output Stream

   • Buffered input Stream and Buffered Output Stream

   • Line Number input Stream

   • Push back input Stream

   • Print Stream

The java.io package contains only one sub-class of Filter Reader known as Push back Reader.

To create filter input or output stream, we should attach the filter stream to another input or output stream. For example, we can attach a filter stream to the standard input stream in the following manner:

 BufferedReader d = new BufferedReader(new InputStreamReader(System. in));

                 String input;

                 While((input = d.readLine()) != null)

                {

                    ……

               }

The above code is useful for reading the data from the console. Here, Input Stream Reader is attached to Buffered Reader which acts as the filter stream.

Data input Stream and Data Output Stream

Data input Stream (Data Output Stream) is a filtered input (output) stream and hence must be attached to some other input (output) stream. Data input Stream handles reading in data as well as lines of text. Program stores the data which are read from the console in tabular format using Data Output Stream. After that, the program reads the data using the Data input Stream.

Program Using Data Output Stream and Data input Stream.

import java.io.*;

class Sample Stream

{                      

      public static void main(String a[ ]) throws IOException

     {

            DataOutputStream out = new DataOutputStream(new

                                                       File Output Stream(“file.txt”));

            InputStreamReader isr = new Input Stream Reader(System. in);

            Buffered Reader is = new BufferedReader(isr);

            char sep = System.get Property(“file.separator”).charAt(0);

            for (int i = 0; i < 5; i ++)

           {

                  System.out.print(“Read the item name:”);

                  String item=br.readLine();

                  out.WriteChars(item+separator);

                  out.WriteChar(‘\t’);

                  System.out. print(“Read the quantity:”);

                  int qun=integer.Parselnt(br.readLine());

                  out.writelnt(qun); 

                  out.writeChar(‘\n’);

           }

            out.c1ose();

            DatalnputStream in = new DatalnputStream(new

            FilelnputStream(“file.txt”));

            try

           {

                  char chr;

                  while (in.avaiiable()>0)

                 {

                       StringBuffer item1 = new StringBuffer(20);

                       while ((chr = in.readChar())!= sep)

                       {

                            item1.append( chr);

                        }

                        System.out.print(item1);

                        System.out.print(in.readChar() );

                        System.out.print(in.read Int());                      

                        System.out.print(in.readChar() );

                }

           }

           catch (EOFException e)

          {

           }

                   in.c1ose();

                }

            }

Running Program  gives the following output:

              Read the item name: Mouse

               Read the quantity: 4

               Read the item name: Keyboard

               Read the quantity: 3

               Read the item name: Monitor

               Read the quantity: 2

               Read the item name: Modem

               Read the quantity: 4

               Read the item name: Hub

               Read the quantity: 4

             Mouse 4

              Keyboard 3

             Monitor 2

              Modem 4

              Hub 4

The above example stores the items required and the quantity of the item. Although the data are read or written in binary form, they appear on the console as characters .Data Output Stream is attached to a File Output Stream that is set up to write to a file namedfile.txt. Data Output Stream writes the data in the file.txt file by using specialized write XXX()methods. Here, XXX represents a Java data type. Next, Sample Stream opens a Data input Stream .on the file just written to read the data from it by using Data input Stream’s specialized read XXX()methods. In general, we use null or -1 to indicate the end of the file. Some methods such as read String()and read Char() in the Data input Stream do not identify null or-1 as an end of file marker. Thus, programmer must be careful while writing loops using Data Input stream for reading characters from a file. The available() method of Data input Stream, which returns the number of bytes remaining, can be used to check whether there are any data remaining to read.

Push back input Stream

Pushback is used on input streams to allow a byte to be read from and returned to the stream. Like all filter streams, Push back input stream is also attached to another stream. It is typically used for some specific implementation, for example, to read the first byte of the data from a stream forth purpose of testing the data. For example, it is mostly required in the case of designing parsers, while reading data, to have glance on the next set of input data. Data must be read and if not found appropriate, it should be placed back into the input stream, which may be read again and processed normally. A Push back input Stream object can be created as follows:

Push back input Stream imp = new Push back input Stream(new Input Stream);

In order to satisfy the requirement of pushing back a byte (or bytes) of an array into the input stream, this stream has the special method called the unread () method.

                        void unread( int ch );

                        void unread( bute buf[ ] );

                        void unread( byte buf[ ], int offset, int numchars );

the first form pushes back the lowest-order byte of ch, which is returned as the next byte when another byte is read. The second and the third forms of the method return the byte in a buffer with the difference that the third method pushes back the number of characters (numchars) starting from the offset. Push back Reader also does the same thing on the character stream.

File input Stream and File Output Stream

By Dinesh Thakur

The File class explains only the file system. Java provides two special types of stream called the File input Stream and File Output Stream to read data from and write data into the file. These classes operate on the files in the native file system. File input Stream and File Output Stream are subclasses of Input Stream and Output Stream, respectively. Usually, we use File input Stream(for byte streams) or File Reader (for character streams) for reading from a file and File Output Stream(for byte streams) or File Writer (for character streams) for writing into a file.

 

We can create a file stream by giving the file name as a parameter in the form of a string, File object or File Descriptor object. File Writer and File Output Stream will create a new file by that name if the file does not already exist.

The constructors of these two streams are:

• FileinputStream(String filename);    • File Output Stream(String filename);

• FileinputStream(File file object);       • File Output Stream(File file object);

• FileinputStream(File Descriptor fdesobject);  • File Output Stream(File Descriptor

                                                                              fdes object);

File Descriptor is an object that holds the information about a file.

A File input Stream object can be created in the following manner:

                        File input Stream fin = new File input Stream(string filename);

Alternatively, it can be created with the following set of statements:

                      File = new File(string filename);

                      File input Stream fin = new File input Stream(f);

A File Output Stream object can be created as follows:

                 File Output Stream foot = new File Output Stream(string filename);

Note that in the case of File Output Stream if it is opened on a file that does not already exist then a new file by that name is created.

Program  implementing the class Copy File uses File input Stream and File Output Stream to copy the contents of input File to output File: input File and output File are the command line arguments arg[0] and arg[1].

 Using Copy File, File input Stream and File Output Stream.

import java.io.*;

public class Copy File

{

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

     {

            if(args.length<2)

            System.out.println(“\n No sufficient parameters”);

            else

            {

                File input File = new File(args[0]);

                File output File = new File(args[1]);

                FileinputStream in = new FileInputStream(inputFile);

                FileOutputStream out = new FileOutputStream(outputFile);

               int c;

                while ((c= in.read()) != -1)

                out. write(c);

                   in.c1ose();

                   out.c1ose();

             }

       }

}

In Program the file input File is opened using File input Stream and another file output File is opened using File Output Stream. If input File does not exist, the program gives an error because File input Stream cannot work if the file does not exist. On the other hand, if output File does not exist, then a file by that name will be created. The program continues to read characters from File input Stream as long as there are inputs in the input file and writes these characters on to File Output Stream. When all the inputs have been read, the program closes both File input Stream and File Output Stream. Program  can also be written using File Reader and File Writer with the small changes shown below:

                                         File inputFile = new File(args[0]);

                                         FileReader in = new FileReader(input File);

This code creates a File object that represents the named file on the native file system. File is a utility class provided by java.io. Program the Copy File program uses this file object only to construct a File Reader on a file; however, the program could also use the input file to get information about the file, such as its full path name. If we run Program an exact copy of input File (args[0]) will be found in a file named output File (args[1]) in the same directory. It should be remembered that File Reader and File Writer read and write 16-bit characters; however, most native file systems are based on 8-bit bytes. These streams encode the characters as they operate according to the default character-encoding scheme. The default character-encoding scheme can be found by using System. Get Property(“file. Encoding”). To specify an encoding scheme other than the default, we should construct an Output Stream Writer on a File Output Stream and specify the encoding scheme. It is important to note that the File Output Stream object does not support the means to append file. If the file exists already, File Output Stream only overwrites and cannot add content to amend of the file.

File Streams

By Dinesh Thakur

A file can be created using File class.

                          File;

                          f = new File (string filename);

The File class is defined in the package java.io The File class is used to store the path and name of a directory or file. But this class is not useful in retrieving or storing data. The File object can be used to create, rename or delete file or directory it represents. A directory is treated as a file that contains a list of files. Each file (or directory) in Java is an object of the File class. A File object is used to manipulate the information associated with a disk file, such as last modification date and time, directory path and also to navigate through the hierarchies of sub-directories.

  The File class has three constructors that are used to create a file object. They are the following:

  • File(String pathname);                    II pathname could be file or a directory name

  • File(String dirPathname, String filename); II specify directory where the file is created

                                                                         II and file name

  • File(File directory, String filename);         II file object as the directory path

These constructors return the reference to the file object. The File class provides several methods that deal with the files, file system, properties of the file and tests on the files. Some of the important methods that serve these purposes are listed in Table.

                Some methods in the File class and their description.

Name of method

Description

string get Name ()

Returns the name of the file excluding the directory name

string get Path ()

Returns the path of the file.

string get Parent ()

Returns the parent directory of the file

Boolean exists ()

Returns true if the file exists and returns false if the file does not exist.

Boolean can Read ()

Returns true if the file is readable, otherwise returns false

Boolean can Write ()

Returns true if the file is writable, otherwise returns false

Boolean is File ()

Returns true if the object is a file, otherwise returns false.

Boolean is Directory ()

Returns true if the object is a directory, otherwise returns false.

Boolean is Absolute ()

Returns true if the file path is the absolute path, otherwise it returns false, indicating that it is a relative path.

long length ()

Returns the length of the file (in bytes).

long last Modified ()

Returns the date on which the file was last modified

String[] list ()

Returns the list of all files and directories that exist in the current directory

There are other methods also which are useful for handling file operations such as renaming a

the file and deleting a file. The syntax of these two methods is the following:

                           boolean renameTo(File new file name);

                           boolean delete();

The following methods are used to create a directory:

                          boolean mkdir(File newdirectoryname)

                          boolean mkdirs(File newdirectoryname)

The first method creates a directory and returns true if it is successful. If the directory cannot be created, it returns false. In addition to creating a directory, the second method creates all its parent directories. The path of the directly to be created will be passed as a parameter to the mkdirs method. If the program fails to execute the mkdirs() method fully, it may be successful in creating partial directories list from the user specified path. The method mkdirs() returns true if the directory was created with all the necessary parent directories, otherwise it returns false. Directory is the name of an object in the File class with an extra property referred to as ‘list’ which is examined by the List () method. This method returns the string array with all files that exist in the directory. Program illustrates the List () method.

Using the methods List () and is Directory ()

import java.io.*;

class ListOfiles

{

      public static void main(String a[ ])

     {

           String name = arg[0];

           Filefile1= new File(name);

           if ( file1.isDirectory() )

          {

                 string arr[] = file1.list();

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

               {

                        if(arr[i]. isDirectory())

                             System.out.println(arr[i]+ “is directory”);

                       else

                           System.out.println(arr[i]+”is file”);

                }

          }

     }

}

Program illustrates the is Directory () method, which returns the value true if the in voting file object is a directory and returns the value false if it is a file. This program is run with the command line arguments in which arg [0] specifies the name of the directory. The output of the program consists of a list of all the files and directories in the present directory that is, the directory given as the input.

Java I/O

By Dinesh Thakur

Streams are represented in Java as classes. The java.io package defines a collection of stream classes that support input and output (reading and writing). To use these classes, a program needs to import the java.io package, as shown below. [Read more…] about Java I/O

I/O Streams

By Dinesh Thakur

A flow of data is often referred to as a data stream. A stream is an ordered sequence of bytes that has a SOURCE (input stream) or a DESTINATION (output stream). In simple terms, a stream can be defined as follows.

 

A stream is a logical device that represents the flow of a sequence of characters. Programs can get inputs from a data source by reading a sequence of characters from the input stream. Similarly, programs can produce outputs by writing a sequence of characters on to an output stream. A stream can be associated with a file, an Internet resource (For example, a socket), to a pipe or a memory buffer. Streams can be chained together so that each type of stream adds its own processing to the bytes as they pass through the stream. For the purpose of letting information flow, a program opens a stream on an information source (whether it be a file, memory, a network socket or any other source) and reads the information sequentially and uses it in the program. All streams behave in the same way even though the physical device connected to them may differ. A program can send information to an external destination by opening a stream to a destination and writing the information out sequentially. In previous chapters, we used the following two methods for taking inputs and giving outputs:

                 System.in.read ()

                 System.out.printIn( );

These two form the basic input and output streams, which are managed by the System class; they use the standard input and standard output streams, respectively.

LinkedList Java Example

By Dinesh Thakur

[Read more…] about LinkedList Java Example

Random File Handling in Java Example

By Dinesh Thakur

[Read more…] about Random File Handling in Java Example

Java RandomAccessFile Read Example

By Dinesh Thakur

[Read more…] about Java RandomAccessFile Read Example

RandomAccessFile in Java Example

By Dinesh Thakur

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

By Dinesh Thakur

[Read more…] about Copying Contents after Converting Each Character in Capital in a File Java Example

Counting Uppercase, LowerCase, Digits in a File Java Example

By Dinesh Thakur

[Read more…] about Counting Uppercase, LowerCase, Digits in a File Java Example

Counting Lines,words,Char in a File Java Example

By Dinesh Thakur

[Read more…] about Counting Lines,words,Char in a File Java Example

FileReader in Java Example

By Dinesh Thakur

[Read more…] about FileReader in Java Example

Copying Contents After Removing Vowels in Java Example

By Dinesh Thakur

[Read more…] about Copying Contents After Removing Vowels in Java Example

Copying Contents of One File to Another Java example

By Dinesh Thakur

[Read more…] about Copying Contents of One File to Another Java example

Reading File in Java using FileInputStream Example

By Dinesh Thakur

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();
        }
}

Reading File in Java

FileInputStream in Java Example

By Dinesh Thakur

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();
       }
 }   

FileInputStream

FileOutputStream in Java Example

By Dinesh Thakur

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();
         }                                                                           
   }

FileOutputStream

Split Function in Java with Example

By Dinesh Thakur

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]);
                 }
        }
}

Split Function in Java with Example

Properties in Java Example

By Dinesh Thakur

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");
          }
}

Properties in Java Example

Java StringTokenizer example

By Dinesh Thakur

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);
      }
}

Java StringTokenizer example

StringTokenizer in Java Example

By Dinesh Thakur

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

By Dinesh Thakur

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”));
      }
}

Hashtable

BitSet in Java Example

By Dinesh Thakur

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);
             }
                                                                                   
   }

BitSet

Stack in Java Example

By Dinesh Thakur

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 in Java Example

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());
       }
                                                                                       
}

Stack implementation in Java Example

SequenceInputStream in Java Example

By Dinesh Thakur

The SequencelnputStream class allows you to concatenate (or combine) two or more input streams serially and make them appear as if they were a single input stream. Each input stream is read beginning from the first one until end of file (EOF) is reached, where upon it reads from the second one and so on, until end of file is reached on the last of the contained input streams.

In order to create SequencelnputStream, the following two constructors are provided.

SequencelnputStream(IntputStream s1, InputStream s2)

This constructor creates a SequencelnputStream that reads from the InputStream s1 until its EOF is reached, then closes it and switched to reading from InputStream s2 until itsEOF is reached.

SequencelnputStream(Enumeration e)

This constructor creates a SequencelnputStream initialized to the specified enumeration of InputStreams.

Now let us consider a program that uses SequencelnputStream to concatenate two files.

import java.io.*;  
class SequenceInputStreamExample
{
     public static void main(String[] args)
    {
        int ch;
        try
        {
          FileInputStream file1 = new  FileInputStream  ("std.dat");
          FileInputStream file2 = new FileInputStream  ("mydata.dat");
          SequenceInputStream fin=new SequenceInputStream(file1,file2);
          while((ch=fin.read())!=-1)
              System.out.println(ch);
              fin.close();
          }
          catch(IOException e)  { e.printStackTrace(); }
        }
     }

PrintWrite in Java Example

By Dinesh Thakur

The java.io.PrintWriter is another very convenient I/O class that makes writing text to a file as easy as writing text to the console. The PrintWri ter class defines several constructors, the one we would be using is as follows.

Printwriter(OutputStream oStream, boolean autoFlush)

Here, oStreamis an object oftype OutputStream and autoFlush is an boolean variable which if set to true flushes the output stream every time a prin tln () method is invoked.

PrintWriter includes different versions of the print () and prin tln () methods of all types such as int, float etc. including Object. Thus, you can use these methods in the same way as they have been used in System. out. If the argument is not a primitive type, the printWriter methods will call the Object’s toString () method and then print out the result.

Now let us consider a program that reads lines of text typed at the keyboard and then writes the same text into a file by appending a line number at the front of each line.

import java.io.*; 
import java.util.Scanner;
public class PrintWriterExample
{
      public static void main(String[] args) throws FileNotFoundException
      {
         Scanner input = new Scanner(System.in);
         System.out.println("Enter Name of File to Read : ");
         String inputfileName = input.next();
         System.out.print("Enter Name of File in Which Data to be Written : ");
         String outputfileName = input.next();
         FileReader reader = new FileReader(inputfileName);
         Scanner in = new Scanner(reader);
         PrintWriter out = new PrintWriter(outputfileName);
         int lineNumber = 1;
         while (in.hasNext())
         {
              String line = in.nextLine();
              out.print(lineNumber + " : " + line);
              lineNumber++;
         }
             System.out.println("Data Written Successfully");
      }
   }

PrintWrite in Java Example

Next Page »

Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW