Back to Study material
OOP

UNIT-6I/O System Basics, File I/O
  • Write in brief an introduction of File Handling
  • In programming, we may require some specific input data to be generated several numbers of times. Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited amount of data can be displayed on the console, and since the memory is volatile, it is impossible to recover the programmatically generated data again and again. However, if we need to do so, we may store it onto the local file system which is volatile and can be accessed every time. Here, comes the need of file handling in C.File handling in C enables us to create, update, read, and delete the files stored on the local file system through our C program. The following operations can be performed on a file.
  • Creation of the new file
  • Opening an existing file
  • Reading from the file
  • Writing to the file
  • Deleting the file
  • Functions for file handlingThere are many functions in the C library to open, read, write, search and close the file. A list of file functions are given below:

    No.

    Function

    Description

    1

    fopen()

    opens new or existing file

    2

    fprintf()

    write data into the file

    3

    fscanf()

    reads data from the file

    4

    fputc()

    writes a character into the file

    5

    fgetc()

    reads a character from file

    6

    fclose()

    closes the file

    7

    fseek()

    sets the file pointer to given position

    8

    fputw()

    writes an integer to file

    9

    fgetw()

    reads an integer from file

    10

    ftell()

    returns current position

    11

    rewind()

    sets the file pointer to the beginning of the file

     Opening File: fopen()We must open a file before it can be read, write, or update. The fopen() function is used to open a file. The syntax of the fopen() is given below.
  • FILE *fopen( const char * filename, const char * mode );  
  • The fopen() function accepts two parameters:
  • The file name (string). If the file is stored at some specific location, then we must mention the path at which the file is stored. For example, a file name can be like "c://some_folder/some_file.ext".
  • The mode in which the file is to be opened. It is a string.
  • We can use one of the following modes in the fopen() function.

    Mode

    Description

    r

    opens a text file in read mode

    w

    opens a text file in write mode

    a

    opens a text file in append mode

    r+

    opens a text file in read and write mode

    w+

    opens a text file in read and write mode

    a+

    opens a text file in read and write mode

    rb

    opens a binary file in read mode

    wb

    opens a binary file in write mode

    ab

    opens a binary file in append mode

    rb+

    opens a binary file in read and write mode

    wb+

    opens a binary file in read and write mode

    ab+

    opens a binary file in read and write mode

     The fopen function works in the following way.
  • Firstly, It searches the file to be opened.
  • Then, it loads the file from the disk and place it into the buffer. The buffer is used to provide efficiency for the read operations.
  • It sets up a character pointer which points to the first character of the file.
  • Consider the following example which opens a file in write mode.
  • #include<stdio.h>  
  • void main( )  
  • {  
  • FILE *fp ;  
  • char ch ;  
  • fp = fopen("file_handle.c","r") ;  
  • while ( 1 )  
  • {  
  • ch = fgetc ( fp ) ;  
  • if ( ch == EOF )  
  • break ;  
  • printf("%c",ch) ;  
  • }  
  • fclose (fp ) ;  
  • }  
  • OutputThe content of the file will be printed.#include;void main( ){FILE *fp; // file pointerchar ch; fp = fopen("file_handle.c","r");while ( 1 ){ch = fgetc ( fp ); //Each character of the file is read and stored in the character file.  if ( ch == EOF )break;printf("%c",ch);}fclose (fp );}Closing File: fclose()The fclose() function is used to close a file. The file must be closed after performing all the operations on it. The syntax of fclose() function is given below:
  • int fclose( FILE *fp );  
  • C fprintf() and fscanf()C fputc() and fgetc()C fputs() and fgets()C fseek()2.    Explain Concepts of Stream.We are using the iostream standard library, it provides cin and cout methods for reading from input and writing to output respectively.To read and write from a file we are using the standard C++ library called fstream. Let us see the data types define in fstream library is:

    Data Type

    Description

    fstream

    It is used to create files, write information to files, and read information from files.

    ifstream

    It is used to read information from files.

    ofstream

    It is used to create files and write information to the files.

     FileStream example: writing to a fileLet's see the simple example of writing to a text file testout.txt using C++ FileStream programming.
  • #include <iostream>  
  • #include <fstream>  
  • using namespace std;  
  • int main () {  
  •   ofstream filestream("testout.txt");  
  •   if (filestream.is_open())  
  •   {  
  •     filestream << "Welcome to javaTpoint.\n";  
  •     filestream << "C++ Tutorial.\n";  
  •     filestream.close();  
  •   }  
  •   else cout <<"File opening is fail.";  
  •   return 0;  
  • }  
  • Output:The content of a text file testout.txt is set with the data:Welcome to javaTpoint.C++ Tutorial.FileStream example: reading from a fileLet's see the simple example of reading from a text file testout.txt using C++ FileStream programming.
  • #include <iostream>  
  • #include <fstream>  
  • using namespace std;  
  • int main () {  
  •   string srg;  
  •   ifstream filestream("testout.txt");  
  •   if (filestream.is_open())  
  •   {  
  •     while ( getline (filestream,srg) )  
  •     {  
  •       cout << srg <<endl;  
  •     }  
  •     filestream.close();  
  •   }  
  •   else {  
  •       cout << "File opening is fail."<<endl;   
  •     }  
  •   return 0;  
  • }  
  • Note: Before running the code a text file named as "testout.txt" is need to be created and the content of a text file is given below:
    Welcome to javaTpoint.
    C++ Tutorial.Output:Welcome to javaTpoint.C++ Tutorial.3.    Read and Write ExampleLet's see the simple example of writing the data to a text file testout.txt and then reading the data from the file using C++ FileStream programming.
  • #include <fstream>  
  • #include <iostream>  
  • using namespace std;  
  • int main () {  
  •    char input[75];  
  •    ofstream os;  
  •    os.open("testout.txt");  
  •    cout <<"Writing to a text file:" << endl;  
  •    cout << "Please Enter your name: ";   
  •    cin.getline(input, 100);  
  •    os << input << endl;  
  •    cout << "Please Enter your age: ";   
  •    cin >> input;  
  •    cin.ignore();  
  •    os << input << endl;  
  •    os.close();  
  •    ifstream is;   
  •    string line;  
  •    is.open("testout.txt");   
  •    cout << "Reading from a text file:" << endl;   
  •    while (getline (is,line))  
  •    {  
  •    cout << line << endl;  
  •    }      
  •    is.close();  
  •    return 0;  
  • }  
  • Output:Writing to a text file:   Please Enter your name: Nakul Jain    Please Enter your age: 22   Reading from a text file:   Nakul Jain   224.    Explain Stream ClassesIn C++ stream refers to the stream of characters that are transferred between the program thread and i/o.Stream classes in C++ are used to input and output operations on files and io devices. These classes have specific features and to handle input and output of the program.The iostream.h library holds all the stream classes in the C++ programming language.Let's see the hierarchy and learn about them,

    https://www.tutorialspoint.com/assets/questions/media/28272/ios.jpg

    Now, let’s learn about the classes of the iostream library.ios class This class is the base class for all stream classes. The streams can be input or output streams. This class defines members that are independent of how the templates of the class are defined.istream Class The istream class handles the input stream in c++ programming language. These input stream objects are used to read and interpret the input as a sequence of characters. The cin handles the input.ostream class The ostream class handles the output stream in c++ programming language. These output stream objects are used to write data as a sequence of characters on the screen. cout and puts handle the out streams in c++ programming language.ExampleOUT STREAMCOUT#include <iostream>using namespace std;int main(){   cout<<"This output is printed on screen";}OutputThis output is printed on screenPUTS#include <iostream>using namespace std;int main(){   puts("This output is printed using puts");}OutputThis output is printed using putsIN STREAMCIN#include <iostream>using namespace std;int main(){   int no;   cout<<"Enter a number ";   cin>>no;   cout<<"Number entered using cin is "<OutputEnter a number 3453Number entered using cin is 3453gets#include <iostream>using namespace std;int main(){   char ch[10];   puts("Enter a character array");   gets(ch);   puts("The character array entered using gets is : ");   puts(ch);}OutputEnter a character arraythdgfThe character array entered using gets is :thdgf5.    Explain Byte Stream ClassesThese handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images etc.The InputStream and OutputStream classes (abstract) are the super classes of all the input/output stream classes: classes that are used to read/write a stream of bytes. Following are the byte array stream classes provided by Java

    InputStream

    OutputStream

    FIleInputStream

    FileOutputStream

    ByteArrayInputStream

    ByteArrayOutputStream

    ObjectInputStream

    ObjectOutputStream

    PipedInputStream

    PipedOutputStream

    FilteredInputStream

    FilteredOutputStream

    BufferedInputStream

    BufferedOutputStream

    DataInputStream

    DataOutputStream

    ExampleFollowing Java program reads data from a particular file using FileInputStream and writes it to another, using FileOutputStream.import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class IOStreamsExample {   public static void main(String args[]) throws IOException {      //Creating FileInputStream object      File file = new File("D:/myFile.txt");      FileInputStream fis = new FileInputStream(file);      byte bytes[] = new byte[(int) file.length()];      //Reading data from the file      fis.read(bytes);      //Writing data to another file      File out = new File("D:/CopyOfmyFile.txt");      FileOutputStream outputStream = new FileOutputStream(out);      //Writing data to the file      outputStream.write(bytes);      outputStream.flush();      System.out.println("Data successfully written in the specified file");   }}OutputData successfully written in the specified file6.    Explain Character StreamCharacter Streams These handle data in 16 bit Unicode. Using these you can read and write text data only.The Reader and Writer classes (abstract) are the super classes of all the character stream classes: classes that are used to read/write character streams. Following are the character array stream classes provided by Java

    Reader

    Writer

    BufferedReader

    BufferedWriter

    CharacterArrayReader

    CharacterArrayWriter

    StringReader

    StringWriter

    FileReader

    FileWriter

    InputStreamReader

    InputStreamWriter

    FileReader

    FileWriter

    ExampleThe following Java program reads data from a particular file using FileReader and writes it to another, using FileWriter.import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;public class IOStreamsExample {   public static void main(String args[]) throws IOException {      //Creating FileReader object      File file = new File("D:/myFile.txt");      FileReader reader = new FileReader(file);      char chars[] = new char[(int) file.length()];      //Reading data from the file      reader.read(chars);      //Writing data to another file      File out = new File("D:/CopyOfmyFile.txt");      FileWriter writer = new FileWriter(out);      //Writing data to the file      writer.write(chars);      writer.flush();      System.out.println("Data successfully written in the specified file");   }}OutputData successfully written in the specified file7.    Explain in detail Other Useful I/O Classes with examplesThe java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io package supports many data such as primitives, object, localized characters, etc.StreamA stream can be defined as a sequence of data. There are two kinds of Streams
  • InPutStream The InputStream is used to read data from a source.
  • OutPutStream The OutputStream is used for writing data to a destination.
  • Streams

    Java provides strong but flexible support for I/O related to files and networks but this tutorial covers very basic functionality related to streams and I/O. We will see the most commonly used examples one by one Byte StreamsJava byte streams are used to perform input and output of 8-bit bytes. Though there are many classes related to byte streams but the most frequently used classes are, FileInputStream and FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an output file Exampleimport java.io.*;public class CopyFile {   public static void main(String args[]) throws IOException {        FileInputStream in = null;      FileOutputStream out = null;       try {         in = new FileInputStream("input.txt");         out = new FileOutputStream("output.txt");          int c;         while ((c = in.read()) != -1) {            out.write(c);         }      }finally {         if (in != null) {            in.close();         }         if (out != null) {            out.close();         }      }   }}Now let's have a file input.txt with the following content This is test for copy file.As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following $javac CopyFile.java$java CopyFileCharacter StreamsJava Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit unicode. Though there are many classes related to character streams but the most frequently used classes are, FileReader and FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode characters) into an output file Exampleimport java.io.*;public class CopyFile {    public static void main(String args[]) throws IOException {      FileReader in = null;      FileWriter out = null;       try {         in = new FileReader("input.txt");         out = new FileWriter("output.txt");          int c;         while ((c = in.read()) != -1) {            out.write(c);         }      }finally {         if (in != null) {            in.close();         }         if (out != null) {            out.close();         }      }   }}Now let's have a file input.txt with the following content This is test for copy file.As a next step, compile the above program and execute it, which will result in creating output.txt file with the same content as we have in input.txt. So let's put the above code in CopyFile.java file and do the following $javac CopyFile.java$java CopyFileStandard StreamsAll the programming languages provide support for standard I/O where the user's program can take input from a keyboard and then produce an output on the computer screen. If you are aware of C or C++ programming languages, then you must be aware of three standard devices STDIN, STDOUT and STDERR. Similarly, Java provides the following three standard streams
  • Standard Input This is used to feed the data to user's program and usually a keyboard is used as standard input stream and represented as System.in.
  • Standard Output This is used to output the data produced by the user's program and usually a computer screen is used for standard output stream and represented as System.out.
  • Standard Error This is used to output the error data produced by the user's program and usually a computer screen is used for standard error stream and represented as System.err.
  • Following is a simple program, which creates InputStreamReader to read standard input stream until the user types a "q" Exampleimport java.io.*;public class ReadConsole {    public static void main(String args[]) throws IOException {      InputStreamReader cin = null;       try {         cin = new InputStreamReader(System.in);         System.out.println("Enter characters, 'q' to quit.");         char c;         do {            c = (char) cin.read();            System.out.print(c);         } while(c != 'q');      }finally {         if (cin != null) {            cin.close();         }      }   }}Let's keep the above code in ReadConsole.java file and try to compile and execute it as shown in the following program. This program continues to read and output the same character until we press 'q' $javac ReadConsole.java$java ReadConsoleEnter characters, 'q' to quit.11eeqqReading and Writing FilesAs described earlier, a stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data to a destination.Here is a hierarchy of classes to deal with Input and Output streams.

    Files IO

    The two important streams are FileInputStream and FileOutputStream, which would be discussed in this tutorial.FileInputStreamThis stream is used for reading data from the files. Objects can be created using the keyword new and there are several types of constructors available.Following constructor takes a file name as a string to create an input stream object to read the file InputStream f = new FileInputStream("C:/java/hello");Following constructor takes a file object to create an input stream object to read the file. First we create a file object using File() method as follows File f = new File("C:/java/hello");InputStream f = new FileInputStream(f);Once you have InputStream object in hand, then there is a list of helper methods which can be used to read to stream or to do other operations on the stream.

    Sr.No.

    Method & Description

    1

    public void close() throws IOException{}

    This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.

    2

    protected void finalize()throws IOException {}

    This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.

    3

    public int read(int r)throws IOException{}

    This method reads the specified byte of data from the InputStream. Returns an int. Returns the next byte of data and -1 will be returned if it's the end of the file.

    4

    public int read(byte[] r) throws IOException{}

    This method reads r.length bytes from the input stream into an array. Returns the total number of bytes read. If it is the end of the file, -1 will be returned.

    5

    public int available() throws IOException{}

    Gives the number of bytes that can be read from this file input stream. Returns an int.

    There are other important input streams available, for more detail you can refer to the following links
  • ByteArrayInputStream
  • DataInputStream
  • FileOutputStreamFileOutputStream is used to create a file and write data into it. The stream would create a file, if it doesn't already exist, before opening it for output.Here are two constructors which can be used to create a FileOutputStream object.Following constructor takes a file name as a string to create an input stream object to write the file OutputStream f = new FileOutputStream("C:/java/hello") Following constructor takes a file object to create an output stream object to write the file. First, we create a file object using File() method as follows File f = new File("C:/java/hello");OutputStream f = new FileOutputStream(f);Once you have OutputStream object in hand, then there is a list of helper methods, which can be used to write to stream or to do other operations on the stream.

    Sr.No.

    Method & Description

    1

    public void close() throws IOException{}

    This method closes the file output stream. Releases any system resources associated with the file. Throws an IOException.

    2

    protected void finalize()throws IOException {}

    This method cleans up the connection to the file. Ensures that the close method of this file output stream is called when there are no more references to this stream. Throws an IOException.

    3

    public void write(int w)throws IOException{}

    This methods writes the specified byte to the output stream.

    4

    public void write(byte[] w)

    Writes w.length bytes from the mentioned byte array to the OutputStream.

    There are other important output streams available, for more detail you can refer to the following links
  • ByteArrayOutputStream
  • DataOutputStream
  • ExampleFollowing is the example to demonstrate InputStream and OutputStream import java.io.*;public class fileStreamTest {    public static void main(String args[]) {       try {         byte bWrite [] = {11,21,3,40,5};         OutputStream os = new FileOutputStream("test.txt");         for(int x = 0; x < bWrite.length ; x++) {            os.write( bWrite[x] );   // writes the bytes         }         os.close();          InputStream is = new FileInputStream("test.txt");         int size = is.available();          for(int i = 0; i < size; i++) {            System.out.print((char)is.read() + "  ");         }         is.close();      } catch (IOException e) {         System.out.print("Exception");      }    }}The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.File Navigation and I/OThere are several other classes that we would be going through to get to know the basics of File Navigation and I/O.
  • File Class
  • FileReader Class
  • FileWriter Class
  • Directories in JavaA directory is a File which can contain a list of other files and directories. You use File object to create directories, to list down files available in a directory. For complete detail, check a list of all the methods which you can call on File object and what are related to directories.Creating DirectoriesThere are two useful File utility methods, which can be used to create directories
  • The mkdir( ) method creates a directory, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists, or that the directory cannot be created because the entire path does not exist yet.
  • The mkdirs() method creates both a directory and all the parents of the directory.
  • Following example creates "/tmp/user/java/bin" directory Exampleimport java.io.File;public class CreateDir {    public static void main(String args[]) {      String dirname = "/tmp/user/java/bin";      File d = new File(dirname);       // Create directory now.      d.mkdirs();   }}Compile and execute the above code to create "/tmp/user/java/bin".Note Java automatically takes care of path separators on UNIX and Windows as per conventions. If you use a forward slash (/) on a Windows version of Java, the path will still resolve correctly.Listing DirectoriesYou can use list( ) method provided by File object to list down all the files and directories available in a directory as follows Exampleimport java.io.File;public class ReadDir {    public static void main(String[] args) {      File file = null;      String[] paths;       try {               // create new file object         file = new File("/tmp");          // array of files and directory         paths = file.list();          // for each name in the path array         for(String path:paths) {            // prints filename and directory name            System.out.println(path);         }      } catch (Exception e) {         // if any error occurs         e.printStackTrace();      }   }}This will produce the following result based on the directories and files available in your /tmp directory Outputtest1.txttest2.txtReadDir.javaReadDir.class8.    Explain Using the File ClassThe File class is an abstract representation of file and directory pathname. A pathname can be either absolute or relative. The File class have several methods for working with directories and files such as creating new directories or files, deleting and renaming directories or files, listing the contents of a directory etc.Fields

    Modifier

    Type

    Field

    Description

    Static

    String

    pathSeparator

    It is system-dependent path-separator character, represented as a string for convenience.

    Static

    Char

    pathSeparatorChar

    It is system-dependent path-separator character.

    Static

    String

    separator

    It is system-dependent default name-separator character, represented as a string for convenience.

    Static

    Char

    separatorChar

    It is system-dependent default name-separator character.

    Constructors

    Constructor

    Description

    File(File parent, String child)

    It creates a new File instance from a parent abstract pathname and a child pathname string.

    File(String pathname)

    It creates a new File instance by converting the given pathname string into an abstract pathname.

    File(String parent, String child)

    It creates a new File instance from a parent pathname string and a child pathname string.

    File(URI uri)

    It creates a new File instance by converting the given file: URI into an abstract pathname.

    Useful Methods

    Modifier and Type

    Method

    Description

    static File

    createTempFile(String prefix, String suffix)

    It creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

    Boolean

    createNewFile()

    It atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist.

    Boolean

    canWrite()

    It tests whether the application can modify the file denoted by this abstract pathname.String[]

    Boolean

    canExecute()

    It tests whether the application can execute the file denoted by this abstract pathname.

    Boolean

    canRead()

    It tests whether the application can read the file denoted by this abstract pathname.

    Boolean

    isAbsolute()

    It tests whether this abstract pathname is absolute.

    Boolean

    isDirectory()

    It tests whether the file denoted by this abstract pathname is a directory.

    boolean

    isFile()

    It tests whether the file denoted by this abstract pathname is a normal file.

    String

    getName()

    It returns the name of the file or directory denoted by this abstract pathname.

    String

    getParent()

    It returns the pathname string of this abstract pathname's parent, or null if this pathname does not name a parent directory.

    Path

    toPath()

    It returns a java.nio.file.Path object constructed from the this abstract path.

    URI

    toURI()

    It constructs a file: URI that represents this abstract pathname.

    File[]

    listFiles()

    It returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname

    Long

    getFreeSpace()

    It returns the number of unallocated bytes in the partition named by this abstract path name.

    String[]

    list(FilenameFilter filter)

    It returns an array of strings naming the files and directories in the directory denoted by this abstract pathname that satisfy the specified filter.

    Boolean

    mkdir()

    It creates the directory named by this abstract pathname.

     9.    Explain Input/output ExceptionsIntroductionThe java.io.Exceptions provides for system input and output through data streams, serialization and the file system.Interface Summary

    Sr.No.

    Interface & Description

    1

    CharConversionException

    This is a base class for character conversion exceptions.

    2

    EOFException

    These are signals that an end of file or end of stream has been reached unexpectedly during input.

    3

    FileNotFoundException

    These are the signals that an attempt to open the file denoted by a specified pathname has failed.

    4

    InterruptedIOException

    This is signals that an I/O operation has been interrupted.

    5

    InvalidClassException

    This is thrown when the Serialization runtime detects one of the following problems with a Class.

    6

    InvalidObjectException

    This indicates that one or more deserialized objects failed validation tests.

    7

    IOException

    These are the signals that an I/O exception of some sort has occurred.

    8

    NotActiveException

    This is thrown when serialization or deserialization is not active.

    9

    NotSerializableException

    This is thrown when an instance is required to have a Serializable interface.

    10

    ObjectStreamException

    This is a superclass of all exceptions specific to Object Stream classes.

    11

    OptionalDataException

    This is an exception indicating the failure of an object read operation due to unread primitive data, or the end of data belonging to a serialized object in the stream.

    12

    StreamCorruptedException

    This is thrown when control information that was read from an object stream violates internal consistency checks.

    13

    SyncFailedException

    These are the signals that a sync operation has failed.

    14

    UnsupportedEncodingException

    This character encoding is not supported.

    15

    UTFDataFormatException

    This are signals that a malformed string in modified UTF-8 format has been read in a data input stream or by any class that implements the data input interface.

    16

    WriteAbortedException

    This are signals that one of the ObjectStreamExceptions was thrown during a write operation.

     10.                       Explain Handling Primitive Data TypesNot everything in Java is an object. There is a special group of data types (also known as primitive types) that will be used quite often in programming. For performance reasons, the designers of the Java language decided to include these primitive types. Java determines the size of each primitive type. These sizes do not change from one operating system to another. This is one of the key features of the language that makes Java so portable. Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. The primitive types are also commonly referred to as simple types which can be put in four groups
  • Integers: This group includes byte, short, int, and long, which are for whole-valued signed numbers.
  • Floating-point numbers: This group includes float and double, which represent numbers with fractional precision.
  • Characters: This group includes char, which represents symbols in a character set, like letters and numbers.
  • Boolean: This group includes boolean, which is a special type for representing true/false values.
  • Let’s discuss each in details:byteThe smallest integer type is byte. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. Byte variables are declared by use of the byte keyword. For example, the following declares and initialize byte variables called b:byte  b =100;short:The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters. Following example declares and initialize short variable called s:short  s =123;int:The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to index arrays. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.int  v = 123543;int  calc = -9876345;long:long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use of this data type might be in banking application when large amount is to be calculated and stored.long  amountVal = 1234567891;float:Floating-point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example interest rate calculation or calculating square root. The float data type is a single-precision 32-bit IEEE 754 floating point. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision. The declaration and initialization syntax for float variables given below, please note “f” after value initialization. float  intrestRate = 12.25f;double:Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values. The declaration and initialization syntax for double variables given below, please note “d” after value initialization.double  sineVal = 12345.234d;boolean:The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This is the type returned by all relational operators, as in the case of a < b. boolean is also the type required by the conditional expressions that govern the control statements such as if or while.boolean  flag = true;booleanval  = false;char:In Java, the data type used to store characters is char. The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). There are no negative chars.char ch1 = 88; // code for Xchar  ch2 = 'Y';Primitive Variables can be of two types(1) Class level (instance) variable:It's not mandatory to initialize Class level (instance) variable. If we do not initialize instance variable compiler will assign default value to it. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad coding practice.The following chart summarizes the default values for the above data types.

    Primitive Data Type

    Default Value 3.6

    byte

    0

    short

    0

    int

    0

    long

    0L

    float

    0.0f

    double

    0.0d

    char

    '\u0000'

    boolean

    false

    (2) Method local variable:Method local variables have to be initialized before using it. The compiler never assigns a default value to an un-initialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an un-initialized local variable will result in a compile-time error.Let’s See simple java program which declares, initialize and print all of primitive types. Java class PrimitiveDemo as below:package primitive;public class PrimitiveDemo { public static void main(String[] args) {  byte b =100;  short s =123;  int v = 123543;  int calc = -9876345;  long amountVal = 1234567891;  float intrestRate = 12.25f;  double sineVal = 12345.234d;  boolean flag = true;  boolean val = false;  char ch1 = 88; // code for X  char ch2 = 'Y';  System.out.println("byte Value = "+ b);  System.out.println("short Value = "+ s);  System.out.println("int Value = "+ v);  System.out.println("int second Value = "+ calc);  System.out.println("long Value = "+ amountVal);  System.out.println("float Value = "+ intrestRate);  System.out.println("double Value = "+ sineVal);  System.out.println("boolean Value = "+ flag);  System.out.println("boolean Value = "+ val);  System.out.println("char Value = "+ ch1);  System.out.println("char Value = "+ ch2); }} CopyOutput of above PrimitiveDemo class as below:  Summary of Data Types

    Primitive Type

    Size

    Minimum Value

    Maximum Value

    Wrapper Type

    char

    16-bit

    Unicode 0

    Unicode 216-1

    Character

    byte

    8-bit

    -128

    +127

    Byte

    short

    16-bit

    -215
    (-32,768)

    +215-1
    (32,767)

    Short

    int

    32-bit

    -231
    (-2,147,483,648)

    +231-1
    (2,147,483,647)

    Integer

    long

    64-bit

      -263
    (-9,223,372,036,854,775,808)

    +263-1
    (9,223,372,036,854,775,807)

    Long

    float

    32-bit

    Approx range 1.4e-045 to 3.4e+038

    Float

    double

    64-bit

    Approx range 4.9e-324 to 1.8e+308

    Double

    boolean

    1-bit

    true or false

    Boolean