Core Java Questions And Answers Part-10

What is a IO stream?
It is a stream of data that flows from source to destination. Good example is file copying. Two streams are involved – input stream and output stream. An input stream reads from the file and stores the data in the process (generally in a temporary variable). The output stream reads from the process and writes to the destination file.

What is the necessity of two types of streams – byte streams and character streams?
Byte streams were introduced with JDK 1.0 and operate on the files containing ASCII characters. We know Java supports other language characters also known as Unicode characters. To read the files containing Unicode characters, the designers introduced character streams with JDK 1.1. As ASCII is a subset of Unicode, for the files of English characters, we can go with either byte streams or character streams.

What are the super most classes of all streams?
All the byte stream classes can be divided into two categories (input stream classes and output stream classes) and all character streams classes into two (reader classes and writer classes). There are four abstract classes from which all these streams are derived. The super most class of all byte stream classes is java.io.InputStream and for all output stream classes, java.io.OutputStream. Similarly for all reader classes is java.io.Reader and for all writer classes is java.io.Writer.

What are FileInputStream and FileOutputStream?
These two are general purpose classes used by the programmer very often to copy file to file. These classes work well with files containing less data of a few thousand bytes as by performance these are very poor. For larger data, it is preferred to use BufferedInputStream (or BufferedReader) and BufferedOutputStream (or BufferedWriter).

Which you feel better to use – byte streams or character streams?
I feel personally to go with character streams as they are the latest. Many features exist in character streams that do not in byte streams like a) using BufferedReader in place of BufferedInputStreams and DataInputStream (one stream for two) and b) using newLine() method to go for next line and for this effect we must go for extra coding in byte streams etc.

What are filter streams?
Filter streams are a category of IO streams whose responsibility is to add extra functionality (advantage) to the existing streams like giving line numbers in the destination file that do not exist int the source file or increasing performance of copying etc.

What is PrintStream and PrintWriter?
Functionally both are same but belong to two different categories – byte streams and character streams. println() method exists in both classes.

Which streams are advised to use to have maximum performance in file copying? 
BufferedInputStream and BufferedOutputStream on byte streams side and BufferedReader and BufferedWriter on character streams side.


What is File class?
It is a non-stream (not used for file operations) class used to know the properties of a file like when it was created (or modified), has read and write permissions, size etc.

What is RandomAccessFile?
It is a special class from java.io package which is neither a input stream nor a output stream (because it can do both). It is directly a subclass of Object class. Generally, a stream does only one purpose of either reading or writing; but RandomAccessFile can do both reading from a file and writing to a file. All the methods of DataInputStream and DataOutStream exist in RandomAccessFile.


How to restrict a class from creating multiple objects?
Or
Restricting a class from creating multiple objects or restricting class from creating not more than three objects 


 Yes we can restrict a class from creating multiple objects.
As we know using singleton we can restrict a class from creating multiple objects it will create single object and share it.
Same design pattern we can apply here with counter
In this we will take a static variable counter to check how many objects created
As we can access static variables in constructor and static variables are class level we can stake help of static variable to count number object created.
First three time we will create new objects and forth time we need to return 3rd object reference. if we don't want same object 4th time we can return null
By printing the hashcode() of the object we can check how many objects created.


Basic java example program to restrict a class from not to create more than three instances
package com.instanceofjava;

public class RestrictObjectCreation{

private static RestrictObjectCreationobject;
public static int objCount = 0;

private RestrictObjectCreation()
{
     System.out.println("Singleton(): Private constructor invoked");

objCount  ++;
}

public static RestrictObjectCreation getInstance()
{

if (objCount < 3)
{

object = new RestrictObjectCreation();

 }

return object;

}

}


package instanceofjava;

public class Test{

public static void main(String args[]) {

RestrictObjectCreation obj1= RestrictObjectCreation.getInstance();
RestrictObjectCreation obj2= RestrictObjectCreation.getInstance();
RestrictObjectCreation obj3= RestrictObjectCreation.getInstance();
RestrictObjectCreation obj4= RestrictObjectCreation.getInstance();
RestrictObjectCreation obj5= RestrictObjectCreation.getInstance();

System.out.println(obj1.hashCode());
System.out.println(obj2.hashCode());
System.out.println(obj3.hashCode());
System.out.println(obj4.hashCode());
System.out.println(obj5.hashCode());

}
}



