Package
A group of related classes and interfaces designed under a single unit is called package.
Benefits of Package:-
1) All related classes is designed under a single unit leads to high modularity.
2) Same class names designed in 2 different packages. It is not possible in other programs.
3) It is possible to design a sub package under a package.
4) Package members are accessible inside a package only. It is not possible from outside hence it
shows data hiding technic.
5) Package can be created once and that can be used multiple without redefining.
Packages can be divided into 2 types:
1) Java Standard Library:- Java contains so many predefined packages, they are called java
libraries. Ex:- lang, util, io etc.
2) User defined package:- The programmer can also create his/her own package based on
necessity. They are called user defined packages.
For accessing the package programmer has 2 methods:-
1) Using import statement
2) Using fully qualified name
1) Using import statement:- programmer can access the properties by writing import
statement at beginning point of program.
Syntax:- import package.*; / import [Link];
Ex: import [Link].*; / import [Link];
2) Witting fully qualified name:- in this method the programmer can create object from
package and classname.
Ex:- [Link] st=new [Link]();
Implementation of user defined package involve the following steps:-
Step 1:- Package is created just like normal program. It should contain single public class and that class
name and it should be saved with same file name. It should has package name followed package
keyword.
Syntax:-
Package packagename;
Public class Classname
{
-------
-------
}
Step 2:- That package should be compiled with –d option. This option can create a main folder with
Packagename and this folder contain byte code text file with public classname .
Syntax:- javac –d . [Link]
Program 1:- Arithmetic operations
package pack1;
public class Arith
{
public static int add(int x,int y)
{
return(x+y);
}
public static int mul(int x,int y)
{
return(x*y);
}
}
Compile:- C:\Raghava\Package>javac -d . [Link]
We can use above package wherever we want:
Program 2:-
import [Link];
class PackageEx1
{
public static void main(String[] args)
{
int a=[Link](10,20);
int b=[Link](10,20);
[Link]("Add="+a+" Mul="+b);
}
}
O/P:-
Add=30 Mul=200
Sub Package:-Programmer can also create sub package under a main Package.
Program:-
package pack1.pack2;
public class Stat
{
public int max(int a[])
{
int m=a[0];
for(int i=1;i<[Link];i++)
{
if(a[i]>m)
m=a[i];
}
return m;
}
}
Compile:-
C:\Raghava\Package>javac -d . [Link]
Program:-
class PackageEx2
{
public static void main(String[] args)
{
int a[]={11,22,5,66,7};
[Link] x=new [Link]();
int y=[Link](a);
[Link]("Max="+y);
}
}
O/P:-
Max=66
If 2 packages contains same classname, then we should use fully qualified name without using
import statement.
Ex:-
Package dept1; Package dept2; Import [Link];
Public class Emp Public class Emp Import [Link];
{ { Class Demo
----- ----- {
---- ---- Emp e=new Emp(); [x] Ambiguity
} }
Class Demo
{
[Link] e1=new [Link]();
[Link] e2=new [Link]();
--------
}
If programmer wants to design 2 public classes then he/she should design 2 different programs with
same package name.
Package x; Package x;
Public class Y Public class Z
{ {
------- -------
------- -------
} }
Access Modifiers (Related to packages):-
They represent accessibility of class members. They are:- 1)private 2)default 3)protected
4)public
Access Modifiers-> Private <default> Protected Public
Access Location-
Same package T T T T
Sub class in same F T T T
packate
Non-sub class in F T T T
same package
Sub class in other F F T T
package
Non-sub class in F F F T
other package
Program:-
package own;
public class A
{
private int a=10;
int b=20; //default
protected int c=30;
public int d=40;
}
Program 2:-
package own;
public class B extends A
{
public B()
{
[Link]("Sub class in same package:");
//[Link]("a="+a);
[Link]("b="+b);
[Link]("c="+c);
[Link]("d="+d);
}
}
Program 3:-
package own;
public class C
{
public C()
{
A x=new A();
[Link]("Non-Sub class in same package:");
//[Link]("a="+x.a);
[Link]("b="+x.b);
[Link]("c="+x.c);
[Link]("d="+x.d);
}
}
Program 4:-
package other;
public class D extends own.A
{
public D()
{
[Link]("Sub class in other package:");
//[Link]("a="+a);
//[Link]("b="+b);
[Link]("c="+c);
[Link]("d="+d);
}
}
Program 5:-
package other;
public class E
{
public E()
{
own.A x=new own.A();
[Link]("Non-Sub class in other package:");
//[Link]("a="+x.a);
//[Link]("b="+x.b);
//[Link]("c="+x.c);
[Link]("d="+x.d);
}
}
Program 6:-
class PackageEx3
{
public static void main(String[] args)
{
new own.B();
new own.C();
new other.D();
new other.E();
}
}
Compile:-
C:\Raghava\Package>javac -d . [Link]
C:\Raghava\Package>javac -d . [Link]
C:\Raghava\Package>javac -d . [Link]
C:\Raghava\Package>javac -d . [Link]
C:\Raghava\Package>javac -d . [Link]
C:\Raghava\Package>javac [Link]
C:\Raghava\Package>java PackageEx3
Sub class in same package:
b=20
c=30
d=40
Non-Sub class in same package:
b=20
c=30
d=40
Sub class in other package:
c=30
d=40
Non-Sub class in other package:
d=40
Set Classpath:- it is an environment to call the package which is designed in other path(drive).
Ex:- The package is in c drive but the program file is in E drive rag folder. So the programmer first set the
path like this.
E:\Rag>set classpath=c:\Raghava\Package; . ; %classpath%
E:\Rag>javac [Link]
E:\Rag>java PackageEx1
Interface
It is one type of class which contains final variables and abstract methods only.
Benefits:-
1) It supports for 100% abstraction.
2) It supports for multiple inheritance.
Interface variables public static final and methods are public abstract by default.
Syntax:-
Interface InterfaceName
{
Returntype methodname([args]);
}
Program:-
interface A
{
void show();
}
interface B
{
void show();
}
class C implements A,B
{
public void show()
{
[Link]("Implemented show()");
}
public static void main(String[] args)
{
C x=new C();
[Link]();
}
}
O/P:- Implemented show()
Programmer can’t create object for interface.
Variables in Java Interface:-
In interface the variables are public static final by default. So initialized value does not
change and the variable should be initialized in interface itself. These variables are
considered as symbolic constants.
Ex:- double PI=3.1415
Program:-
interface Circle
double PI=3.1415;
void area();
class AreaOfCircle implements Circle
{
public void area()
double r=2.5;
double a=PI*r*r;
[Link]("Area="+a);
public static void main(String[] args)
AreaOfCircle x=new AreaOfCircle();
[Link]();
Extending an interface in Java:-
An interface can be extend another interface by using “extend” keyword.
An interface cannot extend multiple interface.
The class that implements child interface needs to provide code for all the methods defined
both child and parent interface.
Program:-
interface Parent
void show();
interface Child extends Parent
{
void display();
class A implements Child
public void show()
[Link]("Parent interface show method");
public void display()
[Link]("Child interface display method");
public static void main(String[] args)
A x=new A();
[Link]();
[Link]();
O/P:-
Parent interface show method
Child interface display method
Nested Interface:- It is possible to design an interface within another interface. This process is known as
nested interface. First interface is called outer interface and second interface is called inner interface.
Program:-
interface OuterInterface
{
void outerMethod();
interface InnerInterface
{
void innerMethod();
}
}
class OnlyOuter implements OuterInterface
{
public void outerMethod()
{
[Link]("Outer Interface Method");
}
}
class OnlyInner implements [Link]
{
public void innerMethod()
{
[Link]("Inner Interface Method");
}
}
class NestedInterfaceEx
{
public static void main(String[] args)
{
OnlyOuter x=new OnlyOuter();
OnlyInner y=new OnlyInner();
[Link]();
[Link]();
}
}
O/P:-
Outer Interface Method
Inner Interface Method
Differences between Abstract class and interface:-
Abstract class Interface
[Link] programmer known implementation details [Link] programmer known requirement
but not completely, there we should prefer astract specification(planning) only. There we should
class prefer interface
[Link] shows 0 to 100% abstraction [Link] shows 100% abstraction
[Link] need not be public static by default [Link] should be public static by default
[Link] should not be public abstract [Link] are public abstract by default
[Link] may contains multiple concrete methods and [Link] may contain multiple dynamic methods and
constructor static methods.
[Link] can’t create instance(object) from abstract [Link] can’t create instance (object) from interface
class
I/O Operations
Java contains so many predefined classes for I/O operation. They are defined in IO Packages.
They are used to perform Console I/O Operation and File I/O operations.
1) Console I/O operation:- Taking the data from Standard input unit(keyboard) & displaying the
data through standard output unit(Monitor) is called Console I/O operations
2) File I/O operations:- Reading the data from a file and storing(writing) into a file is called File I/O
operations.
Java supports 3 static objects for I/O operations:-
1) [Link](keyboard):- This static object defined in System class and defined from InputStream
class. It is used for Input Operations
2) [Link](Monitor):- This static object defined in System class and defined from PrintStream
class. It is used for Output Operations.
3) [Link]:- It is same as [Link] but it display error messages only.
Ex:- [Link](“Less Balance”);
Description for [Link]():-
class Test
{
static String s="Shiva";
}
class Demo
{
public static void main(String []args)
{
int l=[Link]();
[Link](l);
}
}
System ->Test
out -> s
println() -> length()
File class:- It is a predefined defined in io package. It is used to display file attributes. Ex: File size, File
type etc.
Syntax:-
1) File f=new File(“File name”);
2) File f=new File(“File Path”,“File name”);
File Class Methods:-
1) exists():- It can test weather file is existed or not
2) isFile():- It can test weather given name is a file name or not
3) isDirectory():- It can test weather given name is a directory name or not
4) canWrite():- It can test weather file is writable or not.
5) canRead():-It can test weather file is readable or not.
6) getName() :- It returns file name.
7) getParent():- It returns folder name.
8) getPath() :- It returns the total file path.
Program:-
import [Link].*;
class IOEx1
{
public static void main(String[] args)
{
File f=new File("[Link]");
if([Link]())
{
if([Link]())
[Link]("It is a file");
if([Link]())
[Link]("It is a Directory");
if([Link]())
[Link]("File is Writeable");
if([Link]())
[Link]("File is Readable");
[Link]("File Path="+[Link]());
[Link]("File Name="+[Link]());
[Link]("File Size="+[Link]());
[Link]("Folder Name="+[Link]());
}
else
[Link]("File not found");
}
}
O/P:-
It is a file
File is Writeable
File is Readable
File Path=[Link]
File Name=[Link]
Folder Name=null
Streams:- It represents the flow of data .
Stream Classes:- They supports the programmer to transfer the data from source to destination.
Source:- Array, socket, File, keyboard etc
Destination:- Array, socket, File, Monitor etc.
Stream Classes is divided into 2 types:-
1) Byte Stream Classes:- They stores and read the file information in Byte(Binary) format. It can
handle text, audio, images and video files. These classes are ends with Input Stream or Output
Stream.
2) Character Stream Classes:- They stores and read the file information in Character format. It can
handle text files only. These classes are ends with Reader or Writer.
Byte Stream classes given below:-
1. Output Stream(main class)
1.1. ByteArrayOutputStream
1.2. FileOutputStream
1.3. FilterOutputStream
[Link]
[Link]
[Link]
1.4. PipedOutputStream
2. InputStream(main class)
2.1. ByteArrayInputStream
2.2. FileInputStream
2.3. FilterInputStream
[Link]
[Link]
[Link]
2.4. PipedInputStream
Character Stream List given below:-
1. Writer
1.1. CharArrayWriter
1.2. StringWriter
1.3. PrintWriter
1.4. BufferedWriter
[Link]
1.5. PipedWriter
1.6. FilterWriter
2. Reader
2.1. CharArrayReader
2.2. StringReader
2.3. InputReader
2.4. BufferedReader
[Link]
2.5. PipedReader
2.6. FilterReader
OutputStream:- It is super class for all OutputStream classes. It is used to display result on the screen or
store the result into the file.
Methods:-
1) write():- It is used to read the integer value from keyboard and stores it as character value in
file. Ex:- 65 as ‘A’.
2) flush () :- It can flush(store) all the characters from buffer to file.
InputStream:- It is super class for all InputStream classes. It is used to take the data from keyboard or
Read the information from file.
Methods:-
1) read():- It is used to read a character from keyboard and returns it as integer value.
2) available():- It returns the size of file(byte).
3) close():- It is used to close a file.
DataInputStream:- This class belongs to InputStream class.
1) read() :- It is used to take the data from Keyboard.
2) readLine():- It is used to take string information from keyboard.
Program:-
import [Link].*;
class IOEx2
{
public static void main(String[] args) throws IOException
{
DataInputStream dis=new DataInputStream([Link]);
[Link]("Enter first Value:");
int a=[Link]([Link]());
[Link]("Enter second Value:");
int b=[Link]([Link]());
[Link]("Result="+(a+b));
}
}
O/P:-
Enter first Value:
10
Enter second Value:
20
Result=30
FileOutputStream:- This class is used to store the data in Byte format into a file.
Syn:- FileOutputStream obj=new FileOutputStream(File name);
FileInputStream:- This class is used to read the data from file which is stored in Byte format.
Syn:- FileInputStream obj=new FileInputStream(File name);
Program:-
import [Link].*;
class IOEx3
{
public static void main(String[] args) throws IOException
{
FileOutputStream fos=new FileOutputStream("[Link]");//storing
int x=0; //ASCII
[Link]("Enter Text and press ctrl+c at end:");
do
{
x=[Link](); //It reads a character from keyboard and stores in RAM(ASCII)
[Link](x);
}
while (x!=-1);//End of file ctrl+c
[Link]();
}
}
Program:- To read the information from above file
import [Link].*;
class IOEx4
{
public static void main(String[] args) throws IOException
{
FileInputStream fis=new FileInputStream("[Link]");//Reading
int x=0; //ASCII
[Link]("File Information is:");
do
{
x=[Link](); //It reads a character from file and stores in RAM(ASCII)
[Link](x); //Shows the output on screen
}
while (x!=-1);
[Link]();
}
}
O/P:-
File Information is:
Bunny
Chinni
Munni
Program:- Read above file DataInputStream(Increases execution speed by using readLine())
Import [Link].*;
class IOEx5
{
public static void main(String[] args) throws IOException
{
FileInputStream fis=new FileInputStream("[Link]");
DataInputStream dis=new DataInputStream(fis);
[Link]("File Information:");
String line=null;
do
{
line=[Link]();//It reads a line and stores in RAM
[Link](line);
}
while (line!=null);
[Link]();
}
}
O/P:-
File Information:
Bunny
Chinni
Munni
BufferedInputStream and BufferedOutputStream:- In FileInputStream and FileOutputStream, the data
read as character by character and stores the data character by character. So, it decreases program
execution speed. To overcome this problem the programmer should use high level streams. They are
BufferedInputStream and BufferedOutputStream. It stores the data in temporary memory and it flush all
the data from buffer to file at once
flush():- It can flush all the characters from buffer to File at once.
Program:- To copy the data from one File to another File
import [Link].*;
class IOEx7
{
public static void main(String[] args) throws IOException
{
FileInputStream fis=new FileInputStream("[Link]");
BufferedInputStream bis=new BufferedInputStream(fis);
FileOutputStream fos=new FileOutputStream("[Link]");
BufferedOutputStream bos=new BufferedOutputStream(fos);
int x=0;
do
{
x=[Link]();
[Link](x);
}
while (x!=-1);
[Link]();
[Link]("File has been copied");
[Link]();
[Link]();
}
}
O/P:- File has been copied
Character Stream Classes:- It ends with writer and Reader. Writer is used for output operation and
Reader is used for Input operations.
1. Writer
1.1. BufferedWiter
1.2. CharArrayWriter
1.3. OutputStreamReader(FileWriter)
1.4. FilterWriter
1.5. PipedWriter
1.6. StringWriter
2. Reader
2.1. BufferedReader
2.2. CharArrayReader
2.3. InputStreamReader(FileReader)
2.4. FilterReader
2.5. PipedReader
2.6. StringReader
Program by using Character Stream Classes:-
import [Link].*;
class IOEx8
{
public static void main(String[] args) throws IOException
{
InputStreamReader isr=new InputStreamReader([Link]);
BufferedReader br=new BufferedReader(isr);
[Link]("Enter First value:");
int a=[Link]([Link]());
[Link]("Enter Second value:");
int b=[Link]([Link]());
int c=a+b;
[Link]("Result="+c);
}
}
O/P:-
Enter First value:
23
Enter Second value:
45
Result=68
Program to copy the information from one file to another by using Character Stream classes:-
import [Link].*;
class IOEx9
{
public static void main(String[] args) throws IOException
{
InputStreamReader isr=new InputStreamReader([Link]);
BufferedReader br=new BufferedReader(isr);
[Link]("Enter Source File name:");
String sfn=[Link]();
[Link]("Enter Target File name:");
String tfn=[Link]();
FileReader fr=null;
FileWriter fw=null;
try
{
fr=new FileReader(sfn);
fw=new FileWriter(tfn);
int x=0;
do
{
x=[Link]();
[Link](x);
}
while (x!=-1);
}
catch (FileNotFoundException k)
{
[Link]([Link]());
[Link](1);
}
finally
{
[Link]();
[Link]();
}
[Link]("File Has been Copied");
}
}
O/P:-
Enter Source File name:
[Link]
Enter Target File name:
[Link]
File Has been Copied
Searialization:- It is a process to store object information in a file(Recordwise data). The programmer
should implement Serializable interface for serialization . It is a Tagged/Marker interface,
ObjectOutputStream:- It is predefined class used to store Object type of information into the file by
using writeObject()
ObjectInputStream:- It is predefined class used to read Object type of information in a file by using
readObject() (desearilization)
transient:- It is a keyword which makes a variable not to involve in Searilization process.
Program:-
import [Link].*;
class Emp implements Serializable
{
int code;
String name;
double sal;
void get(int c,String n,double s)
{
code=c;
name=n;
sal=s;
}
void put()
{
[Link]("Code="+code+" Name="+name+" Salary="+sal);
}
}
class IOEx10
{
public static void main(String[] args) throws IOException
{
FileOutputStream fos=new FileOutputStream("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(fos);
Emp e1,e2,e3;
e1=new Emp();
e2=new Emp();
e3=new Emp();
[Link](111,"Raghu",65000);
[Link](222,"Ravi",75000);
[Link](333,"Raji",55000);
[Link](e1);
[Link](e2);
[Link](e3);
FileInputStream fis=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(fis);
try
{
Emp e=null;
while((e=(Emp)[Link]())!=null)
[Link]();
}
catch (Exception k)
{
}
}
}
O/P:-
Code=111 Name=Raghu Salary=65000.0
Code=222 Name=Ravi Salary=75000.0
Code=333 Name=Raji Salary=55000.0
RandomAccessFile class:- This in-built class is used to access the data randomly (from required position)
by using seek().
seek():- It is used to change the file pointer from one place to another place directly.
Syn:- [Link](index);
writeUTF():- UTF stands from Unicode Transformation Format. This method is used to store string type
of data.
readUTF():-This method is used to read string type of data.
Program:-
import [Link].*;
class RAFDemo
{
public static void main(String[] args) throws IOException
{
RandomAccessFile raf = new RandomAccessFile("[Link]", "rw");
[Link]("Some students are stupids");
[Link](0);
[Link]([Link]());
[Link](19);
[Link]("Gems!!!");
[Link](0);
[Link]([Link]());
}
}
O/P:-
Some students are stupids
Some students are Gems!!!
Generic Concept :- It allows to store specified type only. Hence it leads type safety.
Program:-
import [Link].*;
class ALEx
{
public static void main(String[] args)
{
ArrayList <String>l=new ArrayList<>(); //diamond operator
[Link]("Shiva");
[Link]("Raghava");
[Link]("Geetha");
[Link](l);
}
}
O/P: [Shiva, Raghava, Geetha]
Program by using Enumeration class:-
import [Link].*;
class EEx
{
public static void main(String[] args)
{
Vector <String>l=new Vector<>();
[Link]("Raghu");
[Link]("Mahesh");
[Link]("Bhanu");
Enumeration i=[Link]();
while([Link]())
[Link]([Link]());
}
}
O/P:-
Raghu
Mahesh
Bhanu
Autoboxing & Autounboxing
Premitive type converts into Object type automatically is called Autoboxing. Object type
converts into primitive type automatically is called Autounboxing. It is introduced in java 1.7 version.
Program:-
class Demo
{
public static void main(String[] args)
{
int x=10;
Integer obj;
obj=x; //autoboxing
[Link](obj);
Integer k=new Integer(10);
int y=k; //autounboxing
[Link](y);
}
}