java abstract class

24
Java Abstract class In this chapter you will learn: 1. What is abstract class 2. How to create abstract class 3. Example - abstract class 4. A demo for using abstract methods and classes Description Abstract class is for abstract idea or concept. For example, int data type is a concrete data type and double is another concrete data type. They are both numbers. Here number is an abstract concept. Shape is another example. We can have spare, rectangle or triangle or circle. They are all concrete while shape is an abstract class. In Java we use abstract class to define the abstract concept. Abstract concept must have some abstract aspects. For example, the abstract concept is the Shape while the abstract aspect is how to calculate area. The abstract concept becomes abstract class in Java and the abstract aspect becomes the abstract method. Syntax You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. To declare an abstract method, use this general form: abstract type name(parameter-list); No method body is present for abstract method. Any class that contains one or more abstract methods must also be declared abstract. abstract class MyAbstractClass{ abstract type name(parameter-list); } Example Here is an abstract class, followed by a class which implements its abstract method. abstract class MyAbstractClass { abstract void callme(); /* w w w . jav a 2s .com*/ void callmetoo() { System.out.println("This is a concrete method."); } } class B extends MyAbstractClass { void callme() { System.out.println("B's implementation of callme."); }

Upload: gangadri524

Post on 18-Apr-2017

258 views

Category:

Documents


2 download

TRANSCRIPT

Java Abstract class

In this chapter you will learn:

1. What is abstract class 2. How to create abstract class 3. Example - abstract class 4. A demo for using abstract methods and classes

Description

Abstract class is for abstract idea or concept. For example, int data type is a concrete data type and double is another concrete data type. They are both numbers. Here number is an abstract concept. Shape is another example. We can have spare, rectangle or triangle or circle. They are all concrete while shape is an abstract class.

In Java we use abstract class to define the abstract concept. Abstract concept must have some abstract aspects. For example, the abstract concept is the Shape while the abstract aspect is how to calculate area. The abstract concept becomes abstract class in Java and the abstract aspect becomes the abstract method.

Syntax

You can require that certain methods be overridden by subclasses by specifying the abstract type modifier. To declare an abstract method, use this general form:

abstract type name(parameter-list);

No method body is present for abstract method. Any class that contains one or more abstract methods must also be declared abstract.

abstract class MyAbstractClass{

abstract type name(parameter-list);

}

Example

Here is an abstract class, followed by a class which implements its abstract method.

abstract class MyAbstractClass {

abstract void callme();

/* w w w . jav a 2s .com*/

void callmetoo() {

System.out.println("This is a concrete method.");

}

}

class B extends MyAbstractClass {

void callme() {

System.out.println("B's implementation of callme.");

}

}

public class Main {

public static void main(String args[]) {

B b = new B();

b.callme();

b.callmetoo();

}

}

The output:

Example 2

The following code defines Shape class as abstract. Shape class has abstract method called area(). Rectangle class extends abstract class Shape and implements the area() method for itself.

abstract class Shape {

double height;// w w w . ja va2 s . c o m

double width;

Shape(double a, double b) {

height = a;

width = b;

}

abstract double area();

}

class Rectangle extends Shape{

Rectangle(double a, double b) {

super(a, b);

}

double area() {

System.out.println("Inside Area for Rectangle.");

return height * width;

}

}

class Triangle extends Shape{

Triangle(double a, double b) {

super(a, b);

}

double area() {

System.out.println("Inside Area for Triangle.");

return height * width / 2;

}

}

public class Main {

public static void main(String args[]) {

Rectangle r = new Rectangle(10, 5);

Triangle t = new Triangle(10, 8);

Shape figref;

figref = r;

System.out.println("Area is " + figref.area());

figref = t;

System.out.println("Area is " + figref.area());

}

}

The output:

Next chapter...

Java Class Access Control

In this chapter you will learn:

1. What is Java access control level 2. Java Class Access Control Level 3. Example - effects of public and private access 4. How does the access control act on the inheritance 5. What is the access matrix for Java 6. What are the targets for different access modifiers

Description

We can control the access level for class member variables and methods through access specifiers.

Java's access specifiers are public, private, protected and a default access level.

Level

A public class member can be accessed by any other code. A private class member can only be accessed within its class. A default access class member has no access specifiers. A class's default features are

accessible to any class in the same package. A protected feature of a class is available to all classes in the same package(like a default)

and to its subclasses.

protected features are more accessible than default features.

Example

To understand the effects of public and private access, consider the following program:

class Test {//from w ww.ja v a 2s . c om

int a; // default access

public int b; // public access

private int c; // private access

// methods to access c

void setc(int i) {

c = i;

}

int getc() {

return c;

}

}

public class Main {

public static void main(String args[]) {

Test ob = new Test();

ob.a = 1;

ob.b = 2;

// This is not OK and will cause an error

// ob.c = 100; // Error!

// You must access c through its methods

ob.setc(100); // OK

System.out.println("a, b, and c: " + ob.a +

" " + ob.b + " " + ob.getc());

}

}

The output:

Member Access and Inheritance

A subclass cannot access the private members of the superclass. For example, consider the following simple class hierarchy. If you try to compile the following program, you will get the error message.

class A {/* w w w .j av a 2s . c o m*/

private int j; // private to A

}

class B extends A {

int total;

void sum() {

total = j; // ERROR, j is not accessible here

}

}

The output:

Access matrix for Java

The following table shows the access matrix for Java. Yes means accessible, no means not accessible.

Position Private No modifier Protected Public

Same class Yes Yes Yes Yes

Position Private No modifier Protected Public

Same package subclass No Yes Yes Yes

Same package non-subclass No Yes Yes Yes

Different package subclass No No Yes Yes

Different package non-subclass No No No Yes

Access Modifiers and their targets

Not all modifiers can be applied to all features. Top-level classes may not be protected. Methods may not be transient. Static can apply it to free-floating blocks of code.

The following table shows all possible combinations of features and modifiers. yes means we can use that modifier to control the access for the corresponding entities.

Modifier Class Variable Method Constructor Code Block

public yes yes yes yes no

protected no yes yes yes no

empty accessor yes yes yes yes yes

private no yes yes yes no

final yes yes yes no no

abstract yes no yes no no

static no yes yes no yes

native no no yes no no

transient no yes no no no

volatile no yes no no no

synchronized no no yes no yes

Next chapter...

Java Interface

In this chapter you will learn:

1. What is a Java Interface 2. How to define an interface 3. Note for Java Interface 4. How to implement an interface

Description

interface specifies what a class must do, but not how it does it.

An interface in Java is like a contract. It defines certain rules through Java methods and the class which implements that interface must follow the rules by implementing the methods.

To implement an interface, a class must create the complete set of methods defined by the interface.

Syntax

An interface is defined much like a class. This is the general form of an interface:

access interface name {

return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

//from w w w . j a v a 2s.c o m

type final-varname1 = value;

type final-varname2 = value;

// ...

return-type method-nameN(parameter-list);

type final-varnameN = value;

}

Note

Variables can be declared inside of interface declarations. They are implicitly final and static. Variables must also be initialized with a constant value. All methods and variables are implicitly public if the interface, itself, is declared as public.

Here is an example of an interface definition.

interface MyInterface{

void callback(int param);

}

Implementing Interfaces

To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface.

The general form of a class that includes the implements clause looks like this:

access-level class classname [extends superclass] [implements interface [,interface...]] {

// class-body

}

Here is a small example class that implements the interface shown earlier.

interface MyInterface {

void callback(int param);

}/* w w w . jav a 2 s .co m*/

class Client implements MyInterface{

// Implement Callback's interface

public void callback(int p) {

System.out.println("callback called with " + p);

}

}

callback() is declared using the public access specifier. When you implement an interface

method, it must be declared as public.

Next chapter...

Java Interface as data type

In this chapter you will learn:

1. How to access implementations through interface references 2. Example - Java Interface as data type 3. How to use interface to do polymorphism

Access Implementations Through Interface References

Once we define an interface we can use it as a type for object instance we create through its implementation class.

Example

The following example calls the callback( ) method via an interface reference variable:

interface MyInterface {

void callback(int param);

}/*from w w w. ja va2 s.c om*/

class Client implements MyInterface{

// Implement Callback's interface

public void callback(int p) {

System.out.println("callback called with " + p);

}

}

public class Main {

public static void main(String args[]) {

MyInterface c = new Client();

c.callback(42);

}

}

The output of this program is shown here:

Polymorphism and interface

interface is designed for polymorphism. interface defines a list of methods acting as the contract between the interface and its implementation. One interface can be implements by more than once and each different implementation of the same interface would follow the same list of methods. Therefore if we know several classes implement the same interface we can use that interface to reference all of its implementer classes. The compiler will determine dynamically which implementation to use.

interface MyInterface {

void callback(int param);

}//from w ww .j a v a 2s . c o m

class Client implements MyInterface{

// Implement Callback's interface

public void callback(int p) {

System.out.println("Client");

System.out.println("p squared is " + (p * 2));

}

}

class AnotherClient implements MyInterface{

// Implement Callback's interface

public void callback(int p) {

System.out.println("Another version of callback");

System.out.println("p squared is " + (p * p));

}

}

class TestIface2 {

public static void main(String args[]) {

MyInterface c = new Client();

AnotherClient ob = new AnotherClient();

c.callback(42);

c = ob; // c now refers to AnotherClient object

c.callback(42);

}

}

The output from this program is shown here:

Next chapter...

Java interface as build block

In this chapter you will learn:

1. How to partially implement an interface 2. How to use interface to organize constants 3. How to extend interface

Partial interface Implementations

If a class implements an interface but does not fully implement its methods, then that class must be declared as abstract. For example:

interface MyInterface {

void callback(int param);

/* www . j a va 2s. c o m*/

void show();

}

abstract class Incomplete implements MyInterface {

int a, b;

public void show() {

System.out.println(a + " " + b);

}

}

Variables in Interfaces

We can use interface to organize constants.

interface MyConstants {

int NO = 0;/*from w w w . j av a 2s . co m*/

int YES = 1;

}

class Question implements MyConstants {

int ask() {

return YES;

}

}

public class Main implements MyConstants {

static void answer(int result) {

switch (result) {

case NO:

System.out.println("No");

break;

case YES:

System.out.println("Yes");

break;

}

}

public static void main(String args[]) {

Question q = new Question();

answer(q.ask());

}

}

The output:

Extend Interface

One interface can inherit another interface with the keyword extends.

interface IntefaceA {

void meth1();/*from ww w . j a v a 2 s . co m*/

void meth2();

}

interface IntefaceB extends IntefaceA {

void meth3();

}

class MyClass implements IntefaceB {

public void meth1() {

System.out.println("Implement meth1().");

}

public void meth2() {

System.out.println("Implement meth2().");

}

public void meth3() {

System.out.println("Implement meth3().");

}

}

public class Main {

public static void main(String arg[]) {

MyClass ob = new MyClass();

ob.meth1();

ob.meth2();

ob.meth3();

}

}

The output:

Next chapter...

Java instanceof operator

In this chapter you will learn:

1. How and when to instanceof operator 2. Syntax for Java instanceof operator 3. Example - Java instanceof operator

Description

Java provides the run-time operator instanceof to check class type for an object.

Syntax

The instanceof operator has this general form:

object instanceof type

Example

The following program demonstrates instanceof:

class A {/*from w ww .j a v a2 s.c o m*/

}

class B {

}

class C extends A {

}

class D extends A {

}

public class Main{

public static void main(String args[]) {

A a = new A();

B b = new B();

C c = new C();

D d = new D();

if (a instanceof A)

System.out.println("a is instance of A");

if (b instanceof B)

System.out.println("b is instance of B");

if (c instanceof C)

System.out.println("c is instance of C");

if (c instanceof A)

System.out.println("c can be cast to A");

if (a instanceof C)

System.out.println("a can be cast to C");

A ob;

ob = d; // A reference to d

System.out.println("ob now refers to d");

if (ob instanceof D)

System.out.println("ob is instance of D");

ob = c; // A reference to c

System.out.println("ob now refers to c");

if (ob instanceof D)

System.out.println("ob can be cast to D");

else

System.out.println("ob cannot be cast to D");

if (ob instanceof A)

System.out.println("ob can be cast to A");

// all objects can be cast to Object

if (a instanceof Object)

System.out.println("a may be cast to Object");

if (b instanceof Object)

System.out.println("b may be cast to Object");

if (c instanceof Object)

System.out.println("c may be cast to Object");

if (d instanceof Object)

System.out.println("d may be cast to Object");

}

}

The output from this program is shown here:

Next chapter...

Java Package

In this chapter you will learn:

1. What is Java package 2. How to define a Java package 3. How to create a hierarchy of packages 4. How to map Java package to directory

Description

Packages are containers for classes. Packages are used to keep the class name space compartmentalized. In Java, package is mapped to a folder on your hard drive.

Syntax

To define 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.This is the general form of the package statement:

package packageName;

Create a hierarchy of packages

To create a hierarchy of packages, separate each package name from the one above it by use of a period. The general form of a multileveled package statement:

package pkg1[.pkg2[.pkg3]];

A package hierarchy must be reflected in the file system of your Java development system.

Java package maps to directory

Java package maps to physical directory on your hard drive. As what is defined in the following example, you have to save the following file to a file named Main.java and create a folder named MyPack to actually store Main.java file.

package MyPack;//from w w w. j av a 2 s .c o m

public class Main {

public static void main(String args[]) {

System.out.println("hi");

}

}

Then try executing the class, using the following command line:

Next chapter...

Java Packages Import

In this chapter you will learn:

1. How to write import statement 2. Syntax for Java Packages Import 3. What is static import and how to use static import

Description

In a Java source file, import statements occur immediately following the package statement and before class definitions.

Syntax

This is the general form of the import statement:

import pkg1[.pkg2].(classname|*);

* means including all classes under that package. For example,

import java.lang.*;

Any place you use a class name, you can use its fully qualified name, which includes its full package hierarchy.

For example, this fragment uses an import statement:

import java.util.*;

class MyDate extends Date {

}

The same example without the import statement looks like this:

class MyDate extends java.util.Date {

}

static import

In order to access static members, it is necessary to qualify references. For example, one must say:

double r = Math.cos(Math.PI * theta);

The static import construct allows unqualified access to static members.

import static java.lang.Math.PI;

or:

import static java.lang.Math.*;

Once the static members have been imported, they may be used without qualification:

double r = cos(PI * theta);

The static import declaration imports static members from classes, allowing them to be used without class qualification.

Next chapter...

Error Handling

1. You can isolate code that may cause a runtime error using the try statement. 2. try statement normally is accompanied by the catch and the finally statements. 3. In case of an error, Java stops the processing of the try block and jump to the catch block. 4. In the catch block, you can handle the error or notify the user by 'throwing' a java.lang.Exception

object. Or you can re-throw the exception or a new Exception object back to the code that called the method.

5. If a thrown exception is not caught, the application will stop abruptly. 6. In the finally block, you write code that will be run whether or not an error has occurred. 7. The finally block is optional. 8. You can have more than one catch block. This is because the code can throw different types of

exceptions. 9. If the type of exception thrown does not match the exception type in the first catch block, the JVM

goes to the next catch block and does the same thing until it finds a match. 10. If no match is found, the exception object will be thrown to the method caller. 11. If the caller does not put the offending code that calls the method in a try block, the program

crashes.

This is the syntax of the try statement.

try {

[code that may throw an exception]

} catch (ExceptionType-1 e) {

[code that is executed when ExceptionType-1 is thrown]

} [catch (ExceptionType-2 e) {

[code that is executed when ExceptionType-2 is thrown]

}]

...

} [catch (ExceptionType-n e) {

[code that is executed when ExceptionType-n is thrown]

}]

