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

Module 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Module 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 70

Module 5

ENUMERATIONS
ENUMERATION FUNDAMENTALS

• An enumeration can be defined simply by creating a list of enum


variable

• Ex

• Identifiers JAVA, CPP, C and DBMS are called enumeration constants.


These are public, static and final by default.
• Variables of Enumeration can be defined directly without any new
keyword.
• Ex: Subject sub;
ENUMERATIONS
• We define an enum variable as: enum_variable =
enum_type.enum_constant;
• Ex: sub = Subject.Java;
• Two enumeration constants can be compared for
equality by using the = = relational operator.
• Ex
Program 1: Example of Enumeration
enum WeekDays
{
sun, mon, tues, wed, thurs, fri, sat
}
class Test
{
public static void main(String args[])
{
WeekDays wk; //wk is an enumeration variable of type WeekDays
wk = WeekDays.sun; //wk can be assigned only the constants
defined under enum type Weekdays
System.out.println("Today is "+wk);
}
}

Output : Today is sun


values() and valueOf() Methods
JAVA ENUMERATIONS ARE CLASS TYPES
• Enumeration with Constructor, instance
variable and Method
• Java E
• When you define a constructor for an enum,
the constructor is called when each
enumeration constant is created.
• Also, each enumeration constant has its own
copy of any instance variables defined by the
enumerations Are Class Type.
ENUMERATIONS INHERITS ENUM
• All enumerations automatically inherit one:
java.lang.Enum.
• final int ordinal( ):It returns the ordinal value of the
invoking constant. Ordinal values begin at zero
• compareTo( ) method:If the invoking constant has
an ordinal value less than e‘s, then compareTo( )
returns a negative value
• enum-type is the type of the enumeration, and e is
the constant being compared to the invoking
constant
TYPE WRAPPERS
• Java uses primitive data types such as int, double, float
etc. to hold the basic data types
• Java provides type Wrappers which provide classes that
encapsulate a primitive type within an object.
• Character : It encapsulates primitive type char within
object.
Character (char ch)
• To obtain the char value contained in a Character
object, call charValue( )
• char charValue( ): It returns the encapsulated character.
• Boolean : It encapsulates primitive type boolean within
object.
• Boolean (boolean boolValue) : boolValue must be either
true or false
• Boolean(String boolString): if boolString contains the string
―true‖ (in uppercase or lowercase), then the new Boolean
object will be true. Otherwise, it will be false.
• Numeric type wrappers : It is the most commonly used
type wrapper.
• byte byteValue( )
• double doubleValue( )
• float floatValue( )
• int intValue( )
• long longValue( )
• short shortValue( )
Ex

• It use a numeric type wrapper to encapsulate


a value and then extract that value.
I/O, Applets, and Other Topics
I/O Basics:
• In the progrms print( ) and println( ), none of
the I/O methods have been used significantly
• most real applications of Java are not text-
based, console programs.
• Java‘s support for console I/O is limited and
somewhat awkward to use—even in simple
example programs
• I/O as it relates to files and networks.
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.
• There are two types of streams: byte and
character
Byte Streams and Character Streams

Byte Streams: Byte streams provide a convenient means


for handling input and output of bytes.
• Byte streams are used, for example, when reading or
writing binary data.
• The original version of Java (Java 1.0) was I/O was byte-
oriented.
Character Streams: Character streams provide a
convenient means for handling input and output of
characters.
• Character streams were added by Java 1.1, and certain
byte-oriented classes and methods were deprecated.
• The character-based streams handling characters.
The Byte Stream Classes
• Byte streams are defined by using two class
hierarchies.
• At the top are two abstract classes: InputStream
and OutputStream
• The abstract classes InputStream and
OutputStream define several key methods that the
other stream classes implement.
• Two of the most important are read( ) and write( ),
which, respectively, read and write bytes of data
The Character Stream Classes
• Character streams are defined by using two class
hierarchies. At the top are two abstract classes,
Reader and Writer.
• These abstract classes handle Unicode character
streams.
• The abstract classes Reader and Writer define
several key methods that the other stream classes
implement.
• Two of the most important methods are read( ) and
write( ), which read and write characters of data
The Predefined Streams

• All Java programs automatically import the java.lang package.


• This package defines a class called System
• System also contains three predefined stream variables: in,
out, and err.
• These fields are declared as public, static, and final within
System.
• System.out refers to the standard output stream. By default,
this is the 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.
• System.in is an object of type InputStream; System.out and
System.err are objects of type PrintStream.
Reading Console Input

• Console input is accomplished by reading from System.in.


