JAVA-2
JAVA-2
Packages in Java
A package is a collection of similar types of classes, interfaces and sub-packages.
Types of packages
Package are classified into two type which are given below.
1. Predefined or built-in package
2. User defined package
Defining a package
To create a package include a package command as the first statement in a Java source file.
Any classes declared within that file will belong to the specified package.
If you omit the package statement, the class names are put into the default package, which
has no name.
Syntax
package packagename;
Example
package mypack;
Explanation: In above syntax "-d" is a specific tool which is tell to java compiler create a
separate folder for the given package in given path. When we give specific path then it create
a new folder at that location and when we use . (dot) then it crate a folder at current working
directory.
Note: Any package program can be compile but can not be execute or run. These program
can be executed through user defined program which are importing package program.
package mypack;
public class A
{
public void show()
{
System.out.println("Sum method");
}
}
Importing Packages
Import above class in below program using import packageName.className
Example
import mypack.A;
public class Hello
{
public static void main(String args[])
{
A a=new A();
a.show();
System.out.println("show() class A");
}
}
Explanation: In the above program first we create Package program which is save with
A.java and compiled by "javac -d . A.java". Again we import class "A" in class Hello
using "import mypack.A;" statement.
Classpath
CLASSPATH can be set by any of the following ways:
• CLASSPATH can be set permanently in the environment: In Windows, choose control
panel ? System ? Advanced ? Environment Variables ? choose “System Variables” (for all
the users) or “User Variables” (only the currently login user) ? choose “Edit” (if
CLASSPATH already exists) or “New” ? Enter “CLASSPATH” as the variable name ? Enter
the required directories and JAR files (separated by semicolons) as the value (e.g.,
“.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar”). Take note that you need to
include the current working directory (denoted by ‘.’) in the CLASSPATH.
To check the current setting of the CLASSPATH, issue the following command:
• > SET CLASSPATH
• CLASSPATH can be set temporarily for that particular CMD shell session by issuing the
following command:
• > SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
• Instead of using the CLASSPATH environment variable, you can also use the command-
line option -classpath or -cp of the javac and java commands, for example,
> java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3
Access protection
Packages act as containers for classes and other subordinate packages. Classes act as
containers for data and code. The class is Java’s smallest unit of abstraction.
Because of the interplay between classes and packages, Java addresses four categories of
visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses.
Let us see how access specifiers are applied here:
• Anything declared public can be accessed from anywhere.
• Anything declared private cannot be seen outside of its class.
• When a member does not have an explicit access specification, it is visible to subclasses
as well as to other classes in the same package. This is the default access.
• If you want to allow an element to be seen outside your current package, but only to
classes that subclass your class directly, then declare that element protected.
Interfaces
Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract
methods in the interface. It is used to achieve fully abstraction and multiple inheritance in
Java.
There properties can be reused commonly There properties commonly usable in any
in a specific application. application of java environment.
The default access specifier of abstract class There default access specifier of interface
methods are default. method are public.
These class properties can be reused in These properties can be reused in any other
other class using extend keyword. class using implements keyword.
Inside abstract class we can take Inside interface we can not take any
constructor. constructor.
For the abstract class there is no restriction For the interface it should be compulsory to
like initialization of variable at the time of initialization of variable at the time of variable
variable declaration. declaration.
There are no any restriction for abstract For the interface method can not declare
class method modifier that means we can method as strictfp, protected, static, native,
use any modifiers. private, final, synchronized.
Defining Interfaces:
The interface keyword is used to declare an interface.
Syntax
interface interface_name
{
declare constant fields
declare methods that abstract
}
Example
interface A
{
Public static final int a = 10;
void display();
}
Implementing Interfaces
A class uses the implements keyword to implement an interface.
Example
interface A
{
Public static final int a = 10;
void display();
}
class B implements A
{
public void display()
{
System.out.println("Hello");
}
}
class InterfaceDemo
{
public static void main (String[] args)
{
A obj= new A();
obj.display();
System.out.println(a);
}
}
Applying Interfaces
To understand the power of interfaces, let’s look at a more practical example.
Here is the interface that defines an integer stack. Put this in a file called IntStack.java.
Example
interface IntStack
{
void push(int item);
int pop();
}
class FixedStack implements IntStack
{
private int stck[];
private int top;
FixedStack(int size)
{
stck = new int[size];
top = -1;
}
public void push(int item)
{
if(top==stck.length-1)
System.out.println("Stack is full.");
else
stck[++top] = item;
}
public int pop()
{
if(top ==-1)
{
System.out.println("Stack underflow.");
return 0;
}
else
return stck[top--];
}
}
class InterfaceTest
{
public static void main(String args[])
{
FixedStack mystack1 = new FixedStack(5);
FixedStack mystack2 = new FixedStack(8);
for(int i=0; i<5; i++)
mystack1.push(i);
for(int i=0; i<8; i++)
mystack2.push(i);
for(int i=0; i<5; i++)
System.out.println(mystack1.pop());
for(int i=0; i<8; i++)
System.out.println(mystack2.pop());
}
}
Variables in interface
Variables can be declared inside of interface declarations. They are implicitly final and static,
meaning they cannot be changed by the implementing class.
You can use interfaces to import shared constants into multiple classes by simply declaring an
interface that contains variables that are initialized to the desired values.
Example
interface SharedConstants
{
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int NEVER = 4;
}
class Question implements SharedConstants
{
BufferedReader br=new BufferedReader(new InputStreamreader(System.in));
int ask()
{
System.out.println(“would u like to have a cup of coffee?)
String ans=br.readLine();
if (ans= =”no”)
return NO;
else if (ans==”yes”)
return YES;
else if (ans==”notnow”)
return LATER;
else
return NEVER;
}
}
class AskMe
{
public static void main(String args[])
{
Question q = new Question();
System.out.println(q.ask());
}
}
Extending interfaces
One interface can inherit another by use of the keyword extends.
When a class implements an interface that inherits another interface, it must provide
implementations for all methods defined within 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("Implement meth1().");
}
public void meth2()
{
System.out.println("Implement meth2().");
}
public void meth3()
{
System.out.println("Implement meth3().");
}
}
class InterfaceDemo
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Nested Interface
• An interface i.e. declared within another interface or class is known as nested interface.
• The nested interfaces are used to group related interfaces so that they can be easy to
maintain.
• The nested interface must be referred by the outer interface or class. It can't be accessed
directly.
• 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 implicitely.
interface Showable
{
void show();
interface Message
{
void msg();
}
}
class TestNestedInterface1 implements Showable.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[])
{
Showable.Message message=new TestNestedInterface1();
message.msg();
}
}
class A
{
interface Message
{
void msg();
}
}
class TestNestedInterface2 implements A.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[])
{
A.Message message=new TestNestedInterface2();
message.msg();
}
}
Stream
In Java, streams are the sequence of data that are read from the source and written to the
destination.
In Java, 3 streams are created for us automatically. All these streams are attached
with the console.
1.System.in: This is the standard input stream that is used to read characters from the
keyboard or any other standard input device.
2.System.out: This is the standard output stream that is used to produce the result of a
program on an output device like the computer screen.
3.System.err: This is the standard error stream that is used to output all the error data that
a program might throw, on a computer screen or any standard output device.
Types of Streams
Depending on the type of operations, streams can be divided into two primary
classes:
InputStream Class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
Subclasses of InputStream
In order to use the functionality of InputStream, we can use its subclasses. Some of them are:
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an output
stream of bytes.
Subclasses of OutputStream
In order to use the functionality of OutputStream, we can use its subclasses. Some of them are:
Methods of OutputStream
The OutputStream class provides different methods that are implemented by its subclasses.
Here are some of the methods:
• write() - writes the specified byte to the output stream
• write(byte[] array) - writes the bytes from the specified array to the output stream
• flush() - forces to write all data present in output stream to the destination
• close() - closes the output stream
2. Character Stream
Character stream is used to read and write a single character of data.
Reader Class
The Reader class of the java.io package is an abstract superclass that represents a stream of
characters.
Methods of Reader
The Reader class provides different methods that are implemented by its subclasses. Here
are some of the commonly used methods:
Subclasses of Writer
Stream class Description
BufferedWriter Handles buffered output stream.
FileWriter Output stream that writes to file.
PrintWriter Output Stream that contain print() and println() method.
Methods of Writer
The Writer class provides different methods that are implemented by its subclasses. Here
are some of the methods:
• write(char[] array) - writes the characters from the specified array to the output
stream
• write(String data) - writes the specified string to the writer
• append(char c) - inserts the specified character to the current writer
• flush() - forces to write all the data present in the writer to the corresponding
destination
• close() - closes the writer
This constructor create an object of Scanner class by talking an object of InputStream class. An
object of InputStream class is called in which is created as a static data member in the System
class.
Syntax of Scanner Class in Java
Scanner sc=new Scanner(System.in);
Here the object 'in' is use the control of keyboard
Example
import java.io.*;
class consoleEg
{
public static void main(String args[])
{
String name;
System.out.println ("Enter your name: ");
Console c = System.console();
name = c.readLine();
System.out.println ("Your name is: " + name);
}
}
Here, we have created a file object named file. The object can be used to work with files and
directories.
Note: In Java, creating a file object does not mean creating a file. Instead, a file object is an
abstract representation of the file or directory pathname (specified in the parenthesis).
If newFile.txt doesn't exist in the current location, the file is created and this message is
shown.
The new file is created.
However, if newFile.txt already exists, we will see this message.
The file already exists.
Constructor
Constructor Description
RandomAccessFile(File Creates a random access file stream to read from, and optionally
file, String mode) to write to, the file specified by the File argument.
RandomAccessFile(String Creates a random access file stream to read from, and optionally
name, String mode) to write to, a file with the specified name.
Methods
void close() It closes this random access file stream and releases
any system resources associated with the stream.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
Example
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample
{
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args)
{
try
{
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
}
catch (IOException e)
{
e.printStackTrace();
}
}
private static byte[] readFromFile(String filePath, int position, int size) throws IOException
{
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
}
private static void writeToFile(String filePath, String data, int position) throws IOException
{
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
}
}
Serialization
• In java, the Serialization is the process of converting an object into a byte stream so that it
can be stored on to a file, or memory, or a database for future access.
• The reverse operation of serialization is called deserialization where byte-stream is
converted into an object.
• Using serialization and deserialization, we can transfer the Object Code from one Java
Virtual machine to another.
• For serializing the object, we call the writeObject() method ObjectOutputStream, and for
deserialization we call the readObject() method of ObjectInputStream class.
• We must have to implement the Serializable interface for serializing the object.
ObjectOutputStream class
The ObjectOutputStream class is used to write primitive data types, and Java objects to an
OutputStream. Only objects that support the java.io.Serializable interface can be written to
streams.
Constructor
1) public ObjectOutputStream(OutputStream out) creates an ObjectOutputStream that
throws IOException {} writes to the specified OutputStream.
Important Methods
Method Description
1) public final void writeObject(Object obj) throws writes the specified object to the
IOException {} ObjectOutputStream.
2) public void flush() throws IOException {} flushes the current output stream.
3) public void close() throws IOException {} closes the current output stream.
Enumeration
• The Enum in Java is a data type which contains a 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), season
(SPRING, SUMMER, WINTER, and AUTUMN or FALL), colors (RED, YELLOW, BLUE, GREEN,
WHITE, and BLACK) etc.
• According to the Java naming conventions, we should have all constants in capital letters.
So, we have enum constants in capital letters.
• Java Enums can be thought of as classes which have a fixed set of constants (a variable that
does not change).
• The Java enum constants are static and final implicitly.
• Enums are used to create our own data type like classes.
• The enum data type (also known as Enumerated Data Type) is used to define an enum in
Java. Unlike C/C++, enum in Java is more powerful. Here, we can define an enum either
inside the class or outside the class.
• Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods
in Java enum.
Points to remember for Java Enum
• Enum improves type safety
• Enum can be easily used in switch
• Enum can be traversed
• Enum can have fields, constructors and methods
• Enum may implement many interfaces but cannot extend any class because it
internally extends Enum class
Autoboxing
The automatic conversion of primitive data types into its equivalent Wrapper type is known as
boxing.
(OR)
Converting a primitive value into an object of the corresponding wrapper class is called
autoboxing.
For example, converting int to Integer class.
No need of conversion between primitives and Wrappers manually so less coding is required.
The following table lists the primitive types and their corresponding wrapper classes,
which are used by the Java compiler for autoboxing:
Simple Example of Autoboxing in java:
class BoxingExample
{
public static void main(String args[])
{
int a=50;
Integer a2=new Integer(a);//Boxing
Integer a3=5;//Boxing
System.out.println(a2+" "+a3);
}
}
Output: 50 5
Generics in Java
The Java Generics programming is introduced to deal with type-safe objects. It makes the code
stable by detecting the bugs at compile time.
Before generics, we can store any type of objects in the collection, i.e., non-generic. Now
generics force the java programmer to store a specific type of objects.
Type-safety: We can hold only a single type of objects in generics. It doesnt allow to store
other objects.
Without Generics, we can store any type of objects.
List list = new ArrayList();
list.add(10);
list.add("10");
With Generics, it is required to specify the type of object we need to store.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add("10");// compile-time error
Compile-Time Checking: It is checked at compile time so problem will not occur at runtime.
The good programming strategy says it is far better to handle the problem at compile time
than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error