[finally {

[code that runs regardless of whether an exception was thrown]]

}]

Types of Exceptions

1. An exception is an object of the subclass of class Throwable. 2. Class Error and the class Exception cover all the standard exceptions.

Java's Unchecked Runtime Exception Subclasses

Exception Meaning

ArithmeticException Arithmetic error, such as divide-by-zero.

ArrayIndexOutOfBoundsException Array index is out-of-bounds.

ArrayStoreException Assignment to an array element of an incompatible type.

ClassCastException Invalid cast.

IllegalArgumentException Illegal argument used to invoke a method.

IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked t

hread.

IllegalStateException Environment or application is in incorrect state.

IllegalThreadStateException Requested operation not compatible with current thread stat

e.

IndexOutOfBoundsException Some type of index is out-of-bounds.

NegativeArraySizeException Array created with a negative size.

NullPointerException Invalid use of a null reference.

NumberFormatException Invalid conversion of a string to a numeric format.

SecurityException Attempt to violate security.

StringIndexOutOfBounds Attempt to index outside the bounds of a string.

TypeNotPresentException Type not found. (Added by J2SE 5.)

UnsupportedOperationException An unsupported operation was encountered.

Java's Checked Exceptions Defined in java.lang

Exception Meaning

ClassNotFoundException Class not found.

