Вы находитесь на странице: 1из 46

Reading Command Line Arguments

(i) Common way


class ReadCmdLineArgs {
public static void main(String[] args) {
System.out.println("Command Line Args:");
System.out.println("------------------");
if (args.length != 0) {
for (int i = 0; i < args.length; i++) {
System.out.println((i + 1) + ". " + args[i]);
}
} else {
System.out.println("No command line args. specified");
}
}
}

(ii) Another for loop syntax


class ReadCmdLineArgs {
public static void main(String[] args) {
System.out.println("Command Line Args:");
System.out.println("------------------");
if (args.length != 0) {
int i = 1;
for (String arg : args) {
System.out.println((i++) + ". " + arg);
}
} else {
System.out.println("No command line args. specified");
}
}
}

------------------------------------------------------------------------------
Object Instantiation

class ObjInstantiation {
public static void main(String[] args) {

new Greet().showGreeting();//Nameless object

Greet g = new Greet();


g = new Greet();//implicit deref.
g.showGreeting();
g = null;//explicit deref.
g.showGreeting();// NullPointerException
}
}

class Greet {

Page | 1
dhanoopbhaskar@gmail.com
void showGreeting() {
System.out.println("Hello World!");
}
}

Note: Greet g; - loads Greet.class to the memory.


creates a reference variable (g) for class
Greet.
g = new Greet() - creates a new object of class Greet.
assigns the object’s address to the reference
variable g.
--------------------------------------------------------------------------------
Variable length argument
class VarArgs {
public static void main(String[] args) {
SomeClass sc = new SomeClass();

System.out.println("Sum: " +
sc.sum(10, 20, 30, 40));
System.out.println("Sum: " +
sc.sum(10, 20));
}
}

class SomeClass {
int sum(int... values) {
int result = 0;
/*common method using for loop type 1*/
for (int i = 0; i < values.length; i++) {
result += values[i];
}

/* using for loop type 2


for (int value : values) {
result += value;
}*/

return result;
}
}

Note: Variable length arguments are internally treated as arrays.

---------------------------------------------------------------------------------
Class-level variables are implicitly initialized with default value.

Data Type Default Value (for fields)


byte 0
short 0
int 0

Page | 2
dhanoopbhaskar@gmail.com
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false

Local variables should be initialized before accessing as they are not implicitly
assigned with default value.

---------------------------------------------------------------------------------
Access Modifiers

---------------------------------------------------------------------------------
Reference
|
x-- Direct – reference of fields (class-level variables) inside the class
|
x-- Qualified
|
x-- Instance ref/Non-static ref – using instance variable of the
class.
|
x-- Static ref – using class-name itself.

Note: Direct non-static reference should not be made from a static context.

class StaticInstanceVars {
String msg = "Hello World!";//class-level var.
public static void main(String[] args) {
String msg = "Hello World!";//local var.

Page | 3
dhanoopbhaskar@gmail.com
System.out.println(msg);

//qualified static/class ref.


System.out.println(Rectangle.company);

//non-static qualified instance ref.


StaticInstanceVars siv = new StaticInstanceVars();
System.out.println(siv.msg);

}
}

class Rectangle {
public static String company = "Think Force";
private int length = 0;
private int breadth = 0;
}

---------------------------------------------------------------------------------
Variable Declaration
|
x---------------------------- x------------------------------ x
| | |
Local Class-level Super class-level
| | |

local to a function instance variables instance variables


static variables static variables
private variables

Private variables
|
x-- direct reference

Instance variables
|
x-- direct reference
|
x-- instance reference

Static variables
|
x-- direct reference
|
x-- instance reference (conventionally discouraged)
|
x-- static reference

Note: Static variable declaration in the main() causes compilation error :


illegal start of expression.

Page | 4
dhanoopbhaskar@gmail.com
* Local variable should not be static

* The keywords that can come with an Outer class – abstract


final
public
* The keywords that can come with a Nested class - static
private
protected
public

* The only modifier that can come with a local variable is final.

* Non-static nested class = Inner class

class VarDeclaration {
public static void main(String[] args) {
static int i=0;
OtherClass oc = new OtherClass();
oc.showX();
}
}

class SomeClass {
int x = 10;//super class-level
}

class OtherClass extends SomeClass {


int x = 20;//class-level
void showX() {
int x = 30;//local
System.out.println("local x: " + x);
System.out.println("class-level x: " +
this.x);
System.out.println("super class-level x: " +
super.x);
}
}
* Predefined reference variable refines the scope of the variables with same name
declared in different levels.
* Predefined reference should not be done in static context.

---------------------------------------------------------------------------------
Constructors

class Constructors {
public static void main(String[] args) {
Greet g = null;//local variable should be initialized before use
if (args.length != 0) {
g = new Greet(args[0]);
} else {/*provided to avoid NullPointerException when no command line

Page | 5
dhanoopbhaskar@gmail.com
argument is given*/
g = new Greet();
}
g.showGreeting();

}
}

class Greet {
private String name = "Anonymous";

Greet() {//provided to ensure the success of g = new Greet();


}/*if not given:
cannot find symbol
symbol : constructor Greet()*/

Greet(String name) {
/*refining the scope of instance variable name using the predefined reference
variable this since, its direct usage refers only to the local variable name*/
this.name = name;
}

void showGreeting() {
System.out.println("Hi " + name + "!!!");
}
}

Case Study:
java Constructors
Hi Anonymous!!!

java Constructors uce


Hi uce!!!

Note: Default constructor is provided by the JVM only when a class does not have
one of its own.

---------------------------------------------------------------------------------
Counting the instance of a class
Class TestInstanceCounter

class TestInstanceCounter {
public static void main(String[] args) {
SomeClass sc1 = new SomeClass();
SomeClass sc2 = new SomeClass();

System.out.println("You have created "


+ SomeClass.countInstances()
+ " instances of "
+ "the class called \"SomeClass\"");

Page | 6
dhanoopbhaskar@gmail.com
System.out.println("---------------------------------------------");

SomeClass sc3 = new SomeClass();


SomeClass sc4 = new SomeClass();
SomeClass sc5 = new SomeClass();

System.out.println("You have created "


+ SomeClass.countInstances()
+ " instances of the class called \"SomeClass\"");

System.out.println("---------------------------------------------");
}
}

Class SomeClass

class SomeClass {
/*initialized when class is loaded and all the instances of the class share the
same static variable*/
private static int instanceCtr = 0;
SomeClass() {
instanceCtr++;
}
public static int countInstances() {
return instanceCtr;
}
}

---------------------------------------------------------------------------------

Inheritance
Class Rectangle

public class Rectangle {


private int length = 0;
private int breadth = 0;
public Rectangle() {
}
public Rectangle(int value) {
length = value;
breadth = value;
}
public Rectangle(int length, int breadth) {
this.length = length;
this.breadth = breadth;
}
public int getLength() {
return length;

Page | 7
dhanoopbhaskar@gmail.com
}
public int getBreadth() {
return breadth;
}
public void setLength(int length) {
this.length = length;
}
public void setBreadth(int breadth) {
this.breadth = breadth;
}
public int calcArea() {
return length * breadth;
}
}

