Primitive and non primitive data type in java

TypeSize in bits(in Ram)Min ValueMax ValuePrecisionExample
booleanJVM specific(1 bit)--true or falseboolean x =true;
byte8-128127+127 or -127
byte b = 120;
char1602^16 -1All unicode characterschar c ='A';
char c = 65;
short16-2^152^15-1+32,767 to -32,768short s = 30000;
int32-2^312^31-1+2,147,483,647 to -2,147,483,648int i = 10;
long64-2^632^63-1+9,223,372,036,854,775,807 to -9,223,372,036,854,775,808long l = 90;
float322^-149(2-2^-23).2^1273.402,823,5 E+38 to 1.4 E-45 float f = 65f;
double642^-1074(2-2^-52).2^10231.797,693,134,862,315,7 E+308 to 4.9 E-324double d = 65.55;

PrintWriter

  • It is the most enhanced writer to write character data to the file.
  • The main advantage of print writer is we can write any Type of Primitive Type Data Directly to the file.
  • bw.write(true)//compile timer error because boolean is not accepted by BufferWriter
  • bw.write(100)//will print the letter d, so to print 100 we have to cast it to string
  • bw.write(10.5)//compile time error because it does not support double.
  • Every time we need to use primitive data type with BufferWriter we need to cast it to String to use it, and casting every type to string will eat up the system memory and reduce the system performance.
  • Using BufferReader for new line we have to call a separate method bw.newLine() which adds an extra line of code and in FileWrite adding “\n” every time make the code unreadable now in print writer println method automatically adds the breakline at the end of the line.
  • All the above problems are addressed in print and println method of PrintWriter class

Constructors:

PrintWriter pw = new PrintWriter(String fileName);
PrintWriter pw = new PrintWriter(File f);
PrintWriter pw = new PrintWriter(Writer w);

Note : PrintWriter can communicate either directly to the file or via some writer object also.

Methods of PrintWriter :

write(int ch);
write(char[] ch);
write(String s);
flush();
close();

print(char ch);
print(int i);
print(double d);
print(boolean b);
print(String s);

println(char ch);
println(int i);
println(double d);
println(boolean b);
println(String s);

Below program show an example of PrintWriter

package com.fileDemo;

import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class Demo {
	public static void main(String[] args) throws FileNotFoundException {
		PrintWriter pw = new PrintWriter("/home/tyson/Desktop/temp/file3");
		pw.write(100);
		pw.print(100);
		pw.println(700);
		pw.println(true);
		pw.println('K');
		pw.println("Tyson");
		pw.flush();
		pw.close();
	}
}

Output :

d100700
true
K
Tyson

What is the difference betwen pw.write(100) and pw.print(100) in the above code ?

  • In the case of pw.write(100) the character d will be written into file.
  • In case of pw.print(100) the string 100 will be written into the file.

BufferedReader

  • We can use BufferedReader to Read Character Data(text data) from file.
  • The main advantage of BufferedReader over FileReader is we can Read Data Line by line in addition to Character by Character, which is more convenient to the programmer.

Constructors :

BufferedReader br = new BufferedReader(Reader r);
BufferedReader br = new BufferedReader(Reader r, int bufferSize);

Note : BufferedReader cannot directly communicate with the file, it has to communicate via some reader object.

Methods :

int read();
int read(char[] ch);
void close();
String readLine();
  • It attempts to read next line from the file and returns it, if it is available.
  • It next line is not available, then it will return null.

Sample program to read line using buffered reader :

package com.fileDemo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Demo {
	public static void main(String[] args) throws IOException {
		File f = new File("/home/tyson/Desktop/temp/file2");
		FileReader fr = new FileReader(f);
		BufferedReader br = new BufferedReader(fr);
		String line = br.readLine();
		while(line!=null) {
			System.out.println(line);
			line = br.readLine();
		}
		br.close();
	}
}

Note :

  • We need not close FileReader object, while closing BufferedReader object the FileReader object is closed implicitly.
  • Most enhanced reader to read data from the file is BufferedReader

BufferedWriter

Use of FileReader and FileWriter is not recommended because :

  • While Writing Data by FileWriter we have to insert line separator manually, which is varied from System to System. It is difficult to the programmer.
  • While Reading Data by using FileReader we can read data character by character which is not convenient to the programmer.

