JAVA IO

The java.io package contains all the classes required for input and output operations.

IMPORTANT TERMS

Input Output Redirection : I/O stream ends change direction and placed on file , console, or printer whenever required.

Stream : Its the flow of data

Input Stream :  Input Stream is used for many things that you read from in the form of  stream of bytes.

Output Stream : Output Stream is used for many things that you write to in the form of  stream of bytes.

Reader : Similar to Input Stream but data read character by character.

Writer : Similar to Output Stream but data read character by character.

BufferedReader : This class reads text from a character-input stream, buffering characters so as to provide for the efficient reading.

 

FILE OPERATIONS

File(String pathname) : creates a new File instance by converting  pathname string into an abstract pathname. eg.


File file=new File("C:/prog/AnyName.txt");

 

getName() : returns the name of the file or directory. eg.


String name = file.getName();

 

getAbsolutePath() : returns the absolute pathname string. eg.

String path = file.getAbsolutePath();

 

exists() : checks whether the file or directory exists or not. eg.


if(file.exists()){
  //do the coding here
 }

 

isDirectory() : tests whether the file is a directory. eg.


if(file.exists()){
  if(file.isDirectory()){
    System.out.println(file.getName()+" is a directory..");
  }
 }

 

lastModified() : returns the time when the file was last modified. eg.


long time = file.lastModified();

 

mkdir() : creates single directory. eg.

 file = new File("C:/Java");
 // creates directory
  bool = file.mkdir();    

 

mkdirs() : creates recursive directories. eg.

 file = new File("C:/Folder1/Folder2/Java");
  // create directories
  bool = file.mkdirs();    

 

GENERICS AND COLLECTIONS

GENERICS

Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively.

class Points <T>{
T x,y;

public Points() {

}

public Points(T x, T y) {
super();
this.x = x;
this.y = y;
}

public T getX() {
return x;
}

public void setX(T x) {
this.x = x;
}

public T getY() {
return y;
}

public void setY(T y) {
this.y = y;
}

@Override
public String toString() {
return "Points [x=" + x + ", y=" + y + "]";
}

}

public class Generics {
public static void main(String[] args) {
//Integer
Points<Integer> ref=new Points<Integer>(12,34);
System.out.println(ref);

//Float
Points<Float> ref1=new Points<Float>();
ref1.setX(23.5F);
ref1.setY(55.4F);
System.out.println(ref1);

}
}

Output :

Points [x=12, y=34]
Points [x=23.5, y=55.4]


COLLECTIONS

Collections in java is a framework that provides an architecture to store and manipulate the group of objects.

ArrayList :

  • This class can contain duplicate elements.
  • This class maintains insertion order.

LinkedList :

  • This class can contain duplicate elements.
  • This class maintains insertion order.

HashSet :

  • uses hashtable to store the elements.
  • contains unique elements only.

List can contain duplicate elements whereas Set contains unique elements only.

HashMap :

  • A HashMap contains values based on the key.
  • It contains only unique elements.

METHODS USED IN COLLECTIONS

  • add(Object element) : insert an element in this collection.
  • addAll(Collection c) :  insert all elements of collection in the invoking collection.
  • remove(Object element) : delete an element from collection
  • removeAll(Collection c) : deletes all the elements of the collection
  • size() :total number of elements of the collection
  • clear() : removes the total no of element from the collection
  • containsAll(Collection c) :search the specified collection in this collection

VARIOUS FUNCTIONS ON STRING

  • toString()

toString() function shows what is there in reference variable. By default, it prints address kept in reference variable. But, toString() can be overrried to show desired output.

  • hashcode()

Hashcode is any unique value assigned to every object present in memory. This function returns that integer value.

  • toUpper()

Converts lowercase letter to uppercase.

  • toLower()

Converts uppercase letter to lowercase.

  • split(String regex)

The java string split() method splits this string against given regular expression(regex) and returns a char array.

  • substring()

