0% found this document useful (0 votes)
3 views21 pages

Java Unit2 Complete Notes

The document provides an overview of Java packages, including user-defined and predefined packages, their creation, and usage. It explains the concept of classpath, access control, and how to use package classes and interfaces in Java programs. Additionally, it covers interfaces, nested interfaces, and input/output streams in Java, detailing methods for reading from and writing to the console and files.

Uploaded by

avanchadeepak96
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)
3 views21 pages

Java Unit2 Complete Notes

The document provides an overview of Java packages, including user-defined and predefined packages, their creation, and usage. It explains the concept of classpath, access control, and how to use package classes and interfaces in Java programs. Additionally, it covers interfaces, nested interfaces, and input/output streams in Java, detailing methods for reading from and writing to the console and files.

Uploaded by

avanchadeepak96
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

PACKAGE:

Def: “A package is a collection of classes, interfaces and sub-packages. A sub-package in turns


divides into classes, interfaces, sub-sub-packages, etc.”

 Learning about JAVA is nothing but learning about various packages. By default one
predefined package is imported for each and every JAVA program and whose name is
[Link].*.
 Whenever we develop any java program, it may contain many number of user defined
classes and user defined interfaces. If we are not using any package name to place user
defined classes and interfaces, JVM will assume its own package called NONAME
package.

In java we have two types of packages they are predefined or built-in or core packages and user
or secondary or custom defined packages.

1. User Defined packages


2. Predefined packages

1. User defined Packages:

A user defined package is one which is developed by java programmers to simplify the task of
the java programmers to keep set of classes, interfaces and sub packages which are
commonly used. Any class or interface is commonly used by many java programmers that class
or interface must be placed in packages.

Whenever we create user defined package statement as a part of java program, we must use
package statement as a first executable statement.

Syntax:
package pack1[.pack2[.pack3……[.packn]…..]];
Here, package is a keyword which is used for creating user defined packages, pack1 represents
upper package and pack2 to packn represents sub packages.

For example:
package p1; statement-1
package p1.p2; statement-2
The statements 1 and 2 are called package statements.
STEPS for developing a PACKAGE:
i. Choose the appropriate package name, the package name must be a JAVA valid variable name
and we showed ensure the package statement must be first executable statement.
ii. Choose the appropriate class name or interface name and whose modifier must be public.
iii. The modifier of Constructors of a class must be public.
iv. The modifier of the methods of class name or interface name must be public.
v. At any point of time we should place either a class or an interface in a package and give the
file name as class name or interface name with extension .java

 Whenever we develop any JAVA program it contains ‘n’ number of classes and
interfaces.
 Each and every class and interface which are developed by the programmer must
belong to a package (according to industry standards). If the programmer is not keeping
the set of classes and interfaces in a package, JVM will assume its own package called
NONAME package.
 NONAME package will exist only for a limited span of time until the program is
completing.

Ex1:
package tp;
public class Test
{
public Test ()
{
[Link] ("TEST - DEFAULT CONSTRUCTOR");
}
public void show ()
{
[Link] ("TEST - SHOW");
}
}

Ex2:
package tp;
public interface ITest
{
void disp ();
}
Syntax for compiling a package:
javac –d . [Link]

For example:
javac –d . [Link]

Here, -d is an option or switch which gives an indication to JVM saying that go to [Link]
program take the package name and that package name is created as directory automatically

CLASSPATH: CLASSPATH is an environment variable which is used by Application ClassLoader


to locate and load the .class files. The CLASSPATH defines the path.

 You need to load a class that is not present in the current directory or any sub-
directories.
 You need to load a class that is not in a location specified by the extensions mechanism.

This raises an important question: How does the Java run-time system know where to look for
packages that you create?

The answer has two parts. First, by default, the Java run-time system uses the current working
directory as its starting point.

Thus, if your package is in the current directory, or a subdirectory of the current directory, it will
be found.

you can specify a directory path or paths by setting the CLASSPATH environmental variable.