Class TestRectangle

class TestRectangle {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
System.out.println("r1 Length: " + r1.getLength()); // 0
System.out.println("r1 Breadth: " + r1.getBreadth()); // 0
System.out.println("r1 Area: " + r1.calcArea()); // 0
System.out.println("-----------------------------------------");

Rectangle r2 = new Rectangle(10);


System.out.println("r2 Length: " + r2.getLength()); // 10
System.out.println("r2 Breadth: " + r2.getBreadth()); // 10
System.out.println("r2 Area: " + r2.calcArea()); // 100
System.out.println("-----------------------------------------");

Rectangle r3 = new Rectangle(10, 20);


System.out.println("r3 Length: " + r3.getLength()); // 10
System.out.println("r3 Breadth: " + r3.getBreadth()); // 20
System.out.println("r3 Area: " + r3.calcArea()); // 200
System.out.println("-----------------------------------------");

r1.setLength(100);
r1.setBreadth(200);
System.out.println("r1 Length: " + r1.getLength()); // 100
System.out.println("r1 Breadth: " + r1.getBreadth()); // 200
System.out.println("r1 Area: " + r1.calcArea()); // 20000
}
}

Class Container

public class Container extends Rectangle {


private int height = 0;

Page | 8
dhanoopbhaskar@gmail.com
public Container() {
super(0);
}
public Container(int value) {
super(value);
height = value;
}
public Container(int length, int breadth, int height) {
super(length, breadth);
this.height = height;
}
public void setHeight(int height) {
this.height = height;
}
public int getHeight() {
return height;
}
public int calcVolume() {
return calcArea() * height;
}
}

Class TestContainer

class TestContainer {
public static void main(String[] args) {
Container c1 = new Container();
System.out.println("c1.getLength(): " + c1.getLength()); //0
System.out.println("c1.getBreadth(): " + c1.getBreadth()); //0
System.out.println("c1.getHeight(): " + c1.getHeight()); //0
System.out.println("c1.calcArea(): " + c1.calcArea()); //0
System.out.println("c1.calcVolume(): " + c1.calcVolume()); //0
System.out.println("----------------------------------------");

Container c2 = new Container(10);


System.out.println("c2.getLength(): " + c2.getLength()); //10
System.out.println("c2.getBreadth(): " + c2.getBreadth()); //10
System.out.println("c2.getHeight(): " + c2.getHeight()); //10
System.out.println("c2.calcArea(): " + c2.calcArea()); //100
System.out.println("c2.calcVolume(): " + c2.calcVolume()); //1000
System.out.println("----------------------------------------");

Container c3 = new Container(10, 20, 30);


System.out.println("c3.getLength(): " + c3.getLength()); //10
System.out.println("c3.getBreadth(): " + c3.getBreadth()); //20
System.out.println("c3.getHeight(): " + c3.getHeight()); //30
System.out.println("c3.calcArea(): " + c3.calcArea()); //200

Page | 9
dhanoopbhaskar@gmail.com
System.out.println("c3.calcVolume(): " + c3.calcVolume()); //6000
}
}

---------------------------------------------------------------------------------
Rectangle r = new Container(10, 20, 30); /*valid
because where ever a class (instance) is expected, we can pass its instance or
the instance of its direct or indirect subclass*/
Container c = new Rectangle(10, 20); /*invalid
because of the reason above; Here class Rectangle is the super class of class
Container*/
---------------------------------------------------------------------------------

Page | 10
dhanoopbhaskar@gmail.com
Testing Inheritance

class TestInheritance {
public static void main(String[] args) {
SomeClass sc = new SomeClass();
Shape s = sc.getShape(Integer.parseInt(args[0]));
s.draw();
if (s instanceof Square) {
Square sq = (Square) s;
System.out.println("It's an instance of Square.");
sq.someFunction();
} else if (s instanceof Circle) {
System.out.println("It's an instance of Circle.");
} else if (s instanceof Triangle) {
System.out.println("It's an instance of Triangle.");
}
}
}

class SomeClass {
Shape getShape(int option) {
Shape s = null;
Page | 11
dhanoopbhaskar@gmail.com
switch (option) {
case 1:
s = new Square();
break;
case 2:
s = new Circle();
break;
case 3:
s = new Triangle();
}
return s;
}
}

class Shape {
void draw() {
System.out.println("This is an unknown shape.");
}
}
class Square extends Shape {
void draw() {
System.out.println("This is a square.");
}
void someFunction() {
super.draw();
}
}
class Circle extends Shape {
void draw() {
System.out.println("This is a circle.");
}
}
class Triangle extends Shape {
void draw() {
System.out.println("This is a triangle.");
}
}

Case Study
java TestInheritance
ArrayIndexOutOfBoundException
 args[0] is not initialized but is referred

java TestInheritance 0
NullPointerException
 Shape s = null; -initially
No case in the switch is matched and hence null is returned.
s.draw() {<null>.draw()} causes the NullPointerException

java TestInheritance 1

Page | 12
dhanoopbhaskar@gmail.com
This is a square.
It’s an instance of Square.
This is an unknown shape.
 case 1 in the switch is matched and an object of Square is returned from
getShape(). It is assigned to s [up-casting: super-class object = sub-class
object. sub-class object is wrapped inside a super-class object]. It is down-
casted [unwrapped it from the cover of super-class that hinders the visibility of
sub-class specific fields and methods] to type Square after proper checking using
instanceof before actually using it.

java TestInheritance 2
This is a circle.
It’s an instance of Circle.
 case 2 in the switch is matched and an object of Circle is returned from
getShape(). It is assigned to s [up-casting: super-class object = sub-class
object. sub-class object is wrapped inside a super-class object]. It should be
down-casted [unwrapped it from the cover of super-class that hinders the
visibility of sub-class specific fields and methods] to type Circle after proper
checking using instanceof before actually using it.

java TestInheritance 3
This is a triangle.
It’s an instance of Triangle.
 case 3 in the switch is matched and an object of Triangle is returned from
getShape(). It is assigned to s [up-casting: super-class object = sub-class
object. sub-class object is wrapped inside a super-class object]. It should be
down-casted [unwrapped it from the cover of super-class that hinders the
visibility of sub-class specific fields and methods] to type Triangle after
proper checking using instanceof before actually using it.

java TestInheritance square


NumberFormatException
 “square” [String type] cannot be parsed into int using
Integer.parseInt(String);

