0% found this document useful (0 votes)
21 views38 pages

18CS653 Module 5

Uploaded by

bneelagund
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)
21 views38 pages

18CS653 Module 5

Uploaded by

bneelagund
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/ 38

PROGRAMMING IN JAVA

18CS653
MODULE-5
ENUMERATION , APPLET ,
STRING
TOPICS

Chapter: 12.1,12.2, chap-13 and chap-15

5 Enumerations
5.1 Enumeration Fundamentals
5.1.1The values( ) and valueOf( ) Methods
5.1.2 Java Enumerations Are Class Types
5.2 Type Wrappers
5.3 I/O Basics
5.3.1 Streams
5.3.2 Byte Streams and Character Streams
5.4 Reading Console Input
5.4.1 Reading Characters
5.4.2 Reading Strings.
TOPICS

5.5 Writing Console Output


5.5.1 The PrintWriter Class
5.6 Reading and Writing Files
5.7 Applet Fundamentals
5.8 The transient and volatile Modifiers
5.9 Using instanceof
5.10 strictfp
5.11 Native Methods
5.11.1Problems with Native Methods
5.12 Using assert
5.12.1 Assertion Enabling and Disabling Options
5.13 Static Import
5.14 Invoking Overloaded Constructors Through this( )
TOPICS

5 Enumeration:

enumeration is a list of named constants.


In Java, an enumeration defines a class type.
an enumeration can have constructors, methods, and instance variables.

5.1 Enumeration Fundamentals:


An enumeration is created using the enum keyword.

Example:

// An enumeration of apple varieties.


enum Apple {
Jonathan, GoldenDel, RedDel, Winesap, Cortland
}
The identifiers Jonathan, GoldenDel, RedDel, Winesap, Cortland are
called enumeration constatnts
Each is implicitly declared as a public, static final member of Apple.
 We can create a variable of type Apple
Example Apple ap; // ap is a variable of type Apple enumerator
 We can assign the value to the variable as shown below
ap = Apple.RedDel

Here the value of RedDel is assigned to the variable ap.


 Two enumeration constants can be compared for equality by using the = =
relational operator.
For example, this statement compares the value in ap with the GoldenDel

constant
if ( ap = = Apple.GoldenDel)
An enumeration value can also be used to control a switch statement. Of
course, all of the case statements must use constants from the same enum
as that used by the switch expression.
For example, this switch is perfectly valid:
// Use an enum to control a switch statement.
switch(ap)
{
case Jonathan:
// ...
case Winesap:
// ...
When an enumeration constant is displayed, such as in a println( )
statement, its name is output. For example, given this statement:
System.out.println(Apple.Winesap);
Example of Enumeration
5.1.1 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.
Example for values( ) and valueOf( ) Methods:
5.1.2 Java Enumerations Are Class Types:

 In java although we don’t instantiate an enum using new


 but still we can give them constructors, add instance variables and methods,
and even implement interfaces.

It is important to understand that each enumeration constant is an object of its


enumeration type.
Thus, 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 enumeration.
5.1.2 Example:
5.2 Type Wrappers:

 The type wrappers are Double, Float, Long, Integer, Short, Byte,
Character, and Boolean.
Wrapper classes provide a way to use primitive data types (int, boolean,
etc..) as objects.
The table below shows the primitive type and the equivalent wrapper class:
Character:

Character is a wrapper around a char. The constructor for Character is


Character(char ch)

Here, ch specifies the character that will be wrapped by the Character object
being created.
To obtain the char value contained in a Character object, call charValue( ),
shown here:
char charValue( )

It returns the encapsulated character.


Boolean:
Boolean is a wrapper around boolean values. It defines these
constructors:
Boolean(boolean boolValue)
Boolean(String boolString)

In the first version, boolValue must be either true or false.


In the second version, if boolString contains the string “true” (in uppercase or
lowercase), then the new Boolean object will be true. Otherwise, it will be
false.

To obtain a boolean value from a Boolean object, use booleanValue( ),


shown here:
boolean booleanValue( )
It returns the boolean equivalent of the invoking object.
The Numeric Type Wrappers
The most commonly used type wrappers are those that represent numeric
values.
These are Byte, Short, Integer, Long, Float, and Double.
All of the numeric type wrappers inherit the abstract class Number.
Number declares methods that return the value of an object in each of the
different number formats.
These methods are shown here:

byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )
Example:
Example:
5.3 I/O Basics

Java provide strong, flexible support for I/O as it relates to files and
networks.
Java I/O (Input and Output) is used to process the input and produce the
output.
Example:
In java we can perform file handling using java io API
5.3.1 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.
The input stream can abstract many different kinds of input: from a disk file,
a keyboard, or a network socket.
The output stream may refer to the console, a disk file, or a network
connection.
 example. Java implements streams within class hierarchies defined in the
java.io package.
5.3.2 Byte Streams and Character Streams

Java defines two types of streams: byte and character.


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.
 Character streams provide a convenient means for handling input and
