Gadgets

Monday, 2 March 2015

Java File I/O operations with an examples

1. How to create a file and directory programmatically?
Constructors to create file and directory:
=================================
File f=new File(String name);
File f=new File(String subdirname,String name);
File f=new File(File subdir,String name);
File Creation:
===========
import java.io.*;
class FileDemo
{
               public static void main(String[] args) throws IOException
               {
                               File f=new File("abc.txt");
                               f.createNewFile();
               }
}
File f=new File("abc.txt");// this line  won’t create any file
f.createNewFile();// file will be create at this line only
Directory Creation:
===============
import java.io.*;
class FileDemo
{
               public static void main(String[] args) throws IOException
               {
                               File f=new File("java_programs");
                               f.mkdir();
               }
}
 
Create directory and file in a specific Directory:
========================================
import java.io.*;
class FileDemo
{
               public static void main(String[] args) throws IOException
               {
                               File f=new File("E:\\programs");
                               f.mkdir();
                               File f1=new File(f,"abc.txt");
                               f1.createNewFile();
               }
}
--------------------------------------------------------------------------------------
2. What are the FileReader and BufferedReader?
We have 2 ways to read data from the file.
FileReader:-
=========
We can use FileReader to read data from the file.
Constructors:-
============
FileReader fr=new FileReader(String filename);
FileReader fr=new FileReader(File f);
Methods:-
=========
int read():- by using this method we read the data character by character. If the next character is not 
available then we will get -1. It return Unicode value, while printing we have to perform type casting 
to char.
Example:-
========
import java.io.*;
class FileDemo
{
               public static void main(String[] args) throws IOException
               {
                               FileReader fr=new FileReader("ab.txt");
                               int i=fr.read();//to read the data
                               while(i!=-1){ //if  next char is not available then we will get -1
                               System.out.println((char)i);//perform type casting char
                               i=fr.read();//to read next line
                               }
               }
}
int read(char[] ch):-it attempts to read enough characters from the file into char[].
Example:-
========
import java.io.*;
class FileDemo
{
               public static void main(String[] args) throws IOException
               {
                               File f=new File("ab.txt");
                               FileReader fr=new FileReader(f);
                               char[] ch=new char[(int)f.length()];
                               char[] ch=new char[(int)f.length()];//length() to find number of char in file
                               fr.read(ch);//to read the data from file into char[]
                               for(char ch1:ch){
                               System.out.println(ch1);
                               }
               }
}
In this approach FileReader read the data character by character from the file.
BufferedReader:-
==============
To overcome FileReader problem we use BufferedReader.
BufferedReader read the file line by line and it can’t communicate directly with
the file, it can communicate with some reader object.It is most enhance reader.
Constructors:-
============
BufferedReader br=new BufferedReader(Reader r);
BufferedReader br=new BufferedReader(Reader r,int buffersize);
Methods:-
=========
int read(), int read(char[] ch),close(),String readLine()
Example:-
========
import java.io.*;
class FileDemo
{
               public static void main(String[] args) throws IOException
               {
                   FileReader fr=new FileReader("ab.txt");
                               BufferedReader br=new BufferedReader(fr);
                  String line=br.readLine();//to read line
                  while(line!=null){//repeat until line null
                               System.out.println(line);
                               line=br.readLine();// for next line
                               }
                               br.close();
               }
}
 ----------------------------------------------------------------------------------------
