1. APPLETS
A Java applet is a special kind of Java program that a browser enabled with Java technology
can download from the internet and run. An applet is typically embedded inside a web page
and runs in the context of a browser. An applet must be a subclass of the java.applet.Applet
class. The Applet class provides the standard interface between the applet and the browser
environment.
The Applet class is contained in the java.applet package.Applet contains several methods
that give you detailed control over the execution of your applet.
In addition,java.applet package also defines three interfaces: AppletContext, AudioClip,
and AppletStub.
Applet Basics:
All applets are subclasses of Applet. Thus, all applets must import java.applet. Applets must
also import java.awt. AWT stands for the Abstract Window Toolkit. Since all applets run in a
window, it is necessary to include support for that window by importing java.awt package.
Applets are not executed by the console-based Java run-time interpreter. Rather, they are
executed by either a Web browser or an applet viewer.
Execution of an applet does not begin at main( ). Output to your appletâs window is not
performed by System.out.println( ). Rather, it is handled with various AWT methods, such
as drawString( ), which outputs a string to a specified X,Y location. Input is also handled
differently than in an application.
Once an applet has been compiled, it is included in an HTML file using theAPPLET tag. The
applet will be executed by a Java-enabled web browser when it encounters the APPLET tag
within the HTML file.
To view and test an applet more conveniently, simply include a comment at the head of your
Java source code file that contains the APPLET tag.
Here is an example of such a comment:
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet called MyApplet in a window
that is 200 pixels wide and 60 pixels high. Since the inclusion of an APPLET command
makes testing applets easier, all of the applets shown in this tutorial will contain the
appropriate APPLET tag embedded in a comment.
2. The Applet Class:
Applet extends the AWT class Panel. In turn, Panel extends Container, which extends
Component. These classes provide support for Javaâs window-based, graphical interface.
Thus, Applet provides all of the necessary support for window-based activities
Applet Architecture:
An applet is a window-based program. As such, its architecture is different from the so-called
normal, console-based programs .
First, applets are event driven. it is important to understand in a general way how the event-
driven architecture impacts the design of an applet.
Here is how the process works. An applet waits until an event occurs. The AWT notifies the
applet about an event by calling an event handler that has been provided by the applet. Once
this happens, the applet must take appropriate action and then quickly return control to the
AWT.
An Applet Skeleton:
Four methodsâinit( ), start( ), stop( ), and destroy( )âaredefined by Applet. Another,
paint( ), is defined by the AWT Component class. All applets must import java.applet.
Applets must also import java.awt.
These five methods can be assembled into the skeleton shown here:
// An Applet skeleton.
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet
{
// Called first.
public void init()
{
// initialization
}
/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start()
{
// start or resume execution
}
// Called when the applet is stopped.
public void stop()
{
// suspends execution
3. }
/* Called when applet is terminated. This is the last
method executed. */
public void destroy()
{
// perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g)
{
// redisplay contents of window
}
}
Applet Initialization and Termination:
It is important to understand the order in which the various methods shown in theskeleton are
called. When an applet begins, the AWT calls the following methods, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
init( ):init( ) method is called onceâthe first time an applet is loaded. The init( ) method is
the first method to be called. This is where you should initialize variables.
start():The start( ) method is called after init( ). It is also called to restart an applet after it
has been stopped(i.e start() method is called every time, the applet resumes execution).
Paint():The paint( ) method is called each time your appletâs output must be redrawn. This
situation can occur for several reasons. For example, the window in which the applet is
running may be overwritten by another window and then uncovered. Or the applet window
may be minimized and then restored. paint( ) is also called when the applet begins execution.
Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The
paint( ) method has one parameter of type Graphics.
stop( ):The stop() method is called when the applet is stopped(i.e for example ,when the
applet is minimized the stop method is called).
destroy( ):The destroy( ) method is called when the environment determines that your applet
needs to be removed completely from memory(i.e destroy() method is called when the applet
is about to terminate).The stop( ) method is always called before destroy( ).
4. Simple Applet programe:
SimpleApplet.java
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleApplet" width=300 height=100>
</applet>
*/
public class SimpleApplet extends Applet
{
String msg="";
// Called first.
public void init()
{
msg="Hello";
}
/* Called second, after init().
Also called whenever the applet is restarted. */
public void start()
{
msg=msg+",Welcome to Applet";
}
// whenever the applet must redraw its output, paint( ) is called.
public void paint(Graphics g)
{
g.drawString(msg,20,20);
}
}
Output:
5. How To Run an Applet Programe:
There are two ways in which you can run an applet:
â Executing the applet within a Java-compatible Web browser.
â Using an applet viewer, such as the standard SDK tool, appletviewer. An applet viewer
executes your applet in a window. This is generally the fastestand easiest way to test your
applet.
Using an applet viewer to run applet(demonstrates you to run SimpleApplet.java):
Place the applet tag in comments in java source code.
Note:Code attribute value must be equal to name of class which extends Applet class.
Compiling: javac SimpleApplet.java
Run: AppletViewer SimpleApplet.java
Executing the applet within a Java-compatible Web browser(demonstrates you to run
SimpleApplet.java):
Compiling: javac SimpleApplet.java
Create an Html file and embeded Applet tag in html file.
Attributes in applet tag:
Code(attribute):specify name of applet class to load into browser.
Width(attribute):width of an applet.
Height(attribute):height of an applet.
SimpleApplet.html
<html>
<body>
<applet code="SimpleApplet" width=300 height=100></applet>
</body>
</html>
When you open SimpleApplet.html , SimpleApplet.class applet is loaded into browser.
Note: The Browser must be java enabled to load applet programe.
Simple Applet Display Methods:
As weâve mentioned, applets are displayed in a window and they use the AWT to perform
input and output.To output a string to an applet, use drawString( ), which is a member of the
Graphics class.Graphics class is defined in java.awt package.
void drawString(String message, int x, int y)
Here, message is the string to be output and x and y are x-coordinate ,y-coordinate
respectively. In a Java window, the upper-left corner is location 0,0.
6. To set the background color of an appletâs window, use setBackground( ). To set the
foreground color (the color in which text is shown, for example), use setForeground( ).
These methods are defined by Component, and they have the following general forms:
void setBackground(Color newColor)
void setForeground(ColornewColor)
Here, newColor specifies the new color. The class Color defines the constants shown
here that can be used to specify colors:
Color.black Color.magenta
Color.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellow
Color.lightGray
For example, this sets the background color to green and the text color to red:
setBackground(Color.green);
setForeground(Color.red);
Sample.java
/* A simple applet that sets the foreground and background colors and outputs a string. */
import java.awt.*;
import java.applet.*;
/*
<applet code="Sample" width=300 height=200>
</applet>
*/
public class Sample extends Applet
{
String msg;
public void init()
{
setBackground(Color.gray);
setForeground(Color.white);
msg = "Inside init( ) --";
}
// Initialize the string to be displayed.
public void start()
{
msg += " Inside start( ) --";
}
// Display msg in applet window.
public void paint(Graphics g)
{ msg += " Inside paint( ).";
g.drawString(msg, 10, 30);
}
}
7. Output:
Requesting Repainting:
Whenever your applet needs to update the information displayed in its window, it simply
calls repaint( ).The repaint( ) method is defined by the AWT. It causes the AWT run-time
system to execute a call to your appletâs update( ) method, which, in its default
implementation, calls paint( ).
The simplest version of repaint( ) is shown here:
void repaint( )
This version causes the entire window to be repainted. The following version specifies a
region that will be repainted:
void repaint(int left, int top, int width, int height)
Here, the coordinates of the upper-left corner of the region are specified by left and top, and
the width and height of the region are passed in width and height. These dimensions are
specified in pixels. You save time by specifying a region to repaint.
The other two versions of repaint():
void repaint(long maxDelay)
void repaint(long maxDelay, int x, int y, int width, int height)
Here, maxDelay specifies the maximum number of milliseconds that can elapse before
update( ) is called.
Using the Status Window:
In addition to displaying information in its window, an applet can also output a message to
the status window of the browser or applet viewer on which it is running. To do so, call
showStatus( ) with the string that you want displayed.
// Using the Status Window.
import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=300>
</applet>
*/
public class StatusWindow extends Applet
{
public void init()
{
8. setBackground(Color.cyan);
}
// Display msg in applet window.
public void paint(Graphics g)
{
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}
Output:
The HTMLAPPLET Tag:
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
. . .
[HTML Displayed in the absence of Java]
</APPLET>
Letâs take a look at each part now.
CODEBASE: CODEBASE is an optional attribute that specifies the base URL of the
applet code, which is the directory that will be searched for the appletâs executable
class file (specified by the CODE tag).
CODE :CODE is a required attribute that gives the name of the file containing your
appletâs compiled .class file. This file is relative to the code base URL of the applet,
which is the directory that the HTML file was in or the directory indicated by
CODEBASE if set.
9. ALT :The ALT tag is an optional attribute used to specify a short text message that
should be displayed if the browser understands the APPLET tag but canât currently
run Java applets.
NAME: NAME is an optional attribute used to specify a name for the applet instance.
Applets must be named in order for other applets on the same page to find them by
name and communicate with them.
WIDTH AND HEIGHT :WIDTH and HEIGHT are required attributes that give the
size (in pixels) of the applet display area.
ALIGN: ALIGN is an optional attribute that specifies the alignment of the applet.The
possible values:LEFT, RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP,
ABSMIDDLE,and ABSBOTTOM.
VSPACE AND HSPACE :These attributes are optional. VSPACE specifies the space,
in pixels, above and below the applet. HSPACE specifies the space, in pixels, on each
side of the applet.
PARAM NAME AND VALUE: The PARAM tag allows you to specify applet specific
arguments in an HTML page. Applets access their attributes with the getParameter( )
method.
Passing Parameters to Applets:
The APPLET tag in HTML allows you to pass parameters to your applet. To retrieve a
parameter, use the getParameter( ) method. It returns the value of the specified parameter in
the form of a String object. Here is an example that demonstrates passing parameters:
ParamDemo.java
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width=300 height=300>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/
public class ParamDemo extends Applet
{
String fn=null,fz=null,l=null,ae=null;
public void init()
{
setBackground(Color.gray);
setForeground(Color.white);
}
10. public void start()
{
fn=getParameter("fontName");
fz=getParameter("fontSize");
l=getParameter("leading");
ae=getParameter("accountEnabled");
repaint();
}
public void paint(Graphics g)
{
g.drawString("FontName:"+fn,10,10);
g.drawString("FontSize:"+fz,10,30);
g.drawString("Leading:"+l,10,50);
g.drawString("AccountEnabled:"+ae,10,70);
}
}
Output:
getDocumentBase( ) and getCodeBase( ):
Java will allow the applet to load data from the directory holding the HTML file that started
the applet (the document base) and the directory from which the appletâs class file was loaded
(the code base). These directories are returned as URL objects by getDocumentBase( ) and
getCodeBase( ).
Bases.java
import java.awt.*;
import java.applet.*;
import java.net.*;
/*<applet code="Bases" width=300 height=50></applet>*/
public class Bases extends Applet
{
// Display code and document bases.
public void paint(Graphics g)
{
String msg;
//URL class is defines in java.net package.
URL url = getCodeBase(); // get code base
11. msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);
url = getDocumentBase(); // get document base
msg = "Document base: " + url.toString();
g.drawString(msg, 10, 40);
}
}
Sample output from this program is shown here:
AppletContext and showDocument( ):
To allow your applet to transfer control to another URL, you must use the showDocument( )
method defined by the AppletContext interface.
ACDemo.java
import java.awt.*;
import java.applet.*;
import java.net.*;
/*<applet code="ACDemo" width=300 height=50></applet>*/
public class ACDemo extends Applet
{
URL u;
public void start()
{
AppletContext ac = getAppletContext();
URL url = getCodeBase(); // get url of this applet
try
{
u=new URL(url+"Test.html");
ac.showDocument(u);
}
catch(MalformedURLException e)
{
showStatus("URL not found");
}
}
}
Explanation:In this programe,the control is transfered from ACDemo.class (i.e applet) to
Test.html file.
12. Two Types of Applets:
There are two varieties of applets. The first are those based directly on the Applet class.
These applets use the Abstract Window Toolkit (AWT) to provide the graphic user interface
(or use no GUI at all). This style of applet has been available since Java was first created.
The second type of applets are those based on the Swing class JApplet. Swing applets use
the Swing classes to provide the GUI. Swing offers a richer and often easier-to-use user
interface than does the AWT. Thus, Swing-based applets are now the most popular. JApplet
inherits Applet, all the features of Applet are also available in Japplet.
13. JAVA EXCEPTIONS
GENERAL
An exception is a problem that arises during the execution of a program. An exception can occur for many
different reasons, including thefollowing:
ďˇ A user hasentered invalid data.
ďˇ A file that needs to be opened cannot be found.
ďˇ A network connection has been lost in the middle of communications or the JVM has run out of
memory.
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in somemanner.
To understand how exception handling works in Java,you need to understand the three categories of
exceptions:
ďˇ Checked exceptions: A checked exception is an exception that is typically a user error or a
problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the
file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of
compilation.
ďˇ Runtime exceptions: A runtime exception is an exception that occurs that probably could have
been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored
at the time of compilation.
ďˇ Errors: These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at
the time of compilation.
EXCEPTION HIERARCHY
All exception classes are subtypes of the java.lang.Exception class.The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is derived
from the Throwableclass.
Errors are not normally trapped form the Javaprograms. These conditions normally happen in case of severe
failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the
runtime environment. Example :JVM is out of Memory. Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
14. EXCEPTIONS METHODS
Following is the list of important medthods available in the Throwable class.
Methods with Description
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the
Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object
3 public String toString()
Returns the name of the class concatenated with the result of getMessage()
4 public voidprintStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5 public StackTraceElement []getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top
of the call stack,and the last element in the array represents the method at the bottom of the call stack.
6 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous
information in the stacktrace.
CATCHING EXCEPTIONS
A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed
around the code that might generate an exception. Code within a try/catch block is referred to as protected
code, and the syntax for using try/catchlooks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in
protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that
15. occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed
into a methodparameter.
EXAMPLE
The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array
which throws anexception.
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
This would produce the followingresult:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
MULTIPLE CATCH BLOCKS
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of them after a single
try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If
the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception
passes down to the second catch statement. This continues until the exception either is caught or falls through
16. all catches, in which case the current method stops execution and the exception is thrown down to the
previous method on thecall stack.
EXAMPLE
Here is code segment showing how to use multiple try/catch statements.
try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}
THE THROWS/THROW KEYWORDS
If a method does not handle a checked exception, the method must declare it using the throws keyword. The
throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the
throw keyword. Try to understand the different in throws and throw keywords.
The following method declares that it throws a RemoteException:
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions are declared in a
list separated by commas. For example, the following method declares that it throws a RemoteException
and an InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
17. // Method implementation
}
//Remainder of class definition
}
THE FINALLY KEYWORD
The finally keyword is used to create a block of code that follows a try block. A finally block of code always
executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanupâtype statements that you want to execute, no matter what
happens in the protectedcode.
A finally block appears at the end of the catch blocks and has the following syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
EXAMPLE
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
}
}
}
18. This would produce the followingresult:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
NOTE
ďˇ A catch clause cannot exist without a try statement.
ďˇ It is not compulsory to have finally clauses when ever a try/catchblock is present.
ďˇ The try block cannot be present without either catch clause or finally clause.
ďˇ Any code cannot be present in between the try,catch, finally blocks.
DECLARING YOU OWN EXCEPTION
You can create your own exceptions in Java.Keep the following points in mind when writing your own
exception classes:
ďˇ All exceptions must be a child of Throwable.
ďˇ If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule,
you need to extend the Exception class.
ďˇ If you want to write a runtime exception, you need to extend the RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception{
}
You just need to extend the Exception class to create your own Exception class. These are considered to be
checked exceptions. The following InsufficientFundsException class is a userâdefined exception that extends
the Exception class, making it a checked exception. An exception class is like any other class, containing useful
fields and methods.
EXAMPLE
// File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
19. {
return amount;
}
}
To demonstrate using our userâdefined exception, the following CheckingAccount class contains a
withdraw() method that throws anInsufficientFundsException.
// File Name CheckingAccount.java
import java.io.*;
public class CheckingAccount
{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of
CheckingAccount.
// File Name BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
20. CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo, this would produce the following result:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
COMMON EXCEPTIONS
In Java,it is possible to define two catergories of Exceptions and Errors.
ďˇ JVM Exceptions: â These are exceptions/errors that are exclusively or logically thrown by the
JVM. Examples :NullPointerException, ArrayIndexOutOfBoundsException,ClassCastException,
ďˇ Programmatic exceptions: â These exceptions are thrown explicitly by the application or the
API programmers Examples: IllegalArgumentException, IllegalStateException.
21. byte a = 68;
char a = 'A';
byte, int, long, and short can be expressed in decimal (base 10), hexadecimal (base 16) or octal (base 8) number
systems as well. Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these
number systems for literals.
FOR EXAMPLE:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
String literals in Javaare specified like they are in most other languages by enclosing a sequence of characters
between a pair of doublequotes.
23. What is String?
⢠String is non-primitive data type and it is also class which is
under java.lang.package.
⢠String is a collection of characters.
⢠String is immutable
⢠Without new keyword we can create object .
⢠It introduced in JDK1.1.
24. What is String literals?
⢠String s=âJavaâ;
⢠SCP is part of Heap memory.
âJavaâ string literal which is
stored in String Constant Pool
(SCP)
SCP
25. Why String is immutable?
⢠Strings are constant, values canât be changed after they are created.
⢠Because java uses the concept of string literal.
⢠Suppose, if one reference variable changes the value of the object, it will
be affected to all the reference variables. That is why string objects are
immutable in java.
⢠So, String is immutable.
30. Example 3: subString()
substring(int start/begin index)
substring(int startindex, int endindex)
Overloading
Returns a new string that is
a substring of this string.
31. Example 4: equals()
Return type is boolean
The String equals() method overrides the equals() method of Object class.
35. Example 8: split()
It returns array of strings computed by splitting this string around matches of the given regular
expression. It introduced in JDK 1.4.
36. Example 9: split()
It returns array of strings computed by splitting this string around matches of the given regular
expression. It introduced in JDK 1.4.
Overloading
37. Example 10: concat()
⢠It returns a string that represents the concatenation of this object's
characters followed by the string argument's characters.
48. Methods Name Introduced
Version
Description Return Type Parameter
charAt() 1.0 The char value at the specified
index. An index ranges
from 0 to length() â 1(length in
interface CharSequence)
The char value at the
specified index of this
string. The
first char value is at
index 0.
index - the index of
the char value.
IsEmpty() 1.6 If it is true, and only
if, length() is 0.
True if length() is 0,
otherwise false
No
concat() 1.0 Concatenates the specified string to
the end of this string.If the length
of the argument string is 0, then
this String object is returned
A string that
represents the
concatenation of this
object's characters
followed by the string
argument's characters.
The String that is
concatenated to the
end of this String.
compareTo() 1.0 The comparison is based on the
Unicode value of each character in
the strings.
The value 0 if the
argument string is
equal to this string
The String to be
compared.
49. Methods
Name
Introduced
Version
Description Return Type Parameter
contains() 1.5 True if and only if this string
contains the specified sequence
of char values.
True if this string contains s, false
otherwise
The sequence to
search for.
trim() 1.0 a copy of the string, with
leading and trailing whitespace
omitted.
Acopy of this string with leading
and trailing white space removed, or
this string if it has no leading or
trailing white space.
No
equals
IgnoreCas
e()
1.0 Compares this String to
another String, ignoring case
considerations
true if the argument is not null and it
represents an
equivalent String ignoring
case; false otherwise.
The String to compare
this String against
length() 1.0 The length of this string. The
length is equal to the number
of Unicode code units in the
string. (charAt in
interface CharSequence)
the length of the sequence of
characters represented by this object.
No
50. Methods
Name
Introduced
Version
Description Return Type Parameter Exception
replaceAll() 1.4 Replaces each substring of
this string that matches the
given regular
expression with the given
replacement.
The resulting String. the sequence to
search for
PatternSyntaxE
xception
replaceFirst() 1.4 Replaces the first substring
of this string that matches
the given regular
expression with the given
replacement.
The resulting String. the regular
expression to which
this string is to be
matchedreplacement
- the string to be
substituted for the
first match
IndexOutOfBo
undsException
-
compareTo 1.2
IgnoreCase()
Compares two strings
lexicographically, ignoring
case differences.
The specified String is
greater than, equal to,
or less than this
String, ignoring case
considerations.
The String to be
compared.
No
51. Methods
Name
Introduced
Version
Description Return Type Parameter Exception
toUpperCase() 1.0 Converts all of the
characters in this String to
upper case using the rules
of the default locale.
the String,
converted to
uppercase.
No No
toLoweCase() 1.0 Converts all of the
characters in this String to
lower case using the rules
of the default locale.
the String,
converted to
lowercase.
No No
join() 1.8 A string joined with given
delimiter. In string join
method, delimiter is copied
for each elements.
Joined string with
delimiter.
delimiter : char
value to be added
with each element
elements : char
value to be
attached with
delimiter
NullPointerExce
ption
52. Methods Name Introduced
Version
Description(Overrides a class
Object)
Return Type Parameter
equals() 1.0 Compares this string to the specified
object. The result is true if and only if
the argument is not null and is
a String object that represents the
same sequence of characters as this
object.
True if the given
object represents
a String equivalent to
this
string, false otherwise
The object to compare
this String against
hashCode() 1.0 A hash code for this string. A hash code value for No
this object.
toString() 1.0 The toString method for
class Object returns a string consisting
of the name of the class of which the
object is an instance.
This object (which is already a string!)
is itself returned.
Astring representation No
of the object.
53. Methods
Name
Introduce
d Version
Description(Overloading) Return Type Parameter Exception
substring() 1.0 Returns a new string that is a
substring of this string. The
substring begins with the
character at the specified
index and extends to the end
of this string.
the specified
substring.
beginIndex - the
beginning index,
inclusive.
IndexOutOfBoun
dsException -
substring() 1.0 Returns a new string that is
a substring of this string.
The substring begins at the
specified beginIndex and
extends to the character at
index endIndex - 1. Thus the
length of the substring
is endIndex-beginIndex.
the specified
substring.
beginIndex - the
beginning index,
inclusive.
endIndex - the
ending index,
exclusive.
IndexOutOfBoun
dsException -
54. Methods
Name
Introduce
d Version
Description(Overloading) Return Type Parameter Exception
replace() 1.0 Returns a new string resulting
from replacing all occurrences
of oldChar in this string
with newChar.
A string derived
from this string by
replacing every
occurrence
of oldChar with ne
wChar.
oldChar - the old No
character.newChar
- the new
character.
replace() 1.5 Replaces each substring of
this string that matches the
literal target sequence with the
specified literal replacement
sequence.
The
resulting String.
NullPointerExcept
target - The
sequence of char ion
values to be
replacedreplaceme
nt - The
replacement
sequence of char
values
55. Methods
Name
Introduced
Version
Description(Overloading) Return Type Parameter Exception
split() 1.4 Splits this string around
matches of the given regular
expression
The array of strings
computed by
splitting this string
around matches of
the given regular
expression
The delimiting
regular expression.
PatternSyntaxExce
ption
split() 1.4 Splits this string around
matches of the given regular
expression.
the array of strings
computed by
splitting this string
around matches of
the given regular
expression.
regex - the
delimiting regular
expressionlimit -
the result
threshold, as
described above
PatternSyntaxExce
ption -
56. Methods
Name
Introduced
Version
Description(Overloading) Return Type Parameter Exception
index() 1.0 The index within this string
of the first occurrence of the
specified character.
the index of the
first occurrence of
the character in the
character sequence
represented by this
object
a character
(Unicode code
point).
No
index() 1.0
â â
fromIndex - the
index to start the
search from.
No
index() 1.0
â
The index of the
first occurrence of
the specified
substring
the substring to
search for.
No
index() 1.0 â â fromIndex - the
index from which
to start the search.
No
57. Methods
Name
Introduced
Version
Description(Overloading) Return Type Parameter Exception
lastIndex() 1.0 The index within this string
of the last occurrence of the
specified character.
the index of the last
occurrence of the
character in the
character sequence
represented by this
object
a character
(Unicode code
point).
No
lastIndex() 1.0
â â
fromIndex - the
index to start the
search from.
No
lastIndex() 1.0
â
The index of the
first occurrence of
the specified
substring
the substring to
search for.
No
lastIndex() 1.0 â â fromIndex - the
index from which
to start the search.
No
58. What is String Buffer?
⢠StringBuffer is mutable String.
⢠Java StringBuffer class is (synchronized )thread-safe i.e. multiple threads
cannot access it simultaneously.
⢠So it is safe and will result in an order.
59. Why String Buffer is mutable?
append() it return many data types
Overloading
61. Methods
Name
Introduced
Version
Description Return Type Parameter Exception
delete() 1.2 Removes the characters in a
substring of this sequence.
This object. start - The
beginning index,
inclusive.end - The
ending index,
exclusive.
StringIndexOutOf
BoundsException
deleteCharAt() 1.2 Removes the char at the
specified position in this
sequence. This sequence is
shortened by one char.
â Index of char to
remove
â
replace() 1.2 Replaces the characters in a
substring of this sequence
with characters in the
specified String.
â start - The
beginning index,
inclusive.end - The
ending index,
exclusive.str -
String that will
replace previous
contents.
â
62. Methods
Name
Introduced
Version
Description Return Type Parameter Exception
reverse() 1.0.2 Causes this character
sequence to be replaced by
the reverse of the sequence
A reference to this
object.
No No
setLength() 1.0 Sets the length of the
character sequence. The
sequence is changed to a new
character sequence whose
length is specified by the
argument
No The new length IndexOutOfBoun
dsException
charAt() 1.0 Returns the char value in this
sequence at the specified
index.
the char value at the
specified index
index - the index
of the
desired char value.
IndexOutOfBoun
dsException
setCharAt() 1.0 The character at the specified No
index is set.
index - the index
of the character to
modify.ch - the
new character.
IndexOutOfBoun
dsException
63. Methods
Name
Introduced
Version
Description(Overloading) Return Type Parameter Exception
append() 1.0 Appends the specified string
to this character sequence.
A reference to this
object.
A string. No
insert() 1.0 Inserts the string into this
character sequence
A reference to this
object.
offset - the
offset.str - a string.
StringIndexOutOf
BoundsException
Append() and insert() methods has many types in
StringBuffer.
69. What is String Builder?
⢠StringBuilder is mutable String.
⢠The Java StringBuilder class is same as StringBuffer class except that it is
non-synchronized (not thread-safe).
⢠It is available since JDK 1.5.
70. Methods
⢠append(), replace(), subsequence(), substring(), charAt() , trimToSize()
⢠insert() delete(), capacity(), ensureCapacity(), reverse(), length()
⢠StringBuffer methods is similar to StringBuilder
71. Methods
Name
Introduced
Version
Description(Overloading) Return Type Parameter Exception
subsequence 1.5
()
the new character sequence
from given start index to
exclusive end index value of
this sequence.
The
subSequence(int
start, int end)
method returns the
specified
subsequence.
The start and end
index of a
subsequence.
IndexOutOfBou
ndsException
)
trimToSize( 1.5 To reduce the storage used
for the character sequence.
No No No
reverse() 1.5 Causes this character
sequence to be replaced by
the reverse of the sequence
A reference to this
object.
No No
75. Difference
String String Buffer
It is immutable It is mutable.
String is slow and consumes more memory String is fast and consumes less memory
When you concat too many strings because every
time it creates new instance.
When you cancat strings.
1.0 1.0
Java.lang.package Java.lang.pakage
76. Difference
StringBuffer String Builder
It is immutable It is immutable.
It is synchronized i.e. thread safe. It is non-synchronized i.e. not thread safe.
It means two threads can't call the methods of
StringBuffer simultaneously.
It means two threads can call the methods of
StringBuilder simultaneously.
1.0 1.5
It is less efficient. It is more efficient.