Saturday, 9 March 2013

Byte Streams in Java


We saw in last post in Java Tutorials section what streams in Java are.Byte stream is one of the type of streams used to perform to perform input and output of 8-bit bytes.All byte stream classes are descended from InputStream and OutputStream.

     There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and FileOutputStream. Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.

Let us examine the way bytes streams are used by looking at an example -

Example code

public class ByteStreamDemonstrator {
    public static void main(String args[]) throws IOException
        FileInputStream in = new FileInputStream(new File("inFile.txt"));
        FileOutputStream out = new FileOutputStream(new File("outFile.txt"));
        int c;
        while((c =!= -1)

Lets analyze the code now.

    We have define two byte streams FileInputStream in and FileOutputStream out.
Each stream take a File object as an input which in turn takes filename as an argument.Note that you can directly give filename as an argument to FileInputStream and FileOutputStream. Also note this filename is of type String.This file must be in your source directory, if not you can always give absolute path in the place of filename.
    In above code we have inFile and outFile as two files in src directory.We read from inFile and write to outFile.Note that read() function return an integer and when all data in input stream is read it will return -1 which can be used as a condition to terminate our loop.

Always close streams

   Never forget to close the streams you have opened. In above code we close the streams using .close() function. Note that we are checking if the stream is open or not before closing it because if due to some error stream was not opened and if we try closing it, it will throw runtime Exception. 

Better approach to write above code

    Above code is not the best way to write it.Since Exceptions are not explained yet above code will suffice our requirements in understanding byte stream.But the more correct approach to do above is put out reading/writing logic in try statement, catch the exception to handle the exceptions like FileNotFound Exception in catch block and use the Finally block to close the streams.

What is this throwing Exception?

   In above code observer the line throws IOException besides the main function.What it means that if there is any Exception just throw it (don't catch). Generally when a function throws an exception Exception is thrown to the function which has called the function throwing that Exception.The calling function must then either catch it and handle it or again throw it to it's parent function.

So what happens when every function throws the Exception and no one catches it?

   If no function catches the Exception it will finally come to the main() function.If even the main() function does not handle the Exception and just throws it like what we have done in above code then JVM will just shut down, terminating the program.Lets not worry about this at this point. We will cover this in much details when we learn about Exception handling.

When not to use byte stream?

    Since inFile and outFile contains characters the best way to do it is to use character stream which will be explained in our next post. Byte streams should only be used for primitive I/O.

So why talk about byte streams?

     Because all other stream types are built on byte streams. 

Related Links 

MCQ #5

Question) In switch construct , the default statement must be placed after all the case statements.


  • True
  • False
Answer) False

Explanation) Go through the Java tutorial on switch statement to know more about switch statement and it's usage.As for our question, default statement can be put anywhere in the switch construct but it will be called only when none of the other cases match. Also since default statement is the last one to be checked we need not even write break statement in default statement.So the answer is clearly False.

MCQ #4

Question) Member (instance) variables are always assigned a default value if not explicitly initialized.


  • True
  • False
Answer) True

Explanation) Go through the Java tutorial on Objects in java to know the difference between instance variables and local variables.As for our question, yes instance variables are assigned default values if not explicitly initialized.On the other hand compiler will complaint if local variables are used without initialization.

MCQ #3

Question)Assume x = 6 and y = 7 .What is the result of (!(y == x))


  • True
  • False
Answer) True

Explanation) The answer is pretty straight forward . x=6  and y=7 so y == x is false. Negation ( ! ) of false is true and hence our final result is True. Remember brackets have higher preference than any of the operators.

MCQ #2

Question) Using a break in a for loop causes the loop to break out of the current execution and jump to next iteration.

  • True
  • False
Answer) Flase

Explanation) I would recommend go through the post on Transfer Statements in Java Tutorials section.break keyword will cause loop to break out of current execution permanently and continue with the code after the loop.Note that break statement is used only in loops and switch statement.So answer is False.

MCQ #1

Question) Methods which are marked protected can be accessed only by classes within the same package

  • True
  • False
Answer) Flase

Explanation) I would recommend go through the post on Access Modifiers in Java Tutorials section.If a member (be it a member variable or a member function) is defined to be protected then it is accessible by members in same class, in same package and also in all the sub classes of class in which the protected member is defined. So it is not just the same package.Hence answer is False.

Understanding I/O streams in Java


User input is required to make our programs more interactive and dynamic.For this it is essential to know what are Input and Output streams and how they work.

What are I/O streams in Java?

  • An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.
  •  Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.
  • No matter how they work internally, all streams present the same simple model to programs that use them: A stream is a sequence of data

Types of Streams in Java.

     A program uses an input stream to read data from a source, one item at a time:

A program uses an output stream to write data to a destination, one item at time:


   Streams can hold all sorts of data from primitive types to advanced objects.
   In next few posts we will go through various types of I/O streams like byte stream, character stream, object stream etc. Check for links in the Relates Links section at the bottom of this post.

The library defines four abstract classes that are the parents of all stream classes defined within the API:
  1. InputStream, 
  2. OutputStream, 
  3. Reader, and 
  4. Writer.

Above are classified into two sets of classes - InputStream/OuputStream and Reader/Writer. Difference being -
  • The stream classes are used for inputting and outputting all types of binary or byte data.
  • The reader and writer classes are used for inputting and outputting only character and String data.
