0% found this document useful (0 votes)
10 views43 pages

Interface: © Oxford University Press 2013. All Rights Reserved

Module 2.2 covers interfaces in Java, explaining their characteristics, syntax, and differences from abstract classes. It also discusses Object and Wrapper classes, string manipulation, and enumerations, including examples of their usage. Key concepts include the immutability of strings, the use of StringBuffer and StringBuilder for mutable strings, and the introduction of autoboxing and unboxing for primitive types.

Uploaded by

pandukhant81
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)
10 views43 pages

Interface: © Oxford University Press 2013. All Rights Reserved

Module 2.2 covers interfaces in Java, explaining their characteristics, syntax, and differences from abstract classes. It also discusses Object and Wrapper classes, string manipulation, and enumerations, including examples of their usage. Key concepts include the immutability of strings, the use of StringBuffer and StringBuilder for mutable strings, and the introduction of autoboxing and unboxing for primitive types.

Uploaded by

pandukhant81
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
You are on page 1/ 43

Module 2.

Interface

© Oxford University Press 2013. All rights reserved.


Objective
• Understand what interfaces are and how they are
different from abstract classes
• Understand Object and Wrapper class
• Understand how Strings are created, manipulated,
and split in Java
• Understand enumerations

© Oxford University Press 2013. All rights reserved.


Interfaces

• Interfaces is a collection of methods which are public


and abstract by default.
• The implementing objects have to inherit the
interface and provide implementation for all these
methods.
• multiple inheritance in Java is allowed through
interfaces
• Interfaces are declared with help of a keyword
interface

© Oxford University Press 2013. All rights reserved.


Syntax for Creating Interface

interface interfacename
{
returntype methodname(argumentlist);

}
The class can inherit interfaces using implements
keyword
– class classname implements interfacename{}

© Oxford University Press 2013. All rights reserved.


Interface Example

interface Calculator {
int add(int a,int b);
int subtract(int a,int b);
int multiply(int a,int b);
int divide(int a,int b);
}

© Oxford University Press 2013. All rights reserved.


Example (contd.)
class Normal_Calculator implements Calculator
{
public int add(int a,int b){
return a+b;}
public int subtract(int a,int b){
return a-b;}
public int multiply(int a,int b){
return a*b;}
public int divide(int a,int b){
return a/b;}
public static void main(String args[]){
Normal_Calculator c=new Normal_Calculator();
System.out.println(“Value after addition = “+c.add(5,2));
System.out.println(“Value after Subtraction = “+c.subtract(5,2));
System.out.println(“Value after Multiplication = “+c.multiply(5,2));
System.out.println(“Value after division = “+c.divide(5,2)); }}

© Oxford University Press 2013. All rights reserved.


The Output

Value after addition = 7


Value after Subtraction = 3
Value after Multiplication= 10
Value after division = 2

© Oxford University Press 2013. All rights reserved.


Variables in Interface

• They are implicitly public, final, and static


• As they are final, they need to be assigned a
value compulsorily.
• Being static, they can be accessed directly
with the help of an interface name
• as they are public we can access them from
anywhere.

© Oxford University Press 2013. All rights reserved.


Extending Interfaces

• One interface can inherit another interface


using the extends keyword and not the
implements keyword.
• For example,
interface A extends B { }

© Oxford University Press 2013. All rights reserved.


Interface Vs Abstract class

© Oxford University Press 2013. All rights reserved.


Similarities Between Interface and abstract
class
• Both cannot be instantiated, i.e. objects cannot be
created for both of them.
• Both can have reference variables referring to their
implementing classes objects.
• Interfaces can be extended, i.e. one interface can
inherit another interface, similar to that of abstract
classes (using extends keyword).
• static / final methods can neither be created in an
interface nor can they be used with abstract
methods.

© Oxford University Press 2013. All rights reserved.


java.lang package
• java.lang is a imported by default in all the
classes that we create.
• Remember String and System class

© Oxford University Press 2013. All rights reserved.


Java.lang.Object class

• parent by default of all the classes (predefined


and user-defined) in Java.
• The methods of Object class can be used by all
the objects and arrays.
• toString() and equals() are methods of Object
class

© Oxford University Press 2013. All rights reserved.


toString() method
class Demo {
public String toString() {
return “My Demo Object created”;
}
public static void main(String args[]) {
System.out.println(new Demo()); }}

Output
My Demo Object created

© Oxford University Press 2013. All rights reserved.


Java Wrapper classes
• For each primitive type, there is a corresponding
wrapper class designed.
• Are wrapper around primitive data types.
• allow for situations where primitives cannot be used
but their corresponding objects are required.
• Normally Used to convert a numeric value to a String
or vice-versa.
• Just like String, Wrapper objects are also immutable
• All the wrapper classes except Character and Float
have two constructors—one that takes the primitive
value and another that takes the String
representation of the value.
• Character has one constructor and float has three.
© Oxford University Press 2013. All rights reserved.
Wrappers classes

© Oxford University Press 2013. All rights reserved.