---------------------------------------------------------------------------------
Reference variable: this
class TestThisFunc {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
class SomeClass {
private int x = 0;
private int y = 0;
private int z = 0;

SomeClass(int x) {
this(x, 0, 0);

Page | 13
dhanoopbhaskar@gmail.com
}
SomeClass(int x, int y) {
this(x, y, 0);
}
SomeClass(int x, int y, int z) {
if (x != 0) {
}
if (y != 0) {
}
if (z != 0) {
}
}
}
---------------------------------------------------------------------------------
Reference variable: super
class TestSuperFunc {
public static void main(String[] args) {
SubClass sub = new SubClass(10, 20, 30);
}
}

class SuperClass {
private int x = 0;
private int y = 0;

SuperClass() {
}
SuperClass(int value) {
x = value;
y = value;
}
SuperClass(int x, int y) {
this.x = x;
this.y = y;
}
}
class SubClass extends SuperClass {
private int z = 0;

SubClass() {
}
SubClass(int value) {
super(value);
z = value;
}
SubClass(int x, int y, int z) {
super(x, y);
this.z = z;
}
}

Page | 14
dhanoopbhaskar@gmail.com
---------------------------------------------------------------------------------
Printing the Object
class PrintObject {
public static void main(String[] args) {
Rectangle r = new Rectangle(10, 20);
Container c = new Container(100, 200, 300);
System.out.println(r);/*Classname@hashCode*/
System.out.println(r.toString());/*Classname@hashCode*/

System.out.println(r.hashCode());/*hash code in integer form*/


System.out.println(Integer.toHexString(
r.hashCode()));/*hash code in hexadecimal form*/
System.out.println(r.getClass().getName());/*returns classname*/

System.out.println(r);
System.out.println(r.getClass().getName() +
"@" +
Integer.toHexString(r.hashCode()));/*mimicking the operation done
while an object is printed*/

System.out.println(r);
System.out.println(c);

}
}
---------------------------------------------------------------------------------
java.lang.Object.toString(); //programmer need to override it to personalize it
java.lang.Object.hashCode();//programmer need to override it to personalize it
java.lang.Object.getClass();//no overriding
java.lang.Object.equals();//programmer need to override it to personalize it
---------------------------------------------------------------------------------
Overriding toString() in class Rectangle
public String toString() {
return "Rectangle[length=" + length +
", breadth=" + breadth + "]";
}

Overriding toString() in class Container


public String toString() {
return "Container[length=" + getLength() +
", breadth=" + getBreadth() +
", height=" + height + "]";
}
/*length and breadth are private in Rectangle and are not inherited to Container.
So getLength() and getBreadth() are used in Container*/

---------------------------------------------------------------------------------
Object Comparison
class ObjectComparison {
public static void main(String[] args) {

Page | 15
dhanoopbhaskar@gmail.com
String s1 = new String("Hello");
String s2 = new String("Hello");

System.out.println("[Ref. Comparison]s1" +
((s1 == s2) ? " is " : " is not " ) +
"equal to s2.");/*(s1==s2) always return false since the
references are compared here*/

System.out.println("[Value Comparison]s1" +
((s1.equals(s2)) ? " is " : " is not " ) +
"equal to s2.");/*(s1.equals(s2)) always return true since the
values are compared here*/
}
}
---------------------------------------------------------------------------------
Overriding hashCode() in Rectangle
public int hashCode() {
String hashStr = "L" + length + "B" + breadth;
return hashStr.hashCode();
}
 class String has overridden the hashCode() in Object.
Implicitly created String object [String str = “hello”;] are stored in the
string constant pool. Hence same valued String objects created implicitly have
the same reference (and hence same hash code)- to impart optimization.
 Implicit creation of object: String str = “hello”;
 Explicit creation of object: String str = new String(“hello”);
 class Rectangle makes use of hashCode() in the class String to mimic this
behavior.
 L and B are used as delimiters since Rectangle (11, 20) and Rectangle (1, 120)
may have same hash code otherwise.
---------------------------------------------------------------------------------
Overriding hashCode() in Container
public int hashCode() {
String hashStr = "L" + getLength() + "B" + getBreadth() + “H” +
height;
return hashStr.hashCode();
}
---------------------------------------------------------------------------------
Overriding equals() in Rectangle
public boolean equals(Object object) {
boolean equals = false;

if (object instanceof Rectangle &&


((Rectangle) object).getLength() == length &&
((Rectangle) object).getBreadth() == breadth) {
equals = true;
}

return equals;
}
Page | 16
dhanoopbhaskar@gmail.com
---------------------------------------------------------------------------------
Overriding equals() in Container
public boolean equals (Object object) {
boolean equals = false;

if (object instanceof Container &&


((Container) object).getLength() == getLength() &&
((Container) object).getBreadth() == getBreadth()&&
((Container) object).getHeight() == height) {
equals = true;
}

return equals;
}
---------------------------------------------------------------------------------
Boxing and un-boxing
class Boxing {
public static void main (String[] args) {
Integer integer = 10; /*boxing of primitive type 10 [int] into class
type integer [class Integer]. From jdk 1.5 onwards. Assigning an int to Integer
was not possible in earlier version of jdk.*/
int j = integer + 10; /*un-boxing*/
System.out.println (integer);
System.out.println (j);
}
}
---------------------------------------------------------------------------------
Abstraction

/** Abstraction refers to vague definition or not very definitive nature of a


class or a method.
* An abstract function should not have a body.
* If a class contains abstraction explicitly coded or inherited then the class
must be stated as an abstract class using abstract keyword.
* A class with at least one abstract method should be declared abstract.
* We cannot create objects of an abstract class.
* Abstraction is used to enforce specifications and to hide complexity.
* A class inheriting an abstract class should define (should give body by
overriding them) all the abstract functions in it or should be explicitly
declared abstract.
**/

Abstract Class Abstract Function

Cannot create object. No body.

Can contain 0 or more abstract Overridden in direct or indirect


function. sub-class.

Page | 17
dhanoopbhaskar@gmail.com
Keyword abstract can also be used
just to prevent the object
creation rather than to explicitly
specify the abstraction. When the
class contains only static
functions, we may prevent it from
accessing through instance.

If a class contains abstraction


explicitly coded or inherited then
the class must be stated as an
abstract class using abstract
keyword.

abstract class Vehicle {


public abstract int numOfWheels();
public abstract String steeringType();
public abstract boolean hasGears();
public abstract String fuelType();
public abstract String getModel();
}

abstract class TwoWheelers extends Vehicle {


public int numOfWheels() {
return 2;
}
public String steeringType() {
return "Handle Bar";
}
}

abstract class FourWheelers extends Vehicle {


public int numOfWheels() {
return 4;
}
public String steeringType() {
return "Steering Wheel";
}
}

class Stallion extends TwoWheelers {


public boolean hasGears() {
return true;
}
public String fuelType() {
return "Aviation Fuel";
}

Page | 18
dhanoopbhaskar@gmail.com
public String getModel() {
return "AK Automobiles - Stallion[NxtGen]";
}
}

class Turtle extends TwoWheelers {


public boolean hasGears() {
return false;
}
public String fuelType() {
return "Diesel";
}
public String getModel() {
return "AK Automobiles - Turtle[No Worries]";
}
}

class LoneRider extends FourWheelers {


public boolean hasGears() {
return true;
}
public String fuelType() {
return "Petrol";
}
public String getModel() {
return "AK Automobiles - LoneRider[Care For No One]";
}
}

abstract class RentAVehicle {


public static Vehicle getVehicle(String model) {
Vehicle vehicle = null;

if (model.equalsIgnoreCase("Stallion")) {
vehicle = new Stallion();
} else if(model.equalsIgnoreCase("Turtle")) {
vehicle = new Turtle();
} else if(model.equalsIgnoreCase("LoneRider")) {
vehicle = new LoneRider();
}

return vehicle;
}
}

class TestAbstraction {
public static void main(String[] args) {
try {
Vehicle vehicle = RentAVehicle.getVehicle(
args[0]);

Page | 19
dhanoopbhaskar@gmail.com
System.out.println(" Type: " +
vehicle.numOfWheels() + " Wheeler");
System.out.println("Steering Type: " +
vehicle.steeringType());
System.out.println(" Gear: " +
(vehicle.hasGears() ? "Geared" : "Gearless"));
System.out.println(" Fuel Type: " +
vehicle.fuelType());
System.out.println(" Model: " +
vehicle.getModel());
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.println("Error in usage !!!");
System.out.println(getUsage());
} catch (NullPointerException ex) {
System.out.println("Sorry we do not have the specified model: " +
args[0]);
}
}

private static String getUsage() {


return "Usage: java TestAbstraction <\"vehicle name\">";
}
}
---------------------------------------------------------------------------------
Interface

