0% found this document useful (0 votes)
2 views145 pages

Java Programming Notes 8

The document provides an overview of Java arrays, constructors, and method overloading, detailing their definitions, examples, and rules. It explains how to create and manipulate arrays, the significance of constructors in object initialization, and the concept of method overloading with various examples. Additionally, it covers the use of the 'this' keyword and static elements in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views145 pages

Java Programming Notes 8

The document provides an overview of Java arrays, constructors, and method overloading, detailing their definitions, examples, and rules. It explains how to create and manipulate arrays, the significance of constructors in object initialization, and the concept of method overloading with various examples. Additionally, it covers the use of the 'this' keyword and static elements in Java.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 145

Java Arrays

● Normally, an array is a collection of similar type of elements which has contiguous memory location.
● Java array is an object which contains elements of a similar type. Additionally, The elements of an array
are stored in a contiguous memory location. It is a data structure where we store similar elements. We can
store only a fixed set of elements in a Java array.

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
import java.util.Arrays;

class Main { Here,


public static void main(String[] args) {
int[] n1 = {2, 3, 12, 4, 12, -2}; src - source array you want to copy

int[] n3 = new int[5]; srcPos - starting position (index) in


the source array
// Creating n2 array of having length of n1 array
int[] n2 = new int[n1.length]; dest - destination array where
elements will be copied from the
// copying entire n1 array to n2 source
System.arraycopy(n1, 0, n2, 0, n1.length);
System.out.println("n2 = " + Arrays.toString(n2));
destPos - starting position (index) in
the destination array
// copying elements from index 2 on n1 array
// copying element to index 1 of n3 array
// 2 elements will be copied length - number of elements to copy
System.arraycopy(n1, 2, n3, 1, 2);
System.out.println("n3 = " + Arrays.toString(n3));
}}
Cloning an Array in Java
/Java Program to clone the array
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
System.out.println("Printing original array:");
for(int i:arr)
System.out.println(i);

System.out.println("Printing clone of the array:");


int carr[]=arr.clone();
for(int i:carr)
System.out.println(i);

System.out.println("Are both equal?");


System.out.println(arr==carr);

}}
class Test2 {
public static void main(String[] args)
{
String str[] = { "Christ", "University", "Bangalore" };
System.out.println(str.length);
System.out.println(str[0].length);
} class Test4 {
} public
static void main(String[] args)
{
int number = 11;
int NUMBER = 22;
int Number = 33;
System.out.print(number + " ");
System.out.print(NUMBER + " ");
System.out.println(Number);
}
}
class Test1 {
public
static void main(String[] args)
{
int arr[] = { 11, 22, 33 };
System.out.print(arr[-2]);
}
}
class Test2 { class Test2 {
public public
static void main(String[] args) static void main(String[] args)
{ {
int arr[][] = { { 11, 22 }, { 33, 44, 55 } }; int arr[][] = { { 11, 22 }, { 33, 44, 55 } };
for (int i = 0; i < 2; i++) { for (int i = 0; i < 2; i++) {
for (int j = 0; j < arr.length; j++) for (int j = 0; j < arr[i].length; j++)
System.out.print(arr[i][j] + " "); System.out.print(arr[i][j] + " ");
System.out.println(); System.out.println();
} }
} }
} }
Method Overloading in Java

● If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.In short multiple methods with same name but with different signatures.
For example the signature of method add(int a, int b) having two int parameters is different from
signature of method add(int a, int b, int c) having three int parameters.

● This is one of the most popular OOP feature in java, there are several cases where we need more
than one methods with same name. For example let’s say we are writing a java program to find
the sum of input numbers, we need different variants of add method based on the user inputs
such as add(int, int), add(float, float) etc.

Advantage of method overloading


Method overloading increases the readability of the program.
Three ways to overload a method

In order to overload a method, the parameter list of the methods must differ in either of these:

1. Number of parameters.

For example: This is a valid case of overloading

add(int, int)add(int, int, int)


2. Data type of parameters.

For example:

add(int, int)

add(int, float)
3. Sequence of Data type of parameters.