CloneNotSupportedException Attempt to clone an object that does not implement the Clon

eable interface.

IllegalAccessException Access to a class is denied.

InstantiationException Attempt to create an object of an abstract class or interfa

ce.

InterruptedException One thread has been interrupted by another thread.

NoSuchFieldException A requested field does not exist.

NoSuchMethodException A requested method does not exist.

Throwing an Exception from a Method

public class MainClass {

public static void main(String[] args) {

String input = null;

try {

String capitalized = capitalize(input);

System.out.println(capitalized);

} catch (NullPointerException e) {

System.out.println(e.toString());

}

}

public static String capitalize(String s) throws NullPointerException {

if (s == null) {

throw new NullPointerException("Your passed a null argument");

}

Character firstChar = s.charAt(0);

String theRest = s.substring(1);

return firstChar.toString().toUpperCase() + theRest;

}

}

Write a catch block that handles java.lang.Exception

All Java exception classes derive from the java.lang.Exception class. When a method throws multiple exceptions, rather than catch all the exceptions, you can simply write a catch block that handles java.lang.Exception:

public class MainClass {

public static void main(String[] args) {

String input = null;

try {

String capitalized = capitalize(input);

System.out.println(capitalized);

} catch (Exception e) {

System.out.println(e.toString());

}

}

static String capitalize(String s) throws NullPointerException, AlreadyCapitalizedException {

if (s == null) {

throw new NullPointerException("Your passed a null argument");

}

Character firstChar = s.charAt(0);

if (Character.isUpperCase(firstChar)) {

throw new AlreadyCapitalizedException();

}

String theRest = s.substring(1);

return firstChar.toString().toUpperCase() + theRest;

}

}