 100% abstract data structure.


 It can contain only constant variables, abstract methods, classes and other
interfaces.
 An interface cannot contain non-abstract functions and variables.
 We cannot create objects of an interface.
 On compilation, an interface generates a .class extension file.

---------------------------------------------------------------------------------
TestInterface1.java

interface Shapes {
int i = 10;// implicit conversion to public static final int i = 10;
void drawCircle();// public abstract void drawCircle();
}

class DrawShape1 implements Shapes { //directly implementing Shapes


public void drawCircle() {//Interface methods are implicitly public abstract
System.out.println(
"drawCircle() - implemented in DrawShape1.");
}
public void function1() {
System.out.println(
"function1()- implemented in DrawShape1.");
}
Page | 20
dhanoopbhaskar@gmail.com
}

class SomeClass extends DrawShape1 {


//indirectly implementing Shapes via DrawShape1
}

class DrawShape2 implements Shapes { //directly implementing Shapes


public void drawCircle() {
System.out.println(
"drawCircle() - implemented in DrawShape2.");
}
public void function1() {
System.out.println(
"function1()- implemented in DrawShape2.");
}
}

class TestInterface1 {
public static void main(String args[]) {
/*DrawShape1 ds1 = new DrawShape1();
ds1.drawCircle();
ds1.function1();

DrawShape2 ds2 = new DrawShape2();


ds2.drawCircle();
ds2.function1(); */

Shapes s = new Shapes(); /*Shapes is abstract and cannot be


instantiated*/

Shapes s = new DrawShape2();


s.drawCircle();
s.function1(); /*cannot find symbol function1() in interface Shapes since
function1() is invisible to Shape (reference variable s)*/
}
}

---------------------------------------------------------------------------------
TestInterface3.java
interface Circle {
void drawCircle();
}

interface Square {
void drawCircle(int radius);
void drawSquare();
}

class DrawShape implements Circle, Square {


public void drawCircle(int r) {

Page | 21
dhanoopbhaskar@gmail.com
System.out.println("This is a circle with a radius of " + r);
}
public void drawCircle() {
System.out.println("This is a circle.");
}
public void drawSquare() {
System.out.println("This is a square.");
}
}

class TestInterface3 {
public static void main(String args[]) {
DrawShape ds1 = new DrawShape();
ds1.drawCircle();
ds1.drawCircle(10);
ds1.drawSquare();
}
}

---------------------------------------------------------------------------------
TestInterface4.java
interface Circle {
void drawCircle();
}
interface Square {
void drawSquare();
}
class Triangle {
public void drawCircle() {
System.out.println(
"This is a circle - in Triangle.");
}
public void drawTriangle() {
System.out.println(
"This is a triangle - in Triangle.");
}
}

class DrawShape extends Triangle implements Circle, Square {


public void drawCircle() {
System.out.println(
"This is a circle - in DrawShape.");
}
public void drawSquare() {
System.out.println(
"This is a square - in DrawShape.");
}
}

class TestInterface4 {

Page | 22
dhanoopbhaskar@gmail.com
public static void main(String args[]) {
DrawShape ds = new DrawShape();
ds.drawCircle();
ds.drawSquare();
ds.drawTriangle();
}
}

---------------------------------------------------------------------------------
TestInterface5.java
interface Circle {
void drawCircle();
}

interface Square extends Circle {


void drawSquare();
}

interface CircleSquareTriangle extends


Circle, Square {
void drawTriangle();
}

class DrawShape implements CircleSquareTriangle {


public void drawCircle() {
System.out.println("This is a circle.");
}
public void drawSquare() {
System.out.println("This is a square.");
}
public void drawTriangle() {
System.out.println("This is a triangle.");
}
}

class TestInterface5 {
public static void main(String args[]) {
DrawShape ds1 = new DrawShape();
ds1.drawCircle();
ds1.drawTriangle();
ds1.drawSquare();
}
}

---------------------------------------------------------------------------------
TestInterface6.java
interface Circle {
void drawCircle();

Page | 23
dhanoopbhaskar@gmail.com
}
interface Square {
void drawSquare();
}
interface Triangle {
void drawTriangle();
}

interface CircleSquareTriangle extends Circle,Square,Triangle{ // Extending


multiple interfaces
}

class DrawShape implements CircleSquareTriangle {


public void drawCircle() {
System.out.println("This is a circle.");
}
public void drawSquare() {
System.out.println("This is a square.");
}
public void drawTriangle() {
System.out.println("This is a triangle.");
}
}

class TestInterface6 {
public static void main(String args[]) {
DrawShape ds1=new DrawShape();
ds1.drawCircle();
ds1.drawTriangle();
ds1.drawSquare();
}
}

---------------------------------------------------------------------------------
 The modifier final with a method prevents it from being overridden.
A final method cannot be overridden.
 The modifier final with a class prevents it from being inherited.
A final class cannot be inherited.
 Return type of functions is not considered in overloading.
 If the return type is non-primitive then we can use sub-type while
overloading the method.
public Rectangle doSomething() {
}

public Container doSomething() { //overriding


}