For example:

add(int, float)
add(float, int)
Invalid case of method overloading:

Parameters list doesn’t mean the return type of the method, for example if two methods have
same name, same parameters and have different return type, then this is not a valid method
overloading example. This will throw a compilation error.

int add(int, int)


float add(int, int)

Case 1:
int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)

Case 2:
int mymethod(int a, int b)
int mymethod(float var1, float var2)
Case 3:

int mymethod(int a, int b)


int mymethod(int num)

Case 4:

float mymethod(int a, float b)


float mymethod(float var1, int var2)

Case 5:

int mymethod(int a, int b)


float mymethod(int var1, int var2)
Example 1: Overloading – Different Number of parameters in signature

class DisplayOverloading
{
int add(int a, int b)
{
int sum = a+b;
return sum;
}
int add(int a, int b, int c)
{
int sum = a+b+c;
return sum;
}}
class JavaExample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
System.out.println(obj.add(10, 20));
System.out.println(obj.add(10, 20, 30));
}}
Example 2: Overloading – Data type of parameters are different
class DisplayOverloading2
{
public int add(int a, int b)
{
int sum = a+b;
return sum;
}
public float add(float a, float b)
{
float sum = a+b;
return sum;
}}
class JavaExample
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
System.out.println(obj.add(5, 15));
System.out.println(obj.add(5.5f, 2.5f));
}}
Example3: Overloading – Sequence of data type of parameters is different
class DisplayOverloading3
{
public float add(int a, float b)
{
System.out.println("Method with (int, float) param list.");
return a+b;
}
public float add(float a, int b)
{
System.out.println("Method with (float, int) param list.");
return a+b;
}}
class JavaExample
{
public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
System.out.println(obj.add(10, 10.5f));
System.out.println(obj.add(1.5f, 1));
}}
Constructors in Java

● In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class
is created. At the time of calling constructor, memory for the object is allocated in the memory.
● It is a special type of method which is used to initialize the object.
● Every time an object is created using the new() keyword, at least one constructor is called.
● It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.

Rules for creating Java constructor

There are two rules defined for the constructor.

● Constructor name must be the same as its class name.


● A Constructor must have no explicit return type.
● A Java constructor cannot be abstract, static, final, and synchronized.
Types of Java constructors
There are two types of constructors in Java:

● Default constructor (no-arg constructor)


● Parameterized constructor

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time
of object creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the
type.

//method to display the value of id and name


class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Java Parameterized Constructor

class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student4 s1 = new Student4(111,"Curran");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Constructor Overloading in Java
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n; }
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
} }
Java Copy Constructor

class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
‘this’ in JAVA
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}

class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
this: to invoke current class method
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
this() : to invoke current class constructor

class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course; }
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee; }
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
class Teak
{
Teak()
{
this(5);
System.out.println("Default Constructor");
}
Teak(int x)
{
this(5,20);
System.out.println(x);
}
Teak(int x,int y)
{
System.out.println(x*y);
}
public static void main(String args[])
{
new Teak();
}}
class Teak
{
Teak()
{
System.out.println("Default Constructor");
}
Teak(int x)
{
this();
System.out.println(x);
}
Teak(int x,int y)
{
this(5);
System.out.println(x*y);
}
public static void main(String args[])
{
new Teak(8,10);
}}
public class MainMethodOverload2
{
//original main() method
public static void main(String args[])
{
MainMethodOverload mmo= new MainMethodOverload ();
//calling overloaded main() method from the original main() method
mmo.main();
}
//overloaded main() method
public static void main()
{
System.out.println("Overloaded main() method invoked");
}
}
public class MainMethodOverload3
{
public static void main(boolean args) {
if (args) {
System.out.println("First overloaded main() method executed");
System.out.println(args);
}}
public static void main(String str) {
System.out.println("Second overloaded main() method executed");
System.out.println(str);
}
public static void main(int args) {
System.out.println("Third overloaded main() method executed");
System.out.println(args);
}
public static void main(String[] args) {
System.out.println("Original main() method executed");
System.out.println("Hello");
MainMethodOverload3.main(true);
MainMethodOverload3.main("mango");
MainMethodOverload3.main(112);
}}
Java – Static Class, Block, Methods and Variables