c/>:set classpath=”D:/mypackage”;

Access control

The public members can be accessed everywhere.

The private members can be accessed only inside the same class.

The protected members are accessible to every child class (same package or other packages).

The default members are accessible within the same package but not outside the package.
In java, the access modifiers define the accessibility of the class and its members. For example,
private members are accessible within the same class members only. Java has four access
modifiers, and they are default, private, protected, and public.

In java, the package is a container of classes, sub-classes, interfaces, and sub-packages. The
class acts as a container of data and methods. So, the access modifier decides the accessibility
of class members across the different packages.

In java, the accessibility of the members of a class or interface depends on its access specifiers.
The following table provides information about the visibility of both data members and
methods.

How to use PACKAGE CLASSES and INTERFACES in another java program:


In order to refer package classes and interfaces in JAVA we have two approaches,
they are using import statement and using fully qualified name approach.

Using import statement:


Import is a keyword which is used to import either single class or interface or set
of classes and interfaces all at once.

Syntax -1:
Import pack1 [.pack2 [.………[.packn]]].*;

For example:
Import p1.*; ---1
Import p1.p2.*; ---2
Import p1.p2.p3.*; ---3

When statement 1 is executing we can import or we can access all the classes and
interfaces of package p1 only but not its sub packages p2 and p3 classes and
interfaces.
When statement 2 is executing we can import as the classes and interfaces of
package p2 only but not p1 and p3 classes and interfaces.
When statement 3 is executing we can import as the classes and interfaces of
package p3 only but not p1 and p2 classes and interfaces.
Syntax-2:
Import pack1 [.pack2 [.…………[.packn]]].class name/interface name;
For example:
Import p1.c1; ---4
Import p1.p2.c3; ---5
When statement 4 is executing can import c1 class of package p1 only but not
other classes and interfaces of p1 package, p2 package and p3 package.
Write a JAVA program which illustrates the usage of package classes?

Answer:
Import approach:
import [Link];
class PackDemo
{
public static void main (String [] args)
{
Test t1=new Test ();
[Link] ();
}
};
When we compile the above program we get the following error “package tp does
not exist”. To avoid the above error we must set the classpath as., SET CLASSPATH
=%CLASSPATH%;.;

This is the alternate technique for import statement:


p1.c2 o2=new p1.c2 ();
p1.p2.p3.c4 o4=new p1.p2.p3.c4 ();
p1.p2.i3 o3=new p1.p2.p3.c4 ();

Fully qualified approach:


class PackDemo
{
public static void main (String [] args)
{
[Link] t1=new [Link] ();
[Link] ();
}
};

NOTES:
1. Whenever we develop user defined packages, to use the classes and interfaces
of user defined packages in some other program, we must set classpath before
there usage.
2. In order to set the classpath for predefined packages we must use the following
statement: D:\core\set classpath=C: \Program Files\Java\jdk1.5.0\lib\[Link];.;
[[Link] contains all the .class files for the predefined classes which are supplied as a
port of predefined packages by the SUN micro systems.]
Interfaces
Def: An interface is a construct which contains the collection of purely undefined methods or an
interface is a collection of purely abstract methods.

Syntax:
interface <interface name>
{
variable declaration;
method declaration;
}

Example:
interface i1
{
int a;
int b=20;
void f1 ();
void f2 ();
}

Advantages

1. Interfaces are basically used to develop user defined data types.


2. With respect to interfaces we can achieve the concept of multiple inheritances.
3. With interfaces we can achieve the concept of polymorphism, dynamic binding and hence we
can improve the performance of a JAVA program in turns of memory space and execution time.

Interface name represent a JAVA valid variable name and it is treated as name of the interface.
With respect to interface we cannot create an object directly but we can create indirectly.

Whatever the variables we write in the interface, they are by default belongs to:
public static final xxx data_members

