Sunday, September 9, 2012

Streams in Java


Java Streams has following abstract classes:
InputStream , OutputStream , Reader and Writer

IO Streams: Designed for byte streams
Reader and Writer: Character Streams

Writing to File Using Java Programming Language


package com.io;

import java.io.*;
import java.util.Scanner;

public class FileWrite {

public static void main(String args[]){

try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter File name");

//Passing File name to File Class
String file=br.readLine();
File fname = new File(file);

boolean exist=fname.createNewFile();

                       //Verifying file exists or not ..
if(!exist){
System.out.println("File already exists");
System.exit(0);
}
else
{
FileWriter fwrite=new FileWriter(file);
BufferedWriter bwr=new BufferedWriter(fwrite);
bwr.write(br.readLine());
bwr.close();

System.out.println("Successfully created");
}

} catch (IOException e) {
e.printStackTrace();
}

}
}

Output:
========
Enter File name
Hello.txt
Hello first file
Successfully created

Reading File in Java Using Java Programming


package com.io;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class FileRead {

public static void main(String args[]){

try
{
String str;
FileInputStream in=new FileInputStream("C:\\Downloads\\FRead.txt.txt");
DataInputStream din=new DataInputStream(in);
BufferedReader br=new BufferedReader(new InputStreamReader(in));

while((str=br.readLine())!= null){
System.out.println(str);
}
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}

}
}

Output:
==========
Hi,
This is first file for reading
Thanks

Saturday, September 1, 2012

Polymorphism in Java Using Overloading and Overridden methods


Polymorphism
One form and many implementations.
It can be acheived by using inheritence,overloading and Overriding.
Compile time Polymorphism: Over loading
Runtitme Polymorphism: Over riding
Runtime Polymorphism /Dynamic method dispatch:
Its a process in which a call to an overridden methodis resolved at runtime rather than compile itme.
Dynamic Binding: Refers to linking of a procedure call to the code to be executed in response to the call
Also known as late binding :Code associated to procedure call is not known untile the time of the call at runtime.

Overloading.
Two or more methods with same name in the same class with different arguments.

  • Overloaded methods Must change the argument list
  • May change the return type
  • May change the access modifiers.
  • May change the checded exceptions.

Example:
package com.oops;

public class OverLoadingExample {

public int sum(int a,int b){
System.out.println("Int Int");
return a+b;
}

public double sum(double a,double b){
System.out.println("Double Double");
return a+b;
}

public int sum(int a,double b){
System.out.println("Int Double");
return (int) (a+b);
}
public static void main(String args[]){

OverLoadingExample oe=new OverLoadingExample();
System.out.println("Overloading method"+oe.sum(3, 7));
System.out.println("Overloading method"+oe.sum(2.5, 5.7));
System.out.println("Overloading method"+oe.sum(2, 5.5));
}
}

Output:
=======
Int Int
Overloading method10
Double Double
Overloading method8.2
Int Double
Overloading method7


Overriding:

Occurs in the subclass and declares method that has same type arguments as a method and declared by one of its super class.

  • It can be used for defining the behaviour of child class.
  • Argument list same as overriden method.
  • Constructors canot be overridden.
  • final methods canot be overridden.
  • Static method cannot be overridden but can be re-declared.
  • super() can be used for invoking parent class(Super class) methods.

Example
package com.oops;

class OverExample{

public void fun1(){
System.out.println("Super Function1");
}

public void fun2(){
System.out.println("Super Using super() Function2");
}

}
public class OverRiddingExample extends OverExample{

public void fun1(){
System.out.println("Subclass Function1");
}


public void fun2(){
super.fun2();
System.out.println("Subclass Function2");
}

public static void main(String[] args) {
OverExample or=new OverRiddingExample();
OverExample oe=new OverExample();
or.fun1();
oe.fun1();
or.fun2();
}

}

Output:
========

Subclass Function1
Super Function1
Super Using super() Function2
Subclass Function2


Inheritance in Object Orient Programming and Java


Inheritance
Its a process where one object acquire properites another.
Inheritence reduces the code re-usablity.

Inheritence can be achieved by using extends or implemnts keyword

Single Inheritance:
Class A extends B{
statements
}

Example:
=============
Pulsar is subclass of Bike
TVS is subclass of Bike.

package com.oops;

class TwoWheeler{

int count=1;

public void setProp(){
System.out.println("Color: Red & Brand:Own");
}

}
public class SingleInheritence extends TwoWheeler {

public static void main(String args[]){
TwoWheeler two=new TwoWheeler();
SingleInheritence si=new SingleInheritence();

System.out.println(si instanceof TwoWheeler);
System.out.println("Calling method in SuperClass");
si.setProp();
}
}