class AlreadyCapitalizedException extends Exception {

public String toString() {

return "Input has already been capitalized";

}

}

Handling Exceptions

public class MainClass {

public static void main(String[] args) {

int i = 1;

int j = 0;

try {

System.out.println("Try block entered " + "i = " + i + "j = " + j);

System.out.println(i / j); // Divide by 0 - exception thrown

System.out.println("Ending try block");

} catch (ArithmeticException e) { // Catch the exception

System.out.println("Arithmetic exception caught");

}

System.out.println("After try block");

return;

}

}

Multiple catch Blocks

public class MainClass {

public static void main(String[] args) {

int[] x = { 10, 5, 0 };

try {

System.out.println("First try block in main() entered");

divide(x, 0);

x[1] = 0;

divide(x, 0);

x[1] = 1;

divide(x, 1);

} catch (ArithmeticException e) {

System.out.println("Arithmetic exception caught in main()");

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Index-out-of-bounds exception caught in main()");

}

}

private static void divide(int[] intArray, int j) {

for (int i : intArray) {

System.out.println(i);

System.out.println(j);

System.out.println(i / j);

System.out.println();

}

}

}

The finally Block

A finally block is always executed, regardless of whether or not exceptions are thrown.

import java.io.IOException;

public class MainClass {

public static void main(String[] args) {

try {

System.out.println("In second try block in main()");

System.in.read();

return;

} catch (IOException e) {

System.out.println("I/O exception caught in main()");

} finally {

System.out.println("finally block for second try block in main()");

}

System.out.println("Code after second try block in main()");

}

}