3. What are the FileWriter, BufferedWriter and PrintWriter?
We have 3 ways to write character data into a file.
1. FileWriter:-
===========
FileWriter Constructors:-
====================
FileWriter fw=new FileWriter(String name);
FileWriter fw=new FileWriter(File f);
Note:- if the specified file is not already available then this constructor will create that file.
Methods:-
=========
write(int ch):- to write single character.
write(char[] ch):- to write characters.
write(String s):- to write string.
flush():- to  guaranty that total data should be written properly to the file including last character.
close():- to close the string.
delete():- to delete file or directory.
Example:-
=========
import java.io.*;
class FileDemo
{
               public static void main(String[] args) throws IOException
               {
                               FileWriter fw=new FileWriter("abc.txt");
                               fw.write(100);
                               fw.write(‘\n’);
                               fw.write("iam\ngood programmer");
                               fw.write(‘\n’);
                               char[] ch={‘a’,’b’,’c’,’d’};
                               fw.write(ch);
                               fw.flush();
                               fw.close();
               }
}
fw.write(100) write Unicode value of 100 is ‘d’.
If we want to add (append) data to the file we use boolean append as shown below.
FileWriter fw=new FileWriter(String filename,boolean append);
FileWriter fw=new FileWriter("abc.txt",true);
In this approach the line separator “\n” is varied from system to system(“\n” may not work in some systems) so it is very difficult to the programmer.
BufferedWriter:-
=============
To overcome FileWriter problem we use BufferedWriter to write text data in to the file.
In this we have one extra method “newline()”:- to insert a newline.
BufferedWriter Constructors:-
========================
BufferedWriter bw=new BufferedWriter(writer w);
BufferedWriter bw=new BufferedWriter(writer w,int buffersize);
BufferedWriter can’t communicate directly with the file, it can communicate with some writer object
 like as shown in below.
BufferedWriter bw=new BufferedWriter(new FileWriter("abc.txt"));
BufferedWriter bw=new BufferedWriter(new BufferedWriter(new FileWriter("abc.txt")));
We can take two BufferedWriter also.
Example:-
========
import java.io.*;
class FileDemo
{
               public static void main(String[] args) throws IOException
               {
                               FileWriter fw=new FileWriter("abc.txt",true);
                               BufferedWriter bw=new BufferedWriter(fw);
                               bw.write(100);
                               bw.newLine();
                               bw.write("iam good programmer");
                               bw.newLine();
                               char[] ch={‘a’,’b’,’c’,’d’};
                               bw.write(ch);
                               bw.newLine();
                               bw.flush();
                               bw.close();
               }
}
Whenever we are closing BufferWriter automatically under line FileWriter will be close and we not 
required to close.
In this approach we should take newline() method for every line so length of the code will be increased.
PrintWriter:-
==========
To overcome the BufferedWriter Problem we use PrintWriter to write any type of data into the file.
printWriter is most enhance writer. If file not available then I will create the file and write data into file.
Constructors:-
============
PrintWriter pw=new PrintWriter(String filename);
PrintWriter pw=new PrintWriter(File f);
PrintWriter pw=new PrintWriter(writer w);
Methods:-
========
Here we have some more extra methods print(char ch), print(int i), print(double d), print(String s), 
print(Boolean b).
Example:-
========
import java.io.*;
class FileDemo
{
               public static void main(String[] args) throws IOException
               {
                               PrintWriter pw=new PrintWriter("ab.txt");                       
                                  pw.write(100);
                                pw.print(100);
                               pw.println("iam good programmer");
                                  pw.println(true);
                               char[] ch={‘a’,’b’,’c’,’d’};
                               pw.println(ch);
                               pw.println(‘e’);
                               pw.flush();
                               pw.close();
               }
}
In the above program print(100) write int value “100” but write(100) write Unicode value of ‘d’.
------------------------------------------------------------------------------------------------------
4. What are the most enhanced Writer and Reader?
The most enhanced writer is PrintWriter and the most reader is BufferedReader.
-----------------------------------------------------------------------------------------------
5. Exapain about flush() method?
To guaranty that total data should be written properly to the file including last character.
------------------------------------------------------------------------------------------------
6. How can we list out the files and directories in a specific directory?
Display all file and directories from D:\Java location:
===========================================
import java.io.*;
class FileDemo
{
               public static void main(String[] args) throws IOException
               {
                               int count=0;
                               File f=new File("D:\\Java");
                               String[] s=f.list();
                               for(String s1:s)
                               {
                                              count++;
                                              System.out.println(s1);
                               }
                               System.out.println(count);
               }
}
Display files only:
==============
import java.io.*;
class FileDemo
{
               public static void main(String[] args) throws IOException
               {
                               int count=0;
                               File f=new File("D:\\Java");
                               String[] s=f.list();
                               for(String s1:s)
                               {
                                              File f1=new File(f,s1);
                                              if(f1.isFile()){
                                              count++;
                                              System.out.println(s1);
                               }
                               }
                               System.out.println(count);
               }
}
Display Directories only:
====================
Just change the if condition if(f1.isDirectory()).
--------------------------------------------------------------------------------------------------
7. What is the difference between write(100) and print(100) of PrintWriter class?
In the case of write(100) the corresponding character ‘d’ will be written in to the file where as print(100) is written int value ‘100’.
-------------------------------------------------------------------------------------------------------
8. What is the difference between Reader Writer and input output streams?
Generally we use Reader and Writer to handle data where as we can use streams to handle binary data(like images, videos files, audio files ect.).
We use FileOutPutStream to write binary data to the file where as we use FileInputStream to read binary data from the file.