• To obtain a character based stream that is attached to the
console, wrap System.in in a BufferedReader object.
• BufferedReader supports a buffered input stream.
BufferedReader(Reader inputReader)
• InputReader is the stream that is linked to the instance of
BufferedReader that is being created. Reader is an abstract
class.
• To obtain an InputStreamReader object that is linked to
System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
• Combining together we have
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Reading Characters
• To read a character from a BufferedReader, use
read( ).
• The version of read( ) that we will be using is
int read( ) throws IOException
• Each time that read( ) is called, it reads a
character from the input stream and returns it
as an integer value.
• It returns –1 when the end of the stream is
encountered.
Reading Strings
• To read a string from the keyboard, use the
version of readLine( ) that is a member of the
BufferedReader class.
• Its general form is shown here:
• String readLine( ) throws IOException: it
returns a String object.
Writing Console Output
• Console output is most easily accomplished with print( ) and
println( ), These methods are defined by the class PrintStream.
• PrintStream is an output stream derived from OutputStream,
it also implements the low-level method write( ).
• write( ) can be used to write to the console.
• The simplest form of write( ) defined by PrintStream is shown
here:
void write(int byteval)
• This method writes to the stream the byte specified by
byteval.
• Although byteval is declared as an integer, only the low-order
eight bits are written.
The Print Writer Class:
• PrintWriter is one of the character-based classes.
• PrintWriter defines several constructors. The one we will use
is shown here:
• PrintWriter(OutputStream outputStream, boolean
flushOnNewline)
• Here, outputStream is an object of type OutputStream, and
flushOnNewline controls whether Java flushes the output
stream every time a println( ) method is called.
• If flushOnNewline is true, flushing automatically takes place.
If false, flushing is not automatic.
• PrintWriter supports the print( ) and println( ) methods for
all types including Object.
For example,
• PrintWriter pw = new PrintWriter(System.out, true);
Reading and Writing Files
• Two of the most often-used stream classes are FileInputStream
and FileOutputStream
• To open a file, you simply create an object of one of these classes,
specifying the name of the file as an argument to the constructor.
• FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
• When you create an input stream, if the file does not exist, then
FileNotFoundException is thrown.
• When you are done with a file, you should close it by calling close(
).
void close( ) throws IOException
• To read from a file, you can use a version of read( ) int read( )
throws IOException
Applet Fundamentals
• Applets are small applications that are
accessed on an Internet server
• Transported over the Internet
• Automatically installed, and run as part of a
web document.
• After creation,it can produce a graphical user
interface and run complex computations
without introducing the risk of viruses
Description:
• The first imports the Abstract Window Toolkit (AWT) classes.
• Applets interact with the user.
• The AWT contains support for a window-based, graphical user
interface.
• The second import statement imports the applet package,
which contains the class Applet.
• The next line in the program declares the class SimpleApplet.
• This class must be declared as public, because it will be
accessed by code that is outside the program
• Inside SimpleApplet, paint( ) is declared. This method is
defined by the AWT and must be overridden by the applet.
• paint( ) is called each time that the applet must redisplay its
output.
There are two ways in which you can run an
applet:
1. Executing the applet within a Java-compatible
web browser.
2. Using an applet viewer, such as the standard
tool, appletviewer.
An applet viewer executes your applet in a
window.
Steps for excution of applet
1. Edit a Java source file.
2. Compile your program.
3. Execute the applet viewer, specifying the
name of your applet‘s source file. The applet
viewer will encounter the APPLET tag within
the comment and execute your applet.
The transient and volatile Modifiers
• Java defines two interesting type modifiers: transient and volatile
• When an instance variable is declared as transient, then its
value need not persist when an object is stored.

• Here, if an object of type T is written to a persistent storage area,


the contents of a would not be saved, but the contents of b
would.
• The volatile modifier tells the compiler that the variable
modified by volatile can be changed unexpectedly by other parts
of your program
Using instanceof
• Type of an object during run time: we use
instanceof
• The instanceof operator has this general
form: objref instanceof type
• Here, objref is a reference to an instance of a
class, and type is a class type.
• instanceof operator evaluates to true.
Otherwise, its result is false.
strictfp

– By modifying a class or a method with strictfp, you