The static keyword in Java is used for memory management mainly. We can apply static keyword with
variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the
class.
The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class
class JavaExample{
static int var1=77;
String var2;

public static void main(String args[])


{
JavaExample ob1 = new JavaExample();
JavaExample ob2 = new JavaExample();
ob1.var1=88;
ob1.var2="I'm Object1";
ob2.var1=99;
ob2.var2="I'm Object2";
System.out.println("ob1 integer:"+ob1.var1);
System.out.println("ob1 String:"+ob1.var2);
System.out.println("ob2 integer:"+ob2.var1);
System.out.println("ob2 STring:"+ob2.var2);
}
}
class Counter2{
class Counter{
static int count=0;
int count=0;
Counter2(){
Counter(){
count++;
count++;
System.out.println(count);
System.out.println(count);
}
}
public static void main(String args[]){
public static void main(String args[]){
Counter2 c1=new Counter2();
Counter c1=new Counter();
Counter2 c2=new Counter2();
Counter c2=new Counter();
Counter2 c3=new Counter2();
Counter c3=new Counter();
}
}
}
}
class SimpleStaticExample
{
// This is a static method
static void myMethod()
{
System.out.println("myMethod");
}

public static void main(String[] args)


{
/* You can see that we are calling this
* method without creating any object.
*/
myMethod();
}
}
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change()
{
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change()
{
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
class A2{
static{
System.out.println("static block is invoked");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
class A{
int a=40;//non static

public static void main(String


args[]){
System.out.println(a);
}
}
class Test
{
// static variable
static int a = 10;
static int b;

// static block
static {
System.out.println("Static block initialized.");
b = a * 4;
}

public static void main(String[] args)


{
System.out.println("from main");
System.out.println("Value of a : "+a);
System.out.println("Value of b : "+b);
}
}
class Test
{
static int a = m1();

static {
System.out.println("Inside static block");
}
static int m1() {
System.out.println("from m1");
return 20;
}
public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}
}
class Test
{
static int a = 10;
int b = 20;
static void m1()
{
a = 20;
System.out.println("from m1");
b = 10;
m2();
}
void m2()
{
System.out.println("from m2");
}
public static void main(String[] args)
{
}
}
class Test1 {
public static void main(String[] args)
{
int x = 20;
System.out.println(x);
}
static
{
int x = 10;
System.out.print(x + " ");
}
}
class Test1 {
int x = 10;
public static void main(String[] args)
{
System.out.println(x);
}
static
{
System.out.print(x + " ");
}
}
class Test1 {
int x = 10;
public static void main(String[] args)
{
Test1 t1 = new Test1();
System.out.println(t1.x);
}
static
{
int x = 20;
System.out.print(x + " ");
}
}
class Basic2
{
Basic2()
{
System.out.print("Inside Constructor. "); }

{
System.out.print("Inside the instance block. ");
}

static
{
System.out.print("Inside the static block. ");
} }
class Main
{
public static void main(String argvs[])
{
Basic2 obj = new Basic2();
}}
public class interview
{
public static void main(String[] arr)
{
System.out.println("first main");
}
public static void main(String arr)
{
System.out.println("second main");
}
}
public class Solution{
public static void main(String[] args){
int[] x = {120, 200, 016};
for(int i = 0; i < x.length; i++){
System.out.print(x[i] + "\n" );
}
}
}
Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When
you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add
new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java


● For Method Overriding (so runtime polymorphism can be achieved).
● For Code Reusability.
Terms used in Inheritance

Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.

Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.

Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields
and methods already defined in the previous class.
The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class. The meaning
of "extends" is to increase the functionality.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class
inherits the Animal class, so there is the single inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given
below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel
inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given
below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel
inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
}}
Why multiple inheritance is not supported in java?

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
public class A {
int x = 20;
}
public class B extends A {
int x = 30;
}
public class Test {
public static void main(String[] args)
{
B b = new B();
System.out.println(b.x);

A a = new A();
System.out.println(a.x);

A a2 = new B();
System.out.println(a2.x);
}
}
class A
{
{
System.out.println(1);
}}
class B extends A
{
{
System.out.println(2);
}}
class C extends B
{
{
System.out.println(3);
}}
public class MainClass
{
public static void main(String[] args)
{
C c = new C();
}}
class A
{
int i = 10;
}

class B extends A
{
int i = 20;
}

public class MainClass


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

System.out.println(a.i);
}
}
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer
immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is