Java Interview Questions on Development

Interview questions on java development. In this article I have given solutions in programmatically and diagrammatically for each and every question.
Here the questions are how to compile and run java programs, how to compile multiple java source files etc.
1) What is the purpose of javac command?
We use javac command to compile a single or group of java source files.

Monday, 2 February 2015

Java Literals



Literals:-
int i=10;
int – data type/keyword
i – name of variable/identifier
10 – literal/constant/value
Any constant value which can be assigned to the variable is called literal.
Integral Literals:-
We can specify literal values to the integral data types (byte, short, int, long) in the following 3 ways
Note:- JVM converts every value into decimal form value.
Decimal Form:-
Decimal form base 10(0-9) and it is allowed digits are 0 to 9.
int x=10;    int x=20;
Octal Form:-
Octal form base 8(0-7) and allowed digits are 0 to 7.
Literal value should be prefix with zero (0)
int x=010;     int x=020;
Hexadecimal form:-
Hexadecimal form base 16 (0-9 and ‘a’ to ‘f’), for extra digit we use lower case or upper case (a to f or A to F).
Literal value should be prefixed with 0x or 0X
int i=0x10;      int i=0x20;      int i=0X30;
Example 1:-
class Test{
public static void main(String arg[])
{
int a=10;
int b=010;
int c=0x10;
System.out.println("decimal : "+a+"  oct : "+b+"   hexa decimal : "+c);
}
}
Output:-
Example 2:-
int a=20, b=020,c=0x20;
By default every integral literal is ‘int’ type, if we want declare ‘long’ type we should suffixed with l or L.
int x=10;  correct
long y=10l;   correct
long z=10; correct
int i=10l;   Wrong(here ‘10l’ is long type so we can’t assign long type to the int type)
Example:-
class Test{
public static void main(String arg[])
{
int x=10;
long y=10l;
long z=10;
System.out.println("x value : "+x+"  y value : "+y+"   z value : "+z);
}
}
Output:-
There is no direct way to specify ‘byte’ and ‘short’ literal but when we are assigning integral to the ‘byte’ variable and if that value is with the range of ‘byte’ then compiler treats it automatically as ‘byte’ literal similarly ‘short literal also.
Example:-
byte a=10;  correct
byte a=127;  correct
byte a=128; wrong (it is out of the byte range, we will get compile time error)
short a=32767;   correct
short b=32768;  wrong (it is out of the short range, we will get compile time error)
Note:- these are the only possible ways to specify literal value for integral data types.
Floating Point Literals:-
By default every floating point literal is double type and hence we can’t assign directly to float variables but we can assign float type by using suffixed with f or F.
Note:- we can assign integer values to the float type and that integer value either in decimal or octal or hexadecimal. But we can’t assign float value to int type.
float f=123.456f;  correct
float x=0x123; correct(integer hexadecimal value)
float y=01234; correct(integer octal value)
float f=123;   correct
float f=123.456d;  wrong(here 123.456d is double type, we will get compile time error)
float f=123.456;  wrong(By default JVM treats every float value is double type so here 123.456 is double type, we will get compile time error)
Example 1:-
class Test
{
public static void main(String arg[])
{
float x=123.456f;
float y=123;
double z=123.456;
System.out.println("x value : "+x+" y value: "+y+" z value : "+z);}
}
Output
Example 2:-
class Test
{
public static void main(String arg[])
{
float x=123.456d;
float y=123.456;
System.out.println("x value : "+x+" y value: "+y);
}
}
Output
We can specify suffixed to the double type with d or D but this convention is not required.
Double d=123.456; correct
Double d=123.456d; correct (but suffix ‘d’ is not required)
Double d=123; correct
Example 3:-
class Test{
public static void main(String arg[])
{
double x=123.456d;
double y=123;
double z=123.456;
System.out.println("x value : "+x+" y value: "+y+" z value : "+z);
}
}
Output
 
