JAVA-UNIT 1
JAVA-UNIT 1
JAVA PROGRAMMING
UNIT - I
Review of Object Oriented Concepts
The main aim of object-oriented programming is to implement real-world
entities, for example, object, classes, abstraction, inheritance,
polymorphism, etc.
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard,
bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or code.
The only necessary thing is the type of message accepted and the type of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like
wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object. Class doesn't
consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as inheritance.
It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to convince the
customer differently, to draw something, for example, shape, triangle, rectangle, etc.
Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone call, we
don't know the internal processing.
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example,
a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.
JAVA HISTORY
Java is a general-purpose, object-oriented programming language developed by Sun
Microsystems of USA in 1991. It was originally called oakby James Gosling, one of the
inventors of the language.
Java is a platform-neutrallanguage, because this programming language that is not tied to any
particular hardware or operating system. Programs developed in Java can be executed anywhere
on any system.
The most striking feature of java is
Platform-independent (neutral) language
Object oriented language
Platform-neutral:
Java is the first program language that is not tied to any particular hardware or operating system.
It can be executed anywhere on any system.
During the compilation, the compiler converts java program into its generic code language called
byte code.
Object oriented:
It is a way of organizing programs as collections of objects, which represents an instance of class.
It includes a set of class library that provides basic data types, system input & output and other
utility functions.
Java Milestones
Year Development
1990 Sun Microsystems decided to develop special software team headed by James Gosling.
1991 After object-oriented language C++, the team announced a new language called "Oak".
1992 Green Project team by Sun demonstrated the application of new language to control a list of
home appliances.
1993 Developing Web applets (tiny programs) by Green Project teams.
1998 Sun releases Java 2 with version 1.2 of the Software Development Kit 1.1 (SDK 1.2).
1999 Sun releases Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition (J2EE).
2004 J2SE with JDK 5.0 was released. This is known as J2SE 5.0.
JAVA BUZZWORDS
1. Simple
2. Object-Oriented
3. Distributed
4. Compiled and Interpreted
5. Robust
6. Secure
7. Architecture-Neutral
8. Portable
9. High Performance
10. Multithreaded
11. Dynamic
1. Simple
Java is designed to be easy for beginners and professional programmers to learn and use
effectively.
It’s simple and easy to learn if you already know the basic concepts of Object-Oriented
Programming.
Java has removed many complicated and rarely-used features, such as explicit pointers and
operator overloading.
2. Object-Oriented
3. Distributed
Java combines both compiled and interpreted approaches, making it a two-stage system.
Compiled: Java compiles programs into an intermediate representation called Java Bytecode.
Interpreted: Bytecode is then interpreted, generating machine code that can be directly
executed by the machine that provides a JVM.
5. Robust
Java provides many features that make programs execute reliably in a variety of
environments.
Java is a strictly typed language that checks code at compile time and runtime.
Java handles memory management with garbage collection and captures serious errors
through exception handling.
6. Secure
Java does not use pointers, which helps prevent unauthorized memory access.
The JVM verifies Java bytecode before execution, ensuring that it adheres to Java’s security
constraints.
Java applications run in a restricted environment (sandbox) that limits their access to system
resources and user data, enhancing security.
7. Architecture-Neutral
Java language and JVM help achieve the goal of “write once; run anywhere, any time,
forever.”
Changes and upgrades in operating systems, processors, and system resources do not force
any changes in Java programs.
8. Portable
9. High Performance
10. Multithreaded
11. Dynamic
Java can link in new class libraries, methods, and objects dynamically.
Java programs carry substantial amounts of run-time type information, enabling dynamic
linking in a safe and expedient manner.
JVM Architecture
Java compiler translates source code into byte code for a machine, which is also referred to as
virtual machine code. The java provides an intermediate code called as byte code for a machine.
This machine is called as java virtual machine(JVM).
Figure: Process of Compilation
The virtual machine code is not machine specific. The machine specific code is generated by the
Java interpreter, by acting as an intermediate between the virtual machine and real machine.
DATA TYPES
Every variable in Java has a data type. It also specifies the size and type of values that can be
stored. The variety of data types available allows the programmer to select the type appropriate
to the needs of the application.
Figure: Data Types in Java
Integer Types:
It can hold whole numbers. The size of the values that can be
stored depending upon the integer type. The long integer is used
by appending the letter L or l at the end of the number. It supports
four type of integers are:
byte One byte
short Two bytes
int Four bytes
long Eight bytes
Java does not support the concept of unsigned types and therefore
all Java values are signed meaning they can be positive or
negative.
VARIABLES
A Variable is an identifier that denotes a storage location used to store a data value. Unlike
constants that remain unchanged during the execution of a program, a variable may take
different values at different times during the execution of the program.
Variable name can be chosen by the programmer in a meaningful way.
Example: average, height, classstrength.
Rules:
They must not begin with a digit.
Upper case and lower case are distinct.
It should not be a keyword.
White space is not allowed.
It can be of any length.
SCOPE OF VARIABLES
The area of the program where the variable is accessible is called its scope. The Java variable
classified into three types:
Instance
Class
Local
Instance Variable:
These variables are declared inside a class. It was created when the objects are instantiated and
associated with the objects. They take different value for each object.
Class Variable:
These variables are global to a class and belong to the entire set of objects that class creates.
Only one memory location is created for each class variable.
Local Variable:
The variables declared and used inside the methods are called local variables. It also be declared
inside the program blocks that are defined between an open brace {and a close brace}.
ARRAY
Introduction
An array is a group of contiguous or related data items that share a common name. Each and
every element of an array is identified using index or subscript number.
Example: employee [10];
Example: salary[10] , It represent the salary of the 10th employee.
Types of Arrays:
The array consists of the following types:
One-dimensional Array
Multi-dimensional Array
One-dimensional Arrays
A list of items is specified by one variable name using only one subscript is called
single-subscripted or one-dimensional.
Example: int number[] = new int[5];
Java subscripts start with the value 0.
The values to the array elements can be assigned as follows:
number[0]=20;
number[1]=30;
number[2]=40;
number[3]=50;
number[4]=60;
CREATING AN ARRAY
Creation of an array involves three steps.
1. Declare the array.
2. Create memory locations.
3. Put values into the memory location.
Declaration of Arrays
Arrays in java can be declared in two forms.
Form1: type array_name[];
Form2: type[] array_name;
Example: int number[]; float[] marks;
Creation of Arrays
After declaring an array, we need to create it in the memory.
array_name=new type[size];
Example: number =new int[5];
Initialization of Arrays:
The final step is put values into the array created. This process is known as initialization.
Syntax: arrayname[subscript]=value;
Example: a[0]=25; number[4]=30;
We can also initialize arrays automatically in the same way as the ordinary variables when they are
declared.
Syntax: type arrayname[]={list of values};
Example: int number[]={20,40,50,60};
Array length:
The length of the array can be determined using length.
e.g., int num[]=new int[5];
int size=num.length; // size=5
Two-dimensional Arrays
In java, a table of items can be defined using two dimensional arrays.
It is an array of arrays. The left index determines row and right index determines columns.
It must be initialized with a list of initial values enclosed in braces must initialize the two-
dimensional array.
We can create a two-dimensional array as
int myarray[][];
myarray=new int[3][4];
Or
int myarray[][]=new int[3][4];
This will create a table that can store 12 integer values, four across and three down.
Example 1:
int table[2][3] = {0, 0, 0, 1, 1, 1};
int table[][] = {{0, 0, 0}, {1, 1, 1}};
int table[][] = {
{0, 0, 0},
{1, 1, 1}
};
Example 2:
class twoarray
{
public static void main(String args[])
{
int twod[][]=new int[4][5];
int i,j,k=0;
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
twod[i][j]=k; k++;
}
}
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
System.out.print(""+twod[i][j]);
}
System.out.println();
}
}
}
VARIABLE SIZE ARRAYS
Java treats multidimensional array as “arrays of arrays”.
It is possible to declare a two-dimensional array as follows:
int x[][]=new int[3][];
x[0]=new int[2];
x[1]=new int[4];
x[2]=new int[3];
These statements create a two-dimensional array as having different lengths for each row.
EXAMPLE:
import java.io.*;
class sample }
{ System.out.println(“”);
public
static void
}
main(String args[]) }
{ }
int a[i] [j] =
{0, 1, 1, 3};
for(i=0;i<2;i++)
{
Output:
for(j=0;j<2;j++) 0 1
{ 1 3
System.out.println(a[i][j]);
OPERATORS
Introduction:
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. The Java operators can be classified into number of related categories:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Increment and Decrement Operators
Conditional Operators
Bit-wise Operators
Special Operators
Arithmetic Operators:
The basic and common operators in computer programming language are Arithmetic operators
also called as Binary operators since they require two operands. They are addition (+),
subtraction (-), multiplication (*), division (/), modulus (%).
Arithmetic operators cannot be used as Boolean type. It is used to construct mathematical
expressions as in algebra. Java supports the following categories:
Operator Meaning
+ Addition (or) Unary Plus
- Subtraction (or) Unary Minus
* Multiplication
/ Division
% Modulo Division (Remainder)
Integer Arithmetic:
When both the operands in a single arithmetic expression are integer, the expressions are called
an integer expression and the operation is called integer arithmetic. It always yields an integer
value.
Example:
a = 10 and b = 4
a * b = 40
a%b=2
Real Arithmetic:
An arithmetic operation involving only real operands is called real arithmetic.
Example: a = 10.5 and b = 5.4 a + b = 15.9
Mixed-Mode Arithmetic:
When one of the operands is real and the other is integer, the expression is called mixed-mode
arithmetic expression. If either operand is of the real type, then the other operand is converted
to real and the real arithmetic is performed.
Example: a = 25 and b = 20.0 a / b = 1.5
Relational Operators:
It is used for comparisons between two quantities and depending on their relation, takes certain
decisions.
The comparison operators are used to compare the values of two variables. These are used in
the program flow. These operators in ‘C’ produce true (1) or false (0) results. These operators
can be grouped as relational and equality operators.
Operator Meaning
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
!= not equal to
Syntax: ae-1 relational operator ae-2
In the above syntax, ae-1 and ae-2 are arithmetic expressions, which may be simple constants,
variables or combination of them.
Example:
Operator Meaning
20 < 8 + 5 False
-25 >= 0 False
5.5 <= 10 True
Logical Operators:
The Java language consists of three logical operators. They are:
Operator Meaning
&& logical AND
|| logical OR
! logical NOT
The logical operators && and || are used to combining two or more relations, is termed as logical
expression or a compound relational expression.
Truth Table:
op -1 op -2 op - 1 && op – 2 op - 1 || op – 2
True True True True
True False False True
False True False True
False False False False
Assignment Operators:
It is used to assign the value of an expression to a variable.
Syntax: v op = exp;
In the above syntax V is a variable, exp is an expression and op is a Java binary operator. The
operator op= is known as shorthand assignment operator.
Advantages:
What appears on the left-hand side need not be repeated and therefore it becomes easier to write.
The statement is more concise and easier to read.
Use of shorthand operator results in a more efficient code.
Example:
Example:
m = 15; n = 10;
x = (n > m)? n : m;
Example:
If (a>b)
X=a;
Else
X=b;
This may be expressed in ternary condition as follows:
a=10;
b=15;
x=(a>b)?a:b;
Bitwise Operators:
It is used to test the bits or shifting them to the right to left. It may not be applied to float or
double.
Operator Meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
~ one's complement
<< shift left
Example: >> shift right
1010 0101 (bitwise NOT)
1010 & >>> shift right with zero fill 11111010 (bitwise
AND – produces a 1 bit if both
operands are also 1, otherwise 0)
1010 | 1110 1110 (bitwise OR – produces a 1 bit if either of the bits in the operands is a 1,
otherwise 0)
1010 ^ 1111 0101 (bitwise XOR – produces a 1 bit if exactly one operand is 1, otherwise 0)
Special Operators:
The Java language contains some special operators. They are: instanceof, dot operator.
Instanceof Operator:
It is an object reference operator and returns true if the object on the left-hand side is an instance
of the class given on the right-hand side.
Example: person instanceof student
Is true if the object person belongs to the class student; otherwise it is false.
Dot(.) Operator:
It is used to access the instance variables and methods of class objects.
Example:
Person2.no // Reference to the variable no
Person2.getdata () // Reference to the method getdata()
CONTROL STATEMENTS
Selection Statement:
These select one of several control flows. There are three types of selection statements in Java:
if
if-else
switch
Iteration Statement:
These specify how and when looping will take place. There are three types of iteration statements
in Java:
while
do
for
Jump Statement:
It passes control to the beginning or end of the current block, or to a labeled statement. It consists
of four types of jump statements:
break
continue
return
throw
The Java language supports the following decision making and control statements:
if Statement
switch Statement
Conditional Operator Statement
Decision Making with if Statement:
The if statement is a powerful decision making statement.
It is used to control the flow of execution of statements. It is basically two-way decision
statement used within expression.
Syntax: if (test expression)
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested.
Simple if Statement
if…else Statement
Nested if…else Statement Entry
else if Ladder
Simple if Statement: True
The 'statement block' may be a single or group of statements. Test
Expression
If the test expression is true then 'statement block' will be executed
otherwise statement-x will be executed. Statement-block
False
When the condition is true both the statement block and the statement
x are executed in sequence. Statement-x
Syntax:
if (test expression)
Next statement
{
statement-block;
} Output:
statement-x;
Example: Largest value is a: 55
import java.io.*;
class first
{
public static void main(String args[ ])
{
int a=55, b= 32;
if (a>b)
{
System.out.println (“Largest value is a:”, +a);
}
}
}
Tes
t
exp
ress
True-block stmt False-block stmt
Statement-
x
{
True-block statement(s);
}
else
{
False-block statement(s);
}
Output:
statement-x;
Example: Largest value is b: 32
import java.io.*;
class first1
{
public static void main(String args[ ])
{
int a=25, b= 32
if (a>b)
{
System.out.println(“Largest value is a: ” , +a);
}
else
{
System.out.println(“Largest value is b: ” , +b);
}
}
}
Stmt -2 Stmt-1
else
{
statement-3;
}
statement-x;
Example: Stmt-x
import java.io.*;
class large
{ public static void main(String args[])
{
int a=325, b=712, c=478;
System.out.println(“Largest value is:”);
if(a>b)
{
if(a>c)
{
System.out.println(a);
}
else
{
System.out.println(c);
}
}
else
{
if(c>b)
{
System.out.println(c);
}
else
{
System.out.println(b);
}
}
}
}
The else-if Ladder:
There is another way of putting ifs together when multipath decisions are involved.
A multipath decision is a chain of ifs in which the statement associated with each else is an if.
Syntax:
if (condition1)
statement-1;
else if (condition2)
statement-2;
else if (condition3)
statement-3;
…
…
else if (condition n)
statement-n;
else
default statement;
statement-x;
The conditions are evaluated from the top
downwards. As soon as the true condition is
found, the statement associated with it is
executed and the control is transferred to the
statement-x.
When all the conditions becomes false, then the final else containing default-statement will be
executed.
Example:
if (code == 1)
Color = "Green";
else if (code == 2)
Color = "Red";
else if (code == 3)
Color = "Yellow";
else
Color = "White";
Example:
import java.io.*;
class second
{
public static void main(String args[]) Output:
{ 100 distinction
int rollnumber [] = {100, 101, 102, 103};
int marks[] = {81, 76, 43, 58};
101 Ist class
for (int i =0; i<rollnumber; i++) 102 Fail
{ 103 2nd class
if(marks [i]> 75)
System.out.println(rollnumber[i] +”” distinction );
else if(marks[i] > 55)
System.out.println(rollnumber[i] +”” Ist class);
else if(marks[i] > 45)
System.out.println(rollnumber[i] +”” 2 nd class);
else
System.out.println(rollnumber[i] +”fail”);
}
}
}
The switch Statement:
Java has a built-in multiway decision statement known as switch. This switch statements test
the value of a given variable against a list of case values and when a match is found, a block of
statements associated with the case is executed.
The expression is an integer expression or characters. value-1, value-2 are constants or constant
expressions are known as case labels. The block-1, block-2 are statement lists and may contain
zero or more statements. The case labels should ends with a colon (:). The default is an optional
one.
When the switch is executed, the value of the expression is successively compared against the
values value-1, value-2…..
If a case is found whose value matches with the value of the expression, then the block of
statements follows the case are executed. The default is an optional case.
The break statement at the end of each block signals the end of a particular case and cause an
exit from the switch statement, transferring control to the statement-x following the switch.
Syntax:
switch (expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
….
default:
default-block;
break;
}
statement-x;
Example:
a = (char)System.in.read();
switch(a)
{
case 'M':
case 'm':
System.out.println("Hello");
break;
case 'S':
case 's':
System.out.println("Hai");
break;
case 'B':
case 'b':
System.out.println("Simple");
break;
default:
System.out.println("Java");
break;
}
Example:
import java.io.*;
class letter
{
public static void main(String args[])
{ Output:
char letter; The given alphabet is a vowel
switch (letter)
{
case ‘a’:
case ‘e’:
case ‘i’ :
case ‘o’:
case ‘u’: System.out.println(“The given alphabet is a vowel”);
break:
default: System.out.println(“the given alphabet is not a vowel”);
}
}
}
The ?: Operator:
It is combination of ? and : and takes three operands.
General Format: conditional expression? expression1: expression2;
The conditional expression is evaluated first. If the result is true, expression1 is evaluated,
otherwise, expression2 is evaluated and its value is returned.
Example: y = (a < 0)? 0:1;
Initialization;
Initialization;
do
{
body of the loop;
}
while (test condition);
i = 1;
sum = 0;
do
{
sum = sum + i;
i = i + 2;
}
while(sum <50);
Example:
import java.io.*;
class sample1
{
public static void main (String args[])
{ Output:
j=1: 1
do 2
{ 3
System.out.println (j);
j= j + 1;
4
} while(j <4)
}
}
Difference between while and do while
while do-while
It is a looping construct that will execute only if It is a looping construct that will execute at least
the test condition is true. once even if the test condition is false.
It is an entry controlled loop. It is an exit controlled loop.
The for Statement:
It is another entry-controlled loop that provides a more concise loop control structure. The
execution of statement as follows:
Initialization of the control variables.
The value of the control variable is tested using the test condition.
The variable is incremented using an assignment statement.
Syntax:
Java permits a jump from one statement to the end or beginning of a loop as well as a jump out of a
loop.
Jumping Out Of a Loop
The break statement is used for exit from a loop. It is used within while, do or for loops.
Syntax: break;
Example:
i=0;
while(i<=10) Output
{ 1
2
3
4
i=i+1;
if(i==5)
break;
System.out.println(i);}
There are two rules to be satisfied for the conversion to take place. They are:
1. The source and destination types must be compatible with each other.
2. The size of the destination type must be larger than the source type.
For example, Java will automatically convert a value of byte into int type in expressions since they are
both compatible and int is larger than byte type.
Since a smaller range type is converted into a larger range type this conversion is also known
as widening conversion. Characters can never be converted to boolean type. Both are incompatible.
There may be situations where you want to convert a value having a type of size less than the
destination type size. In such cases Java will not help you. You have do it on your own explicitly. That
is why this type of conversion is known as explicit conversion or casting as the programmer does this
manually.
(destination-type) value
int a = 10;
byte b = (byte) a;
In the above example, I am forcing an integer value to be converted into a byte type. For type casting
to be carried out both the source and destination types must be compatible with each other. For
example, you can’t convert an integer to boolean even if you force it.
In the above example, size of source type int is 32 bits and size of destination type byte is 8 bits. Since
we are converting a source type having larger size into a destination type having less size, such
conversion is known as narrowing conversion.
A type cast can have unexpected behavior. For example, if a double is converted into an int, the
fraction component will be lost.
All char, short and byte values are automatically promoted to int type.
If at least one operand in an expression is a long type, then the entire expression will be
promoted to long.
If at least one operand in an expression is a float type, then the entire expression will be
promoted to float.
If at least one operand in an expression is a double type, then the entire expression will be
promoted to double.
To understand the above type promotion rules let’s consider the following example of expression
evaluation:
classSample{
publicstaticvoidmain(String[] args)
{
int i =1000000;
char c ='z';
short s =200;
byte b =120;
float f =3.45f;
double d =1.6789;
double result =(f * b)+(i / c)-(d * s);
System.out.println("Result = "+result);
}}
In the above program the expression is (f * b) + (i / c) – (d * s). In the first sub expression (f * b), as
one operand is float, the result of the expression will be a float. In the second sub expression (i / c),
char type will be promoted to int and the result of the expression will be an int. In the third sub
expression (d * s), as one operand is double, the result of the expression is a double.
Documentation Section:
This section consists of set of comment lines giving the name of the program, the author and
other details. Java also uses a third style of comment /* *…*/ known as documentation
comment.
Comments must explain why and what classes and how of algorithms.
Package Statement:
The first statement in Java is a package statement, declares a package name and informs the
compiler that the classes defined belong to this package.
Example:
package employee;
Import Statements:
After the package statement may be a number of import statements. This is similar to the
#include statement in C.
Example:
import employee.test;
This statement instructs the interpreter to load the test class contained in the package employee.
Interface Statements:
It is like a class but includes a group of method declarations. It is used to implementing multiple
inheritance features in the program.
This is an optional section and it is used only when we wish to implement the multiple
inheritance.
Class Definitions:
A Java program may contain multiple class definitions. These classes are used to map the
objects of real-world problems. The number of classes used depends on the complexity of the
problem.
Main Method Class:
Every Java stand-alone program requires a main method. It creates objects of various classes
and establishes communications between them.
CONSTRUCTORS
A constructor is a special method which has the same name as class name and that is used
to initialize the objects (fields of an object) of a class. A constructor has the following characteristics:
ClassName([ParametersList]){
//Code of the constructor}
Use of Constructors
A constructor is used for initializing (assigning values to fields) the objects of a class.
Constructor Invocation
A constructor is invoked (called) automatically whenever an object is created using the new keyword.
Types of Constructor
Based on the number of parameters and type of parameters, constructors are of three types:
Parameter less constructor: As the name implies a zero parameter constructor or parameter less
constructor doesn’t have any parameters in its signature. These are the most frequently found
constructors in a Java program. Let’s consider an example for zero parameter constructor:
class Square
int side;
Square()
side = 4;
}
Parameterized constructor: This type of constructor contains one or more parameters in its signature.
The parameters receive their values when the constructor is called. Let’s consider an example for
parameterized constructor:
class Sqaure
int side;
Square(int s)
side = s;
Copy constructor: A copy constructor contains atleast one parameter of reference type. This type of
constructor is generally used to create copies of the existing objects. Let’s consider an example for
copy constructor:
class Sqaure
{
int side;
Square()
{
side = 4;
}
Square(Square original) //This is a copy constructor
{
side = original.side;
}
}
METHODS
A method is a piece of code to solve a particular task. A method is analogous to functions in C and
C++. Methods are defined inside a class. The syntax for creating a method is as shown below:
The return_type specifies the type of value that will be returned by the method. The name of the
method is specified by method_name. Every parameter in the parameters list follows
the below syntax:
datatype parameter_name
STATIC BLOCKS
A static block is a block of statements prefixed with static keyword. The syntax for creating a static
block is shown below:
static
{
//Statements
}
STATIC DATA
When a variable is declared static in Java programming, it means that the variable belongs
to the class itself rather than to any specific instance of the class. This means that there is only one copy
of the variable in memory, regardless of how many instances of the class are created.
Here are some important features and methods of the StringBuffer class:
StringBuffer objects are mutable, meaning that you can change the contents of the buffer
without creating a new object.
The initial capacity of a StringBuffer can be specified when it is created, or it can be set later
with the ensureCapacity() method.
The append() method is used to add characters, strings, or other objects to the end of the buffer.
The insert() method is used to insert characters, strings, or other objects at a specified position in
the buffer.
The delete() method is used to remove characters from the buffer.
The reverse() method is used to reverse the order of the characters in the buffer.
public class StringBufferExample {
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append("");
sb.append("world");
String message = sb.toString();
System.out.println(message);
}
}
Output
Hello world.
------------------------------------UNIT 1 COMPLETED-----------------------------------------