created implicitly which is referred by super reference variable.

Usage of Java super Keyword


● super can be used to refer immediate parent class instance variable.
● super can be used to invoke immediate parent class method.
● super() can be used to invoke immediate parent class constructor.
class X
{
static void staticMethod()
{
System.out.println("Class X");
}}
class Y extends X
{
static void staticMethod()
{
System.out.println("Class Y");
}}
public class MainClass
{
public static void main(String[] args)
{
Y.staticMethod();
}}
super can be used to invoke parent class method

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
super is used to invoke parent class constructor.

class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
super is used to refer immediate parent class instance variable

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);
System.out.println(super.color);
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}
super example: real use
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
} }
class Emp extends Person{
float salary;
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}}
Abstract class in Java

● A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).

● Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java

● Abstraction is a process of hiding the implementation details and showing only functionality to the user.

● Another way, it shows only essential things to the user and hides the internal details, for example, sending
SMS where you type the text and send the message. You don't know the internal processing about the
message delivery.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();
s.draw();
}
}
abstract class Bank{
abstract int getRateOfInterest();
}

class SBI extends Bank{


int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}}
Abstract class having constructor, data member and methods
An abstract class can have a data member, abstract method, method body (non-abstract method), constructor,
and even main() method.

abstract class Bike{


Bike(){System.out.println("bike is created");}

abstract void run();


void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
Can we run abstract class in Java that has main method?

public abstract class TestAbstract


{
public static void main(String[] args)
{
System.out.println("Inside abstract main");
}
}
abstract class Base {
Base()
{
System.out.println("Base Constructor Called");
}
abstract void fun();
}
class Derived extends Base {
Derived()
{
System.out.println("Derived Constructor Called");
}
void fun()
{
System.out.println("Derived fun() called");
}}
class GFG {
public static void main(String args[])
{
Derived d = new Derived();
d.fun();
}}
abstract class GFG {

public static void main(String args[])


{
GFG gfg = new GFG();
}
}
abstract class Helper {
static void demofun()
{
System.out.println("Christ University");
}
}
public class GFG extends Helper {

public static void main(String[] args)


{
Helper.demofun();
}
}
import java.io.*;
abstract class Demo {
abstract void m1();
abstract void m2();
abstract void m3(); }
abstract class FirstChild extends Demo {
public void m1() {
System.out.println("Inside m1");
} }
class SecondChild extends FirstChild {
public void m2() {
System.out.println("Inside m2");
}
public void m3() {
System.out.println("Inside m3");
} }
class GFG {
public static void main(String[] args)
{
SecondChild s = new SecondChild();
s.m1();
s.m2();
s.m3();
Interface in Java
● An interface in Java is a blueprint of a class. It has static constants and abstract methods.

● The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

● In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method
body.Java Interface also represents the IS-A relationship.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

● It is used to achieve abstraction.


● By interface, we can support the functionality of multiple inheritance.
● It can be used to achieve loose coupling.
How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in
an interface are declared with the empty body, and all the fields are public, static and final by default. A class
that implements an interface must implement all the methods declared in the interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
interface Try
{ class Sample implements Try
int a=10; {
public int a=10; public static void main(String args[])
public static final int a=10; {
final int a=10; x=20; //compile time error
static int a=0; }
} }

class A{} //add()


class B{}/add()
class C extends A,B{}
interface Try
{ class A{}
int x;//Compile-time error interface IB{}
} interface IC{}

class D extends A implements IB, IC{

}
Java Interface Example
In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.

interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}}
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Interface inheritance
A class implements an interface, but one interface extends another interface.

interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
interface A
{
int x=10;
}
interface B
{
int x=100;
}
class Hello implements A,B
{
public static void Main(String args[])
{
/* reference to x is ambiguous both variables are x
* so we are using interface name to resolve the
* variable
*/
System.out.println(x);
System.out.println(A.x);
System.out.println(B.x);
}
}
interface A
{
public void aaa();
}
interface B
{
public int aaa();
}

class Central implements A,B


{

public void aaa() // error


{
}
public int aaa() // error
{
}
public static void main(String args[])
{

}
}
Java 8 Default Method in Interface

Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an
example:

File: TestInterfaceDefault.java

interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
What is Exception Handling

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException,


SQLException, RemoteException, etc.

Advantage of Exception Handling


The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the
normal flow of the application that is why we use exception handling. Let's take a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked
exception. According to Oracle, there are three types of exceptions:

• Checked Exception
• Unchecked Exception
• Error
Java Exception Keywords
There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

try The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch or finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.

finally The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It
specifies that there may occur an exception in the method. It is always used with method
signature.
public class TryCatchExample1 {

public static void main(String[] args) {

int data=50/0; //may throw exception

System.out.println("rest of the code");

}
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs


The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that has characters,
converting this variable into digit will occur NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as shown below:
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
public class TryCatchExample4 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

}
public class TryCatchExample6 {
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
} }
public class TryCatchExample8 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception

}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

}
public class TryCatchExample9 {

public static void main(String[] args) {


try
{
int arr[]= {1,3,5,7};
System.out.println(arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

}
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
} }
public class MultipleCatchBlock3 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
public class MultipleCatchBlock4 {

public static void main(String[] args) {

try{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){
System.out.println("common task completed");
}
catch(ArithmeticException e){
System.out.println("task1 is completed");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed")
;}
System.out.println("rest of the code...");
} }
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
super(str); } }
class TestCustomException1
{
static void validate (int age) throws InvalidAgeException{
if(age < 18){
throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote"); } }
public static void main(String args[])
{
try { validate(13); }
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code..."); } }
Java Threads
Typically, we can define threads as a subprocess with lightweight with the smallest unit of processes and also has separate
paths of execution. These threads use shared memory but they act independently hence if there is an exception in threads that
do not affect the working of other threads despite them sharing the same memory.
Thread State Transition Diagram
There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

What is Main Thread?


As we are familiar, we create Main Method in each and every Java Program, which acts as an entry point for
the code to get executed by JVM, Similarly in this Multithreading Concept, Each Program has one Main
Thread which was provided by default by JVM, hence whenever a program is being created in java, JVM
provides the Main Thread for its Execution.
Java Thread Example by extending Thread Java Thread Example by implementing Runnable
class interface

class Multi extends Thread{


public void run(){ class Multi3 implements Runnable{
System.out.println("thread is running..."); public void run(){
} System.out.println("thread is running...");
public static void main(String args[]){ }
Multi t1=new Multi();
t1.start(); public static void main(String args[]){
} Multi3 m1=new Multi3();
} Thread t1 =new Thread(m1); // Using the constructor
Thread(Runnable r)
t1.start();
}
}
Thread Scheduler in Java
A component of Java that decides which thread to run or execute and which thread to wait is
called a thread scheduler in Java. In Java, a thread is only chosen by a thread scheduler if it is
in the runnable state. However, if there is more than one thread in the runnable state, it is up to
the thread scheduler to pick one of the threads and ignore the other ones. There are some
criteria that decide which thread will execute first. There are two factors for scheduling a
thread i.e. Priority and Time of arrival.

Priority: Priority of each thread lies between 1 to 10. If a thread has a higher priority, it
means that thread has got a better chance of getting picked up by the thread scheduler.

Time of Arrival: Suppose two threads of the same priority enter the runnable state, then
priority cannot be the factor to pick a thread from these two threads. In such a case, arrival
time of thread is considered by the thread scheduler. A thread that arrived first gets the
preference over the other threads.
Thread.sleep() in Java with Examples
The Java Thread class provides the two variant of the sleep() method. First one accepts only an arguments,
whereas the other variant accepts two arguments. The method sleep() is being used to halt the working of a thread
for a given amount of time. The time up to which the thread remains in the sleeping state is known as the sleeping
time of the thread. After the sleeping time is over, the thread starts its execution from where it has left.

class TestSleepMethod1 extends Thread{


public void run(){
for(int i=1;i<5;i++){
// the thread will sleep for the 500 milli seconds
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();
t2.start();
}
}
Can we start a thread twice
No. After starting a thread, it can never be started again. If you does so, an
IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will
throw exception.

Let's understand it by the example given below:

public class TestThreadTwice1 extends Thread{


public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
}
}
Java join() method

The join() method in Java is provided by the java.lang.Thread class that permits one thread to wait until the other thread to finish
its execution. Suppose th be the object the class Thread whose thread is doing its execution currently, then the th.join(); statement
ensures that th is finished before the program does the execution of the next statement. When there are more than one thread
invoking the join() method, then it leads to overloading on the join() method that permits the developer or programmer to
mention the waiting period.However, similar to the sleep() method in Java, the join() method is also dependent on the operating
system for the timing, so we should not assume that the join() method waits equal to the time we mention in the parameters. The
following are the three overloaded join() methods.

Description of The Overloaded join() Method

join(): When the join() method is invoked, the current thread stops its execution and the thread goes into the wait state. The
current thread remains in the wait state until the thread on which the join() method is invoked has achieved its dead state. If
interruption of the thread occurs, then it throws the InterruptedException.
public class Threadjoiningmethod extends Thread{
public void run(){
for(int i=1;i<=4;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}}
public static void main(String args[]){
Threadjoiningmethod th1=new Threadjoiningmethod ();
Threadjoiningmethod th2=new Threadjoiningmethod ();
Threadjoiningmethod th3=new Threadjoiningmethod ();
th1.start();
try{
th1.join();
}
catch(Exception e){
System.out.println(e);
}
th2.start();
th3.start();
} }
class ThreadJoin extends Thread
{
public void run()
{
for (int j = 0; j < 2; j++)
{
try { Thread.sleep(300);
System.out.println("The current thread name is: " + Thread.currentThread().getName()); }
catch(Exception e)
{
System.out.println("The exception has been caught: " + e);
}
System.out.println( j );
} } }
public class ThreadJoin1
{
public static void main (String argvs[])
{
ThreadJoin th1 = new ThreadJoin();
ThreadJoin th2 = new ThreadJoin();
ThreadJoin th3 = new ThreadJoin();
th1.start();
try { System.out.println("The current thread name is: "+ Thread.currentThread().getName());
th1.join(); }
catch(Exception e)
{
System.out.println("The exception has been caught " + e);
}
th2.start();
try {
System.out.println("The current thread name is: " + Thread.currentThread().getName());
Java Thread Priority in Multithreading

Priorities in threads is a concept where each thread is having a priority which in layman’s language
one can say every object is having priority here which is represented by numbers ranging from 1 to
10.

The default priority is set to 5 as excepted.


Minimum priority is set to 1.
Maximum priority is set to 10.
Here 3 constants are defined in it namely as follows:

● public static int NORM_PRIORITY


● public static int MIN_PRIORITY
● public static int MAX_PRIORITY
public class A implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread()); // This method is static.
}
public static void main(String[] args)
{
A a = new A();
Thread t = new Thread(a, "NewThread");

System.out.println("Priority of Thread: " +t.getPriority());


System.out.println("Name of Thread: " +t.getName());
t.start();
}
}
public class A implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread()); // This method is static.
}
public static void main(String[] args)
{
A a = new A();
Thread t1 = new Thread(a, "First Thread");
Thread t2 = new Thread(a, "Second Thread");
Thread t3 = new Thread(a, "Third Thread");

t1.setPriority(4); // Setting the priority of first thread.


t2.setPriority(2); // Setting the priority of second thread.
t3.setPriority(8); // Setting the priority of third thread.

t1.start();
t2.start();
t3.start();
}
}
public class A implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread()); // This method is static.
}
public static void main(String[] args)
{
A a = new A();
Thread t = new Thread(a, "NewThread");
t.setPriority(2); // Setting the priority of thread.

System.out.println("Priority of Thread: " +t.getPriority());


System.out.println("Name of Thread: " +t.getName());
t.start();
}
}
Java Package
● A java package is a group of similar types of classes, interfaces and sub-packages.