output of characters.
The top most abstract classes of :
Byte Stream Classes Character Stream Classes
----------------------------------------------------------------------------------------------
-
InputStream Reader
OutputStream Writer
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 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, respectively.
5.4 Reading Console Input

 In older version of java the only way to perform console input was to use a
byte stream and older code that uses this approach persists.
Today, using a byte stream to read console input is still technically possible,
but doing so is not recommended.
The preferred method of reading console input is to use a character-oriented
stream, which makes your program easier to internationalize and maintain.

There are three classes using which we can take console input:
BufferedReader class
Scanner class
Console class
Using command line argument
In Java, console input is accomplished by reading from System.in.
To obtain a character based stream that is attached to the console, we need wrap
System.in in a BufferedReader object.
Its most commonly used constructor is shown here:
BufferedReader(Reader inputReader)
To obtain an InputStreamReader object that is linked to System.in, use the
following constructor:
InputStreamReader(InputStream inputStream)
Putting it all together, the following line of code creates a BufferedReader
that is connected to the keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


5.4 .1 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.
Program to demonstrate how to read characters

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');
}
}
String Handling
The String Constructors
String Length
Special String Operations
String Literals
String Concatenation
String Concatenation with Other Data Types
String Conversion and toString( )
Character Extraction
charAt( )
getChars( )
getBytes( )
toCharArray( )
String Comparison
equals( ) and equalsIgnoreCase( )
regionMatches( )
startsWith( ) and endsWith( )
equals( ) Versus ==
compareTo( )
Searching Strings
Modifying a String
substring( )
concat( )
replace( )
trim( )
Data Conversion Using valueOf( )
Changing the Case of Characters Within a String
Additional String Methods
StringBuffer
StringBuffer Constructors
length( ) and capacity( )
ensureCapacity( )
setLength( )
charAt( ) and setCharAt( )
getChars( )
append( )
insert( )
reverse( )
delete( ) and deleteCharAt( )
replace( )
substring( )
Additional StringBuffer Methods
StringBuilder
Strings

String is a sequence of characters. But, unlike many other languages that


implement strings as character arrays, Java implements strings as objects of type
String.
When you create a String object, you are creating a string that cannot be
changed. That is, once a String object has been created, you cannot change the
characters that comprise that string.
Java provides two options: StringBuffer and StringBuilder. Both hold strings
that can be modified after they are created.
The String, StringBuffer, and StringBuilder classes are defined in
java.lang. Thus, they are available to all programs automatically. All are
declared final
Strings Constructor
To create an empty String, you call the default constructor.
For Example,
String s = new String( );
will create an instance of String with no characters in it.

To create a String initialized by an array of characters, use the constructor as


shown below:
String(char chars[ ])
Here is an example:
char chars[ ] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string “abc”.
Strings Constructor
You can also specify a subrange of a character array as an initializer using the
following constructor:
String(char chars[ ], int startIndex , int numChars)
Here, startIndex specifies the index at which the subrange begins, and
numChars specifies the number of characters to use.

Example:
char chars[ ] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
Strings Constructor
You can also construct a String object that contains the same character
sequence as another String object using this constructor:
String(String strObj)
Here, strObj is a String object.
Example:
// Construct one String from another.
class MakeString
{
public static void main(String args[ ])
{
char c[ ] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
Strings length
String length is nothing but, number of characters that string contains. To get
the length of the string simply call the method length() as shown below:
int length();

Example:
class StringLength
{
public static void main(String args[])
{
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
}
}
Special String Operations
We can perform various operation using string such as:
create a new string object using string literal.
Concatenate multiple String objects by use of the + operator
Convert other data types to a string representation.

String Literal : we can create a string object using string literal


Example: String s1 = "abcd";

class StringLiteral
{
public static void main(String args[ ])
{
String s1 = "abcd";
System.out.println(s1);
System.out.println("abcd".length());
}
}
String Concatenation: We can concatenate two strings using +
operator which produce string object as the result

Example:

class StringConcat
{
public static void main(String args[ ])
{
String s1 = "22";
String s2 = "Currently I am" + s1 + "years old ";
System.out.println(s2);
}
}
String Concatenation with other Data types: We can
concatenate strings with other data types.

Example:

class StringConcatOtherDatatype
{
public static void main(String args[ ])
{
int age = 22;
String s2 = "Currently I am " + age + "years old ";
System.out.println(s2);
String s3 = “four:“ + 2+2;
System.out.println(s2);
}
}

Output:
Currently I am 22 years old
four: 22
String Conversion and toString(): We can concatenate strings
with other data types.

Example:

class StringConcatOtherDatatype
{
public static void main(String args[ ])
{
int age = 22;
String s2 = "Currently I am " + age + "years old ";
System.out.println(s2);
String s3 = “four:“ + 2+2;
System.out.println(s2);
}
}

Output:
Currently I am 22 years old
four: 22

You might also like