To overcome these limitations we should go for BufferedWriter and BufferedReader.

Constructor :

BufferedWriter bw = new BufferedWriter(Write w);
BufferedWriter bw = new BufferedWriter(Write w, int buffersie);

Note : BufferedWriter can’t communicate directly with a file , it has to communicate via some Writer object only.

Which of the following are valid?

BufferedWriter bw = new BufferedWriter("abc.txt");//Not Valid
BufferedWriter bw = new BufferedWriter(new File("abc.txt"));//Not Valid
BufferedWriter bw = new BufferedWriter(new FileWriter("abc.txt"));//Valid
BufferedWriter bw = new BufferedWriter(new BufferedWriter(new FileWriter("abc.txt")));//Valid and called 2 level buffering

Methods of BufferedWriter:

write(int ch);
write(char[] ch);
write(String s);
flush();
close();
newLine();//To insert a line Separator

Writing to a file using BufferedWriter :

package com.fileDemo;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Demo {
	public static void main(String[] args) throws IOException {
		File f = new File("/home/tyson/Desktop/temp/file2");
		FileWriter fw = new FileWriter(f);
		BufferedWriter bw = new BufferedWriter(fw);
		bw.write("Hello");
		bw.write("World");
		bw.newLine();
		bw.write("You are writing a java program");
		bw.flush();
		bw.close();//No need to flush(), close() will call flush() internally
		//fw.close(); //file Writer object is closed automatically closed by buffered writer close method
	}
}

Note :

  • It is recommended to close buffered writer object and buffered writer object automatically closes the file writer.
  • It is not recommended to close fileWriter object.
  • flush() method of buffered writer is automatically closed while calling buffered writer’s close() method call

FileReader

We can use FileReader to Read Character Data from the file.

Constructors :

FileReader fr = new FileReader(String fileName);
FileReader fr = new FileReader(File fileReference);

Note : If the file does not exist then, FileReader will throw java.io.FileNotFoundException

Methods :

int read(); //returns unicode value of character
int read(char[] ch); //returns number of characters copied from file to array
void close();

Example of : int read() method

package com.fileDemo;

import java.io.File;
import java.io.FileReader;

public class Demo {
	public static void main(String[] args) throws Exception {
		File f = new File("/home/tyson/Desktop/temp/file1"); //throws exception if file is not present
		FileReader fr = new FileReader(f);
		int x = fr.read();
		while(x!=-1) {
			System.out.print((char)x); //need to type cast to convert unicode to its character value 
			x = fr.read();
		}
                fr.close();
	}
}

Example of : int read(char []) method

package com.fileDemo;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Demo {
	public static void main(String[] args) throws IOException {
		File f = new File("/home/tyson/Desktop/temp/file1");
		char[] ch = new char[(int)f.length()];
		FileReader fr =	new FileReader(f);
		fr.read(ch);
		for(char c : ch) {
			System.out.print(c);
		}
		fr.close();
	}
}

Note : Line by line reading is not possible in FileReader hence the concept of BufferedReader.

FileWriter

We can use File Writer Object to write Character Data(text data) to the File.

Constructors :

FileWriter fw = new FileWriter(String fileName)
FileWriter fw = new FileWriter(File fileReference)

Above constructors will by default override the file name mentioned but to append the data to the file below constructors can be used.

FileWriter fw = new FileWriter(String fileName, boolean append)
FileWriter fw = new FileWriter(File fileReference, boolean append)

Note : If the file mentioned in the above constructors are not available then all FileWrite constructor will create the a new file to write into it.

Methods of FileWriter Class :

write(int ch); //to Write a single character into the file using its UNICODE
write(char[] ch);
write(String s);
flush(); //To save/write the data into the file we use flush method
close();

Example of FileWriter in java :

package com.fileDemo;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Demo {
	public static void main(String[] args) throws IOException {
		File f = new File("/home/tyson/Desktop/temp/file1");
		FileWriter fw = new FileWriter(f);
		fw.write("Hello World \nThis is java example");
		fw.flush();
		fw.close();
	}
}