All variables must be initialized (otherwise it will be compilation error). Method declaration
represents the type of methods we use as a part of interface. All the methods of interface are
undefined methods and to make those methods as abstract, the JAVA programmer need not to
write a keyword abstract explicitly before the declaration of interface method.
Since all the methods of interface are meant for general purpose hence they must give
universal access. To make it as universal access the JAVA programmer need not to write a
keyword public explicitly before the method declaration. Hence, by default all the methods of
interfaces belong to public abstract methods.

we compile an interface, we get <interface name>.class as an intermediate file, if no errors are


present in interface.
[abstract] class <clsname> implements <intf 1>,<intf 2>.........<intf n>
{
variable declaration;
method definition or declaration;
};
NOTE: When we inherit ‘n’ number of abstract methods from ‘n’ number of interfaces to the
derived class, if the derived class provides definition for all ‘n’ number of abstract methods then
the derived class is known as concrete class.

i. One class can extend only one class.


ii. One class can implement ‘n’ number of interfaces.
iii. One interface can extends more than one interface.
iv. Interface cannot implements or extends a class. Since defined things cannot be made as
undefined things.

Syntax-2 inheriting ‘n’ number of interfaces to another interface:


interface <intf 0 name> extends <intf 1>,<intf 2>.........<intf n>
{
variable declaration cum initialization;
method declaration;
};

If one interface is taking the features of another interface then that inheritance is known as
interface inheritance

For example:
interface I1
{
int a=10;
void f1 ();
};
interface I2 extends I1
{
int b=20;
void f2 ();
};

Important points:
i. An object of interface cannot be created directly since it contains ‘n’ number of abstract
methods. An object of interface can be created indirectly. An object of interface = an object of
that class which implements that interface.
ii. An object of base interface contains the details about those methods which are declared in
that interface only but it does not contain details about those methods which are specially
available in either in derived classes or in derived interfaces.
iii. Interfaces should not be final.
iv. An interface does not contain Constructors.

Nested Interface: An interface i.e. declared within another interface or class is known as
nested interface.

 Nested interface must be public if it is declared inside the interface but it can have any
access modifier if declared within the class.
 Nested interfaces are declared static implicitly

Syntax Using interfaces Syntax Using classes


interface outer_interface_name class class_name
{ {
Interface inner_interface_name Interface nested_interface_name
{ {
….. ……..
} }
} }
Example program on nested Interfaces
I/O STREAMS

stream: sequence of characters moving from source to the destination.

A stream can represent many different kinds of sources and destinations, including disk files,
devices, other programs, and memory arrays.

Streams support many different kinds of data, including simple bytes, primitive data types,
localized characters, and objects.

STREAM ARE OF 2 TYPES:

1. ByteStream
2. CharacterStream

Byte Streams: Java byte streams are used to perform input and output of 8-bit bytes. Though there are
many classes related to byte streams but the most frequently used classes are , FileInputStream and
FileOutputStream.

Prepared by Dayakar Gurram (AVN Institute Of Engineering & Technology)


Character Streams: Java Byte streams are used to perform input and output of 8-bit bytes, where as
Java Character streams are used to perform input and output for 16-bit unicode. Though there are many
classes related to character streams but the most frequently used classes are , FileReader and
FileWriter.. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
here major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a
time.

Reading Input from Console: There are 3 ways to read the input from the console

1. Using Buffered Reader Class


2. Using Scanner Class
3. Using Console Class

1. Using Buffered Reader Class: This method is used by wrapping the [Link] (standard input stream)
in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the
command line.

The input is buffered for efficient reading. The wrapping code is hard to remember.

// Enter data using BufferReader


BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));

// Reading data using readLine


String name = [Link]();

// Printing the read line


[Link](name);

2. Using Scanner Class: This is probably the most preferred method to take input. The main purpose of
the Scanner class is to parse primitive types and strings using regular expressions,

Prepared by Dayakar Gurram (AVN Institute Of Engineering & Technology)


Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
Regular expressions can be used to find tokens. The reading methods are not synchronized.

Scanner in = new Scanner([Link]);