Wrapper classes (contd.)
• converts primitive to wrapper
– double a = 4.3;
– Double wrp = new Double(a);
• Each wrapper provides a method to return the
primitive value.
– double r = wrp.doubleValue();

© Oxford University Press 2013. All rights reserved.


Converting Primitive types to
wrapper objects
• Integer ValueOfInt = new Integer(v)
• Float ValueOfFloat = new Float(x)
• Double ValOfDouble = new Double(y)
• Long ValueOfLong = new Long(z)
• Where v, x, y and z are int, float, double, and
long values, respectively.

© Oxford University Press 2013. All rights reserved.


Converting wrapper objects to
primitives
• int v = ValueOfInt.intValue();
• float x = ValueOfFloat.floatValue();
• long y = ValueOfLong.longValue();
• double z = ValueOfDouble.doubleValue();

© Oxford University Press 2013. All rights reserved.


Converting primitives to String
Object
• String xyz = Integer.toString(v)
• String xyz = Float.toString(x)
• String xyz = Double.toString(y)
• String xyz = Long.toString(z)

© Oxford University Press 2013. All rights reserved.


Converting back from String Object
to Primitives
• int v = Integer.parseInt(xyz)
• long y = Long.parseLong(xyz)
• public float parseFloat(String x)
• public double parseDouble(String x)
• public double parseByte(String x)
• public double parseShort(String x)
• May throw NumberFormatException if the value of
the String does not represent a proper numbers

© Oxford University Press 2013. All rights reserved.


Converting Primitives represented by
String to wrapper
• Double ValueOfDouble = Double.valueOf(xyz);
• Float ValueOfFloat = Float.valueOf(xyz);
• Integer ValueOfInteger = Integer.valueOf(xyz);
• Long ValueOfLong = Long.valueOf(xyz);
• Double ValueOfDouble = Double.valueOf(xyz);
• Float ValueOfFloat = Float.valueOf(xyz);
• Integer ValueOfInteger = Integer.valueOf(xyz);
• Long ValueOfLong = Long.valueOf(xyz);
– String argument method generates a
NumberFormatException in case the value in a String does
not contain a number.

© Oxford University Press 2013. All rights reserved.


Autoboxing and Unboxing
• Introduced in Java 5
• conversion from primitives to wrappers is known as
boxing, while the reverse is known as unboxing.
• Integer wrap_int = 5;
– primitive 5 autoboxed into an Integer
• int prim_int = wrap_int;
– automatic unboxing Integer into int

© Oxford University Press 2013. All rights reserved.


String Example
String a=”Hello”; String b=”Hello”;
String c=new String(“Hello”);
String d=new String(“Hello”);
String e=new String(“Hello, how are you?”);
if(a==b)
System.out.println(“object is same and is being shared by
a & b”);
else
System.out.println(“Different objects”);
if(a==c)
System.out.println(“object is same and is being shared by
a & c”);
else
System.out.println(“Different objects”);

© Oxford University Press 2013. All rights reserved.


String Example
if(c==d)
System.out.println(“same object”);
else
System.out.println(“Different objects”);
String f=e.intern();
if(f==a)
System.out.println(“Interned object f refer to the already
created object a in the pool”);
else
System.out.println(“Interned object does not refer to the
already created objects, as literal was not present in the pool.
It is a new object which has been created in the pool”);
• we have omitted the class and the main method declaration from this example. You need to
add it to run the example (refer Book for complete program).

© Oxford University Press 2013. All rights reserved.


String Example

© Oxford University Press 2013. All rights reserved.


The Output
object is same and is being shared by a & b
Different objects
Different objects
Interned object does not refer to the already created
objects, as literal was not present in the pool. It is a
new object which has been created in the pool

© Oxford University Press 2013. All rights reserved.


String Manipulation
• Strings in Java are immutable (read only) in nature,
Once defined cannot be changed.
• Let us take an example:
– String x = “Hello”; // ok
– String x = x +”World”; // ok, but how?
• the ‘+’ operator concatenates If at least one of the
operand is a string.
• The second statement gets converted to the
following statement automatically
– String x=new StringBuffer(). append(x). append(“World”).
toString();

© Oxford University Press 2013. All rights reserved.


Common methods of the String class

© Oxford University Press 2013. All rights reserved.


Methods of String class

© Oxford University Press 2013. All rights reserved.


StringBuffer class
• StringBuffer class is used for representing changing
strings.
• StringBuffer offers more performance enhancement
whenever we change Strings, because it is this class
that is actually used behind the curtain.
• Just like any other buffer, StringBuffer also has a
capacity and if the capacity is exceeded, then it is
automatically made larger.
• The initial capacity of StringBuffer can be known by
using a method capacity().

© Oxford University Press 2013. All rights reserved.


Methods of StringBuffer class
StringBuilder class
• introduced in Java 5
• a substitute of StringBuffer class.
• This class is faster than StringBuffer class, as it is not
synchronized
• append(), insert(), delete(), deleteCharAt(), replace(),
and reverse() return StringBuilder objects rather
than StringBuffer objects.
• The line creates a StringBuilder object.
– StringBuilder s=new StringBuilder();
– construct a StringBuilder object with an initial capacity of
16 characters. Similar to that of StringBuffer.

