Notes Unit 2 Java
Notes Unit 2 Java
Java Fundamentals
What is Java?
Java is a high-level, general-purpose, object-oriented, and secure programming
language developed by James Gosling at Sun Microsystems, Inc. in 1991. It is formally
known as OAK. In 1995, Sun Microsystem changed the name to Java. In 2009, Sun
Microsystem takeover by Oracle Corporation.
Editions of Java
Each edition of Java has different capabilities. There are three editions of Java:
Java Platform
Java Platform is a collection of programs. It helps to develop and run a program written
in the Java programming language. Java Platform includes an execution engine, a
compiler and set of libraries. Java is a platform-independent language.
Features of Java
o Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex and ambiguous concepts of C++ are either eliminated or
re-implemented in Java. For example, pointer and operator overloading are not
used in Java.
o Object-Oriented: In Java, everything is in the form of the object. It means it has
some data and behavior. A program must have at least one class and object.
o Robust: Java makes an effort to check error at run time and compile time. It uses
a strong memory management system called garbage collector. Exception
handling and garbage collection features make it strong.
o Secure: Java is a secure programming language because it has no explicit pointer
and programs runs in the virtual machine. Java contains a security manager that
defines the access of Java classes.
o Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any
machine.
o Portable: Java Byte code can be carried to any platform. No implementation-
dependent features. Everything related to storage is predefined, for example, the
size of primitive data types.
o High Performance: Java is an interpreted language. Java enables high
performance with the use of the Just-In-Time compiler.
o Distributed: Java also has networking facilities. It is designed for the distributed
environment of the internet because it supports TCP/IP protocol. It can run over
the internet. EJB and RMI are used to create a distributed system.
o Multi-threaded: Java also supports multi-threading. It means to handle more
than one job a time.
Class: A class is a template or blueprint or prototype that defines data members and
methods of an object. An object is the instance of the class. We can define a class by
using the class keyword.
Object: An object is a real-world entity that can be identified distinctly. For example, a
desk, a circle can be considered as objects. An object has a unique behavior, identity,
and state. Data fields with their current values represent the state of an object (also
known as its properties or attributes).
Literals in Java
In Java
, literal is a notation that represents a fixed value in the source code. In lexical analysis, literals
of a given type are generally known as tokens
. In this section, we will discuss the term literals in Java.
Literals
In Java, literals are the constant values that appear directly in the program. It can be
assigned directly to a variable. Java has various types of literals. The following figure
represents a literal.
1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal
Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:
Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a positive
(+) or negative (-) Note that between numbers commas and non-digit characters are not permitted. For
example, 5678, +657, -89, etc.
Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in
Java SE 7 and later). Prefix 0b represents the Binary system. For example, 0b11010.
Real Literals
The numbers that contain fractional parts are known as real literals. We can also represent real
literals in exponent form. For example, 879.90, 99E-3, etc.
Backslash Literals
Java supports some special backslash character literals known as backslash literals. They are
used in formatted output. For example:
Character Literals
String Literals
String literal is a sequence of characters that is enclosed between double quotes ("") marks. It
may be alphabet, numbers, special characters, blank space, etc. For example, "Jack", "12345",
"\n", etc.
The vales that contain decimal are floating literals. In Java, float and double primitive types fall
into floating-point literals. Keep in mind while dealing with floating-point literals.
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
The short data type can also be used to save memory just like byte data type. A short data type is
2 times smaller than an integer.
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example:
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you
need a range of values more than those provided by int.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.
Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the primitive
value in an object, it will change the original value.
Serialization: We need to convert the objects into streams to perform the serialization. If
we have a primitive value, we can convert it in objects through the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.
java.util package: The java.util package provides the utility classes to deal with objects.
Collection Framework: Java collection framework works with objects only. All classes
of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet,
TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to
use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class,
and implements the Serializable as well as Cloneable interfaces. We can store primitive values or
objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
1. arrayRefVar=new datatype[size];
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
Output
10
20
70
40
50
OPERATORS
Programming in Computer Science requires some arithmetical or logical operations. In such
circumstances, we need operators to perform these tasks. Thus, an Operator is basically a symbol
or token, which performs arithmetical or logical operations and gives us meaningful result. The
values involved in the operation are called Operands.
TYPES OF OPERATORS
There are three types of Operators in Java which are −
Arithmetical Operators
Relational Operators
Logical Operators
ARITHMETICAL OPERATORS
The operators which are applied to perform arithmetical calculations in a program, are
known as Arithmetical operators. Some basic calculations like addition, subtraction,
multiplication, division, modulus are often used during programming. One can apply
arithmetic operators like +, -, *, / and % respectively to carry out these calculations. For
example, A + B, A – B, A % B are all examples of arithmetical operator usage.
Do you know what Arithmetical Expressions are? A + B is considered an Arithmetical
Expression. Basically, an Arithmetical expression may contain variables, constants and
arithmetical operators together to produce a meaningful result. A + B, A – B, A % B are
all examples of arithmetical expressions.
Now what happens if we assign an arithmetical expression to a variable? For example,
what do we call X = A + B? Is it an arithmetical expression or is it something else? Well
this is called an Arithmetical Statement. If an arithmetical expression is assigned to a
variable then it is known as Arithmetical Statement. Syntax of Arithmetical Statement is
− X = A + B, Y = A % B etc.
Now we need to know who to write expression in Java Program.
EXPRESSIONS IN JAVA
When you write a program in Java, it is necessary to represent the arithmetical expressions into
Java expressions. Given below are few examples of how to illustrate a mathematical expression
in JAVA.
Java Expression: a * b * c
Mathematical Expression: ab + bc + ca
Java Expression: a * b + b * c + c * a
Mathematical Expression: a2 + b2
Java Expression: a * a + b * b
Now there exist three different types of Arithmetical Operators. They are −
Unary Operator
Binary Operator
Ternary Operator
Let us understand each of them individually.
UNARY OPERATOR
An Arithmetical operator, which is applied with a single operand is known as Unary Operator.
Example: +, -, ++, --, etc. Details of each types of operators are given below.
This operator is applied before the operand. It is just applied as a pointer to a variable which
results in the same value of a variable. Example: If a = 10, then +a will result in 10. If a = -10,
then +a will result in -10.
This operator is applied before the operand, same as that of Unary (+) operator. Unary (-) reverts
the sign of an operand. Example: If a = 10, then –a will result in -10. If a = 0, then –a will result
in 0. If a = -10, then –a will result in 10.
a = 10;
a = ++a * 2;
Before the operation, value of a was 10. Then in the next arithmetical statement, ++a increases
a’s value by 1. So the new value of a is 11. Then the arithmetical operation a * 2 takes place,
after which value of a becomes 22.
a = 10;
a = --a * 2;
Before the operation, value of a was 10. Then in the next arithmetical statement, --a decreases a’s
value by 1. So the new value of a is 9. Then the arithmetical operation a * 2 takes place, after
which value of a becomes 18.
When increment or decrement operators are applied after the operant, it is known as postfix
operators. This operator works on the principle “CHANGE AFTER THE ACTION”. It means
the value of the variable changes after the operation takes place.
a = 10;
a = a++ * 2;
Before the operation, value of a was 10. Then the arithmetical operator a * 2 takes place, after
which value of a become 20. This value is then stored in a. Hence the new value of a becomes
20.
a = 10;
a = a-- * 2;
Before the operation, value of a was 10. Then the arithmetical operator a * 2 takes place, after
which value of a become 20. This value is then stored in a. Hence the new value of a becomes
20.
BINARY OPERATOR
An arithmetic operator which deals with two operands, is known as Binary Arithmetic Operator.
Example
TERNARY OPERATOR
Ternary Operators deal with three operands. It is also called conditional assignment statement
because the value assigned to a variable depends upon a logical expression.
Example: a = 10, b = 7;
Logical OPERATORS
Java uses logical operators AND (&&), OR (||) or NOT (!). These operators yield 1 or 0
depending upon the outcome of different expressions. The different types of logical operators
along with their format are as shown below −
Precedence of logical operators is NOT (!), AND (&&) and OR (||) i.e., if a statement contains
all the three logical operators then NOT operator will perform first. Here are the details of each
logical operator.
Logical NOT operator is applied when you want to revert the outcome of an expression. It is a
unary operator because it uses a single operand.
Example
!(8 > 3) − False, because 8>3 is True, !(3 > 8) − True, because 3>8 is False.
Output
a is not equal to b
Logical OR (||)
This operator is used to combine two conditional expressions. It will result in true if either of two
conditions (expressions) is true otherwise false.
Example
(5 > 4) || (8 > 12) : True, because 5>4 is True, (5 < 4) || (8 > 12) : False, because both the
expressions are false.
Output
Max Element is 10
The AND operator results in true if both the expressions (comprising its operands) are true.
Example
(5 > 3) && (4 > 3) : True, because both the expressions are True, ( 5 > 3) && ( 3 > 5) : False,
because 3 > 5 is False.
Output
Max Element is 13
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Student.java
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or
else-if statement.
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
Cases cannot be duplicate
Default statement is executed when any of the case doesn't match the value of expression.
It is optional.
Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
Student.java
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of instructions
in a repeated order. The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when we
exactly know the number of times, we want to execute the block of code.
Output:
The while loop is also used to iterate over the number of statements multiple times. However, if
we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements after
the loop will be executed.
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at least
once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
Java break statement
As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement. However, it breaks
only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
BreakExample.java
Output:
0
1
2
3
4
5
6
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
Objects and Classes in Java
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
Object Definitions:
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
Fields
Methods
Constructors
Blocks
Nested class and interface
1. class <class_name>{
2. field;
3. method;
4. }
A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when
an object or instance is created. That is why it is known as an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
Code Reusability
Code Optimization
The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.
In this example, we have created a Student class which has two data members id and name. We
are creating the object of the Student class by new keyword and printing the object's value.
File: Student.java
Output:
0
null
1. By reference variable
2. By method
3. By constructor
4. 1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where
we are going to initialize the object through a reference variable.
5. class Student{
6. int id;
7. String name;
8. }
9. class TestStudent2{
10. public static void main(String args[]){
11. Student s1=new Student();
12. s1.id=101;
13. s1.name="Sonoo";
14. System.out.println(s1.id+" "+s1.name);//printing members with a white space
15. }
16. }
Output:
101 Sonoo
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
1) Private
re is a compile-time error.
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides more
accessibility than private. But, it is more restrictive than protected, and public.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }
In simple words, a class that has no name is known as an anonymous inner class in Java. It
should be used if you have to override a method of class or interface. Java Anonymous inner
class can be created in two ways:
TestAnonymousInner.java
Output:
nice fruits
1. A class is created, but its name is decided by the compiler, which extends the Person
class and provides the implementation of the eat() method.
2. An object of the Anonymous class is created that is referred to by 'p,' a reference variable
of Person type.
1. import java.io.PrintStream;
2. static class TestAnonymousInner$1 extends Person
3. {
4. TestAnonymousInner$1(){}
5. void eat()
6. {
7. System.out.println("nice fruits");
8. }
9. }
1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
7. public void eat(){System.out.println("nice fruits");}
8. };
9. e.eat();
10. }
11. }
12.
13. Abstract class in Java
A class which is declared with the abstract keyword is known as an abstract class in
Java. It can have abstract and non-abstract methods (method with the body).
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Why use inheritance in java
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
output
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating.
File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating..
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
Sr.
Basis of Differences throw throws
no.
Java throw keyword is used Java throws keyword is used in
throw an exception the method signature to declare
1. Definition explicitly in the code, inside an exception which might be
the function or the block of thrown by the function while
code. the execution of the code.
2. Type of exception Using throw Using throws keyword, we
keyword, we can only can declare both checked
propagate unchecked exception and unchecked exceptions.
i.e., the checked exception However, the throws
cannot be propagated using keyword can be used to
throw only. propagate checked
exceptions only.
The throw keyword is The throws keyword is
3. Syntax followed by an instance of followed by class names of
Exception to be thrown. Exceptions to be thrown.
throw is used within the throws is used with the method
4. Declaration
method. signature.
We can declare multiple
We are allowed to throw exceptions using throws
only one exception at a time keyword that can be thrown by
5. Internal implementation
i.e. we cannot throw the method. For example,
multiple exceptions. main() throws IOException,
SQLException.
Output
Java Custom Exception
In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception. Basically,
Java custom exceptions are used to customize the exception according to user need.
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we have
passed a string to the constructor of superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.
In this section, we will learn how custom exceptions are implemented and used in Java
programs.
In order to create custom exception, we need to extend Exception class that belongs to java.lang
package.
Modifier and
Method Description
Type
It is used to append the specified string with this
public
string. The append() method is overloaded like
synchronized append(String s)
append(char), append(boolean), append(int),
StringBuffer
append(float), append(double) etc.
It is used to insert the specified string with this string
public
insert(int offset, String at the specified position. The insert() method is
synchronized
s) overloaded like insert(int, char), insert(int, boolean),
StringBuffer
insert(int, int), insert(int, float), insert(int, double) etc.
public
replace(int startIndex, It is used to replace the string from specified
synchronized
int endIndex, String str) startIndex and endIndex.
StringBuffer
public
delete(int startIndex, int It is used to delete the string from specified startIndex
synchronized
endIndex) and endIndex.
StringBuffer
public
synchronized reverse() is used to reverse the string.
StringBuffer
public int capacity() It is used to return the current capacity.
ensureCapacity(int It is used to ensure the capacity at least equal to the
public void
minimumCapacity) given minimum.
It is used to return the character at the specified
public char charAt(int index)
position.
It is used to return the length of the string i.e. total
public int length()
number of characters.
substring(int It is used to return the substring from the specified
public String
beginIndex) beginIndex.
substring(int
It is used to return the substring from the specified
public String beginIndex, int
beginIndex and endIndex.
endIndex)
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a String into tokens. It is simple way to
break a String. It is a legacy class of Java.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one
to the tokens.
Constructor Description
StringTokenizer(String str) It creates StringTokenizer with specified string.
StringTokenizer(String str,
It creates StringTokenizer with specified string and delimiter.
String delim)
It creates StringTokenizer with specified string, delimiter and
StringTokenizer(String str,
returnValue. If return value is true, delimiter characters are
String delim, boolean
considered to be tokens. If it is false, delimiter characters serve
returnValue)
to separate tokens.
Methods Description
boolean hasMoreTokens() It checks if there is more tokens available.
String nextToken() It returns the next token from the StringTokenizer object.
String nextToken(String delim) It returns the next token based on the delimiter.
boolean hasMoreElements() It is the same as hasMoreTokens() method.
Object nextElement() It is the same as nextToken() but its return type is Object.
int countTokens() It returns the total number of tokens.
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life
cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).