Note : The problem with FileWriter is we have to insert line separator (\n) manually, which is varied from System to System. It is very difficult to the programmer. Hence the concept of BufferdWriter and PrintWriter came into picture

File Class in java

File f = new File("abc.txt");
  • The above line won’t create a physical file but it will check if file is available with that name.
  • If the file is available the object f will point to that file.
  • If the files doesn’t exist then it just creates a java File object to represent a file name ‘abc.txt’ but it won’t actually create any physical line

How to create a new file in java?

File f = new File("abc.txt");
f.createNewFile();

How to create a new directory in java?

File f = new File("/home/tyson/HelloWorld");
f.mkdir();

How to check if a file or a directory exist in java?

File f1 = new File("abc.txt");
File f2 = new File("/home/tyson");
f1.exist()
f2.exist()

Note : Java IO Concept is implemented based on the UNIX OS concept and in unix everything is treated as a File.Hence we can use java file object to represent both file and directories.

File Class Constructors :

File f1 = new File(String name);
//Creates f1 object representing file or directory
File f2 = new File(String subDir, String name);
//Creates f2 object within a subdirectory
File f3 = new File(File subDir, String name);

File Class important methods :

boolean exist();
boolean createNewFile();
boolean mkdir();
boolean isFile();
boolean isDirectory();
String[] list(); //returns names of all files and directory present in a directory
long length(); //returns number of characters present in the specified file.
boolean delete(); //deletes a file or directory.

Program to print the list of files and directories in a directory in java :

package com.fileDemo;

import java.io.File;

public class ListOfFilesDemo {
	public static void main(String[] args) {
		File f = new File("/home/tyson/Desktop/temp");
		String[] listOfFiles = f.list();
		for(String name : listOfFiles) {
			System.out.println(name);
		}
	}
}

ArrayList

  • ArrayList is one of the implementation of List interface.
  • Underlying data structure of ArrayList is Resizable Array or Growable Array.
  • Underlying data structure of ArrayList is array, i.e data is stored inside an array.
  • ArrayList are equivalent to Vector but ArrayList are not synchronized.
  • All operations run in around O(n) time complexity.
  • But if you want to remove items, this operation is not so efficient, we have to shift each item in our list O(n), instead we should use linked list.
  • Capacity of an ArrayList should be defined during instantiation when ever possible (List<Object> l = new ArrayList<>(5000)), this may reduce the amount of incremental reallocation.
  • Implements RandomAccess Interface(Only Array List and Vector), Clonable Interface and Serializable Interface

Features of ArrayList :

  • Best choice if reading at random index is required.
  • Worst choice if adding and deleting in middle of list has to be performed.(Use Linkedlist)
  • Duplicates are allowed
  • Insertion order is preserved.
  • Resizable or Growable
  • Store heterogeneous object
  • null insertion is possible
  • Default initial capacity of arraylist is 10
  • New capacity of arraylist will be (currentcapacity * 1.5)+1 (Default capacity increment will be 10, 16, 25…)
  • Implements RandomAccess Interface which helps to access all the index of an array with the same speed as be it 1st element or 1000th element.

Constructors of ArrayList :

ArrayList<Object> l = new Arraylist<>(); //size 10 by default
ArrayList<Object> l = new Arraylist<>(int initialCapacity); //predefined capacity
ArrayList<Object> l = new Arraylist<>(Collection c); //create equivalent array list

Example :

public class ArrayListDemo {
	public static void main(String[] args) {
		ArrayList<String> l = new ArrayList<>();
		l.add("A");
		l.add("B");
		l.add(null);
		System.out.println(l);
		l.remove(2);
		System.out.println(l);
		l.add("M");
		l.add("N");
		System.out.println(l);
	}
}

Collections Framework

  • The java collections Framework defines several classes and interfaces which can be used to represent a group of individual object as a single entity.
  • These classes and interface implement the collection data structures.
  • For Example : list, stack, queue or maps.
  • The collection framework was designed and developed primarily by Joshua Bloch
  • It was introduced in JDK 1.2
  • Why to use these collections?
    • We don’t have to implement every algorithm and data structure from the scratch, its already written into java.
    • It is already been tested.
  • Almost all Collections are derived from the java.utils.Collection interface
  • The main advantage of Collections over array is that collections are grow-able in size, i.e we need not know the size of elements in advance.
  • toArray() method can transform any collection into one dimensional array.
  • The Collection interface extends the java.lang.Iterable interface, this is why we can use for-each loop.