© Oxford University Press 2013. All rights reserved.


Splitting Strings
• StringTokenizer is a utility class provided by the
java.util package.
• Now a legacy code.
• This class used to be of utmost importance when we
want to divide the entire String into parts (Tokens)
on the basis of delimiters.
• The delimiters can be any of the whitespace, tab
space, semicolon, comma, etc.
• J2SE 1.4 added split( ) method to the String class for
simplifying the task of splitting a String and also
added Pattern and Matcher classes in java.util.regex
package.
© Oxford University Press 2013. All rights reserved.
Example
import java.util.*; import java.util.regex.*;
class StringTokenizerDemo {
public static void main(String args[]) {
int i=1;
String str=”Never look down on anybody unless you’re helping him up”;
System.out.println(“Splitting String Using StringTokenizer class”);
StringTokenizer tr=new StringTokenizer(str,” “);
while (tr.hasMoreTokens()) {
System.out.print(“Token “+i+” :”);
System.out.println(tr.nextToken());
++i; }
System.out.println(“Splitting String Using split() method”);
String[] tk=str.split(“ “);
for(String tokens: tk)
System.out.println(tokens);
Pattern p=Pattern.compile(“ “);
tk= p.split(str,3);
for(String tokens: tk)
System.out.println(tokens); }}

© Oxford University Press 2013. All rights reserved.


Enum Type
• is a kind of class definition.
• Subclass of Object class and inherits the Comparable interface
• Defines the type along with the possible set of enum values
which are listed in the curly braces, separated by commas
• All enum types are subclasses of the java.lang.Enum class.
• Each value in an enum is an identifier.
• The following statement declares a type, named Games, with
the values CRICKET, FOOTBALL, TENNIS, and BASKETBALL.
– enum Games { CRICKET, FOOTBALL, TENNIS, BASKETBALL };
• By convention, all names must be in upper case.

© Oxford University Press 2013. All rights reserved.


Enum (contd.)
• Once a type is defined, you can declare a variable of
that type:
– Games G;
– G can hold one of the values defined in the enumerated
type Games or null, but nothing else.
– An attempt to assign a value other than the enumerated
values or null will result in a compilation error.
– The enumerated values can be accessed using the syntax.
• enumeratedTypeName.valueName
• G = Games.TENNIS;

© Oxford University Press 2013. All rights reserved.


Enum Example
public class EnumDemo {
static enum Games {CRICKET, FOOTBALL, CHESS, BASKETBALL,
TENNIS,BADMINTON};
public static void main (String[] args) {
Games G1 = Games.CHESS;
Games G2 = Games.TENNIS;
System.out.println(“First game is “ +G1.name());
System.out.println(“Second game is “ +G2.name());
System.out.println(“First game’s ordinal is “ +G1. ordinal());
System.out.println(“Second game’s ordinal is “ +G2.ordinal());
System.out.println(“G1.equals(G2) returns “ +G1. equals(G2));
System.out.println(“G1.toString() returns “ +G1. toString());
System.out.println(“G1.compareTo(G2) returns
“+G1.compareTo(G2)); }}

© Oxford University Press 2013. All rights reserved.


The output
First game is CHESS
Second game is TENNIS
First game’s ordinal is 2
second game’s ordinal is 4
G1.equals(G2) returns false
G1.toString() returns Chess
G1.compareTo(G2) returns -2

© Oxford University Press 2013. All rights reserved.


for Loop with Enumeration
• Each enumerated type has a static method values( )
associated with them that returns all enumerated
values for the type in an array.
• For example,
– Games[] G = Games.values();
• You can use for loop to process all the values in the
array.
– for (int i = 0; i < G.length; i++)
– System.out.println(G[i]);

© Oxford University Press 2013. All rights reserved.


Conditional Statements with
Enumeration
• can use if or switch-case with Enumerations to test
the value in the variable, as shown below.
If Statement:
if (G1.equals(Games.CRICKET)) {
// action to be performed
} else if (G1.equals(Games.FOOTBALL)) {
// action to be performed
} else ....

© Oxford University Press 2013. All rights reserved.


Conditional Statements with
Enumeration
Switch Statement:
switch (Games) {
case CRICKET: // case CRICKET and not
// Games.CRICKET
// action to be performed;
case FOOTBALL:
// action to be performed;
...
}

© Oxford University Press 2013. All rights reserved.


Attributes and Methods within
Enumeration
public enum Desc {
CRICKET (“Sachin Tendulkar”), CHESS (“Vishwanathan
Anand”), TENNIS (“Sania Mirza”);
private String description;
private Desc(String description) {
this.description = description; }
public String getDesc() {
System.out.print(“Indian Delight: “);
return description; } }

public class UseDesc {


public static void main(String[] args) {
Desc player = Desc.TENNIS; System.out.println(player.getDesc());
}}

© Oxford University Press 2013. All rights reserved.

You might also like