 While overriding a function the access modifier can only be broadened,


widened, or strengthened.

Page | 24
dhanoopbhaskar@gmail.com
 While overriding a function if the data type of an identifier is changed in
the overridden function, it becomes overloading.
 Modifier abstract cannot be used in combination with final, private or
static.
abstract + final  abstraction is resolved by overriding the functions,
but final prevents the function from being overridden.
abstract + private  abstraction is resolved by overriding the functions in
the sub-class, but private members are not inherited.
abstract + static  static methods can be referred to by qualifying using
class-name. Abstract methods are not definitive and hence make no sense.

---------------------------------------------------------------------------------
 implements - has a relationship.
 extends - is a relationship.
 An interface can extend one or more interfaces.
 A class can extend only one class.
 A class can implement one or more interfaces.
 An interface cannot extend a class, since nothing can be non-abstract in an
interface.
 In Java, multiple inheritance can be attained only with the involvement of
interface(s).
 Where ever an interface is expected, we can pass the instance of a class
that directly or indirectly implements the interface.

---------------------------------------------------------------------------------
Packages
In java, packages are used to organize files, physically. It has no significance
as far as source files are concerned. The real use comes when dealt with class
files- they should be in the package hierarchy as defined by the package
statement which comes as the first statement of the source code. Source files
need not be in the package defined.
eg:
---MainFrame.java---
package src.ui;

MainFrame.java need not be in path current-directory\src\ui\ when it is compiled.


But MainFrame.class should be in the path current-directory\src\ui when it is
executed.

Compiling...
source-directory-path\src>javac -d ..\build com\dh\lang\*.java com\dh\math\*.java
: The option “-d” is used to create the class files in some defined
directory. Here the produced class files will be in the path
source-directory-path\build\com\dh\lang\ & source-directory-
path\build\com\dh\math\
[follows that the source files are in source-directory-path\src\com\dh\lang\ and
in source-directory-path\src\com\dh\math\]

Building...
source-directory-path\build>jar -cf ..\dist\MyAPI.jar com
Page | 25
dhanoopbhaskar@gmail.com
: Here the jar file MyAPI.jar is created in source-directory-path\dist\
using the class files in package com. (cf = create file)

source-directory-path\build>jar -cvf ..\dist\MyAPI.jar com


: Here the progress of jar file creation will be displayed.(option v)

Using API...
source-directory-path\src>javac -cp ..\lib\MyAPI.jar;..\lib\YourAPI.jar -d
..\build com\dh\appl\*.java
: Here we create an application using the API collection in MyAPI.jar,
which reside in source-directory-path\lib (option -cp is used). If there is more
than one jar file, each is separated by a semi-colon in Windows and colon in
Linux.

Making application executable on double click...


- While creating a jar file META-INF\MANIFEST.MF is automatically created with
some default attributes.
Manifest-Version: 1.0
Created-By: 1.6.0_17 (Sun Microsystems Inc.)

- for jar file to be executable we must include some more attributes using a text
file manifest.txt--
Main-Class: com.dh.appl.MainFrame
Class-Path: ..\lib\MyAPI.jar ..\lib\YourAPI.jar

source-directory-path\build>jar -cvmf manifest.txt ..\dist\MyAppl.jar com


: The appends the attributes defined in manifest.txt(option m) to META-
INF\MANIFEST.MF
and create a jar file MyAppl.jar which will be executable.

--------------------------------------------------------------------------------
Exception Handling
Exceptions are runtime anomalies that may result in the abnormal termination of
the program.
Exceptions are mainly thrown by system or by a function
Thrown by system
ArrayIndexOutOfBoundsException
ClassCastException
NullPointerException
Thrown by function
NumberFormatException
In java all exceptions are classes. Mainly there are two types of exceptions.
They are:
Exceptions
|
x-- Checked Exceptions: that are trapped by the compiler
|
x-- Unchecked Exceptions: that are not trapped by the compiler

Page | 26
dhanoopbhaskar@gmail.com
A checked exception must be either reported or caught (handled). Otherwise the
compiler may fail to compile the program. An unchecked exception may be excepted
from handling- it causes failure at runtime only.

Checked Exceptions
IOException
SQLException
InterruptedException
SocketException

Unchecked Exceptions
ArrayIndexOutOfBoundsException
ClassCastException
NullPointerException

Hierarchy of Exception classes


java.lang.Object
|
+-- java.lang.Throwable
|
+-- java.lang.Exception
|
+-- java.lang.RuntimeException