Exception Objects: stack trace

public class MainClass {

public static void main(String[] args) {

int[] array = new int[]{1,0,2};

int index = 0;

try {

System.out.println("\nFirst try block in divide() entered");

array[index + 2] = array[index]/array[index + 1];

System.out.println("Code at end of first try block in divide()");

} catch(ArithmeticException e) {

System.err.println("Arithmetic exception caught in divide()\n" +

"\nMessage in exception object:\n\t" +

e.getMessage());

System.err.println("\nStack trace output:\n");

e.printStackTrace();

System.err.println("\nEnd of stack trace output\n");

} catch(ArrayIndexOutOfBoundsException e) {

System.err.println("Index-out-of-bounds exception caught in divide()\n" +

"\nMessage in exception object:\n\t" + e.getMessage());

System.err.println("\nStack trace output:\n");

e.printStackTrace();

System.out.println("\nEnd of stack trace output\n");

} finally {

System.err.println("finally clause in divide()");

}

System.out.println("Executing code after try block in divide()");

}

}

First try block in divide() entered

Executing code after try block in divide()Arithmetic exception caught in

divide()

Message in exception object:

/ by zero

Stack trace output:

java.lang.ArithmeticException: / by zero

at MainClass.main(MainClass.java:8)

End of stack trace output

finally clause in divide()