● Package in java can be categorized in two form, built-in package and user-defined package.

● There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

● Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they
can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Built-in Packages
These packages consist of a large number of classes
which are a part of Java API.Some of the commonly used
built-in packages are:
1) java.lang: Contains language support classes(e.g
classed which defines primitive data types, math
operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output
operations.
3) java.util: Contains utility classes which implement
data structures like Linked List, Dictionary and support ;
for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the
components for graphical user interfaces (like button ,
;menus etc).
6) java.net: Contain classes for supporting networking
operations.
Simple example of java package
The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
How to access package from another package?

There are three ways to access the package from outside the package.

● import package.*;
● import package.classname;
● fully qualified name.

Example of package that import the //save by B.java


packagename.* package mypack;
//save by A.java import pack.*;
package pack;
public class A{ class B{
public void public static void main(String args[]){
msg(){System.out.println("Hello");} A obj = new A();
} obj.msg();
} }
Using fully qualified name

Example of package by import fully //save by B.java


qualified name package mypack;
class B{
//save by A.java
public static void main(String args[]){
package pack;
pack.A obj = new pack.A();//fully qualified name
public class A{
obj.msg();
public void
}
msg(){System.out.println("Hello");} }
}
// Name of the package must be same as the directory
// under which this file is saved
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}}
/* import 'MyClass' class from 'names' myPackage */
import myPackage.MyClass;
public class PrintName
{
public static void main(String args[])
{
String name = "Christ University";
MyClass obj = new MyClass();
obj.getNames(name);
}}
import static java.lang.System.*;