We write for each loop like below example :

for(String fruits : listOfFruits){
   System.out.println(fruits);
}

After compilation of .java file, .class file contains below code :

for (Iterator<String> i = listOfFruits.iterator(); i.hasNext();) {
   String fruits = i.next();
   System.out.println(fruits);
}
ArraysCollections
Fixed in SizeGrow-able in size
Can hold primitive, non primitive and object data type.Can hold only non primitive and object data type.
No underlying Data structure, hence no ready-made method supportImplemented base on standard data structure hence for every collection ready-made collection support is available.

Collection Interface

  • Collection interface defines the most common methods which are applicable for any Collection object.
  • In general Collection interface is considered as root interface of collection framework.
  • Collection Interface extends Iterable Interface.
  • There is no concrete class which implements collection interface directly.
Collection InterfaceCollections Class
If you want to represent a group of individual objects we should use collection InterfaceCollections is a utility class (java.utils.package) which defines several utility methods like sorting,searching for collection object.

Methods of Collection Interface :

boolean add(E e);
boolean addAll(Collection<? extends E> c);
boolean remove(Object o);
boolean removeAll(Collection<?> c);
void clear();
boolean retainAll(Collection<?> c);
boolean contains(Object o);
boolean containsAll(Collection<?> c);

int size();
boolean isEmpty();
Iterator<E> iterator();
Object[] toArray();

boolean equals(Object o);
int hashCode();

Enum

If we want to represent a Group Named Constants then we should go for enum

Example of Enum

enum Month{
JAN,FEB,MAR;
}
  • Semicolon (;) is optional
  • enum concept was introduced in 1.5 Version
  • The main objective of enum is to Define our own Data Types(Enumerated Data Types)
  • When compared with other languages enum, java enum is more powerful

Internally Implementation of enum :

  • Every enum Internally implemented by using Class Concept.
  • Every enum Constant is Always public static final.
  • Every enum Constant Represents an Object of the Type enum.

Example of enum :

enum Month{
JAN,FEB,MAR;
}

Internal Implementation of enum

class Month{
public static final Month JAN = new Month();
public static final Month FEB = new Month();
public static final Month MAR = new Month();
}

A Tree structure using enum

package com.enumTest;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

public class Demo {
	enum Month{
		JAN(1,"january",Climate.WINTER),FEB(2,"Februrary",Climate.WINTER),MAR(3,"March",Climate.SUMMER),APR(4,"April",Climate.SUMMER),
		MAY(5,"May",Climate.SUMMER),JUN(6,"June",Climate.RAINY),JUL(7,"July",Climate.RAINY),AUG(8,"August",Climate.RAINY),SEP(9,"September",Climate.RAINY),
		OCT(10,"October",Climate.WINTER),NOV(11,"November",Climate.WINTER),DEC(12,"December",Climate.WINTER);
		int width;
		String name;
		Climate climate;
		Month(int width,String name, Climate climate ){
			this.width=width;
			this.name=name;
			this.climate=climate;
		}
		public int getWidth() {
			return width;
		}
		public void setWidth(int width) {
			this.width = width;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public Climate getClimate() {
			return climate;
		}
		enum Climate{
			SUMMER,WINTER,RAINY;
			int totalWidth;
			public int getTotalWidth() {
				return totalWidth;
			}
			enum Decade{
				Decade;
			}
		}
	} 
	public static void main(String[] args) {
		int grandTotal;
		List<Month> temp =  new ArrayList<>();
		temp.add(Month.JAN);
		temp.add(Month.FEB);
		temp.add(Month.MAR);
		temp.add(Month.APR);
		temp.forEach(month -> month.climate.totalWidth=month.climate.totalWidth+month.width);
		EnumSet.allOf(Month.Climate.class).forEach(climate -> System.out.println(climate.totalWidth));
		grandTotal = temp.stream().mapToInt(Month::getWidth).sum();
		
		
	}
}