Defining Your Own Exceptions, Throwing Your Own Exception class DreadfulProblemException extends ArithmeticException {

public DreadfulProblemException() {

}

public DreadfulProblemException(String s) {

super(s);

}

}

public class MainClass{

public static void main(String[] a){

int[] array = new int[]{1,0,2};

int index = 0;

try {

System.out.println("First try block in divide() entered");

array[index + 2] = array[index]/array[index + 1];

System.out.println("Code at end of first try block in divide()");

} catch(ArithmeticException e) {

System.out.println("Arithmetic exception caught in divide()");

throw new DreadfulProblemException("index + 1"); // Throw new exception

} catch(ArrayIndexOutOfBoundsException e) {

System.out.println(

"Index-out-of-bounds index exception caught in divide()");

}

System.out.println("Executing code after try block in divide()");

}

}

First try block in divide() entered

Arithmetic exception caught in divide()

Exception in thread "main" DreadfulProblemException: index + 1

at MainClass.main(MainClass.java:20)

Demonstrate exception chaining. class ChainExcDemo {

static void demoproc() {

NullPointerException e = new NullPointerException("top layer");

e.initCause(new ArithmeticException("cause"));

throw e;

}

public static void main(String args[]) {

try {

demoproc();

} catch (NullPointerException e) {

System.out.println("Caught: " + e);

System.out.println("Original cause: " + e.getCause());

}

}

}

Getting the Stack Trace of an Exception

public class Main {

public static void main(String[] argv) throws Exception {

try {

int x = 1, y = 0;

System.out.println(x / y);

} catch (Throwable e) {

StackTraceElement stack[] = e.getStackTrace();

for (int i = 0; i < stack.length; i++) {

String filename = stack[i].getFileName();

if (filename == null) {

System.out.println("filename is not available");

}

String className = stack[i].getClassName();

System.out.println(className);

String methodName = stack[i].getMethodName();

System.out.println(methodName);

boolean isNativeMethod = stack[i].isNativeMethod();

System.out.println(isNativeMethod);

int line = stack[i].getLineNumber();

System.out.println(line);

}

}

}

}

Wrapper Classes Wrapper classes for the primitive types

Basic Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

boolean Boolean

char Character

Primitive Wrappers in detail For the sake of performance, not everything in Java is an object. There are also primitives, such as int, long, float, double, etc.

java.lang.Integer

1. The java.lang.Integer class wraps an int. 2. The Integer class has two static final fields of type int: MIN_VALUE and MAX_VALUE. 3. MIN_VALUE contains the minimum possible value for an int (-2^31) and 4. MAX_VALUE the maximum possible value for an int (2^31 - 1).

Integer class has two constructors:

public Integer (int value)

public Integer (String value)

For example, this code constructs two Integer objects.

Integer i1 = new Integer (12);

Integer i2 = new Integer ("123");

Integer has the no-arg byteValue, doubleValue, floatValue, intValue, longValue, and shortValue methods that convert the wrapped value to a byte, double, float, int, long, and short, respectively. In addition, the toString method converts the value to a String.

static methods parse a String to an int (parseInt) and convert an int to a String (toString).

public static int parsetInt (String string)

public static String toString (int i)

Demonstrate a type wrapper. class Wrap {

public static void main(String args[]) {

Integer iOb = new Integer(100);

int i = iOb.intValue();

System.out.println(i + " " + iOb); // displays 100 100

}

}

Autoboxing/unboxing int class AutoBox {

public static void main(String args[]) {

Integer iOb = 100; // autobox an int

int i = iOb; // auto-unbox

System.out.println(i + " " + iOb); // displays 100 100

}

}

Use Integer constructor to convert int primitive type to Integer object.

public class Main {

public static void main(String[] args) {

int i = 10;

Integer intObj = new Integer(i);

System.out.println(intObj);

}

}

Wrapped Class: boolean, int, long public class WrappedClassApp {

public static void main(String args[]) {

Boolean b1 = new Boolean("TRUE");

Boolean b2 = new Boolean("FALSE");

System.out.println(b1.toString() + " or " + b2.toString());

for (int j = 0; j < 16; ++j)

System.out.print(Character.forDigit(j, 16));

System.out.println();

Integer i = new Integer(Integer.parseInt("ef", 16));

Long l = new Long(Long.parseLong("abcd", 16));

long m = l.longValue() * i.longValue();

System.out.println(Long.toString(m, 8));

System.out.println(Float.MIN_VALUE);

System.out.println(Double.MAX_VALUE);

}

}