 Direct or indirect subclasses of class Exception are checked exceptions with


an exception of class RuntimeException.
 Direct or indirect subclasses of class RuntimeException are unchecked
exceptions.

UncaughtException.java
class UncaughtException {
public static void main(String[] args) {
function1(args.length);
System.out.println(
"Program completed normally.");
}
public static void function1(int length) {
int i = 10 / length;
}
}

CatchingSingleException.java
class CatchingSingleException {
public static void main(String args[]) {
try {
int i = 10 / args.length;
System.out.println("Still inside the try block.");
} catch(ArithmeticException e) {
System.out.println(
"Arithmetic Exception Handled Successfully.");

Page | 27
dhanoopbhaskar@gmail.com
System.out.println(e);
System.out.println(e.getMessage());
//e.printStackTrace();
} finally {//optional block
//write statements for releasing all your resources here.
System.out.println("Inside the finally block.");
}

System.out.println("Program terminated normally.");


}
}

CatchingMultipleExceptions.java
class CatchingMultipleExceptions {
public static void main(String args[]) {
try {
int i = 10 / args.length;
//assume this to be an unforseen exception
new java.io.FileInputStream("abc.txt");

int[] ar = {10, 20, 30};


ar[50] = 25;
System.out.println("I am still inside the try block.");
} catch(ArithmeticException e) {
System.out.println(e.getMessage());
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array element does not exist.");
} catch(Exception e) {//generic exception handling
try {
e.printStackTrace(new java.io.PrintStream("error.log"));
System.out.println(
"An error occurred. Check the error.log for details.");
} catch (java.io.FileNotFoundException ex) {
System.out.println("Could not create error.log file.");
}
}
System.out.println("Program terminated normally.");
}
}
--------------------------------------------------------------------------------
class SomeClass {// created by API provider
public void someFunction() throws IllegalAccessException {
//there are lots of statements here and validations follow before
//I throw the exception
throw new IllegalAccessException(
"Security violation."); //checked exception
}
public void setBlahBlah(int value) throws ArithmeticException{
if (value < 0) {
throw new ArithmeticException(

Page | 28
dhanoopbhaskar@gmail.com
"Negative Number."); //unchecked exception
}
}
}
--------------------------------------------------------------------------------
class NestedTry {
public static void main(String args[]) {
try { //outer try starts here
int i = 10 / args.length;

//----------------------------Inner
Try---------------------------
try {//inner try starts here
int a = 5 / (args.length - 1);
int ar[] = {10, 20};
ar[30] = 50;
} catch(ArrayIndexOutOfBoundsException e) {//inner try catch
System.out.println("Array index out of bounds - Inner
Try.");
} finally {
System.out.println("Inside finally - Inner Try.");
}
//---------------------------Inner try ends
here-------------------

System.out.println("I am still inside the Outer try block.");


} catch(ArithmeticException e) { //outer try catch
System.out.println("Divide by Zero error - Outer Try.");
} catch(ArrayIndexOutOfBoundsException e) { //outer try catch
System.out.println("Array element does not exist - Outer Try.");
}

System.out.println("Program terminated normally.");


// last statement of the program
}
}
--------------------------------------------------------------------------------
class SomeClass {// class provided by an API-Provider
public static void someFunction(int i) {
try {// implicit inner try
if (i == 1) {
i /= 0;
} else {
int ar[] = {10, 20};
ar[50] = 10;
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array element does not exist - Exception caught in
someFunction().");
}

Page | 29
dhanoopbhaskar@gmail.com
}
}

class NestedTryMethod {// My Class


public static void main(String args[]) {
try {//explicit try
int i = 10 / args.length;
SomeClass.someFunction(args.length);
} catch(ArithmeticException e) {
System.out.println(
"Divide by Zero error - Exception caught in main().");
}

System.out.println("Program terminated normally.");


}
}
--------------------------------------------------------------------------------
class ThrowCheckedException {// created by developer of the application
public static void main(String args[]) {
try {
new SomeClass().someFunction();
} catch(IllegalAccessException e) {
System.out.println("You do not have necessary privilege to
continue this operation.");
}

//new SomeClass().someFunction();
}
}
--------------------------------------------------------------------------------
class ThrowUncheckedException {// created by an Application Developer
public static void main(String args[]) {
try {
new SomeClass().setBlahBlah(Integer.parseInt(args[0]));
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println(
"Please input a non-negative number as command line arg.");
} catch(NumberFormatException excp) {
System.out.println("Please input a integer value.");
} catch(ArithmeticException e) {
System.out.println("Please input a non-negative number.");
System.out.println(e);
System.out.println(e.getMessage());
}
}
}

class SomeClass {// created by API provider


void setBlahBlah(int value) {
if (value < 0) {//validation

Page | 30
dhanoopbhaskar@gmail.com
throw new ArithmeticException("Negative Number.");
} else {
System.out.println(value +
" is a positive value. I like it!!!");
}
//other statements follow
}
}
--------------------------------------------------------------------------------
class MyException extends RuntimeException { // created by API provider
MyException() {
}
MyException(String msg) {
super(msg);
}
}

class SomeClass {// created by API provider


public boolean isEvenNo(int x) throws MyException {
if (x < 0) {
throw new MyException(
"Negative value - Invalid.");
} else if (x == 0) {
throw new MyException(
"Zero value - Invalid.");
} else if ((x % 2) != 0) {
throw new MyException(
"Odd Number - Invalid.");
}
return true;
}
}

class UserDefinedException {// created by developer of the application


public static void main(String args[]) {
try {
if (new SomeClass().isEvenNo(
Integer.parseInt(args[0]))) {
//may raise a exception called as MyException
System.out.println(
"The no " + args[0] +
" is a even number.");
}
} catch(MyException e) {
System.out.println(e);
System.out.println(e.getMessage());
System.out.println("----------------------------------------------------");
}
}
}

Page | 31
dhanoopbhaskar@gmail.com
--------------------------------------------------------------------------------
Streams
/
*********************************************************************************
* This program uses the Keyboard as the input device to accept data from the
*
* MS-DOS prompt (console). It gets a character from the keyboard, and prints the
*
* ASCII value of the character inputted as well as the character itself.
*
********************************************************************************
*/

import java.io.*; //for IOException & read() throws and java.io.IOException

public class TestKeyboardIO1 {


public static void main(String[] args) throws IOException {
/*System.out.println("Type in a character and press ENTER.");
System.out.println("------------------------------------");

// reads a byte from the keyboard Buffer.


// Returns an int.
int data = System.in.read();

System.out.println("ASCII : " + data);


System.out.println("Character : " + (char) data);*/

/*System.out.println("Type in a character and press ENTER.");


System.out.println("------------------------------------");

int data = System.in.read();


System.out.println("ASCII : " + data);
System.out.println("Character : " + (char) data);

data = System.in.read();
System.out.println("ASCII : " + data);
System.out.println("Character : " + (char) data);

data = System.in.read();
System.out.println("ASCII : " + data);
System.out.println("Character : " + (char) data);

data = System.in.read();
System.out.println("ASCII : " + data);
System.out.println("Character : " + (char) data);*/

/*System.out.println("Type in a character and press ENTER.");


System.out.println("------------------------------------");

Page | 32
dhanoopbhaskar@gmail.com
int data = System.in.read();
System.out.println("ASCII : " + data);
System.out.println("Character : " + (char) data);

System.in.skip(System.in.available()); // empty the inputstream

data = System.in.read();
System.out.println("ASCII : " + data);
System.out.println("Character : " + (char) data);*/

/*byte[] buffer = new byte[10];


int bytesRead = System.in.read(buffer);
System.out.println("Actual bytes read: " + bytesRead);

//System.out.println(buffer);// invalid usage

for (int i = 0; i < buffer.length; i++) {


System.out.println(buffer[i] + " " + (char) buffer[i]);
}

System.out.println("Converted to string: " +


new String(buffer));*/

/*byte[] buffer = new byte[10];


//System.in.read(buffer, 0, 5);
System.in.read(buffer, 2, 6);

for(int i = 0; i < buffer.length; i++) {


System.out.println(buffer[i] + " " +
(char) buffer[i]);
}

System.out.println(new String(buffer));*/

/*byte b[] = "Hello World".getBytes();


for(int i = 0; i < b.length; i++)
System.out.println(b[i] + " " + (char) b[i]);
*/

System.out.println(System.in.getClass().getName()); //
java.io.BufferedInputStream
System.out.println(System.out.getClass().getName()); // java.io.PrintStream

}
}

Page | 33
dhanoopbhaskar@gmail.com
--------------------------------------------------------------------------------
/********************************************************************************
* This program uses the Keyboard as the input device to accept data from the
*
* MS-DOS prompt (console). It gets a string from the keyboard and prints it.
*
********************************************************************************
/

import java.io.*; //for IOException, InputStream, InputStreamReader,


BufferedReader

public class TestKeyboardIO2 {


public static void main(String args[]) throws IOException {
/* converting from byte stream (InputStream subclass) to character stream
(Reader subclass)*/
/*InputStreamReader in_stream_reader =
new InputStreamReader(System.in);*/

/* converting from Reader subclass (in_stream_reader) to a BufferedReader


object*/
/*BufferedReader buf_reader =
new BufferedReader(in_stream_reader);*/

BufferedReader buf_reader = new BufferedReader(


new InputStreamReader(System.in));

System.out.println("Type in a sentence and press ENTER to terminate.");


System.out.println("------------------------------------------------");
String data1 = buf_reader.readLine();// method to read a line.
//String data1 = new BufferedReader(
// new InputStreamReader(System.in)).readLine();

System.out.println();

System.out.println("Type in a sentence and press ENTER to terminate.");


System.out.println("------------------------------------------------");
String data2 = buf_reader.readLine();// method to read a line.
//String data2 = new BufferedReader(
// new InputStreamReader(System.in)).readLine();

System.out.println();

System.out.println("1st sentence: " + data1);


System.out.println("2nd sentence: " + data2);
}
}
--------------------------------------------------------------------------------
Reading a file

Page | 34
dhanoopbhaskar@gmail.com
import java.io.*;

public class ShowFile {


public static void main(String args[]) throws IOException {
if (args.length != 0) {
File file = new File(args[0]);
if (file.exists() && file.isFile()) {
FileInputStream input_file =
new FileInputStream(file);
/*FileInputStream input_file =
new FileInputStream(args[0]);*/
int file_size = input_file.available();
byte[] data = new byte[file_size];
input_file.read(data);
System.out.println(new String(data));
input_file.close();
} else {
System.out.println("\"" + args[0] +
"\" not found !!!");
}
} else {
System.out.println("Error in usage:");
System.out.println(
" Usage - java ShowFile <filename>");
}
}
}
--------------------------------------------------------------------------------
Writing to a file
import java.io.*;

public class WriteFile {


public static void main(String args[]) throws IOException {
if (args.length != 0) {
File file = new File(args[0]);

if (file.exists()) {
System.out.print("This file already exists. Overwrite? (y/n): ");
int response = System.in.read();
if(response == 'N'||response =='n') {
// if you do not want to overwrite the file.
System.exit(0); // stop program
}
} else {
System.out.print("Creating new file: " + args[0] + "...");
}

System.out.println();
System.out.println(
"[Press \'~\' as the first char on a new line to terminate the file.]");

Page | 35
dhanoopbhaskar@gmail.com
System.out.println("Enter data for file: " + args[0]);
System.out.println(
"--------------------------------------------------------------------------------
");

FileOutputStream output_file = new FileOutputStream(file); // output file.


boolean continue_write = true;
byte[] data; // byte array to which the data is read into.
while (continue_write) {
// continue reading lines till the user types '~' and ENTER.
data = new BufferedReader(
new
InputStreamReader(System.in)).readLine().getBytes();
if (data.length == 1 && ((char)data[0]) == '~') {// if end-of-file
continue_write = false;
} else {// if not end-of-file
output_file.write(data);
output_file.write('\n');
}
}
System.out.println(
"--------------------------------------------------------------------------------
");
output_file.close();
} else {//end of while
System.out.println("Usage: java WriteFile <filename>");
}
}
}

/*public class WriteFile


{
public static void main(String args[]) throws IOException
{
if(args.length!=0)
{
File file=new File(args[0]);

if(file.exists())
{
System.out.print("This file already exists. Overwrite? (y/n): ");
int response=System.in.read();
if(response=='N'||response=='n')
// if you do not want to overwrite the file.
{
System.exit(0); // stop program
}
}

Page | 36
dhanoopbhaskar@gmail.com
else
System.out.print("Creating new file: " + args[0] + "...");

System.out.println();
System.out.println(
"[Press \'~\' as the first char on a new line to terminate the file.]");
System.out.println("Enter data for file: " + args[0]);
System.out.println(
"--------------------------------------------------------------------------------
");

PrintWriter output_file=new PrintWriter(


new FileOutputStream(file), true); // output file.
boolean continue_write=true;
String line;
while(continue_write)
// continue reading lines till the user types '~' and ENTER.
{
line=new BufferedReader(new InputStreamReader(System.in)).readLine();
if(line.length()==1 && line.equals("~")) // if end-of-file
continue_write=false;
else // if not end-of-file
output_file.println(line);
}
System.out.println(
“--------------------------------------------------------------------------------
“);
output_file.close();
}
else
System.out.println(“Usage: java WriteFile <filename>”);
}
}*/

Copying a file
import java.io.*;

public class CopyFile {


public static void main(String[] args) throws IOException {
switch (args.length) {
case 0:
System.out.println("Error in usage:");
System.out.println(
" Usage: java CopyFile <source filename> <destination filename>");
break;
case 1:
System.out.println(
"Specify the destination file.");
System.out.println(

Page | 37
dhanoopbhaskar@gmail.com
" Usage: java CopyFile <source filename> <destination filename>");
break;
case 2:
File sourceFile = new File(args[0]);
File destFile = new File(args[1]);

if (! sourceFile.exists()) {
System.out.println(args[0] + " not found !!!");
System.exit(0); // stopping application
}

if (destFile.exists()) {
System.out.print(args[1] +
" file already exists. Overwrite? (y/n): ");
int response = System.in.read();
if (response == 'N' || response == 'n') {
// if you do not want to overwrite the file.
System.out.print("Copy operation aborted.");
System.exit(0); // stopping application
}
}

System.out.println("Copying file...\n" +
args[0] + " to " + args[1]);

FileInputStream inputFile =
new FileInputStream(sourceFile);
FileOutputStream outputFile =
new FileOutputStream(destFile);

//boolean arg is for "append"


/*FileOutputStream outputFile =
new FileOutputStream(destFile, true);

FileOutputStream outputFile =
new FileOutputStream(args[1]);

FileOutputStream outputFile =
new FileOutputStream(args[1], true);*/

byte[] inputFileData =
new byte[inputFile.available()];
inputFile.read(inputFileData);
outputFile.write(inputFileData);

inputFile.close();
outputFile.close();

System.out.println("File successfully copied !");

Page | 38
dhanoopbhaskar@gmail.com
}
}
}

/*File oldFile = new File("abc.txt");


File newFile = new File("xyz.txt");
oldFile.renameTo(newFile);

new File("abc.txt").renameTo(new File("xyz.txt"));*/

--------------------------------------------------------------------------------
Moving a file
import java.io.*;

public class MoveFile {


public static void main(String args[]) throws IOException {
switch (args.length) {
case 0:
System.out.println("Error in usage:");
System.out.println("Usage: java MoveFile <source filename>
<destination filename>");
break;
case 1:
System.out.println("Specify the destination file.\n");
System.out.println("\tUsage: java MoveFile <source filename>
<destination filename>");
break;
case 2:
File source_file = new File(args[0]);
File dest_file = new File(args[1]);

/****************************************************************
****
* If the file does not exist, show an error message
*
* and stop the program.
*

********************************************************************/
if (! source_file.exists()) {
System.out.println(args[0] + " Not Found !!!");
System.exit(0);
}

/****************************************************************
****
* If the file exists, ask if the file is to be overwritten.
*
* (i) If the response is "Y" or "y", then overwrite it by
*

Page | 39
dhanoopbhaskar@gmail.com
* invoking the move method.
*
* (ii)If the response is "N" or "n", then cancel move
operation. *

********************************************************************/
if (dest_file.exists()) {
System.out.print(args[1] + " file already exists.
Overwrite? (y/n): ");
int response = System.in.read();
if (response == 'Y' || response == 'y') { // if you do not
want to overwrite the file.
moveFile(source_file, dest_file); // user-defined
function
} else {
System.out.println("File move operation aborted !!!");
System.exit(0);
}
} else {
moveFile(source_file, dest_file);
}
}
}
public static void moveFile(File source_file, File dest_file) throws
IOException {
System.out.print("Move file? (y/n): ");
System.in.skip(System.in.available());//Emptying the Keyboard Buffer.
int response = System.in.read();
if (response == 'Y' || response == 'y') { // if you want to move the file.
/**********************************************************************
* Creating streams for reading and writing source/destination files. *
**********************************************************************/
String source_file_str = source_file.getAbsolutePath();
String dest_file_str = dest_file.getAbsolutePath();

String source_file_dir =
source_file_str.substring(0,
source_file_str.lastIndexOf('\\'));//truncating the
filename
String dest_file_dir =
dest_file_str.substring(0,
dest_file_str.lastIndexOf('\\'));

System.out.println("Source File Abs Path: " +


source_file_str);
System.out.println("Source Dir: " + source_file_dir);
System.out.println("Dest File Abs Path: " + dest_file_str);
System.out.println("Dest Dir: " + dest_file_dir);

if (source_file_dir.equals(dest_file_dir)) {

Page | 40
dhanoopbhaskar@gmail.com
System.out.println("Renaming file " +
source_file.getName() + " to " +
dest_file.getName() + " !!!");
source_file.renameTo(new File(dest_file.getName()));
} else {
FileInputStream input_file = new FileInputStream(
source_file);
FileOutputStream output_file = new FileOutputStream(
dest_file);
/**********************************************************************
* (i) Finding the size of the source file using available(). *
* (ii) Creating a byte array, the no. of elements of which is equal *
* to the size of source file. *
* (iii)Read data from the source file into the byte array. *
* (iv) Write the byte array to the destination file. *
**********************************************************************/
System.out.println("Moving file " +
source_file.getName() + " to " +
dest_file.getName() + " !!!");
int file_size = input_file.available();
byte input_file_data[] = new byte[file_size];
input_file.read(input_file_data);
output_file.write(input_file_data);

/**********************************************************************
* Close the input/output streams. *
**********************************************************************/
input_file.close();
output_file.close();

source_file.delete();
}

/**********************************************************************
* Delete the source file and return a successful process message. *
**********************************************************************/

System.out.println("File " + source_file.getName() +


" successfully moved to " + dest_file.getName() +
" !!!");
} else {// if you do not want to move the file.
System.out.println("File move operation aborted !!!");
System.exit(0);
}
}
}
--------------------------------------------------------------------------------
Renaming a file
import java.io.*;

Page | 41
dhanoopbhaskar@gmail.com
class TestFile {
public static void main(String[] args) throws Exception {
File file = new File(args[0]);
System.out.println(file.getAbsolutePath());

File oldFile = new File("a.txt");


File newFile = new File("b.txt");
oldFile.renameTo(newFile);

if (new File("a.txt").renameTo(new File("b.txt"))) {


} else {
}

}
}
--------------------------------------------------------------------------------
Serialization and De-serialization
import java.io.*;

public class Student implements Serializable {


private int rollNo;
private String name;
transient int age;
public Student(int rollNo, String name, int age) {
this.rollNo = rollNo;
this.name = name;
this.age = age;
}
public int getRollNo() {
return rollNo;
}
public String getName() {
return name;
}
}
-----------------------------------------------------------
import java.io.*;

public class TestObjectInputStream {


public static void main(String s[]) throws IOException,
ClassNotFoundException {
/*FileInputStream fileInStream =
new FileInputStream("Student.ser");
ObjectInputStream objInStream =
new ObjectInputStream(fileInStream);*/

ObjectInputStream objInStream =
new ObjectInputStream(
new FileInputStream("Student.ser"));

Page | 42
dhanoopbhaskar@gmail.com
System.out.println("Deserializing object s1...");
Student s1 = (Student) objInStream.readObject();
System.out.println("Object s1 deserialized.");

System.out.println("Roll No.: " + s1.getRollNo());


System.out.println("Name : " + s1.getName());
System.out.println("Age : " + s1.age);

objInStream.close();
}
}
--------------------------------------------------------------------
import java.io.*;

public class TestObjectOutputStream {


public static void main(String s[]) throws IOException {
/*FileOutputStream fileOutStream =
new FileOutputStream("Student.ser");
ObjectOutputStream objOutStream =
new ObjectOutputStream(fileOutStream);*/

ObjectOutputStream objOutStream =
new ObjectOutputStream(
new FileOutputStream("Student.ser"));

Student s1 = new Student(12, "Arvind", 14);

System.out.println("Serializing object s1...");


objOutStream.writeObject(s1);
System.out.println("Object s1 serialized.");
objOutStream.close();
}
}
--------------------------------------------------------------------------------
TCP socket programming
import java.net.*;
import java.io.*;

public class Client1 {


public static void main(String[] args) throws Exception {
String hostAddr = "127.0.0.1"; // Loopback Address
int hostPort = 8000;

System.out.println("Client requesting for connection...");


Socket clientSideSocket = new Socket(hostAddr, hostPort);
System.out.println("Connection established.");

PrintWriter serverWriter = new PrintWriter(


clientSideSocket.getOutputStream(), true);

Page | 43
dhanoopbhaskar@gmail.com
System.out.println("Key in a message for the server:");
serverWriter.println(new BufferedReader(
new InputStreamReader(System.in)).readLine());
System.out.println("Message sent to server.");
}
}
---------------------- ----------------------
import java.net.*;
import java.io.*;

public class Server1 {


public static void main(String[] args) throws Exception {
int port = 8000;
ServerSocket serverSocket = new ServerSocket(port);

System.out.println("Server Started. Waiting for connection...");


Socket serverSideClientSocket = serverSocket.accept();
System.out.println("Client connection request received.");
System.out.println("Sockets bound and ready for communication.");

BufferedReader clientReader = new BufferedReader(new InputStreamReader(


serverSideClientSocket.getInputStream()));

System.out.println("Waiting for message from client...");


String messageFromClient = clientReader.readLine();
System.out.println("Client says: " + messageFromClient);
}
}

--------------------------------------------------------------
import java.net.*;
import java.io.*;

public class Client2 {


public static void main(String args[]) {
try {
Socket clientSideSocket = new Socket("localhost", 8000);
BufferedReader serverReader = new BufferedReader(
new InputStreamReader(clientSideSocket.getInputStream()));
PrintWriter serverWriter = new PrintWriter(
clientSideSocket.getOutputStream(), true);
BufferedReader keyboardReader = new BufferedReader(
new InputStreamReader(System.in));

double radius = 0;
while (true) {
System.out.print("Please enter the Radius of a Circle...");
radius = Double.parseDouble(keyboardReader.readLine());
serverWriter.println(radius);
if (radius != 0) {

Page | 44
dhanoopbhaskar@gmail.com
double area = Double.parseDouble(
serverReader.readLine());
System.out.println("Area received from the Server: " +
area);
} else {
break;
}
}
} catch(IOException e) {
}
}
}

---------------------- ----------------------
import java.io.*;
import java.net.*;

public class Server2 {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8000);
Socket serverSideClientSocket = serverSocket.accept();

BufferedReader clientReader = new BufferedReader(


new InputStreamReader(
serverSideClientSocket.getInputStream()));
PrintWriter clientWriter = new PrintWriter(
serverSideClientSocket.getOutputStream(), true);
while (true) {
double radius = Double.parseDouble(clientReader.readLine());
if (radius != 0) {
System.out.println("Radius Received from Client: " +
radius);
double area = radius * radius * Math.PI;
clientWriter.println(area);
} else {
break;
}
}
} catch(IOException e) {
//System.out.println(e);
}
}
}

--------------------------------------------------------------------------------

Multithreading
class Threading {
public static void main(String[] args) {

Page | 45
dhanoopbhaskar@gmail.com
/*Method No.1
Counter ctr = new Counter();
ctr.start();*/

/*Method No.2*/
Thread thread = new Thread(new Counter());
thread.start();
}
}

/*Method No.1
class Counter extends Thread {
public void run() {
int ctr = 1;

while (ctr <= 10) {


System.out.println(ctr++);
try {
sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}*/

/*Method No.2*/
class Counter implements Runnable {
public void run() {
int ctr = 1;

while (ctr <= 10) {


System.out.println(ctr++);
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
--------------------------------------------------------------------------------

Page | 46
dhanoopbhaskar@gmail.com