We can specify floating point literal only in decimal form, floating point literals not allowed octal and hexadecimal form.
Double b=123.456; correct
Double b=0123.456; correct (0123.456 is not integer octal, it is just float value that value started with zero)
Double b=0x1234.567; wrong (here 0x123.456d is hexadecimal type, we will get compile time error)
Example of correct declaration:-
class Correct{
public static void main(String arg[]){
float a=10;
float b=10.10f;
float c=010;                                                          
float d=010.10f;
float e=0x10;
double f=10;
double g=10.10;
double h=010.10;
double i=0x10;
double j=10.10d;
System.out.println("..."+a+"..."+b+"..."+c+"..."+d+"..."+e+"..."+f+"..."+g+"..."+h+"..."+i+"..."+j);
}
}
Example of Wrong declaration:-
 Example 1:-
class Wrong{
public static void main(String arg[]){
float a=10.10;
float b=10.10d;
}
}
Example 2:-
float f=0x10.00;
Example 3:-
class Wrong{
public static void main(String arg[]){
double a=0x10.10;
double b=0x10.10d;
}
}

We can specify floating point values even in exponent ion form also known as scientific notation.
double d=1.2e3;
float f=1.2e3f;
Boolean Literal:-
The only allowed values for Boolean data type are true and false.
boolean b=true; correct
boolean b=false;  correct
boolean b="true";  wrong(here “true” is String type so Boolean not allowed it)
boolean b=True;  wrong(here ‘T’ is upper case so Boolean type is not allowed it)
boolean b=0;   wrong(here zero is int type so Boolean not allowed it)
Char Literal:-
We can specify ‘char’ literal as a single character with in single cot.
char ch=’a’;
char ch=a;
char ch=”a”;
char ch=’ab’;
Example 1:-
class Test {
public static void main(String arg[]) {
char ch='a';
System.out.println(ch);
}
}
Output:-
Example 2:-
class Test {
public static void main(String arg[]) {
char ch='ab';
System.out.println(ch);
}
}
Output:-
Example 3:-
class Test {
public static void main(String arg[]) {
char ch="a";
char ch1=a;
}
}
Output:-
We can represent char literal as integral literal which represent Unicode of that character that integral literal can be specified either in decimal or octal or hexadecimal form but allowed range is 0 to 65535
Example:-
class Test {
public static void main(String arg[]) {
char ch=97;
char ch1=0777;
char ch2=0xface;
char ch3=65535;
System.out.println("ch-->"+ch+" ch1-->"+ch1+" ch2-->"+ch2+" ch3-->"+ch3);
}
}
Output:-
We can represent char literal even in Unicode which is
‘\uXXXX’ with 4digit hexadecimal
Char ch=’\u0061’;   correct
Char ch=’\uface’;    correct
Char ch=’\iabcd’;   wrong (we should give \u not \i)
Char ch=\uabcd;    wrong (we missed single cot)

String Literal:-
We can specify String literal as sequence of characters with in double cot(“ “).
String s=”scjp”;
Java1.7 version enhanced literals:-
Binary literal:-
In java1.6 version for integral data types (byte,short,injt,long) we can specify literal values in the following ways
Decimal, octal, hexadecimal.
But in java1.7 version we can specify literals values in binary form also
Binary form allowed digits are 0 and 1. Should be prefixed with 0b or 0B
int x=0b1111;
Example:-
class Test {
static public void main(String arg[]) {
int i=0b0110;
System.out.println(i);
}
}
Output:-
0110 value is 6
In java1.7 version we can use underscore symbol between the digits of numeric literal
int x=123_4567_89;
The main advantage of this approach is readability of the code will be improved.
At the time of compilation the underscore symbol is remove automatically by the compiler hence after compilation the x value will become
int x=123456789;
We can add more than one underscore symbol also between the digits and we use underscore symbol only between digits. If we use any ware else we will get compile time error.
Example:-
class Test
{
public static void main(String arg[])
{
int i=12_3_45_678_90;
System.out.println(i);
}
}
Output:-