Unit 2
Unit 2
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.
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.
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
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
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.
– 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.
• 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.
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 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)