0% found this document useful (0 votes)
73 views

Java Programming Unit Iii PDF

The document discusses Java packages and the API. It covers: - Packages are used to group related classes and avoid name conflicts. - The Java API is a prewritten library of classes included in the JDK that can be imported. - There are built-in packages from the Java API and user-defined packages that are created. - To use classes from other packages, they must be imported using import statements.

Uploaded by

Daniel Rajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Java Programming Unit Iii PDF

The document discusses Java packages and the API. It covers: - Packages are used to group related classes and avoid name conflicts. - The Java API is a prewritten library of classes included in the JDK that can be imported. - There are built-in packages from the Java API and user-defined packages that are created. - To use classes from other packages, they must be imported using import statements.

Uploaded by

Daniel Rajan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Java Packages & API

A package in Java is used to group related classes. Think of it as a folder in a file


directory. We use packages to avoid name conflicts, and to write a better
maintainable code. Packages are divided into two categories:

• Built-in Packages (packages from the Java API)


• User-defined Packages (create your own packages)
• The Java API is a library of prewritten classes, that are free to use, included in
the Java Development Environment.

• The library contains components for managing input, database programming,


and much much more.

• The library is divided into packages and classes. Meaning you can either import
a single class (along with its methods and attributes), or a whole package that
contain all the classes that belong to the specified package.

• To use a class or a package from the library, you need to use the import
keyword:

Syntax
• import package.name.Class; // Import a single class
• import package.name.*; // Import the whole package
Built-in Packages
These packages consist of a large number of classes which are a part of Java
API.Some of the commonly used built-in packages are:

1) java.lang: Contains language support classes(e.g classes which defines primitive


data types, math operations). This package is automatically imported.

2) java.io: Contains classes for supporting input / output operations.

3) java.util: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.

4) java.applet: Contains classes for creating Applets.

5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , menus etc).

6) java.net: Contain classes for supporting networking operations.


User-defined packages
These are the packages that are defined by the user. First we create a directory
myPackage (name should be same as the name of the package). Then create the
MyClass inside the directory with the first statement being the package names.

// Name of the package must be same as the directory


// under which this file is saved
package myPackage;

public class MyClass


{
public void getNames(String s)
{
System.out.println(s);
}
}
Now we can use the MyClass class in our program.

/* import 'MyClass' class from 'names' myPackage */


import myPackage.MyClass;

public class PrintName


{
public static void main(String args[])
{
// Initializing the String variable
// with a value
String name = “Good morning";

// Creating an instance of class MyClass in


// the package.
MyClass obj = new MyClass();

obj.getNames(name);
}
}
Note : MyClass.java must be saved inside the myPackage
directory since it is a part of the package.
Important points:
• Every class is part of some package.
• If no package is specified, the classes in the file goes into a special unnamed
package (the same unnamed package for all files).
• All classes/interfaces in a file are part of the same package. Multiple files can
specify the same package name.
• If package name is specified, the file must be in a subdirectory called name
(i.e., the directory name must match the package name).
• We can access public classes in another (named) package using: package-
name.class-name
Using user defined package Arith which contains arithmetic operations

package myPackage;
public class Arith {
public int Add(int a,int b)
{
return(a+b);

}
public int Sub(int a,int b)
{
return(a-b);

}
}
import myPackage.Arith;
import java.util.*;
public class ArithTest {
public static void main(String args[])
{
System.out.println("Enter two numbers");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int b=sc.nextInt();
Arith a1 = new Arith();
System.out.println("The sum is"+a1.Add(a,b));
System.out.println(a1.Sub(a,b));
}
}
Advantages of using packages in Java

• Programmers can define their own packages to bundle a group of


classes/interfaces, etc.

• It is a good practice to group related classes implemented by you so that a


programmer can easily determine that the classes, interfaces, enumerations,
and annotations are related.

• Since the package creates a new namespace there won't be any name
conflicts with names in other packages.

• Using packages, it is easier to provide access control

• It is also easier to locate the related classes.

• Suppose you have developed a very large application that includes many
modules. As the number of modules grows, it becomes difficult to keep track
of them all if they are dumped into one location. This is particularly so if they
have similar names or functionality. You might wish for a means of grouping
and organizing them.
THIS Keyword in Java
Keyword THIS is a reference variable in Java that refers to the current object.
The various usages of 'THIS' keyword in Java are as follows:
•It can be used to refer instance variable of current class
•It can be used to invoke or initiate current class constructor
•It can be passed as an argument in the method call
•It can be passed as argument in the constructor call
•It can be used to return the current class instance
public class Account {
int a;
int b;
void setdata(int a ,int b)
{
a=a;
b=b;
}
void showdata()
{
System.out.println("The value of a is" + a);
System.out.println("The value of b is"+b);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Account acc=new Account();
acc.setdata(5, 10);;
acc.showdata();
}

}
What is Garbage Collection in Java?
• Garbage Collection in Java is a process by which the programs perform memory
management automatically.

• The Garbage Collector(GC) finds the unused objects and deletes them to reclaim the
memory.