Output
=======
true
Calling method in SuperClass
Color: Red & Brand:Own

Multiple Inheritance can be acheived by using interface. 

Interface in Java Language (Click on link to know about interfaces)

Below example contains Single Inheritance and Multiple Inheritance Using Interfaces.

package com.oops;

class TwoWheeler{

int count=1;

public void setProp(){
System.out.println("Color: Red & Brand:Own");
}

}

interface Car
{
   public void setBrandname(String name);
}

interface HeaveyVechile{

public void setProperites(String prop);
}

public class Wheeler extends TwoWheeler implements Car, HeaveyVechile{


public static void main(String args[]){

TwoWheeler two=new TwoWheeler();
Wheeler si=new Wheeler();

System.out.println(si instanceof TwoWheeler);
System.out.println("Calling method in SuperClass");
si.setProp();
si.setBrandname("First");
si.setProperites("HeavyLoadVechile");
}

@Override
public void setBrandname(String name) {
System.out.println("Brand name is"+name);

}

@Override
public void setProperites(String prop) {
System.out.println("Heavy Vechile with 4 or 8 Wheels "+prop);


}

}

Output
=========
true
Calling method in SuperClass
Color: Red & Brand:Own
Brand name isFirst
Heavy Vechile with 4 or 8 Wheels HeavyLoadVechile

interfaces in Object Oriented Programming Language


interface
==========
Descriptive set of methods. Implements class needs to be implemented methods in interface.

Properties of interface:
=========================
Canot mark interface as final
Cannot instiate interface.
Default: Methods in interface are abstract
fields in interface are static and final.
interface can implement class.
interface can extend multiple interfaces.

Class Implementing Interface
============================
package com.oops;

interface Bike{

//final static fields as default
int Capacity=150;

//abstract  methods as default
public void speed();
public void price();
}
public class InterfaceExample implements Bike {

@Override
public void speed() {
System.out.println("Speed of Bike is 100 KMPH");

}

@Override
public void price() {
System.out.println("Price of Bike is 75K");

}

public static void main(String args[]){

InterfaceExample it=new InterfaceExample();
it.speed();
it.price();
}

}

Interface extends Multiple Interfaces

public interface Computer
{
   public void setBrandname(String name);
}

public interface Desktop extends Computer
{
   public void setProperty(String prop);
   public void viewProperty(String id);
}

public interface Laptop extends Computer
{
   public void setProcess(double process);
   public void setScreen(int size);
}

public interface Laptop extends Computer,Device{

statements
}

Encapsulation in Java Programming


Encapsulation: is like information Hiding.
Hiding the properites and behaviors of object and allowing outside access via public methods.

Example for Encapsulation:
============================

EmpDetails.java:
package com.oops;

public class EmpDetails {

private int empid;
private String empname;

public void setEmpid(int id){
empid=id;
}

public int getEmpid(){
return empid;
}

public void setEmpName(String name){
empname=name;
}

public String getEmpName(){
return empname;
}
}

EncapsulationExample.java

package com.oops;

public class EncapsulationExample {

/**
* @param args
*/
public static void main(String[] args) {

EmpDetails emp1=new EmpDetails();
emp1.setEmpid(1);
emp1.setEmpName("First");

System.out.println("Employee details id: "+emp1.getEmpid()+" and name:"+emp1.getEmpName());

}

}

Output
==========
Employee details id: 1 and name:First

Abstraction and Abstract Class in java


Abstraction: Abstraction is act of representing data without including background details.

In java it can be achieved by using abstract classes/interfaces.
Hiding information can be achieved by modifiers.

Example for Abstract method:
  abstract  void function();

Example of abstract class:
 abstract class TestAbstract{

   abstract void fun1();
   public void fun2(){
    statements
   }

abstract classes contain abstract methods and normal methods.

Abstract Class Example:
package com.oops;

abstract class Area{
int side;

Area(int a){
side=a;
}
abstract int area();
public void nonAbstractMethod(){
System.out.println("Non abstract Method");
}
}

class Square extends Area{

Square(int a) {
super(a);
}

@Override
int area() {

System.out.println("Square Area");
return side*side;
}

}

class Rect extends Area{

public Rect(int a) {
super(a);
// TODO Auto-generated constructor stub
}

@Override
int area() {
// TODO Auto-generated method stub
System.out.println("Area of Triangle");
return side*side;
}

}

public class AbstractClassExample {

public static void main(String args[]){

Square sq=new Square(3);
Rect rt=new Rect(5);

Area ar;

ar=sq;
System.out.println("Square Area"+ar.area());

ar=rt;
System.out.println("Rectangle area"+ar.area());
}
}

Output:
============
Square Area
Square Area9
Area of Triangle
Rectangle area25