NOTE : When wrapping a stream you can mix and match only types that inherit from the same abstract parent stream.
Eg. following combinations will not work -

new BufferedInputStream(new FileReader("data.txt")); // char stream inside byte stream
new BufferedWriter(new FileOutputStream("data.txt")); // byte stream inside char stream
new ObjectInputStream(new FileOutputStream("data.txt")); // input and output streams mixed

Note : The data source and data destination pictured above can be anything that holds, generates, or consumes data. Obviously this includes disk files, but a source or destination can also be another program, a peripheral device, a file, a network socket, or an array.

Related Links 

Interview Question #3 What is the difference between a constructor and a method?

  • A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
  •  A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.
  • A constructor is mandatory in a class.If you don't write any constructor compiler will write one for you.This constructor is called default constructor and has no parameters.Writing a method is completely based on user requirement.

Interview Question #2 What are principle concepts of OOP?

There are four principle concepts upon which object oriented design and programming rest. They are: 
  •  Data Abstraction(act of representing essential features without including the background details or explanations)
  • Data Encapsulation (Class structure + Access modifiers)
  • Polymorphism(super class reference for sub class object )
  • Inheritance(to avoid duplicate code)

Interview Question #1 What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused.Garbage collector is invoked automatically by JVM. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used and by  unreachable mean that there are no references of that object on the stack.You can also specify when to invoke garbage collector using System.gc() but it is not necessary that JVM will always invoke garbage collector on encountering this function.

Related Questions

Constructors in Java

Understanding constructors

    Constructor is a special function in the class with same function name as that of the class and no return type.It is called only once when the object is created.Note constructors have no return type but they can have access modifiers.Lets take an example to understand this better -
Lets take the same sample code previously explained and add constructor to it

package greetings;

public class MyGreetings {
    private String welcomeMessage;
    public MyGreetings()    //This is a constructor
        this.welcomeMessage = "default Message";

    public String getWelcomeMessage() {
        return welcomeMessage;

    public void setWelcomeMessage(String welcomeMessage) {
        this.welcomeMessage = welcomeMessage;
    public static void main(String args[])
        MyGreetings greetings = new MyGreetings();


In above code constructor sets default value of welcomeMessage variable to "default Message". So above code will print default Message to standard output.

Constructors can be public, private or default.

Note : If you don't write a constructor compiler writes one for you.This compiler written constructor does not have any arguments or code in it.Remember this will happen only if you have not written any constructor.

What is the use of constructors?

     constructors are use to set default values to member variables.It can also be used to initialize some instance variables when the object is created.

Can we have more than one constructor for a single class?

     Yes you can have multiple constructors in a single class but all of them must have different set of arguments. Number and type of arguments provided while creating object will decide  which constructor must be invoked.Also you can call one constructor from another using this(arguments). I understand just this description makes little sense so lets take up a fresh example to demonstrate what i just described.

public class Student
   private String name;
   private int age;
   public Student()  //constructor with no arguments
   public Student(String name,int age)
   { = name;
      this.age = age;
   //getters and setters for name and age

   public String printStudentDetails()
      return("Name is" + + " and age is " + this.age  + "\n");

   public static void main(String args[])
      Student student1 = new Student();
      System.out.println("student1 details are  + "student1.printStudentDetails());            
      Student student2 = new Student("John",21);
      System.out.println("student2 details are  + "student2.printStudentDetails()); 


Output - 
 student1 details are Name is defaultName  and age is 18
 student2 details are Name is John and age is 21

When student1 is created no arguments are provided and hence default constructor is called i.e
public Student() is called which in turn calls the constructor public Student(String name,int age) with some default values.When student2 is created two arguments are passes of type string and int so constructor
public Student(String name,int age) will automatically be picked up and set name and age to values supplied as arguments.

Note : If you define constructor as private you cannot create object of that class.Reason being private functions can only be called in same class.

So why would any one declare constructor to be private?

     There are cases in which we don't want to explicitly create any objects of a class.Singleton design pattern is one of the use case.We will discuss what design patterns are ans what a singleton class means and what are it's uses but for now keep in mind such cases are very much possible.


  • constructors have same name as that of the class.
  • constructors don't have return type.
  • A single class can have multiple constructors having different arguments.
  • We can call one constructor from another using this() keyword.
  • constructor cannot be static(will be explained later).
  • constructors don't have any return type and yet they return instance of that class.
  • You can't create object of a class whose constructor is private.
  • Which constructor must be invoked will depend on arguments passed.
  • when a constructor is invoked it executes constructor of it's super class first(will be explained in inheritance)
  • If you do not provide any constructor compiler will write one for you.This is a default constructor with no arguments.

Common mistakes

  • Constructor does not have return type. If you provide one it will not be constructor but a normal instance method.
  • See the following code -

    public class HelloWorld {
         int x;
         int y;
         public HelloWorld(int x, int y) {
            x = x;
            y = y;

    Above code is of no use. 'x' and 'y' variables that you see inside constructor are the ones coming from parameter 'x' and 'y'. They do not represent 'x' and 'y' instance variables. To initialize instance variables you need to use this  keyword.

    public class HelloWorld {
        int x;
        int y;
        public HelloWorld(int x, int y) {
            this.x = x;
            this.y = y;

t> UA-39527780-1 back to top