• In Java, dynamic memory allocation of objects is achieved using the new operator that
uses some memory and the memory remains allocated until there are references for
the use of the object.

• When there are no references to an object, it is assumed to be no longer needed, and


the memory, occupied by the object can be reclaimed. There is no explicit need to
destroy an object as Java handles the de-allocation automatically.

• The technique that accomplishes this is known as Garbage Collection. Programs that
do not de-allocate memory can eventually crash when there is no memory left in the
system to allocate. These programs are said to have memory leaks.

• Garbage collection in Java happens automatically during the lifetime of the


program, eliminating the need to de-allocate memory and thereby avoiding memory
leaks.
Benefit of garbage collection:
Garbage collection relieves programmers from the burden of freeing allocated memory.
Knowing when to explicitly free allocated memory can be very tricky. Giving this job to the
JVM has several advantages.
A garbage collector is responsible for
•Allocating memory
•Ensuring that any referenced objects remain in memory, and
•Recovering memory used by objects that are no longer reachable from references in
executing code.
Nested Classes
• In Java, just like methods, variables of a class too can have another class as its member.
Writing a class within another is allowed in Java. The class written within is called
the nested class, and the class that holds the inner class is called the outer class.
Syntax
• Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer
class and the class Inner_Demo is the nested class.
class Outer_Demo {
class Inner_Demo {
}
}
Nested classes are divided into two types −

Non-static nested classes − These are the non-static members of a class.

Static nested classes − These are the static members of a class.


• Inner Classes (Non-static Nested Classes)
• Inner classes are a security mechanism in Java. We know a class cannot be associated
with the access modifier private, but if we have the class as a member of other class, then
the inner class can be made private. And this is also used to access the private members of a
class.

Inner classes are of three types depending on how and where you define them. They are −
• Inner Class
• Method-local Inner Class
• Anonymous Inner Class
Inner Class
Creating an inner class is quite simple. You just need to write a class within a class. Unlike
a class, an inner class can be private and once you declare an inner class private, it
cannot be accessed from an object outside the class.
Following is the program to create an inner class and access it. In the given example, we
make the inner class private and access the class through a method.
class Outer_Demo {
int num;

// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}
// Accessing he inner class from the method within
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
public class My_class {

public static void main(String args[]) {


// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();

// Accessing the display_Inner() method.


outer.display_Inner();
}
}
Method-local Inner Class
In Java, we can write a class within a method and this will be a local type. Like local
variables, the scope of the inner class is restricted within the method.

A method-local inner class can be instantiated only within the method where the inner
class is defined. The following program shows how to use a method-local inner class.
public class Outerclass {
// instance method of the outer class
void my_Method() {
int num = 23;

// method-local inner class


class MethodInner_Demo {
public void print() {
System.out.println("This is method inner class "+num);
}
} // end of inner class

// Accessing the inner class


MethodInner_Demo inner = new MethodInner_Demo();
inner.print();
}
public static void main(String args[]) {
Outerclass outer = new Outerclass();
outer.my_Method();
}
}
Anonymous Inner Class
An inner class declared without a class name is known as an anonymous inner class. In
case of anonymous inner classes, we declare and instantiate them at the same time.
Generally, they are used whenever you need to override the method of a class or an
interface. The syntax of an anonymous inner class is as follows −
abstract class AnonymousInner {
public abstract void mymethod();
}
public class Outer_class {
public static void main(String args[]) {
AnonymousInner inner = new AnonymousInner(){
public void mymethod() {
System.out.println("This is an example of anonymous inner class");
}
};
inner.mymethod();
}
}
Static Nested Class
A static inner class is a nested class which is a static member of the outer class. It can be
accessed without instantiating the outer class, using other static members. Just like static
members, a static nested class does not have access to the instance variables and methods of
the outer class.
public class Outer {
static class Nested_Demo {
public void my_method() {
System.out.println("This is my nested class");
}
}

public static void main(String args[]) {


Outer.Nested_Demo nested = new Outer.Nested_Demo();

nested.my_method();
}
}
Java Wrapper Classes
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as
objects.

The table below shows the primitive type and the equivalent wrapper class:

Primitive Data Type Wrapper Class


byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
Sometimes you must use wrapper classes, for example when working with
Collection objects, such as ArrayList, where primitive types cannot be used (the list
can only store objects)
ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid
Methods Of Wrapper Classes
For example, the following methods are used to get the value associated with the
corresponding wrapper object: intValue(), byteValue(), shortValue(), longValue(),
floatValue(), doubleValue(), charValue(), booleanValue().

public class MyClass {


public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}
}

Output:
5
5.99
A
Methods Of wrapper classes contd-----
Another useful method is the toString() method, which is used to convert wrapper
objects to strings.

In the following example, we convert an Integer to a String, and use the length()
method of the String class to output the length of the "string":
public class MyClass {
public static void main(String[] args) {
Integer myInt = 100;
String myString = myInt.toString();
System.out.println(myString.length());
}
}

Output:
3

You might also like