String s = [Link]();
[Link]("You entered string " + s);

int a = [Link]();
[Link]("You entered integer " + a);

float b = [Link]();
[Link]("You entered float " + b);

3. Using Console Class: It has been becoming a preferred way for reading user’s input from the
command line. In addition, it can be used for reading password-like input without echoing the
characters entered by the user.

Advantages:

 Reading password without echoing the entered characters.


 Reading methods are synchronized.
 Format string syntax can be used.
 Does not work in non-interactive environment (such as in an IDE).

String name = [Link]().readLine();


[Link]("You entered string " + name);

Writing Console: Writing Console Output in Java refers to writing the output of a Java program to the
console or any particular file. The methods used for streaming output are defined in the PrintStream
class.

Both print() and println() methods are used to direct the output to the console.

These methods are defined in the PrintStream class and are widely used Both these methods are used
with the help of the [Link] stream.

print() method displays the string in the same line whereas println() method outputs a newline
character after its execution.

print() method is used for directing output to console only whereas println() method is used for
directing output to not only console but other sources also.

write() method

Alternatively, you can make use of the write() method for directing the output of your program to the
console.

The easiest syntax: void write(int b);

Prepared by Dayakar Gurram (AVN Institute Of Engineering & Technology)


[Link]();
[Link]();
[Link]();
Where System is a class out is a static type reference variable of PrintStream class println() is a method
of PrintStream class.

File Class: The File class is an abstract representation of file and directory pathname. The File class have
several methods for working with directories and files such as creating new directories or files, deleting
and renaming directories or files, listing the contents of a directory etc.

Constructors
File(File parent, String child) It creates a new File instance from a parent abstract pathname and a child
pathname string.
File(String pathname) It creates a new File instance by converting the given pathname string into an
abstract pathname.
File(String parent, String child) It creates a new File instance from a parent pathname string and a child
pathname string.

Methods:
createNewFile() It atomically creates a new, empty file named by this abstract pathname if and only if a
file with this name does not yet exist.
isFile() It tests whether the file denoted by this abstract pathname is a normal file.
isDirectory() It tests whether the file denoted by this abstract pathname is a directory.
getName() It returns the name of the file or directory denoted by this abstract pathname.
list() It returns an array of strings naming the files and directories in the directory
listFiles() It returns an array of abstract pathnames denoting the files in the directory

Prepared by Dayakar Gurram (AVN Institute Of Engineering & Technology)


FileWriter: It is used to write char streams to a file.
Constructors:
FileWriter("Filename")
FileWriter(file File);
FileWriter("Filename",boolean append);
FileWriter(file File,boolean append);

Methods:
write(int ch) to write a single character to a file
write(char[] ch) to write an array of characters into the file.
write(String s) to write the string into a file.
flush() it gives the guarentee that last charcter will be written into the file
close() to close the file.

FileReader: File reader is used to read char by char from the file.
Constructors:
FileReader("Filename")
FileReader(File pointer)

methods:
read() reads the next char from the file / no char then returns -1
read(char[] ch) reads an array of char's at a time from the file.
close() to close the file

Prepared by Dayakar Gurram (AVN Institute Of Engineering & Technology)


Random Access Files: When we preform file operation in any location of file it is called random access of
file. RAF is a byte oriented [Link] reads or write internally in the form of byte.

Constructor of RAF is defined to accept 2 arguments.

1. RandomAccessFile(String fileName,String fileMode);


i. Name of the file - A string class object.
ii. Mode: specified whether the file has to be opended in the read mode ("r") or write mode ("rw");
RAF class supports all the functionalities using which we can read or write data from or into a
file in the form of their premitive types.

2. RandomAccessFile(File f,String fileMode);


File f: File obj needs to be created using File class
ii. Mode: specified whether the file has to be opended in the read mode ("r") or write mode ("rw");
RAF class supports all the functionalities using which we can read or write data from or into a
file in the form of their premitive types.

