0% found this document useful (0 votes)
14 views10 pages

Unit 4 Merged

Uploaded by

Vignana Deepthi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views10 pages

Unit 4 Merged

Uploaded by

Vignana Deepthi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Packages

Definition:
Packages are the containers for grouping a collection of classes together. Using packages we can
achieve the following
Advantages:
1. Classes in the packages can be easily reused by other programs.
2. Packages provide a way of hiding classes.
3. Two classes with two different packages can have the same name.
4. Packages provide a way for separating design and coding.
5. The classes contained in the packages of other programs can be easily reused.
Different types of packages:
Java packages are classified into two types.
1. Built-In Package / Java API (Application Programming Interface) Packages.
2. User Defined Packages.
1. Built-In Package / Java API (Application Programming Interface) Packages:
Java Provides a large number of classes grouped in different packages. According to the
functionality the frequently used packages in java are
java

lang net util io awt Applet sql

• java.lang: This package contains language support classes. It includes classes like String,
Math, Thread etc.,
• java.util: This package contains language utility classes. Such as Vectors, Has Tables etc.
• java.io: This package contains classes which support input / output of data.
• java.awt: This package contains classes which are used for implementing the Graphical
User Interface (GUI) in Java.
• java.net: This package contains classes which are used for networking. Used for
communication between interconnected local computers as well as with internet servers.
• java.Applet: This package contains classes for creating and implementing Applets.
• java.sql: This package contains classes for implementing database connectivity.
(II). User Defined Package:
Just like built-in packages we can create our own packages in java, they are called as user
defined packages. These packages can also be imported into other classes and can be used in the same
way as the built-in packages.

(1). Creating Packages:


Following are the steps to be considered while creating our own packages.

1
1. Create a sub directory under the root directory
2. Define the class, at the beginning of the class write “package” statement as follows.
package packagename;
3. The defining class must be declared as public.
4. Save the file name as “classname.java” in the subdirectory created.
5. Compile the file which creates “dot class file” in the subdirectory.

We can add multiple interfaces and classes with a single source file or individual files. We can
define packages and sub packages using single package statement.
Example: package FirstPackage; // Package Declarations.
public class FirstClass // Class definition.
{
.............
.............
Body of Class;
.............
.............
}
Here Package name is “FirstPackage‟ the class name is “FirstClass‟ which is a part of this
package. This class will be saved as “Firstclass.java”, and must be saved in the directory named
“firstPackage”(package name). When a source file is compiled, Java created a “dot class file” and store
in the same package.
(2). Accessing a Package and Sub-Packages:
Java packages can be accessed either using a fully qualified name or using shortcut method using
the “import” statement.
Syntax:
import package 1 [.package 2] [.package 3].class name;

Here “package 1” is the name of the top level package, “package 2” is the name of the package
that is inside the “package 1” and so on. We can have any number of packages in a package hierarchy.
Finally, the class name is specified with semicolon.
The import statement should appear before any class definitions in a source file. Multiple import
statements are allowed. The following is an example of importing a particular class:
The fully qualified name of a class or interface contains its package and sub-package names
separated with dot ( . ) operator and with the class or interface name at the end. The general form of
import statement for searching a class is as follows:

import firstPackage .secondPackage.MyClass;

After defining this statement, all the members of the class „MyClass‟ can be directly accessed
using the class name or its objects directly without using the package name. We can also use another

2
approach as follows:
import packagename.*;
Here, packagename is the name of the packages. The asterisk ( * ) indicates that the complier
should access all classes contained in the above package directly. let us consider a simple program the
below example shows the packages name p1 containing a single class 'A'
eg.,
package p1;
public class A
{
public void display()
{
System.out.println("Iam display() from class A of Package P1");
}
}
The source file should be names as "A.java" and it is stored in the package A. Now compile the
java file, the resultant class file "A.class" will be stored in the same package. Now consider the below
example
import p1.A;
public class Test
{
public static void main(String args[])
{
A a=new A();
a.display();
}
}
The above program imports the Class A from package P1, the source code must be saved as
Test.java and then compile the file.
During the compilation process the compiler checks for the file "A.class" in the package P1 for
the information it needs

Creating Subpackage in a package:


package Dream.tech;
public class Simple
{
public void show()
{
System.out.println("Iam show() from class simple");
}

3
}
To create a directory "tech" in the Dream folder or directory compile the above class in the
following way
javac -d . Simple.java
After the compilation we can see the "Simple.class" file is created in the tech directory now we
can use the above class simple in the following class
import Dream.tech.Simple;
public class Use
{
public static void main(String args[])
{
Simple S=new Simple();
S.show();
}
}
When the above program is compiled the java compiler creates a sub directory with the name
"Dream". Inside this there would be another sub directory with the name "tech" is created. In this tech
directory "Simple.class" file is stored.
Suppose if the user wants to use the simple class of "Dream.tech" package then the user has to
write the following import statement
import Dream.tech.Simple;

4
Streams in Java.
Stream: A stream represents flow of data from one place to another place. It is like a water- pipe
where water flows. Like a water-pipe carries water from one place to another, a stream carries data from
one place to another place. A stream can carry data from keyboard to memory or from memory to printer
or from memory to a file. A stream is always required if we want to move data from one place to another.
java.io (input and output) package contains a lot of classes, all of which can be classified into two
basic categories: input streams and output streams.
When we write System.in, we are representing a standard input device, i.e., keyboard, by default.
System class is found in java.lang (language) package and has three fields as shown below. All these
fields represent some type of stream:
1. System.in ; This represents Input Stream object, which by default represents standard input device,
i.e., keyboard.
2. System.out : This represents PrintStream object, which by default represents standard output device,
i.e., monitor.
3. System.err : This field also represents PrintStream object, which by default represents monitor.
System.out and System.err both represent the monitor by default and hence can be used to
send data or results to the monitor. But System.out is used to display normal messages and results
whereas System.err is used to display error messages.
Java streams are classified into two basic types, namely Input Stream and Output Stream. An
input stream extracts (reads) data from the source (file) and sends it to the program. Similarly, an output
stream takes data from the program and sends (write) it to the destination (file).

(Q) Explain about Stream Classes?


Java.io package contains a large number of stream classes that provide capabilities for
processing all types of data. These classes may be categorized into two groups based on the type on
data on which they operate.
1. Byte stream classes: This provides support for handling I/O operations on bytes.
2. Character stream classes: This provides support for managing I/O operations on
characters. These two groups may further be classified based on their purpose:

1
(I). Byte stream classes: Byte stream classes have been designed to provide functional features
for creating and manipulating streams and files for reading and writing bytes. Byte stream are defined
by two classes, InputStream and OutputStream.
(a). InputStream Classes: InputStream classes that are used to read 8-bit of bytes, include
a super class known as InputStream and a number of sub-classes for supporting various input
related functions.
(b). OutputStream Classes: OutputStream classes are used to write 8-bit of bytes, these classes
are used for various output related functions.
(II). Character stream classes: Character streams can be used to read and write 16-bit Unicode
character. There are two kinds of characters stream classes namely reader and writer stream classes.
(a). Reader stream classes: Reader stream classes are designed to read character from the files.
Reader class is the base class for all other classes in this group.
(b). Writer stream classes: Writer stream classes are designed to write all output operation
on file. Write class is the base class for all other classes in this group.

(Q) What is File and File Class?


A file is a collection of related records placed in a particular area on the disk. A record is
composed of several fields and field is a group of characters. The console oriented I/O functions,
which always use the terminal (keyboard and monitor) as the target place.
However the console oriented I/O operations poses the following problems:
It is difficult to handle large volumes of data through terminals.
The data is lost either when a variable goes out of scope or when the program is terminated.
We can overcome these problems by storing data on secondary storage devices such as hard disk.
The data is stored in these devices using the concept of files.

2
File Class: The File Class is defined in the package java.io, the file class is used to store the path
and name of a directory or file. The file object can be used to create, rename or delete file or directory.

(Q) Explain how to create a file using FileOutputStream?