Returns new String object containing the substring of the given string from specified startIndex (inclusive).

  • contains(CharSequence c)

This method returns true if and only if this string contains the specified sequence of char values.

  • startswith(CharSequence c)

Returns boolean value , whether  a string starts with the specified prefix beginning a specified index or by default at the beginning.

  • endswith(CharSequence c)

This method returns tests if this string ends with the specified suffix.

EXCEPTION HANDLING

An exception (or exceptional event) is a problem that arises during the execution of a program. Exception normally disrupts the normal flow of the application that is why we use exception handling.

TYPES OF EXCEPTION

CHECKED EXCEPTION :

A checked exception is an exception that occurs at the compile time.

Examples:

  • IOException
  • EOFException
  • SQLException

UNCHECKED EXCEPTION :

An unchecked exception is an exception that occurs at the time of execution.

Examples :

  • NullPointerException
  • NumberFormatException
  • ArithmeticException

ERROR :

Error is irrecoverable.

Examples :

  • VirtualMachineError,
  • AssertionError

TRY-CATCH BLOCK

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

Java catch block is used to handle the Exception. It must be used after the try block only.

FINALLY

  • Java finally block is a block that is used to execute important code such as closing connection, stream etc.
  • Java finally block is always executed whether exception is handled or not.

THROW

The Java throw keyword is used to explicitly throw an exception.We can throw either checked or uncheked exception in java by throw keyword.

THROWS

The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception.

CUSTOM EXCEPION

Custom Exception are the exceptions which are created by programmer.

All terms studied so far , shown in the given example :

class ThrowExceptionOnAge extends Exception{      //Custom exception
	ThrowExceptionOnAge(){
		System.out.println("No Entry");
	}
	ThrowExceptionOnAge(String s){
		System.out.println(s);
	}
}
public class ExceptionDemo{
	public static void main(String args[]) throws ThrowExceptionOnAge{     //throws keyword
		int age;
		age=2;
		try{                 //try block
		   if(age<18){
			throw new ThrowExceptionOnAge("Get out");    //throw keyword
		    }
	            else{
			System.out.println("Welcome");
		    }
		}
		catch(ThrowExceptionOnAge e){       //catch block
			System.out.println(e);
		}
                finally{                      //finally block
                       System.out.println("Bye");
	 }
     }
}

Output :

Get Out
ThrowExceptionOnAge
Bye

 

AUTOBOXING AND UNBOXING

Everything in java is  an Object.

This statement completely holds true. Even the primitive data types(int ,float, char,boolean) can be expressed as Object. This is possible through Boxing.

AUTOBOXING

The automatic conversion of primitive data types into its equivalent Wrapper type is known as boxing.

Example :

int i = 10;
Integer iRef = new Integer (i); &amp;nbsp;&amp;nbsp; //Boxing (explicit way)

Here, in the above example Integer is a wrapper class . It converts primitive types to Reference types. This  is  called Boxing.

int i = 10;
Integer iRef = i;    //Autoboxing (implicit way)

UNBOXING

The automatic conversion of wrapper class type into corresponding primitive type, is known as Unboxing.

Example:

Integer iRef = 20;
int i = iRef.intValue();    //Unboxing  (explicit way)

Above, code converts the wrapper class Integer into primitive type int.

Integer iRef = 20;
int i = iRef;   //Unboxing  (implicit way)

 

ARRAY

DEFINITION

Array is a series of objects all of which are the same size and type. It contains homogeneous data.

DECLARATION OF ARRAY

int arr[] = new int[5];

array

Storage structure of Array in Stack and Heap

If multiple arrays are to be declared ,any syntax of the following can be used:

int ar1[] , ar2[], ar3[];

Or

int[] ar1,ar2,ar3;

PRINTING ELEMENTS OF ARRAY USING  FOR-EACH LOOP