ensure that floating-point calculations (and thus all
truncations) take place precisely as they did in earlier
versions of Java.
– When a class is modified by strictfp, all the
methods in the class are also modified by strictfp
automatically.
• strictfp class MyClass { //...
– Most programmers never need to use strictfp,
because it affects only a very small class of problems.
Using assert
– It is used during program development to create an
assertion
– which is a condition that should be true during the
execution of the program.
– At run time, if the condition actually is true, no other
action takes place. However, if the condition is false, then
an AssertionError is thrown
The assert keyword has two forms. The first is shown here:
• assert condition;
• Here, condition is an expression that must evaluate to
a Boolean result.
– The second form of assert is shown here:
• assert condition : expr;
– expr is a value that is passed to the AssertionError
constructor. This value is converted to its string
format and displayed if an assertion fails.
• Static Import
– JDK 5 added a new feature to Java called static
import that expands the capabilities of the import
keyword.
– By following import with the keyword static, an
import statement can be used to import the static
members of a class or interface
Example:
import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
// Compute the hypotenuse of a right triangle.
class Hypot
{
public static void main(String args[])
{
double side1, side2;
double hypot; side1 = 3.0;
side2 = 4.0;
// Here, sqrt() and pow() can be called by themselves,
// without their class name.
hypot = sqrt(pow(side1, 2) + pow(side2, 2));
System.out.println("Given sides of lengths " + side1 + " and " + side2 + " the
hypotenuse is " + hypot);
}
}
Invoking Overloaded Constructors Through
this( )
– When working with overloaded constructors, it is
sometimes useful for one constructor to invoke
another.
– In Java, this is accomplished by using another form
of the this keyword.
– The general form is shown here:
this(arg-list);
class MyClass {
int a; int b;
// initialize a and b individually MyClass(int i, int j) {
a = i; b = j;
}
// initialize a and b to the same value MyClass(int i) {
this(i, i); // invokes MyClass(i, i)
}
// give a and b default values of 0 MyClass( ) {
this(0); // invokes MyClass(0)
}
}
String Handling
• The String Constructors
– The String class supports several constructors. To create an
empty String, you call the default constructor. For example,
• String s = new String();
– To create a String initialized by an array of characters, use
the constructor shown here:
• String(char chars[ ])
Example:
• char chars[] = { 'm', 'a', 'n' };
• String s = new String(chars);
• Example:
• char chars[] = { 'h', 'e', 'l', 'l', 'o' };
• String s = new String(chars, 2, 3,4);
• This initializes s with the characters llo.
Example:
class MakeString {
public static void main(String args[])
{
char c[] = {'r', 'a', 'm', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
Output:
rama rama
String Length
– The length of a string is the number of characters
that it contains. To obtain this value, call the
length( ) method, shown here:
• int length( );
• Example:
• char chars[] = {‘k‘, ‘r‘, ‘i‘, ‘s‘, ‘h‘};
• s = new String(chars);
System.out.println(s.length());// displays 5
Special String Operations
• String Literals
– To explicitly create a String instance from an array
of characters by using the new operator. an easier
way to do this using a string literal.
• Example:
• char chars[] = {‘k‘, ‘r‘, ‘i‘, ‘s‘, ‘h‘};
• String s1 = new String(chars);
• String s2 = "krish"; // use string literal
String Concatenation
– Java does not allow operators to be applied to String
objects.
– The one exception to this rule is the + operator, which
concatenates two strings, producing a String object
Example:
• String marks = "35";
• String s = "He scored " + marks+ " in internals.";
• System.out.println(s);
o/p:
He scored 35 in internals
Character Extraction
• charAt( ):
– To extract a single character from a String, you can
refer directly to an individual character via the
charAt( ) method. It has this general form:
• char charAt(int where);
• Example:
• char ch;
• ch = "abc".charAt(1);// ch contains b
• getChars( )
– If you need to extract more than one character at a time, you can use the
getChars( ) method.
It has this general form:
• void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart)
• Example:
• String s = "Abhimanyu is a good cricket player";
• int start = 16;
• int end = 20;
• char buf[] = new char[end - start];
• s.getChars(start, end, buf, 0);
• System.out.println(buf);
Output:
• good
getBytes( )
– There is an alternative to getChars( ) that stores
the characters in an array of bytes. This method is
called getBytes( ), and it uses the default
character-to-byte conversions provided by the
platform.
– Here is its simplest form:
• byte[ ] getBytes( )
• toCharArray( )
– If you want to convert all the characters in a
String object into a character array, the easiest
way is to call toCharArray( ).
– It returns an array of characters for the entire
string.
It has this general form:
• char[ ] toCharArray( )
String Comparison
• equals( ) and equalsIgnoreCase( )
– To compare two strings for equality, use equals( ).
It has this general form:
– boolean equals(Object str)
– To perform a comparison that ignores case
differences, call equalsIgnoreCase( ). It has this
general form:
• boolean equalsIgnoreCase(String str)
Example:
class equalsDemo {
public static void main(String args[]) {
String s1 = "Sourabh";
String s2 = "Sourabh";
String s3 = "Nikil";
String s4 = "SOURABH";
System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));

}
}
Modifying a String
• substring( )
– You can extract a substring using substring( ). It
has two forms.
– The first is String substring(int startIndex)
– The second form of substring( ) allows you to
specify both the beginning and ending index of
the substring:
• String substring(int startIndex, int endIndex)
Changing the Case of Characters Within a String
– The method toLowerCase( ) converts all the characters in a string from
uppercase to lowercase.
– The toUpperCase( ) method converts all the characters in a string from
lowercase to uppercase
– General forms of these methods:
• String toLowerCase( ) String toUpperCase( )
Example:
class ChangeCase {
public static void main(String args[])
{
String s = "Lord Krishna";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
Output:
• Origianl: Lord Krishna
• Uppercase: LORD KRISHNA
• Lowercase: lord krishna
StringBuffer
StringBuffer may have characters and substrings
inserted in the middle or appended to the end.
StringBuffer Constructors
– StringBuffer defines these four constructors:
– StringBuffer( ): The default constructor (the one with no
parameters) reserves room for 16 characters without
reallocation.
– StringBuffer(int size): accepts an integer argument that
explicitly sets the size of the buffer.
– StringBuffer(String str): accepts a String argument that
sets the initial contents of the StringBuffer object and
reserves room for 16 more characters without
reallocation
– StringBuffer(CharSequence chars): creates an object that
contains the character sequence contained in chars.
• length( )
– The current length of a StringBuffer can be found
via the length( ) method.
– They have the following general forms:
• int length( ) int capacity( )
class StringBufferDemo {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Krishna");
System.out.println("buffer = " + sb);
// displays Krishna
System.out.println("length = " + sb.length());
// displays 7

}
}
• setLength( )
– To set the length of the buffer within a
StringBuffer object, use setLength( ). Its general
form is shown here:
• void setLength(int len)
charAt( ) and setCharAt( )
– The value of a single character can be obtained from a
StringBuffer via the charAt( ) method.
• You can set the value of a character within a StringBuffer
using setCharAt().
• Their general forms are shown here: char charAt(int
where)
• void setCharAt(int where, char ch)

Example:
• StringBuffer sb = new StringBuffer("Krishna");
sb.charAt(2)// selects i
• sb.setCharAt(2, “u‘)// sets second index value to u means
krushna
insert( )
– The insert( ) method inserts one string into another. It is overloaded to accept
values of all the simple types, plus Strings, Objects, and CharSequences.
These are a few of its forms:
• StringBuffer insert(int index, String str)
Example:
class insertDemo {

StringBuffer insert(int index, char ch) StringBuffer insert(int index,


Object obj)

public static void main(String args[]) {


StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
The output of this example is shown here:
I like Java!
reverse( )
– You can reverse the characters within a StringBuffer object using
reverse( ), shown here:
• StringBuffer reverse( )
Example:
class ReverseDemo {
public static void main(String args[]) {
StringBuffer s = new StringBuffer("abcdef"); System.out.println(s);
s.reverse(); System.out.println(s);
}
}
Here is the output produced by the program:
abcdef fedcba
• replace( )
– You can replace one set of characters with another
set inside a StringBuffer object by calling
replace( ). Its signature is shown here:
• StringBuffer replace(int startIndex, int
endIndex, String str)
• delete( ) and deleteCharAt( )
– You can delete characters within a StringBuffer by
using the methods delete( ) and
• deleteCharAt( ). These methods are shown
here:

StringBuffer delete(int startIndex, int


endIndex) StringBuffer deleteCharAt(int loc)
• substring( )
– You can obtain a portion of a StringBuffer by
calling substring( ). It has the following two forms:
• String substring(int startIndex)
• String substring(int startIndex, int endIndex)
– The first form returns the substring that starts at
startIndex and runs to the end of the invoking
StringBuffer object.
– The second form returns the substring that starts
at startIndex and runs through
• endIndex–1.
• StringBuilder
– J2SE 5 adds a new string class to Java‘s already powerful
string handling capabilities. This new class is called
StringBuilder.
– It is identical to StringBuffer except for one
important difference: it is not synchronized, which
means that it is not thread-safe.
– The advantage of StringBuilder is faster performance.
– However, in cases in which you are using multithreading,
you must use StringBuffer
• rather than StringBuilder.

You might also like