Functions:
1. length() --> returns length of a file
2. seek(long pos) --> moves the cursor to the given location of file.
3. getFilePointer() --> returns the location of cursor.
4. write(int b) --> writes the specified byte into file.
5. writeFloat(float v) --> write float in file after converting into byte.
6. writeUTF(String s) --> write string in file after converting into byte.
7. readInt() --> read data from a file after converting into integer.
8. readUTF() --> read data from a file after converting into string
9. readFloat() --> read data from a file after converting into float.
10. read()(byte[] b,int offset,int length)  read the file from the specified location.
b--buffer to read
offset --> starting position to read
length --> max no of bytes to read

Serialization: The process of saving the state of an object into a file is called serialization.

Prepared by Dayakar Gurram (AVN Institute Of Engineering & Technology)


 It is a process of converting java supported form to file/network supported form.
 We can serialize only serializable objects.
 An Object is said to be serializable and Only if Corresponding class implements serializable
interface.
 Serializable interface present in [Link] package and it doesn’t contain any methods. It is a
marker Interface.
 If we are trying to serialize Non Serializable Object then we will get Runtime Exception saying
NotSerializableException.

transient: (modifier)

 It is applicable only for variables.


 At the time of serialization if we don’t want to save the value of a particular variable to meet
security constraints
 At the time of serialization JVM Ignores Original value of a transient variable and saves the
default value to the file.
 Transient means not to serialize.
 Declaring static variable as transient there is no use because static variable will work in class
level not in object level.
 If final variable is declared as transient then there is no use no effect because it takes value
form.

Example program on serialization

Prepared by Dayakar Gurram (AVN Institute Of Engineering & Technology)


Enumerations: An enumeration is a list of named constants. Introduced in JDK 1.5 Version.
An enumeration is created using the enum keyword. a Java enumeration is a class type you can give
them constructors, add instance variables and methods, and even implement interfaces. each
enumeration constant is an object of its enumeration type.

enum Month
{
JAN,FEB,MARCH,APRIL,MAY,JUNE,JULY,AUG,SEPT,NOV,DEC;
}

each is implicitly declared as a public, static final member of month.


Jan,Feb… are called enumuration constants.
Enumaration variables are defined Month m1,m2;
Here the values are assigned m1=[Link];

enum's are also used with switch if-else e.t.c…

Ex:

Prepared by Dayakar Gurram (AVN Institute Of Engineering & Technology)


Ex2: Enumaration with classes concept

auto boxing: automatic conversion of primitive data types into its equivalent Wrapper type is known
as boxing and opposite operation is known as unboxing.

 Passed as a parameter to a method that expects an object of the corresponding wrapper class.
 Assigned to a variable of the corresponding wrapper class.

int a=20;
Integer a2=new Integer(a); // Boxing
Integer a3=5; //auto Boxing

Unboxing: Converting an object of a wrapper type to its corresponding primitive value is called
unboxing.

 Passed as a parameter to a method that expects a value of the corresponding primitive type.
 Assigned to a variable of the corresponding primitive type.

Integer i=new Integer(50);


int a=i; //auto unboxing

Generics: Generics in Java enable you to specify type parameters When defining classes, interfaces
and methods. Here class parameter is the type of data (class or interface) which these classes, interfaces
and methods will operate upon.

Prepared by Dayakar Gurram (AVN Institute Of Engineering & Technology)


Benefits of Generics in Java
1. stronger type checking at compile time.
2. casting is not required
3. Enabling programmers to implement generic algorithms

List<T> means that a list which will store elements of type T, T is the type parameter

By convention generic type parameter names are single upper case letter.
Class templates:
class name<T1,T2,....Tn>
{
....
}
Function templates:
returntype <T> method(T args)
{
….
}

Example program on Class templates

Example program on function templates

Prepared by Dayakar Gurram (AVN Institute Of Engineering & Technology)


File copy program:

****

Prepared by Dayakar Gurram (AVN Institute Of Engineering & Technology)

You might also like