Output:

RestrictObjectCreation(): Private constructor invoked
RestrictObjectCreation(): Private constructor invoked
RestrictObjectCreation(): Private constructor invoked
705927765
366712642
1829164700
1829164700
1829164700



Enhanced For loop
Posted by: InstanceOfJava  Posted date: Dec 12, 2014  /  comment : 0

Using enhanced for loops we are just simplify the regular for loop and operation of for loop.
Enhanced for loops are applicable to any object that maintains group of elements and supports indexes.
Enhanced for loops are used where ever it is required to access all the elements from the beginning till ending automatically from array or from any object representing group of elements along with index.
Enhanced for loop to iterate Array:
 package com.instanceofjavaforus;

public class EnhancedForloop {

    public static void main(String args[]){
     
        int x[]={1,2,3,4,5,6};
     
        for(int i:x){
            System.out.println(i);
        }
     
    char ch[]={'a','b','c','d','e'};
 
    for(char i:ch){
        System.out.println(i);
    }
 
    }
}
output:
1
2
3
4
5
6
a
b
c
d
e



Enhanced for loop to iterate ArrayList:

package com.instanceofjavaforus;

import java.util.ArrayList;
import java.util.Collection;

public class EnhancedForLoopList {

    public static void main(String args[]){
     
    Collection<String> nameList = new ArrayList<String>();
    nameList.add("Ramu");
    nameList.add("Geetha");
    nameList.add("Aarya");
   nameList.add("Ajay");
    for (String name : nameList) {
      System.out.println(name);
    }
    }
}

Output:

Ramu
Geetha
Aarya
Ajay


Why StringBuffer Class not overriding equals and hashCode methods

YES StringBuffer and StringBuilder classes not overriding equals()method and haschcode() method.
Before discussing about why these classes are not overriding equas() and hashcde() methods lets see the usage of overriding equals and hashcode() methods.


String class is overriding these equals() and hashcode() methods.
When we want to compare two strings we use equals method.
basically equals() method is defined in Object class and it will compares the references of two objects if those two objects reference is same then its returns true.
And if equals() methods returns true on comparing two objects then their hashcode() must be same this is the contract between equals() and hashcode().

Lets see a java program which compares two strings.
package com.instanceofjava;

class StringEqualsDemo{

public static void main(String [] args){

String fstr= new String("Javatutorials");
String sstr= new String("Javatutorials");

System.out.println(fstr.equals(sstr));
System.out.println(fstr==sstr);

System.out.println(fstr.hashCode());
System.out.println(sstr.hashCode());
}
}


Output:
true
false
1921912019
1921912019


In the above program we compared two string using equals() method and it returns true.and comparing using == operator returns false.
Basically equal() will also return false on comparing those two strings because default functionality of equal() method is to compare references and two strings are created using new operator so both references are different.
But String class overriding equals() method and in that equals method it comparing content of the strings and returning true if both are having same content false if not.
Lets see what happen if we compare two stringBuffer objects using equals() method.


package com.instanceofjava;

class StringBufferEqualsDemo{

public static void main(String [] args){

StringBuffer fstr= new StringBuffer("Javatutorials");
StringBuffer sstr= new StringBuffer("Javatutorials");

System.out.println(fstr.equals(sstr));
System.out.println(fstr==sstr);

System.out.println(fstr.hashCode());
System.out.println(sstr.hashCode());
}
}
Output:
false
false
1704856573
705927765

If you observe above java program when we are comparing two stringBuffer objects equal() method returning false even content is same. Because StringBuffer class not overriding equals() and hashcode() methods.
StringBuilder is also not overriding equals() method? lets see a program and clarify.


package com.instanceofjava;

class StringBuilderEqualsDemo{

public static void main(String [] args){

StringBuilder fstr= new StringBuilder("Javatutorials");
StringBuilder sstr= new StringBuilder("Javatutorials");

System.out.println(fstr.equals(sstr));
System.out.println(fstr==sstr);

System.out.println(fstr.hashCode());
System.out.println(sstr.hashCode());
}
}

Output:
false
false
1704856573
705927765

No comments:

Post a Comment