FileOutputStream class belongs to byte stream and stores the data in the form of individual bytes.
It can be used to create text files. We have known that a file represents storage of data on a second
storage media like a hard disk or CD.
Steps are to be followed to create a text file that stores some characters (or text):
Step 1: First of all, we should read data from the keyboard. For this purpose, we should attach
the keyboard to some input stream class. The code for using DataInputStream class for reading data
from the keyboard is
DataInputStream dis = new DataInputStream(System.in);
Here, System.in represents the keyword which is linked with DataInputStream object named as dis.
Step 2: Now, attach a file where the data is to be stored to some output stream. FileOutputStream is used
to send data to the file. Attaching of file to the FileOutputStream is done as below
FileOutputStream fout=new FileOutputStream("myfile.txt");
In the above fout represent the FileOutputStream object
Step 3: The next step is to read data from DataInputStream and write it into FileOutputStream. It means
We read data from “dis” object and write into “fout” object
ch = (char) dis, read(); //read one character into char
fout.write(ch); // write ch into file
After performing input or output operations the file must be closed else the data of the file may
be corrupted.
Write a Java program how to create a file using FileOutputStream?
import java.io.*;
class CreateFile
{
public static void main(String args[]) throws IOException
{
DataInputStream dis = new DataInputStream(System.in);
FileOutputStream fout = new
FileOutputStream("myfile.txt");
System.out.println("Enter text Here: (after typed press $ at the end of line);");
char ch;
while((ch=(char)dis.read()) != '$')
fout.write(ch);
fout.close();

3
}
}
Save: CreateFile.java
Compile: javac CreateFile.java
Run: java CreateFile
Output: Enter text Here: (after typed press $ at the end of
line);
This is my first file
This concept is about creating files in java $
C:\ type myfile.txt
This is my first file
This concept is about creating files in java

(Q) Explain about Reading data from a file using FileInputStream?


FileInputStream is useful to read data from a file in the form of sequence of bytes. It is possible
to read data from a text file using FileInputStream. Following are the steps to be followed to read a
data from text file using FileInputStream:
Step 1: First, we should attach the file a FileInputStream as:
FileInputStream fin=new FileInputStream("myfile.txt");
This will enable us to read data from the file. Then, we should read data from the FileInputStream as
ch = fin.read();
The read() method reads all the characters from the file and it reaches the end of the file.
Step 2: For displaying the data, we use System.out which is PrintStream object.
System.out.println(ch);
Step 3: Finally, we read data from the FileInputStream and write it to System.out. This will display
all the file data on the screen

Write a Java program how to Reading data from a file using FileInputStream?

import
java.io.*;
class
ReadFile
{
public static void main(String args[]) throws IOException
{
FileInputStream fin = new FileInputStream("myfile.txt");

4
char ch;
while ((ch = (char)fin.read() ) !=-1)
System.out.print((char)ch);
fin.close();
}
}

Save: ReadFile.java
Compile: javac ReadFile.java
Run: java ReadFile
Output: This is my first file
This concept is about creating files in java

(Q) Explain about FileWriter and FileReader classes?


Or
Explain about writing character to a file and Reading character from a file ?
Java provides two special types of stream called the FileReader and FileWriter to read character
frm and write characters into a file
1. Writing Characters to a file:
We can use FileWriter class to write characters to a file. FileWriter will create the file before
opening it for output when we create the object.
FileWriter fo=new FileWriter(String filename);
Write a Java program to illustrate the FileWriter Class?
import java.io.*;
import java.io.IOException;
import java.io.FileWriter;
public class FileWriterChar
{
public static void main(String args[]) throws IOException
{
try
{
FileWriter fw = new FileWriter("abc.txt");
fw.write("Sri Venkateswara University.");
fw.close();
}
catch (IOException e)

5
{
System.out.println(e);
}
System.out.println("Success");
}
}
Save: FileWriterChar.java
Compile: javac FileWriterChar.java
Run: java FileWriterChar
Output: Success.

2. Reading Characters from a file:


We can use FileReader class to read characters from a file. FileReader object can be created
as below.
FileReader fi=new FileReader(String filename);
program to illustrate the FileReader Class
import java.io.*;
import java.io.IOException;
import java.io.FileWriter;
public class FileReaderChar
{
public static void main(String args[]) throws IOException
{
FileReader fr = new
FileReader("abc.txt"); int i;
while((i=fr.read())!= -1)
System.out.println((char)i);
fr.close();
}
}
Save: FileReaderChar.java
Compile: javac FileReaderChar.java
Run: java FileReaderChar
Output: Sri Venkateswara University.

You might also like