class A{

public static void main(String args[]){
int ar[] = {23,13,12,45,56};
//Using for - each loop
for(int x : ar){
System.out.println(x+"\n");
}
}

ARRAY OF REFERENCE TYPE OF A CLASS

If Student is class :

class Student{
//some attributes
}

And , ar is an Array declared as follows :

Student ar[] = new Student[5];

Then , in memory  it can be represented as :

object-array

2 D ARRAY

An array of arrays can be called as 2D array.

Example :

int ar[][] = new int[3][4];  //This creates an array with 3 rows and 4 columns

ABSTRACT CLASS AND INTERFACE

ABSTRACT CLASS

  • Abstract function is a function which is just declared but not defined.
  • Abstract function is only declared in Abstract Class.
  • Abstract class may contain concrete methods.
  • Abstract class supports run-time polymorphism.
  • Objects of Abstract classes can’t be created ; only reference variables can be created.

Example :


class A{
abstract void meth();   //Abstract method
}

class B extends A{
void meth(){           //Definition of Abstract method provided by Child class B
System.out.println("B");
}

public static void main(String args[]){
A ref= new B();
ref.meth();
}


Interface

Interface  is more refined version of Abstract class.It is a collection of only abstract methods. Multiple Implementation is possible through interface. Methods in interface are public and abstract by default.

Example :


interface A{
void meth();   //Abstract method by default
}

class B implements A{
void meth(){
System.out.println("B");
}

public static void main(String args[]){
A ref= new B();
ref();
}

INHERITANCE AND METHOD OVERRIDING

Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another.

TYPES OF INHERITANCE :

  1.  SINGLE INHERITANCE : When a class extends another one class only then we  call it a single inheritance.single
  2. MULTILEVEL INHERITANCE : Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a derived class.multilevel
  3. HEIRARCHICAL INHERITANCE  : In such kind of inheritance one class is inherited by many sub classes.hierarchical
  4. HYBRID INHERITANCE  : Hybrid inheritance is a combination of Single and Multiple inheritance.hybrid

METHOD OVERRIDING

If subclass  has the same method as declared in the parent class, it is known as method overriding in java. It is used for runtime polymorphism.

Example :


class A{
void run(){System.out.println("A");}
}

class B extends A{
void run(){System.out.println("B");}

public static void main(String args[]){
B obj = new B();
obj.run();
}

Output :


B

BLOCK , STATIC BLOCK , ACCESS MODIFIER

BLOCKS IN JAVA :

Java has a concept called block that is enclosed between the { and } characters, called curly braces. Blocks get executed before constructor.

Example:

class Blocks{
Blocks(){ System.out.println("Constructor\n");}

{System.out.println("Block 1\n");}

{System.out.println("Block 2\n");}

public static void main(String[] args){
Blocks ob=new Blocks();
}
}

Output:

Block 1
Block 2
Constructor

STATIC BLOCKS :

Static block is executed whenever class is created. Its executed before main() function.

Example:

class Blocks{
Blocks(){ System.out.println("Constructor\n");}

static { System.out.println("Static block\n");}

{System.out.println("Block 1\n");}

public static void main(String[] args){
System.out.println("Main\n");
Blocks ob=new Blocks();
}
}

Output:

Static block
Main
Block 1
Constructor

ACCESS MODIFIER :

It specifies accessibility of a data member, method, constructor or class.

  • Private : Accessible only within class.
  • Default : Accessible only within package.
  • Protected :  Accessible within package and outside the package but through inheritance only.
  • Public : Accessible everywhere.

OPERATORS IN JAVA

ARITHMETIC OPERATORS –  Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.

arithmetic

RELATIONAL OPERATORS – Reltional determine the relationship that one operand has to the other. 

relational

BITWISE OPERATORS –.Bitwise operator works on bits and performs bit-by-bit operation.bitwise.png

BOOLEAN OPERATORS – These are secondary versions of the Boolean AND and OR operators, and are commonly known as short-circuit logical operators.  boolean