class StaticImportDemo
{
public static void main(String args[])
{
out.println("Christ University");
}
}
Access Modifiers in Java

There are four types of Java access modifiers:

Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Default
If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is
more restrictive than protected, and public.

//save by B.java
//save by A.java package mypack;
package pack; import pack.*;
class A{ class B{
void public static void main(String args[]){
msg(){System.out.println("Hello");} A obj = new A();//Compile Time Error
} obj.msg();//Compile Time Error
}
}
Protected
● The protected access modifier is accessible within package and outside the package but through
inheritance only.
● The protected access modifier can be applied on the data member, method and constructor. It can't be
applied on the class.
● It provides more accessibility than the default modifer.

//save by A.java //save by B.java


package pack; package mypack;
public class A{ import pack.*;
protected void
msg(){System.out.println("Hello");} class B extends A{
public static void main(String args[]){
}
B obj = new B();
obj.msg();
}
}
Access within within outside package by outside
Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
`

Java I/O Streams

In Java, streams are the sequence of data that are read from the source and written to the
destination.

An input stream is used to read data from the source. And, an output stream is used to write data
to the destination.
Types of Streams
Depending upon the data a stream holds, it can be classified into:

● Byte Stream
● Character Stream

Byte Stream
Byte stream is used to read and write a single byte (8 bits) of data.

All byte stream classes are derived from base abstract classes called InputStream and OutputStream.

Character Stream

Character stream is used to read and write a single character of data.

All the character stream classes are derived from base abstract classes Reader and Writer.
import java.io.FileOutputStream;
public class FileWrite {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
import java.io.FileOutputStream;
public class FileWrite {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to Christuniversity.";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
import java.io.FileInputStream;
public class FileRead1 {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);

fin.close();
}catch(Exception e){System.out.println(e);}
}
}
import java.io.FileInputStream;
public class FileRead2 {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("s1.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
import java.io.*;
public class CopyFile {
public static void main(String args[]) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}} }}
import java.io.*;
public class CopyFile {

public static void main(String args[]) throws IOException {


FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}}}}
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}

You might also like