Unit Ii Java-1
Unit Ii Java-1
Defining a Package:
A package is a collection of classes and interfaces. To create packages simply
include a package command as the first statement in a Java source file.
Types of packages:
There are two different types of packages in Java. They are:
1. Built-in packages
2. User defined packages
Built-in packages: These are the packages which are already available in Java
language. These packages provide all most all necessary classes, interfaces and
methods for programmer to perform any task in his programs.
Ex: java.lang, java.io, java.util etc.
User-defined packages:
These are defined by the users
The general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement
creates a package called MyPackage:
package MyPackage;
The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
Importing Packages:
Java includes the import statement to bring certain classes, or entire packages,
into visibility.
The general form of the import statement:
import pkg1 [.pkg2].(classname | *);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a
subordinate package inside the outer package separated by a dot (.).Finally,
you specify either an explicit classname or a star (*), which indicates that the
Java compiler should import the entire package.
Example:
C:\VAAGESWARI>md pack1
C:\VAAGESWARI>cd pack1
C:\VAAGESWARI\pack1>edit a.java
package pack1;
public class a
{
public void add(int x, int y)
{
System.out.println("Addition of two numbers is "+(x+y));
}
}
C:\VAAGESWARI\pack1>javac a.java
C:\VAAGESWARI\pack1>cd..
import pack1.*;
class packdemo
{
public static void main(String args[])
{
a a1=new a(); // a is package class name
a1.add(10,20);
}
}
Step4: Now open the command prompt and issue the following commands in
order to run the package programs
C:\VAAGESWARI>javac packdemo.java
C:\VAAGESWARI>java packdemo
Output:-
Suppose our program is running in c:\ and the package pack is available in the
directory d:\sub. In this case, the compiler should be given information
regarding the package location by mentioning the directory name of the
package in class path.
The class path is an environment variable that tells the JAVA compiler where
to look for class files to import. CLASSPATH is generally set to a directory or a
JAR(Java Archive) file.
In the preceding command, we are setting the class path to sub directory and
current directory(.). And then we typed %CLASSPATH% which means retain the
already available class path as it is. This is necessary especially when the class
path in your system is already set to an important application that should not
disturbed
Access protection
1. private
2. public
3. protected
4. default
1. Private members of a class are not accessible in other classes of
same package or another package
2. Public members of a class are available in other classes of same
package or another package.
3. Protected members are available to classes in the same package;
they are not available in other packages.
4. Default members are available to the classes in the same package
but not in other packages.
Defining an Interface
Interface declaration is same as class except that it consists of the methods
that are declared have no method body.
When no access modifier is included, then default access results, and the
interface is only available to other members of the package in which it is
declared. When it is declared as public, the interface can be used by any other
code. In this case, the interface must be the only public interface declared in
the file, and the file must have the same name as the interface. name is the
name of the interface, and can be any valid identifier. Notice that the methods
that are declared have no bodies. They end with a semicolon after the
parameter list. They are, essentially, abstract methods. Each class that
includes such an interface must implement all of the methods.
Example:
interface i1
{
void add(int a,int b);
}
Implementing Interfaces
Once an interface has been defined, one or more classes can implement that
interface. To implement an interface, include the implements clause in a class
definition, and then create the methods required by the interface.
The general form of a class that includes the implements clause looks like this:
If a class implements more than one interface, the interfaces are separated
with a comma. If a class implements two interfaces that declare the same
method, then the same method will be used by clients of either interface. The
methods that implement an interface must be declared public. Also, the type
signature of the implementing method must match exactly the type signature
specified in the interface definition.
Example:
Output:
C:\>javac IDemo.java
C:\>java IDemo
Welcome to Interface
C:\>java MultipleInheritance
welcome to csea
welcome to cseb
welcome to csec
Nested interfaces
Example:
interface i1
{
public void display();
interface i2
{
public void show();
}
}
class abc implements i1
{
public void display()
{
System.out.println("welcome to csea");
}
public void show()
{
System.out.println("welcome to cseb");
}
}
public class NIDemo
{
public static void main(String[] args)
{
abc a=new abc();
a.display();
a.show();
}
}
Output:
C:\>javac NIDemo.java
C:\>java NIDemo
welcome to csea
welcome to cseb
Applying Interfaces
The interface is powerful tool. The same interface can be used by different
classes for some method. Then this method can be implemented by each class
in its own way. Thus same interface can provide variety of implementations.
The selection of different implementations is done at the runtime.
Example:
interface i1
{
public void calc(int a,int b);
}
class abc implements i1
{
public void calc(int a,int b)
{
System.out.println("sum is"+(a+b));
}
}
class xyz implements i1
{
public void calc(int a,int b)
{
System.out.println("sub is"+(a-b));
}
}
class AIDemo
{
public static void main(String[] args)
{
i1 inter;
abc ob1=new abc();
inter=ob1;
inter.calc(10,3);
xyz ob2=new xyz();
inter=ob2;
inter.calc(12,8);
}
}
Output:
C:\>javac AIDemo.java
C:\>java AIDemo
sum is13
sub is4
Variables in Interfaces
The variable in an interface is public, static, and final by default.
The class that implements an interface cannot modify the interface variable,
but it may use as it defined in the interface.
interface i2
{
public void display();
final int balance=1000;
}
class abc implements i2
{
public void display()
{
if(balance>=1000)
{
System.out.println("you are allowed to do the transaction");
}
else
{
System.out.println("you are not allowed");
}
}
}
class VDemo
{
public static void main(String[] args)
{
abc a=new abc();
a.display();
}
}
Interfaces Can Be Extended
One interface can inherit another by use of the keyword extends. The syntax is
the same as for inheriting classes. When a class implements an interface that
inherits another interface, it must provide implementations for all methods
required by the interface inheritance chain.
Example:
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
class MyClass implements B
{
public void meth1()
{
System.out.println("welcome to meth1");
}
public void meth2()
{
System.out.println("welcome to meth2");
}
public void meth3()
{
System.out.println("welcome to meth3");
}
}
class INExtend
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Output:
C:\>javac INExtend.java
C:\>java INExtend
welcome to meth1
welcome to meth2
welcome to meth3
Differences between Abstract class and Interface
The output object that writes the streams of data to a file is called output
stream.
try
{
out.write(msg);
System.out.println("Writing done!!!");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
out.close();
}
}
}
File class
The File is a built-in class in Java. In java, the File class has been defined in
the java.io package. The File class represents a reference to a file or directory.
The File class has various methods to perform operations like creating a file or
directory, reading from a file, updating file content, and deleting a file or
directory.
The File class in java has the following constructors.
S.No. Constructor with Description
1 File(String pathname)
It creates a new File instance by converting the givenpathname string
into an abstract pathname. If the given string isthe empty string, then
the result is the empty abstract pathname.
4 File(URI uri)
It creates a new File instance by converting the given file: URI into an
abstract pathname.
The File class in java has the following methods.
S.No. Methods with Description
1 String getName()
It returns the name of the file or directory that referenced by the current
File object.
2 String getParent()
It returns the pathname of the pathname's parent, or null if the
pathname does not name a parent directory.
3 String getPath()
It returns the path of curent File.
4 File getParentFile()
It returns the path of the current file's parent; or null if it does not exist.
5 String getAbsolutePath()
It returns the current file or directory path from the root.
6 boolean isAbsolute()
It returns true if the current file is absolute, false otherwise.
7 boolean isDirectory()
It returns true, if the current file is a directory; otherwise returns false.
8 boolean isFile()
It returns true, if the current file is a file; otherwise returns false.
9 boolean exists()
It returns true if the current file or directory exist; otherwise returns
false.
10 boolean canRead()
It returns true if and only if the file specified exists and can be read by
the application; false otherwise.
11 boolean canWrite()
It returns true if and only if the file specified exists and the application is
allowed to write to the file; false otherwise.
12 long length()
It returns the length of the current file.
13 long lastModified()
It returns the time that specifies the file was last modified.
S.No. Methods with Description
14 boolean createNewFile()
It returns true if the named file does not exist and was successfully
created; false if the named file already exists.
15 boolean delete()
It deletes the file or directory. And returns true if and only if the file or
directory is successfully deleted; false otherwise.
16 void deleteOnExit()
It sends a requests that the file or directory needs be deleted when the
virtual machine terminates.
17 boolean mkdir()
It returns true if and only if the directory was created; false otherwise.
18 boolean mkdirs()
It returns true if and only if the directory was created, along with all
necessary parent directories; false otherwise.
21 boolean setReadOnly()
It sets the file permission to only read operations; Returns true if and
only if the operation succeeded; false otherwise.
22 String[] list()
It returns an array of strings containing names of all the files and
directories in the current directory.
24 File[] listFiles()
It returns an array of file references containing names of all the files and
directories in the current directory.
S.No. Methods with Description
Example:
import java.io.*;
public class FileClassTest
{
public static void main(String args[])
{
File f = new File("C:\\CSE\\datFile.txt");
System.out.println("Executable File : " + f.canExecute());
System.out.println("Name of the file : " + f.getName());
System.out.println("Path of the file : " + f.getAbsolutePath());
System.out.println("Parent name : " + f.getParent());
System.out.println("Write mode : " + f.canWrite());
System.out.println("Read mode : " + f.canRead());
System.out.println("Existance : " + f.exists());
System.out.println("Last Modified : " + f.lastModified());
System.out.println("Length : " + f.length());
}
}
Output:
In java, there multiple ways to read data from a file and to write data to a file.
The most commonly used ways are as follows.
Using Byte Stream (FileInputStream and FileOutputStream)
Using Character Stream (FileReader and FileWriter)
try
{
in = new FileInputStream("C:\\CSE\\Input-File.txt");
out = new FileOutputStream("C:\\CSE\\Output-File.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
System.out.println("Reading and Writing has been success!!!");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
try
{
in = new FileReader("C:\\CSE\\Input-File.txt");
out = new FileWriter("C:\\CSE\\Output-File.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
System.out.println("Reading and Writing in a file is done!!!");
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
Access Modes
Using the RandomAccessFile, a file may created in th following modes.
r – Creates the file with read mode; Calling write methods will result in
an IOException.
rw – Creates the file with read and write mode.
rwd – Creates the file with read and write mode – synchronously. All
updates to file content is written to the disk synchronously.
rws – Creates the file with read and write mode – synchronously. All
updates to file content or meta data is written to the disk synchronously.
RandomAccessFile methods
The RandomAccessFile class in java has the following methods.
1 int read()
It reads byte of data from a file. The byte is returned as an integer in
the range 0-255.
2 int read(byte[] b)
It reads byte of data from file upto b.length, -1 if end of file is reached.
4 23nitial readBoolean()
It reads a 23nitial value from from the file.
S.No. Methods with Description
5 byte readByte()
It reads signed eight-bit value from file.
6 char readChar()
It reads a character value from file.
7 double readDouble()
It reads a double value from file.
8 float readFloat()
It reads a float value from file.
9 long readLong()
It reads a long value from file.
10 int 24nitial()
It reads a integer value from file.
11 void readFully(byte[] b)
It reads bytes 24nitializing from offset position upto b.length from the
buffer.
13 String readUTF()
t reads in a string from the file.
15 long length()
It returns the length of the file.
S.No. Methods with Description
16 void write(int b)
It writes the specified byte to the file from the current cursor position.
17 void writeFloat(float v)
It converts the float argument to an int using the floatToIntBits method
in class Float, and then writes that int value to the file as a four-byte
quantity, high byte first.
18 void writeDouble(double v)
It converts the double argument to a long using the doubleToLongBits
method in class Double, and then writes that long value to the file as an
eight-byte quantity, high byte first.
Example:
import java.io.*;
public class RandomAccessFileDemo
{
public static void main(String[] args)
{
try
{
double d = 1.5;
float f = 14.56f;
// Writing to file
f_ref.writeUTF("Hello, Good Morning!");
// read() method :
System.out.println("Use of read() method : " + f_ref.read());
f_ref.seek(0);
byte[] b = {1, 2, 3};
// readBoolean() method :
System.out.println("Use of readBoolean() : " + f_ref.readBoolean());
// readByte() method :
System.out.println("Use of readByte() : " + f_ref.readByte());
f_ref.writeChar('c');
f_ref.seek(0);
// readChar() :
System.out.println("Use of readChar() : " + f_ref.readChar());
f_ref.seek(0);
f_ref.writeDouble(d);
f_ref.seek(0);
// read double
System.out.println("Use of readDouble() : " + f_ref.readDouble());
f_ref.seek(0);
f_ref.writeFloat(f);
f_ref.seek(0);
// readFloat() :
System.out.println("Use of readFloat() : " + f_ref.readFloat());
f_ref.seek(0);
// Create array upto geek.length
byte[] arr = new byte[(int) f_ref.length()];
// readFully() :
f_ref.readFully(arr);
f_ref.seek(0);
Console class
The Java Console class is be used to get input from console. It provides
methods to read texts and passwords. If you read password using Console
class, it will not be displayed to the user.
Methods:
String readLine() It is used to read a single line of text from the console.
char[] readPassword() It is used to read password that is not being displayed
on the console.
Ex:
import java.io.*;
class ReadStringTest
{
public static void main(String args[])
{
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
Output:
Enter your name: VAAGESWARI
Welcome VAAGESWARI
Ex2:
import java.io.Console;
class ReadPasswordTest
{
public static void main(String args[])
{
Console c=System.console();
System.out.println("Enter password: ");
char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string
System.out.println("Password is: "+pass);
}
}
Output:
Enter password:
Password is: 123
Serialization
The process of saving an object to a file (or) the process of sending an object
across the network is called serialization. But strictly speaking the process of
converting the object from java supported form to the network supported form
of file supported form.
To do the serialization we required fallowing classes
1. FileOutputStream
2. ObjectOutputStream
Deserialization:-
The process of reading the object from file supported form or network
supported form to the java supported form is called deserialization.
We can achieve the deserialization by using fallowing classes.
1. FileInputStream
2. ObjectInputStream
Ex:-Student.java
import java.io.Serializable;
public class Student implements Serializable
{
int id;
String name;
int marks;
public Student(int id, String name,int marks)
{
this.id = id;
this.name = name;
this.marks=marks;
}
}
To perform serialization :- we are writing the object data to the file called
abc.txt file we are transferring that file across the network.
import java.io.*;
class Serializable1
{
public static void main(String args[])throws Exception
{
Student s1 =new Student(211,"ravi",100);
FileOutputStream fos=new FileOutputStream("abc.txt",true);
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(s1);
oos.flush();
System.out.println("Serializable process success");
}
}
Enumerations:
An enum is a data type which contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH,
SOUTH, EAST and WEST) etc.
The enum constants are static and final implicitely. It is available from Java 5.
Points to remember for Enum:
enum improves type safety
enum can be easily used in switch
enum can have fields, constructors and methods
enum may implement many interfaces but cannot extend any class because it
internally extends Enum class