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

Unit 2

The document discusses Java enumerations, autoboxing, annotations, and generics. Enumerations allow defining a list of named constants that define a new data type and its legal values. All enumerations contain predefined values() and valueOf() methods. Autoboxing automatically wraps primitive types in their object equivalents and vice versa for unboxing. Annotations provide supplemental metadata that does not change program semantics. Generics allow creating reusable classes and methods that work on different data types through type parameters.

Uploaded by

priya j
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)
22 views

Unit 2

The document discusses Java enumerations, autoboxing, annotations, and generics. Enumerations allow defining a list of named constants that define a new data type and its legal values. All enumerations contain predefined values() and valueOf() methods. Autoboxing automatically wraps primitive types in their object equivalents and vice versa for unboxing. Annotations provide supplemental metadata that does not change program semantics. Generics allow creating reusable classes and methods that work on different data types through type parameters.

Uploaded by

priya j
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/ 55

ENUMERATIONS,

AUTOBOXING, AND
ANNOTATIONS
ENUMERATIONS
Introduction
• enumeration is a list of named constants that define a
new data type and its legal values.
• enumeration object can hold only a value that was
declared in the list.
• Enumerations are commonly used to define a set of
values that represent a collection of items.
• For example, an enumeration to represent the error
codes that can result from some operation, such as
success, failed, or pending; or a list of the states that a
device might be in, such as running, stopped, or
paused
Enumeration Fundamentals
The values( ) and valueOf( ) Methods
• All enumerations automatically contain two predefined methods:
values( ) and valueOf( ).
• Their general forms are shown here:
– public static enum-type [ ] values( )
– public static enum-type valueOf(String str )
• The values( ) method returns an array that contains a list of the
enumeration constants.
• The valueOf( ) method returns the enumeration constant whose
value corresponds to the string passed in str.
• In both cases, enum-type is the type of the enumeration
Java Enumerations Are Class Types
// Use an enum constructor, instance class EnumDemo3 {
variable, and method. public static void main(String args[])
enum Apple { {
Jonathan(10), GoldenDel(9), RedDel(12), Apple ap;
Winesap(15), Cortland(8); // Display price of Winesap.
private int price; // price of each apple System.out.println("Winesap costs " +
// Constructor Apple.Winesap.getPrice() +
Apple(int p) { price = p; } " cents.\n");
int getPrice() { return price; } // Display all apples and prices.
} System.out.println("All apple prices:");
for(Apple a : Apple.values())
System.out.println(a + " costs " +
a.getPrice() +
" cents.");
}
}
AUTOBOXING
Introduction
• Beginning with JDK 5, Java added two important features: autoboxing and auto-
unboxing.
• Autoboxing is the process by which a primitive type is automatically
encapsulated (boxed) into its equivalent type wrapper whenever an object of
that type is needed.
• There is no need to explicitly construct an object.
• Auto-unboxing is the process by which the value of a boxed object is
automatically extracted (unboxed) from a type wrapper when its value is needed.
• With autoboxing, it is no longer necessary to manually construct an object in
order to wrap a primitive type. You need only assign that value to a type-wrapper
reference.
• Java automatically constructs the object
Demonstrate autoboxing/unboxing

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
}
}
Autoboxing and Methods
class AutoBox2 {
// Take an Integer parameter and return an int value;
static int m(Integer v) {
return v ; // auto-unbox to int
}
public static void main(String args[]) {
// Pass an int to m() and assign the return value to an Integer. Here, the
//argument 100 is autoboxed into an Integer. The return value is also
//autoboxed into an Integer.

Integer iOb = m(100);


System.out.println(iOb);
}
}
Annotations (Metadata)
• Since JDK 5, Java has supported a feature that enables you to embed
supplemental information into a source file.
• This information, called an annotation, does not change the actions of a
program.
• An annotation leaves the semantics of a program unchanged
Annotation Basics
• An annotation is created through a mechanism based on the interface.
• Let’s begin with an example. Here is the declaration for an annotation called
MyAnno:
// A simple annotation type.
@interface MyAnno {
String str();
int val();
}
• First, notice the @ that precedes the keyword interface.
• This tells the compiler that an annotation type is being declared.
• Next, notice the two members str( ) and val( ).
• All annotations consist solely of method declarations
• All annotation types automatically extend the Annotation interface.
• Annotation is a super-interface of all annotations. It is declared within the
java.lang.annotation package.
The Built-In Annotations
• Java defines many built-in annotations. Most are specialized, but nine
are general purpose.
• Of these, four are imported from java.lang.annotation:
• @Retention, @Documented, @Target, and @Inherited.
• Five - @Override, @Deprecated, @FunctionalInterface, @SafeVarargs,
and @SuppressWarnings are included in java.lang
class Animal{
void eatSomething(){System.out.println("eating something");}
}

class Dog extends Animal{


@Override
void eatsomething(){System.out.println("eating foods");}//should be eatSomething
}

class TestAnnotation1{
public static void main(String args[]){
Animal a=new Dog();
a.eatSomething();
}}
I/O Basics
• Java does provide strong, flexible support for I/O as it relates to files and
networks. Java’s I/O system is cohesive and consistent.
• In fact, once you understand its fundamentals, the rest of the I/O system is easy
to master.
• A general overview of I/O is presented here.
Streams
• Java programs perform I/O through streams.
• A stream is an abstraction that either produces or consumes information.
• A stream is linked to a physical device by the Java I/O system.
• An input stream can abstract many different kinds of input: from a disk file, a
keyboard, or a network socket.
• An output stream may refer to the console, a disk file, or a network connection.
Streams are a clean way to deal with input/output without having every part of
your code understand the difference between a keyboard and a network, for
example.
• Java implements streams within class hierarchies defined in the java.io package.
The Predefined Streams
• System also contains three predefined stream variables: in, out, and err.
• These fields are declared as public, static, and final within System.
• This means that they can be used by any other part of your program and without
reference to a specific System object.
• System.out refers to the standard output stream.
• Console. System.in refers to standard input, which is the keyboard by default.
• System.err refers to the standard error stream, which also is the console by
default
BufferedReader to read characters
from the console
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}
// A tiny editor.
import java.io.*;
class TinyEdit {
public static void main(String args[]) throws IOException
{
// create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str[] = new String[100];
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
for(int i=0; i<100; i++) {
str[i] = br.readLine();
if(str[i].equals("stop")) break;
}
System.out.println("\nHere is your file:");
// display the lines
for(int i=0; i<100; i++) {
if(str[i].equals("stop")) break;
System.out.println(str[i]);
Writing Console Output
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
Generics
• It is possible to create classes, interfaces,
and methods that will work with various
kinds of data.

Eg: Collections Framework.

• Generics means parameterized types.


• Using generics, it is possible to create a
single class, that automatically works with
different types of data.

• A class, interface, or method that operates


on a parameterized type is called generic.
A Simple Generics Example

// A simple generic class.


// Here, T is a type parameter that
// will be replaced by a real type
// when an object of type Gen is created.
class Gen<T> {
T ob; // declare an object of type T
// Pass the constructor a reference to
// an object of type T.
Gen(T o) {
ob = o;
}
// Return ob.
T getob() {
return ob;
}
// Show type of T.
void showType() {
System.out.println("Type of T is " +
ob.getClass().getName());
}
}
// Demonstrate the generic class.

class GenDemo {
public static void main(String args[]) {
// Create a Gen reference for Integers.
Gen<Integer> iOb;
// Create a Gen<Integer> object and assign its
// reference to iOb. Notice the use of autoboxing
// to encapsulate the value 88 within an Integer
object.
iOb = new Gen<Integer>(88);
// Show the type of data used by iOb.
iOb.showType();
// Get the value in iOb. Notice that
// no cast is needed.
int v = iOb.getob();
System.out.println("value: " + v);
System.out.println();
// Create a Gen object for Strings.
Gen<String> strOb = new
Gen<String>("Generics Test");
// Show the type of data used by strOb.
strOb.showType();
// Get the value of strOb. Again, notice
// that no cast is needed.
String str = strOb.getob();
System.out.println("value: " + str);
}
}
Output:

Type of T is java.lang.Integer
value: 88
Type of T is java.lang.String
value: Generics Test
A Generic Class with Two Type Parameters

 We can declare more than one type parameter in a


generic type.

 To specify two or more type parameters,


simply use a comma-separated list.
// A simple generic class with two type
// parameters: T and V.

class TwoGen<T, V> {


T ob1;
V ob2;
// Pass the constructor a reference to
// an object of type T and an object of type V.
TwoGen(T o1, V o2) {
ob1 = o1;
ob2 = o2;
}
// Show types of T and V.
void showTypes() {
System.out.println("Type of T is " +
ob1.getClass().getName());
System.out.println("Type of V is " +
ob2.getClass().getName());
}
T getob1() {
return ob1;
}
V getob2() {
return ob2;
}
}
// Demonstrate TwoGen.
class SimpGen {
public static void main(String args[]) {
TwoGen<Integer, String> tgObj =
new TwoGen<Integer, String>(88, "Generics");
// Show the types.
tgObj.showTypes();
// Obtain and show values.
int v = tgObj.getob1();
System.out.println("value: " + v);
String str = tgObj.getob2();
System.out.println("value: " + str);
}
}
Output:

Type of T is java.lang.Integer
Type of V is java.lang.String
value: 88
value: Generics
The General Form of a Generic Class

 The syntax for declaring a generic class:


class class-name<type-param-list> { // ...

 The syntax for declaring a reference to a


generic class:

class-name<type-arg-list> var-name =
new class-name<type-arg-list>(cons-arg-list);
STRING HANDLING
String class
 String is probably the most commonly used class in Java’s class library.
 The reason for this is that strings are a very important part of programming.
 The first thing to understand about strings is that every string you create is actually
an object of type String.
 Even string constants are actually String objects.
For example, in the statement
System.out.println("This is a String, too");
the string “This is a String, too” is a String constant.
• objects of type String are immutable; once a String object is created, its contents
cannot be altered.
While this may seem like a serious restriction, it is not, for two reasons:
• If you need to change a string, you can always create a new one that contains the
modifications.
• Java defines a peer class of String, called StringBuffer, which allows strings to be
altered, so all of the normal string manipulations are still available in Java.
Strings can be constructed a variety of ways. The easiest is to use a statement like this:
String myString = "this is a test";
Creating Strings
• String str = "abc"; is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);

• If data array in the above example is modified after the string object str is created,
then str remains unchanged.

• Construct a string object by passing another string object.


String str2 = new String(str);
String Operations(1)
1. public char charAt(int index)
• Returns the character at the specified index. An index ranges from 0 to
length() - 1. The first character of the sequence is at index 0, the next at index
1, and so on, as for array indexing.
2. getChars() - Copies characters from this string into the destination character array.
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
• srcBegin - index of the first character in the string to copy.
• srcEnd - index after the last character in the string to copy.
• dst - the destination array.
• dstBegin - the start offset in the destination array.
3. startsWith() – Tests if this string starts with the specified prefix.
public boolean startsWith(String prefix)
“Figure”.startsWith(“Fig”); // true
4. endsWith() - Tests if this string ends with the specified suffix.
public boolean endsWith(String suffix)
“Figure”.endsWith(“re”); // true
String Operations(2)
• compareTo() - Compares two strings lexicographically.
– The result is a negative integer if this String object lexicographically
precedes the argument string.
– The result is a positive integer if this String object lexicographically
follows the argument string.
– The result is zero if the strings are equal.
– compareTo returns 0 exactly when the equals(Object) method would
return true.
public int compareTo(String anotherString)
public int compareToIgnoreCase(String str)
String Operations(3)
indexOf – Searches for the first occurrence of a character or substring.
Returns -1 if the character does not occur.

public int indexOf(int ch)


- Returns the index within this string of the first occurrence of the specified
character.
public int indexOf(String str)
- Returns the index within this string of the first occurrence of the specified
substring.
String str = “How was your day today?”;
str.indexof(‘t’);
str(“was”);
String Operations(4)
• toLowerCase(): Converts all of the characters in a String to lower case.
• toUpperCase(): Converts all of the characters in this String to upper case.

public String toLowerCase()


public String toUpperCase()

Eg: “HELLO THERE”.toLowerCase();


“hello there”.toUpperCase()
Program on String class
class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}
String methods
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " + strOb1.length());
System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
}
StringBuffer
• A StringBuffer is like a String, but can be modified.
• The length and content of the StringBuffer sequence can be changed through
certain method calls.
• StringBuffer defines three constructors:

– StringBuffer()
– StringBuffer(int size)
– StringBuffer(String str)
StringBuffer Operations(1)
• The principal operations on a StringBuffer are the append and insert methods,
which are overloaded so as to accept data of any type.

Here are few append methods:


StringBuffer append(String str)
StringBuffer append(int num)

• The append method always adds these characters at the end of the buffer
StringBuffer Operations(2)
The insert method adds the characters at a specified point.

Here are few insert methods:


StringBuffer insert(int index, String str)
StringBuffer append(int index, char ch)

Index specifies at which point the string will be inserted into the invoking StringBuffer
object.
StringBuffer Operations(3)
• delete() - Removes the characters in a substring of this StringBuffer. The substring
begins at the specified start and extends to the character at index end - 1 or to the
end of the StringBuffer if no such character exists. If start is equal to end, no
changes are made.

public StringBuffer delete(int start, int end)


StringBuffer Operations(4)
• replace() - Replaces the characters in a substring of this StringBuffer with
characters in the specified String.

public StringBuffer replace(int start, int end, String str)

• substring() - Returns a new String that contains a subsequence of characters


currently contained in this StringBuffer. The substring begins at the specified index
and extends to the end of the StringBuffer.

public String substring(int start)


StringBuffer Operations(5)
• reverse() - The character sequence contained in this string buffer is replaced by
the reverse of the sequence.
public StringBuffer reverse()

• length() - Returns the length of this string buffer.


public int length()
StringBuffer Operations(6)
• capacity() - Returns the current capacity of the String buffer. The capacity is the
amount of storage available for newly inserted characters.

public int capacity()

• charAt() - The specified character of the sequence currently represented by the


string buffer, as indicated by the index argument, is returned.

public char charAt(int index)


StringBuffer Operations(7)
• getChars() - Characters are copied from this string buffer into the destination
character array dst. The first character to be copied is at index srcBegin; the last
character to be copied is at index srcEnd-1.

public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

• setLength() - Sets the length of the StringBuffer.

public void setLength(int newLength)


Example : StringBuffer
StringBuffer sb = new StringBuffer(“Hello”);
sb.length(); // 5
sb.capacity(); // 21 (16 characters room is added if no size is specified)
sb.charAt(1); // e
sb.setCharAt(1,’i’); // Hillo
sb.setLength(2); // Hi
sb.append(“l”).append(“l”); // Hill
sb.insert(0, “Big “); // Big Hill
sb.replace(3, 11, “”); // Big
sb.reverse(); // gib

You might also like