Java Notes
Java Notes
Note: This Document is typed by Abhishek Dubey , Hanuman and Vishrut Bhatt
1. Explain characteristics or features of java?
• Features of java are listed below.
• Compiled and Interpreted
• Platform-Independent and portable
• Object-oriented
• Robust and Secure
• Distributed
• Familiar, Simple, Small
• Multithreaded and Interactive
• High Performance
• Dynamic and Extensible
Secures:
Security becomes an important issue for a language which is used for programming
on Internet. Threat of viruses and abuse of resources are everywhere. Java system not
any verifies all memory access but also ensure that no viruses are communicated with
an applets. The absence of pointers in java ensures that programs cannot again access
to memory locations without Proper authorization.
• Distributed
Java is also known as distributed language for creating applications on networks,
which has ability to share both data and programs. Java applications can open and
access remote objects on Internet as easily as they can do in a local system. This
enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.
• Familiar, simple and small
Java is a very small and simple language. Many features of C and C++ that are either
redundant or sources of unreliable code are not part of Java For example, Java does
not use pointer, pre-processor header files, go to statement and many others. It also
eliminates operator overloading and multiple inheritance.
Familiarity is another stinking features of Java. To make the language look familiar to
the existing programmers, it was modelled on C and C++ languages. Java uses many
constructs of C and C++.
• Multithreaded and interactive
Multithreaded means handling multiple tasks simultaneously. Java supports
multithreaded programs. This means that we need not to wait for application to
complete one task before beginning another. This feature improves the interactive
performance in graphics application.
• High Performance
Java Performance is very impressive for an interpreted language, mainly due to the
use of intermediate bytecode. The incorporation of multithreading enhances the
execution speed of java programs.
• Dynamic and Extensible Dynamic
Java is also a Dynamic language. Java is capable dynamically linking in new class
libraries, methods and objects. Java can also determine the type of class through a
query, making it possible to either dynamically link or abort the program, depending
on the resources.
Java programs support functions written in either languages such as C and C++,
known as native methods.
• Documentation Section
The documentation section comprise a set of comment lines - giving the name of
program, the author & other details, Which the programmer would like to refer to at a
later stage. Comments must explain why & what of classes & how of algorithms. This
would help in maintaining the program. In addition to the two styles of comments /**-
------**/ known as documentation comment. This form of comment is used for
generating documentation automatically.
• Package Statement
This first statement allowed in a java file is a package statement. This statement
declares a packages name & informs the compiler that the classes defined here belong
to this package.
Exp:-
Package Student;
• Import Statement
The next thing after a package statement may be a number of import statement. This
is similar to the #Include statement in C.
Exp: - import student. test;
This statement instructs the interpreter to load the test class contained in the package
student. Using import statements we can have access to classes that we are part of
other named packages.
• Interface Statement
An interface is like a class but includes a group methods declaration. This is also
known as “optional section” & is used only when we wish to implement the multiple
interface features in the program.
• Class Definition
A Java program may contain multiple class definitions. Classes are the primary and
essential of a Java program. 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
Since every Java standalone program requires a main method as its starting
point, this class is the essential part of a Java program. A simple program may
contain only this part. The main method creates objects of various classes and
established communications between them. On reaching the end of main, the
program terminates and the control passes back to the operating system.
individuals class is put into its own output file named after the class and using the .class
extension. This is the reason to give the java source file the same name as that of class.
2. Write down the different type of main in JAVA?
ANSWER: - signature of the main () method can be any of these:
Public static main (String args [])
Public static main (String [] args)
Static public void main (String args [])
3. Explain comment line styles in Java.
ANSWER: - Three styles of comment notation are used in Java:--
A.) Any text between ‘//’ and the end of line is a comment.
B.) The starting with ‘/*’ and terminating with ‘*/’ make up multiple line comments.
C.) Special form starting with ‘/**’ and terminating with ‘**/’ is used to create comments
that can be processed by the Java doc program to produce HTML formatted
documentation.
9 Explain operator.
Prefix operator op ++a
Postfix op operator a++
Operators that require two operands are binary operators.
Syntax: op1 operator op2
Ternary operators are those that require three operands.
Syntax :
Expr ? op1 : op2
1) Arithmetic operator.
operator Use description
+ Op1+op2 Adds op1 and op2
-(unary) -op1 Negates op1(-ve op1)
- Op1-op2 Subtracts op2 from op1
* Op1*op2 Multiples op1 by op2
/ Op1/op2 Divides op1 by op2
% Op1%op2 Computes the reminder of dividing op1 by op2.
int x=2; X%10 =2
double y=42.3; Y%10=2.3
+(unary) +op Promotes to int if it’s a byte , short or char.
2) Relational operator.
Compares two values and determines the relationship between them. The outcome of the
expression is a Boolean value.
operator Use Returns true if
Note:- only byte , short , int , long , float , double and characters operands may be comp[ared
to see which is greater or less than the other.
3) Logical operator
Operator Use Returns true if
&& op1&&op2 op1 and op2 are both true, conditionally Evaluates op2
|| op1||op2 either op1 or op2 is true, conditionally evaluates op2
!(Not) ! op1 op is false
4) Short Circuit:
Under specific conditions the && and || operators do not Evaluate both operands.
Case 1: In the statement if (x>0) &&(y>0). If the result of first (x>0) is evaluated as false
Than the compiler knows that the result can be false, so the right operand (y>0)is and
evaluated.
Case 2: In the statement if (x>0) || (y>0), if the result of the false operand is evaluated as
true then the compiler knows that the result can be true,so the right operand (y>0)
is not evaluated.
5) Bitwise Operator:
A Bitwise operator allows you to perform bit manipulation in data.
Operator Use Operation
>> op1>>op2 Shift bits of op1 right by distance op2.
<< op1<<op2 Shift bits of op1 left op1 left by distance op2
>>> op1>>>op2 Shift bits of op1 right by distance op2
& op1&op2 bitwise and
| op1 | op2 bitwise or
^ op1 ^ op2 bitwise xor
~ ~op1 bitwise complement(Not)
The three shift operation (>>= <= >>>) simply shift the bits of the left hand operand
over by the number of position indicated by the right hand operand.
The shift occur in the direction indicated by operator itself.
1101 is binary representation of 13 , 0110 is the result of shifting one bit to right ->
6.
35>>2 001000 11->35>>2 = 0000100->8
Shift the bits of the integer 35 to the right by two position. While shifting
right, the top(leftmost) bits exposed by the right shift are filled in with the
previous contents of top bit. This is called sign extension and serves to
preserve when you shift them to right.
-8>>1 11111000 -> -8>>1 = 11111100 -> -4
Bute x=-1;x=x>>>5;
The above is illegal because results of x>>>5 is int and can’t be assigned to x
which is byte.
A right shift of 1 bit is equivalent to, but more efficient than, dividing the left
hand operand by 2.
Shift the bits of the integer 35 to the right by two positions. While shifting
right, the top (leftmost) bits exposed by the right shift are filled in with
zero.This does not number when you shift them to right.
-8 >>>1
Byte x = - 1; x = x >>> 5;
The above is illegal because result of x >>> 5 is int and can’t be assigned
to x which is byte.
Narrowing conversion:
-It is also called explicit or cast operator.
-When destination type is smaller then the source type then narrowing conversion take
place.
-A cast simply an explicit type conversion it has general form: (target-type) value to.
Here, target-type specifies to convert the specified value to
Ex: When a float is cast into int type its fraction part is lost and the value is truncated.
Int i;
Float f = 12121.121f;
i = (int) f;
o/p: i = 12121
11 Explain Control Statements
• If-else:
The general form of it statement is:
if(condition)
Statement 1;
else
Statement2;
• If the condition 1 is true then state1 is executed ,otherwise statement2 is executed In
case will both state ments be executed.
• Wap to find number is odd or even
class A{
public static void main(String args[]){
int no = 20;
int no = Integer parse Int(args[0]);//For fetch the value user//
if(no%2 = = 0)
System.out.println(“no is even”);
else
System.out.println(“no is odd”);
}
}
2 . if-elseif-(ladder):
Form is:
If (condition)
Statement;
Else if (condition)
Statement;
:
:
:
Else
Statement;
The if statement are executed from top-down. As soon as one of the condition controlling the
if is true the statement associated with that if is executed and the rest of ladder is by passed. If
none of the condition is executed. Else act as a default condition.
Wap to demonstrate if-else if statement
class IfElse{
public static void main(String args[]) {
int month=4;
String season;
if(month==12 || month==1 || month==2)
season=”Winter”;
elseif(month==3 || month=4 || month=5)
season=”Spring”;
elseif(month==6 || month==7 || month==8)
season=”Summer”;
elseif(month==9 || month==10 || month==11)
season=”Autumn”;
else
season=”Bogus Month”;
System.out.println(“April is in the”+season+”.”);
}
}
Statement;
else
statement;
else
statement;
A nested-if is an if statement that is the target of another if or else. When you nest if, the
main theme to remember is that an else statement always refer to the nearest if statement.
That is within the same block as the else and that is not already associated with an else.
WAP to find maximum between 3 numbers using Nested-if.
class A {
public static void main(String args[]) {
int a=20,b=10,c=30;
if(a>b){
if(a>c) {
System.out.println(“Max is : ”+a)
}
else {
System.out.println(“Max is : ”+c);
} }
else{
if(b>c) {
System.out.println(“Max is : ”+b);
}
else {
System.out.println(“Max is : ”+c);
}
} } }
4> Switch-case:
The general form of Switch-case is:
switch(expression)
{
case value1:
statement;
break;
case value2:
statement;
break;
.
.
.
.
.
case valueN:
statement;
break;
default
default statement;
}
The expression must be of type byte, short, int or char; each of the values specified in the
case statements.
Must be of a type compatible with the expression. Each case value must be unique literal.
(that is, it must be a constant, not a variable). Duplicate case values are not allowed.
The switch statement works like this: the value of the expression is compared with each of
the literal values in the case statements. If a match is found, the code sequence following that
case statements is executed. If none of the constant. Matches the value of the expression, then
the default statements is executed. However, the default statements is optional. If no case
matches and no default is present, then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence. When a
break statement is encountred, execution branches to the first line of code that follows the
entire switch statement. This has the effect of “jumping out” of the switch.
Here is a simple example that uses a switch case.
class sampleswitch
{
public static void main(string args[])
{
for(int i=0; i<6; i++)
switch(i)
{
case 0:
System.out.println(“I is zero”);
break;
case 1:
System.out.println(“I is one”);
break;
case 2:
System.out.println(“I is two”);
break;
default:
System.out.println(“is greator than 3”);
}}
The break statement is optional. If you omit the break, execution will continue on into the
next case.
Explain Iteration statements or looping
• WHILE:
while(condition)
{
//body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long
as the conditional expression is true. When condition becomes false, control passes to the
next line of code immediately following the loop. The only braces are unnecessary if only a
single statement is being repeated.
Ex:-
class while{
public static void main(string args[]) {
int n=10;
while(n>0){
System.out.println(“tick”+n);
n--;
}}
}
o/p: tick 10
tick 9
:
:
tick 1
• DO-WHILE:
do
{
//body of loop
} while(condition);
Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will repeat
otherwise, the loop terminates. Condition Must be a Boolean expression
class DoWhile{
public static void main(String arg[]){
int n=10;
do{
System.out.println(“tick”+n);
n--;
}while(n>0);
}
}
o/p:
tick 10
tick 9
|
tick 1
3 for:
for(intilization;condition;interaction)
{
//body
}
The for loop operates as follow. When the loop first starts, the initialization portion of the
loop is sets the value of the loop controls the loop control variable, which acts as counter that
controls the loop. The initialization expression is only executed once.
Next condition is evaluated. This must be a Boolean expression, It usually test the loop
control variable against a target value If this expression is true, then the body of the loop is
executed if it is false, The loop terminates next the interaction portion of the loop is executed
.This is usually an expression that increments or decrements the loop control variable. The
loop then iterates, first evaluating the body of the loop and then executing the interaction
expression with each pass controlling expression is false.
class ForTick{
public static void main(String arg[])
{
int n;
for (n=10;n>0;i++)
System.out.println(“tick”+n);
}}
o/p:
tick 10
tick 9
|
tick 1
Nested loop:-
General Form of nested for.
for(initialization; test condition; increment)
{
for(initialization; test condition; increment)
{
//body for iner loop;
}
}
Ex
class Nested{
public static void main(String arg[]){
int i,j;
for(i=0;i<10;i++){
for(j=0;j<10;j++){
System.out.println(“.”);
}
System.out.println(“”);
}}
}
labelled break statement to exit form a set of nested block. But you cannot use break to
transfer control to a block of code that does not enclose the break statement.
Example:-
class break {
public static void main (string args[]) {
boolean t = true;
First: {
Second: {
Third: {
if(t)
break second;
System.out.println(“this won’t execute”);
}
System.out.println(“this is after second block.”);
}
}
}
Output:-
Before the break
This is after second block.
Continue:-
During the loop operations, it may be necessary to skip a part of the body of the loop
under contain condition the continue statement causes the loop to be continues with the
next iteration after skipping any statements in between the continue statement in tells the
compiler “skip or omit the statement mentioned and continue with the next iteration” in
while and go loop ,the continue the control to go directly to the test condition and then
continue the iteration process. In the case of for loop, the increment section of the loop is
executed before the test condition is evaluated.
Example:-
class continue{
public static void main(string args[]) {
for(int i=0; i<10;i++)
System.out.print(i+” ”);
if (i%2==0)
continue;
System.out.println(“ “);
}
}
}
Output:
0 1
2 3
4 5
6 7
8 9
Label continue:-
The general form of label continue is:
Continue label;
The label is the name of label ,which identifies statement will terminate the loop &
continue with next iteration.
Ex:-
class continuelabel{
public static void main(String args[]){
for(int i=0;i<10;i++){
for (int j+0; j<10;j++)
{
if (j>i){
System.out.println(“”+(i*j));
}}
System.out.println():
}}
Output:-
01
02 4
.
.
.
0 9 18 27 36 45 54 63 72 81
Return:-
The return statement terminates the method in which it is executed return causes execution to
return to java runtime system.
Ex:-
class return {
public static void main(string args[]){
boolean t=true;
System.out.println(“before the return”);
if(t)
return;
System.out.printl(“this wont execute”);
}
}
Outpit:-
Before the return.
Class
What is class ?
Class is a user-defined data type all data & method are encapsulates within the class. The data
& function written within the class are called as a member of a class. The variable & method
are called instance method.
In java, these data items are called field and function are called method.\
Syntax:-
class classname
{
type instance_variable1;
type instance_variable2;
type instance_variableN;
return-type method_name1(Parameter list);
{
}
return-type method_name2(Parameter list);
{
}
return-type method_nameN(Parameter list);
{
}
}
Returning a value:
class box{
double width;
double height;
double depth;
double volume(){
return width * height * depth;
}
}
class boxdemo4{
public static void main(String args[]){
box mybox1=next box();
box mybox2=next box();
double vol;
mybox1.width=10;
mybox1.height=20;
mybox1.depth=15;
mybox2.width=3;
mybox2.height=6;
mybox2.depth=9;
vol=mybox1.volume();
System.out.println(“volume is ”+vol);
vol=mybox2.volume();
System.out.println(“ volume is ” +vol);
}}
->> Adding a method that takes PARAMETER.
class Box{
double width;
double height;
double depth;
double volume(){
return width * height * depth;
}
Constructor:-
Constructor is a special member function whose task is to initialized class object . It is
special because the class name and constructor name is always same.
Characteristics of constructor:-
• The class name and constructor name should always be same.
• Constructor do not have explicit return type not even void , because the implicit return
type of constructor is class itself.
• Constructor code automatically called when object of a class is created.
• When in a class, constructor is not provided the default constructor is created . It will
initialized all the instance variable with 0.
• When a parameter is provided , it is called parameterized Constructor.
class Box
{
double width;
double height;
double depth;
box ( )
{
System.out.println(“ constructing box”);
width=10;
height=10;
depth=10;
}
double volume ( )
{
return width * height * depth;
}}
class boxdemo6{
public static void main(String args[]){
Box mybox1=new box();
Box mybox2=new box();
double vol;
vol=mybox.volume();
System.out.println(“volume”+vol);
}}
Output:
Constructing box
Constructing box
Volume is 1000.0
Volume is 1000.0
Parameterized constructor: When the parameters are added to the constructor or when
constructor takes parameter then it is called as parameterized constructor.
class Box
{
double width;
double height;
double depth;
{
this.width=width;
this.height=height;
this.depth=depth;
}
double volume(){
return width*height*depth;
}
}
class BoxDemo7{
public static void main(String args[]){
Box mybox1=newBox(10,20,15);
Box mybox2=newBox(3,6,9);
double vol;
System.out.prinln(“volume is”+vol);
vol=mybox2.volume();
System.out.prinln(“volume is”+vol);
}
}
Output:-
Volume is 3000.0
Volume is 162.0
Garbage Collection
• Object are dynamically allocated by using new operator
• Such object are destroyed and their memory must be released for later reallocation
• In java destruction of object take place automatically
• This is achieve by a process called Garbage Collection.
• Garbage Collection process runs on allow priority thread.
• The Garbage Collection knows how to release memory allocated with new.
• Any object is eligible for Garbage Collection when your program can no longer
reference it.
• Local variables are eligible for Garbage Collection when your program can no longer
reference it.
• An object is available for Garbage Collection on if it is set to ’null’.
System.out.println(“a:”+a);
}
void test(int a,int b){
System.out.println(“a and b:” +a+ “ ” +b);
}
double test(double a){
System.out.println(“double a:” +a);
return a*a;
}
}
class Overload{
public static void main(String args[]){
OverloadDemo ob=new OverloadDemo( );
double result;
ob.test( );
ob.test(10);
ob.test(10,20);
result = ob.test(123.2);
System.out.println(“Result of ob.test (123.2): result”);
}
}
Output:
No parameters
a : 10
a and b : 10 20
double a : 123.2
result of ob.test (123.2) : 15178.24
Overloading Constructor
Like method constructor can also be overloaded. Since the constructor in a class have the
same name as the class, their signature are differentiated by their parameter list.
Example:
class Box{
double width;
double height;
double depth;
Box (double w, double h, double d){
width = w;
height = h;
depth = d;
}
Box ( ){
width = -1;
height = -1;
depth = -1;
}
Box (double len){
width = height = depth = len;
}
double volume(){
return width*height*depth;
}
}
class overloadcons{
public static void main (string args[])
}
Box mybox1 = new Box (10,20,15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol =Mybox1.volume();
System.out.println (“volume of mybox1 is”+ vol);
vol = Mybox2.volume();
System.out.println (“volume of mybox2 is”+ vol);
vol = Mycube.volume();
System.out.println (“volume of mycube is”+ vol);
}}
Output:-
volume of mybox1 is 3000.0
Example
class test {
void meth (int i , int j){
i*=2;
j/=2;
}
}
class callbyvalue{
public static void main(string args[]){
test 0b = new test();
int a=15, b=20;
System.out.println(“a and b before call:”+a+ “ “ +b);
Obmeth(a,b);
System.out.println(“a and b after call:”+a+ “ “ +b);
}}
o/p:
a and b before call:15 , 20
a and b before call:15, 20
Call by Reference:
In call by reference a reference to an argument is passed to the parameter inside the
subroutine [ this reference is used to access the actual argument specified in the call , this
means that change make to the parameter will after the argument used to subroutine:
Ex.
class test {
int a,b;
{
public static void main(String ar)
{
test ob=new test(15,20);
System.out.println(“ob.a and ob.b before call:”+ob.a+” “+ob.b);
ob.meth(ob);
O/P:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
Returning Object:
class test {
int a;
test (int i)
{
a=i;
}
test incrByTen()
{
test temp=new test(a+10);
return temp;
}
}
class Report{
public static void main(String ar[]){
test ob1=new test (2);
test ob2;
ob2=ob1.incrByTen();
System.out.println(“ob1.a”+ob1.a);
System.out.println(“ob2.a”+ob2.a);
ob2=ob2.incrByTen();
System.out.println(“ob2.a after second increase:”+ob2.a);
}}
O/P:
ob1.a 2
ob2.a 12
ob2.a after second increase 22
Recursion:
Recursion is the process of defining in term of itself. It allows a method to call itself.
The method is called itself, said to be recursive.
Ex.:
class Factorial {
int fact (int n) {
int result;
if(n==1)
return 1;
else
result=fact(n-1)*n;
return result;
}
}
class Recursion{
public static void main(String ar)
{
Factorial f=new Factorial();
System.out.println(“Factorial of 3 is “+ f.fact5(3));
System.out.println(“Factorial of 4 is “+ f.fact5(4));
System.out.println (“Factorial of 3 is “+ f.fact5(3));
} }
o/p
Factorial of 3 is6
Factorial of 4 is24
Factorial of 5 is120
Static keyword:
Static can be three Things:
static variable
static method
static block
-> static variable:
When a member is declared static, it can be access before any object of its class is created
|-> static member can be used independent of any object outside of the class
In which they are declared by specifying Name of the class followed by the dot operator
Syntax: class.memeber;
ii) Static method:
They can only call other static method
They must only access static data
System.out.println(“args[“+i+”]:”+args[i]);
}
}
• javaCommandLine: this is a test 100-1
C/P : args[0] : this
args[1] : is
args[2] : a
args[3] : test
args[4] : 100
args[5] : -1
INHERITANCE
• Definition:-
“The mechanism of deriving new class from old one is called inheritance. The old class is
known as base class or supper class or parent class. The new class is called as sub class. The
inheritance allows all sub classes to inherit all the variables and method of their parent
classes.”
class A{
int i,j;
void showij() {
System.out.println(“I and j:”+i+” “+j);
}
}
class B extend A {
int k;
void showk() {
System.out.println(“k:”+k);
}
void sum() {
System.out.println(“i+j+k:”+(i+j+k));
}
}
class simpleInheritance {
public static void main(String args[]) {
A superob=new A();
B subob=new B();
superob.i=10;
superob.j=20;
System.out.println(“contents of superob:”);
superob.showij();
System.out.println();
subob.i=7;
subob.j=8;
subob.k=9;
System.out.println(“contents of subob: ”);
subob.showij();
subob.showk();
System.out.println();
System.out.println(“sum of I, j and k in subob:”);
sumob.sum();
}
}
O/P:- Contents of superob:
i and j : 10 20
Contents of superob:
i and j : 7 8
k:9
sum of i, j and k in subob:
i+j+k : 24
int total ;
void sum() {
total = i + j;
}}
class Access{
public static void main (String args[]){
B subob = new B ( );
subob.setij (10,12);
subob.sum ( );
System.out.println(“ Total is :” + subob.total);
}
}
• A super class variable can reference a subclass object.
• A reference variable of a super class can be assign a reference to any sub class be
assign a reference to any sub class derived from that super class.
• When a reference to a subclass object is assigned to a super class reference variable.
You will have access only to that part or the object defined by the super class.
Super Keyword:- Whenever a subclass needs to refer to its immediate super class , it can be
do by using keyword super. The super has two general forms:
1.) It is used to access the member of super class that has been hidden by the member of
subclass .
2.) To first call the superclass constructor.
Accessing superclass Members:- Super always refer to the superclass in which it is used . It
has following format:
Super.member
Member can be either a method or an instance variable.
i) Accessing instance variables
class A
{
int i;
}
class B extends A
{
int i;
B(int a,int b){
super.i=a;
i=b;
}
void show(){
System.out.println(“i in superclass:”+super.i);
System.out.println(“i in subclass:”+i);
}
}
class usesuper{
public static void main(String args[]) {
B subOb=new B(1,2);
subOb.show();
}
}
O/P:-- i in superclass 1
i in subclass 2
ii) Accessing instance variables: If method overrides one of its superclass method you
can invoke the overridden method through the use of keyword super.
class superclass {
void printmethod(){
System.out.println(“printed in Superclass”);
}
}
class subclass extends superclass {
void printmethod(){
super.printmethod();
System.out.println(“printed in Subclass”);
}
public static void main(String args[])
{
subclass s = new subclass();
s.printmethod();
}
}
O/P: printed in superclass
printed in subclass
Using super to call superclass constructor : A subclass can call a constructor method defined
by its superclass by use of following form of super.
Super(parameter-list);
Here,parameter-list specifies any parameters needed by the constructor in the
superclass.Super() must always be the first statement executed inside a subclass’s
constructor.
Example:=>
class box{
double width;
double height;
double depth;
box(box ob){
width=ob.width;
height=ob.height;
depth=ob.depth;
}
box(double w,double h,double d){
width=w;
height=h;
depth=d;
}
box(){
width=-1;
height=-1;
depth=-1;
}
box(double len){
width=height=depth=len;
}
double volume(){
return width*height*depth;
}
}
class boxweight extends box{
double weight;
boxweight(box1.length ob)
{
super(ob);
weight=ob.weight;
}
boxweight(double w,double h,double d,double m){
super(w,h,d);
weight=m;
}
boxweight()
{
super();
weight=-1;
}
boxweight(double len,double m)
{
super(len);
weight=m;
}
}
class demosuper
{
public static void main(String args[])
{
boxweight mybox1=new boxweight (10,20,15,34.3);
boxweight mybox2=new boxweight (2,3,4,0.076);
boxweight mybox3=new boxweight ();
boxweight mycable =new boxweight (3,2);
boxweight mycable =new boxweight (mybox1);
double vol;
vol=mybox1.volume();
System.out.println(“Volume of mybox1 is :”+vol);
System.out.println(“Weight of mybox1 is :”+mybox1.height);
System.out.println();
Vol=mybox2.volume();
System.out.println(“Volume od mybox2 is :”+vol);
System.out.println(“Weight of mybox2 is :”+mybox2.height);
System.out.println();
vo1=mybox3.volume();
System.out.println(“volume of mybox3 is”+vo1);
System.out.println(“Weight f mybox3 is”+mybox3.weight);
System.out.println();
vo1=myclone.volume();
System.out.println(“Volume of my clone is”+vo1);
System.out.println(“weight of my clone is”+myclone.weight);
System.out.println();
v01=mycube.volume();
System.out.println(“volume of mycube is”+vo1);
System.out.println(“Weight of mycube is”+vo1);
System.out.println();
}
}
Example:
class A{
A()
{
System.out.println(“inside A’s constructor”);
}
` }
class B extends A
{
B()
{
System.out.println(“inside B’s constructor”);
}
}
class c extends B
{
c()
{
class B extends A{
void call me(){
System.out.println(“inside b’s call me method”) ;
}}
class c extends A{
void call me(){
System.out.println(“inside c’s call me method”) ;
}
}
class dispatch{
public static void main (String args[]){
A a =new A();
B b =new B();
C c =new C();
A r;
r=a;
r.callme();
r=b;
r.callme();
r.c;
r.callme();
}
}
output
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
abstract type_name(parameter_list)
}
}
An abstract method has no body means It defines method signature, return Value and the
exception it throws. If a class contain one or more abstract method then the class become
abstract. The class which inherits the abstract class must override the abstract method else
that class must be declared abstract. Object of abstract class cannot be created but reference
of abstract class can not create.
Abstract class can contain concrete method.
An abstract method can not be private, static, final or synchronized.
Constructor can not be declared as abstract.
Abstract class are used to act as a base class.
A class can be abstract even though no method are declared as abstract.
Ex.
abstract class A
{
abstract void callme();
void callmetoo()
{
System.out.println(“This is a concrete method”);
}
}
class B extends A
{
void callme()
{
System.out.println(“B’s implementation of callme”);
}
}
class AbstractDemo
{
public static void main(“String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}
Final keyword:
The keyword final has three uses.
i) It can be used to create the equivalent of a named constant.
ii) Final is used to prevent overriding.
iii) Final is used to prevent inheritance.
i) Final variable:
It is used to create the equivalent of a name constant.
Variable can be declared as final but their contains can not be modified.
Variable declared as final do not occupy memory on a per instance bases.
It is essentially a constant
Variable declared as final must be initialized with some value.
{
System.out.println(“this is a final method”);
}
}
class B extends A
{
void meth()
{
System.out.println(“Illegal”);
}
}
Visibility control/access modifiers
Java provides four type of visibility modifier
• public
• friendly/default
• protected
• private
• Public:
Any variable or method the entire class.by declaring the variables or method as public
it is possible to make them visible to all the classes outside the class. A variables or
method declared as public has the more possible visibility and accessible everywhere
for example.
public int n;
public void addition()
{
……..
}
Friendly Access
In the situation where no access modifiers is specified, the member defaults to a limited
version off public accessibility known as “friendly” level of access.
The basic difference between the “pubic” access and “friendly” access is that the public
modifier makes field visible in all accesses regardless or their Packages while the
friendly access make fields visible only in the same package, but not in other package.
Protected:
Protected modifiers make the fields visible not only to all classes and subclasses in the
same package but also to subclasses in other packages.
The visibility level of a “protected” field are in between the public access and friendly
access. Non-subclasses in other packages can not access the “protected” members.
Private access:
Private Fields provides highest degree of protection they are accessible only with their
own class. They can not .be inherited by subclasses and therefore not accessible in
subclasses.
A method declared as private behaves like a method declared as final. It prevents the
method form being subclasses
Non-private method can not be overridden in subclass and then make it private.
Rules visibility modifiers:
Use public keyword if fields is to be visible everywhere.
Use protected keyword if the fields is to be visible everywhere in current package and
also the subclasses in other packages.
Use “default” keyword if the fields is nor be visible anywhere except in its only class.
Packages
Packages are container for classes that are used to keep the class name space
compartmentalize. Packages are Java’s way of grouping a variety of classes and interfaces
together. By organizing our classes into Packages we achieve the following benefits.
1. The classes contained in the Package of the other programs can be easily reused.
2. In packages classes can be unique compared with classes in other packages. That is
two classes in two different packages can have the same name. They may be referred
by their fully qualified name, compromising the packages name and the class name.
3. Packages provide a way to hide classes thus preventing other program or packages
from accessing classes that are meant for interval use only.
4. Packages also provide a way for separating design from coding. First we can design
classes and decide their relationships and the needed for the implement the java code
needed for the methods. It is possible to change the implementation of nay method
without affecting the rest of the design.
Creating our own package involves the following steps:
1. Declare the package at the beginning of a file using the form.
Package package name;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source files
are stored.
4. Store the listing as the class name. Java fie in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.
Remember that case is significant and therefore the subdirectory name must
match the package name.
Example:-
package Mypack;
public class Balance {
String name;
double bal;
public Balance (String n, double b) {
name=n;
bal=b;
}
public void show() {
if (bal < 0)
System.out.println(“”);
System.out.println(name+“: $” +bal);
}
}
class AccountBalance{
public static void main(String args[])
{
Balance current[]=new Balance[3];
current[0] = new Balance (“M.J. Patel”,123.23);
current[1] = new Balance (“Will Tell”,157.02);
current[2] = new Balance (“Rajnish Shrivastav”,-12.33);
for(int i=0; i<3; i++)
current[i].show();
}
}
Scope of Access Specifier
Private No modifier Protected Public
Same Class Yes Yes Yes Yes
Same package sub class No Yes Yes Yes
Same package Non sub class No Yes Yes Yes
Different package sub class No Yes Yes Yes
Different package non sub class No No No Yes
Interfaces:
An interface is basically a kind of class like classes interfaces contain methods and variables
with a major difference. Using interface you can specify what a class must do, but not how it
does it.
The general form of an interface:
Access specifier interfacename
{
Returntype methodname1(parameter list);
interface CallBack
{
void Meth();
}
interface CallBack1 extends CallBack
{
void Meth1();
}
interface CallBack2 extends CallBack1
{
void Meth2();
}
class client implemetns CallBack2
{
public void meth()
{
System.out.println (“In method”);
}
public void meth1()
{
EXECPTION HANDLING
There are two types of error:
1. Compile time error
2. Run time error
All syntax error will be detected and displayed by the java compiler and therefore
these errors are known as compile time error.
Sometimes a program may compile successfully creating the classfile but may not run
properly. Such programs may provide wrong results due to wrong logic or may
terminate due to errors. This type of errors are called Run-time errors.
Exception is an abnormal condition that arises in the code sequence at runtime. In
other word it is a runtime error.
In java, exception is an object that decide the exceptional condition that arises in a
code sequence.
Java.lang.object
Java.lang.Throwable
Java.lang.Exception Java.lang.Error
Eg:- checked exception
Java.lang.RuntimeException
Eg:- Runtime exception
OUTPUT:-
Division by zero
class NestTry{
public static void main(String ar[]){
try{
int a=ar.length;
int b=42/a;
System.out.println(“a=”+a);
try{
if(a==1)
a=a/(a-a);
c[42]=99;
}
}
catch(ArrayIndexOutOfBoundsException){
System.out.printn(“Array index out of bound:”+e);
}
}
catch(ArithmeticException)
{
System.out.println(“Divide by 0”+e)
}
}
}
Throw : When we want to throw our own exceptions. We can do this by using the
keyword throw as follow:-
throw new Throwable_subclass;
Example:-
class Throwdemo
{
static void demopro()
{
try
{
Throw new NullPointerException(“demo”);
}
catch(NullPointerException e)
{
{
throwOne();
}
catch(IllegalAccessException e)
{
System.out.println(“caught”+e);
}}
}
}
throw new MyException(“Number is too small”);
}
}
catch(MyException e){
System.out.println(“caught My Exception”);
System.out.println(e.getmessage());
}
finally{
System.out.println(“i am always here”);
}
}}
O/P:
Caught My Exception
Number is too small
I am always here.
MULTITHREADED PROGRAMMING
1. Explain the life cycle of a thread
The thread can enter into many states during its life time. The five types of states
are:
1) Newborn state
2) Runnable state
3) Running state
4) Blocked state
5) Dead state
Stop
Start
Active Thread
Stop Dead
The Thread can be one state from there five states. It can move from one state one
state to another is various ways shown in figure.
1) Newborn state: When a thread object is created, the thread is born, and called as
thread is in New born state. In new born state the thread is not yet scheduled for
running.
When the thread is in newborn states it can be
1) Either scheduled for running using start() method.
2) Or kill it using stop methods.
Newborn
Start Stop
Once, the thread is scheduled it can be moved to runnable state shown in figure.
The exception will be thrown if any attempt is made to use any method at this
stage.
2. Runnable State: The runnable state of a thread means that the thread is ready for
execution and is waiting for the availability of the processor. The threads which re
ready for execution are placed in queue. So the runnable state joins the queue of the
threads that are waiting for execution.
If all threads have same priority then they are given a time slice for execution in
round robin fashion, fist-come-first-serve manner. The thread after compiling its
time slice, joins the end of queue again waits for its run for execution, And this
process of closing time to threads is known as time slicing
To release the control of thread to another thread to equal priority before its turn
comes, yield() method can be used.
Running thread
Runnable Threads
3. Running State: Running state means that the processor has given its time to the
thread for its execution. The thread runs until it releases control on its own or it is
preempted by higher order priority thread. A running thread can relinquish its control
in any one of the following situations:
1) It is suspended using suspended method, which can be useful. When to
suspend thread for some time but do not want to kill.
suspend()
Resume
2) It can be made to sleep. The thread can be made to sleep for specified time period
using the method sleep (time) where time is in milliseconds.
Sleep()
After()
Notify
1) Implementing Runnable:
The easiest way to create thread is to create a class that implements runnable interface. To
implements a runnable class need only implement single method call run which is declared
like this
public void run()
Following are the steps:
1) Declared the class as it is implementing runnable interface.
2) Implement run() method.
3) Crete thread by defining an object that instantiated from this “runnable” class as the target
of the thread.
4) Call the thread’s start() method to run the thread.
5) The run can call other methods, use other classes and declared variables, just like the main
thread can. The only difference is that run() establishes the entry point for another, concurrent
thread of execution within your program. The thread will end when run() returns.
The thread defines several constructors. The one that we will use is shown here:
Thread(Runnalbe threadob, String Threadname)
class NewThread implements Runnalbe
{
Thread t;
NewThread()
{
t=newthread (this , “Demo thread”);
system.out.println(“Child thred:”+t);
t.start();
}
public void run()
{
try
{
for(int i=5; i>0; i--)
{
System.out.println(“Child thread”+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println(“child interrupted”);
}
System.out.println(“Exiting child thread”);
}
}
class Threaddemo
{
public static void main(string arg[])
{
New newthread();
try
{
for(i=5; i>0; i++)
{
System.out.println(“Main method”+i);
Thread.sleep(1000);
}
}
catch(InterruptedException)
{
System.out.println(“Main thread interrupted”);
}
System.out.println(“Main thread existing”);
}
}
2). Extending Threadclass: To create a thread is to create a new class that thread and then
create am instance of that class. Extending a thread class includes following steps:
1. Declare the class extending the thread. The thread class cn be extended as follows:
class MyFirstThread extends Thread
{
……
}
2. Implement the run() method that is responsible for executing the sequence of code that the
thread with executed. The extending class must override the new thread. The run() method is
inherited by the class MyFirstThread implement the code to be executed by new thread
MyfirstThread. The implementation of run() will be like:
public void run()
{
-----
}
When new thread is started with start, Java calls the thread run() method. So it is run()
where all the action takes place.
3. Create a thread object and call the start() method to initiate the thread execution. Following
statement creates new thread.
A) MyFirstThread T = new MyFirstThread().
B) T.start().
C) The start method will automatically call run() method.
Example:-
NewThread()
{
super(“Demo Thread”);
System.out.println(“Child Thread”+ this);
start();
}
public void run()
{
for(int i=5; i>0; i--)
{
System.out.println(“Child thread”+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println(“child interrupted”);
}
System.out.println(“Existing child thread”);
}
}//class Newthread ends here
class ExtendThread
{
public static void main(string ar[])
{
new newthread();
try
{
for(i=5; i>0; i++)
{
System.out.println(“Main method”+i);
Thread.sleep(1000);
}
catch(InterruptedException){
System.out.println(“Main thread interrupted”);
}
System.out.println(“Main thread existing”);
}
}
Creating Multiple Thread
class NewThread implemtns Runnalbe
{
String name;
Thread T;
Prepared by Amit Shah 62 L J Polytechnic
Java Programming 5th CE IT
The sleep() method has second form shown next, which allows you to specify the
period in terms of milliseconds and nanoseconds.
This second form is useful only in environments that allow timing period as short as
nanoseconds.
2).SetName:- You can name the thread by using Setname. The general form is:
final void SetName (String threadname)
3). getName:- we can obtain the name of thread by calling getname method. The general
form is:
final sting getName()
4). isAllive:- there are two ways to determine whether a thread has finish.
1. You can call isAllive() on the thread. And its general form is:
final boolean isAllive()
The isAllive() method returns true, if the thread upon which it is called is still
running. If returns false otherwise.
2. Join():- This method is used to wait for a thread to finish. The general form is:
final void join() throws InterruptedException
This method waits until the thread on which it is called terminates. Its name comes
from concept of the allow thread waiting until the specified thread joins it.
Program of setName and getName method.
class CurrentThreadDemo {
public static void main (String arg[]) {
Thread t = Thread.currentThread();
System.out.println(“Current Thread:”+t);
t.SetName(“My Thread”);
System.out.println(“After name change”+t);
try {
for(int n=5; n>0 ; n--) {
System.out.println(n);
Thread.sleep(1000);
}
}
catch(InterruptedException e) {
System.out.println(“Main Thread Interrupted..”);
}
}
}//class current thread demo is over.
Thread Priority
We can set the priority of a thread.
The thread priority can be assign by using set priority method. The general form is:
ThreadNAme.setPriority(int Number);
Where the number is an integer value, or thread priority.
The Thread class defines following priority contansts:
MIN_PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10
By default intNumber is set to NORM_PRIORITY.
We can obtain the current priority setting by calling the getPriority method of thread.
Final int getPriority()
Whenever higher priority thread come in the currently running thread will be pre-empted
by incoming thread, and thus it forces the current running thread to move to the runnable
state.
Thus, higher priority thread always pre-empted lower priority threads.
class X extends Thread
{
public void run()
{
system.out.println(“It Thread X started”);
for(int i=1; i<=4; i++)
{
system.out.println(“It from Thread X :=”+i);
}
system.out.println(“It Thread X started”);
}
}
class B extends Thread
{
public void run()
{
system.out.println(“It Thread B started”);
for(int j=1; j<=4; j++)
{
system.out.println(“It from Thread B : j=” +j);
}
system.out.println(“It exit from Thread B”);
}
}
class C extends Thread
{
Public void run()
{
system.out.println(“It Thread X started”);
for(int k=1 ; k<=4 ; k++)
{
system.out.println(“It From Thread C=”+k);
}
Synchronization: - When two or more threads need access to a shared resource, they need
some way to ensure that the resource will be used by only one thread at a time. The process
by which this is achieved is called Synchronization.
For example: One thread trying to read records from file while another thread is still
writing to the same file. In Java, this problem can be overcome by using the technique known
as Synchronization. The keyword synchronized is used.
When method is declared as synchronized in Java creates a monitor and hands over to the
thread that calls the method for first time. A monitor is an object that is used as a mutually
exclusive lock, or mutex. Only one thread can own a monitor at a given time. When
a thread acquires a lock , it is said to have entered the monitor. As long as thread
holds the monitor, no other thread can enter the synchronized section of code.
Monitor is similar to key and the thread that holds there key can only open the
lock. These other threads are said to be waiting for the monitor.
class synch
{
public static void main(String args[])
{
callme target=new callme();
caller ob1=new caller(target,”Hello”);
caller ob2=new caller(target,”Synchronized”);
caller ob3=new caller(target,”World”);
try
{
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println(“Interrupted”);
}
}
}
O/P- Hello [Synchronized [World]
]
]
Using synchronize keyword in method
class callme
{
Synchronize void call (String msg)
{
system.out.println(“[“+msg);
Try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
system.out.println(“Interrupted”)
}
system.out.println(“]”);
}
}
class caller implements Runnable{
String msg;
callme target;
Thread t;
public caller (callme targ, String s){
target=targ;
msg=s;
t=new thread(this);
t.start();
}
public void run(){
target.call(msg);
}
}
class synch{
public static void main(String args[]){
callme target=new callme();
caller ob1=new caller(target,”Hello”);
caller ob2=new caller(target,”Synchronized”);
caller ob3=new caller(target,”World”);
try {
Ob1.t.join();
Ob2.t.join();
Ob3.t.join();
}
catch(InterruptedException e){
System.out.println(“Interrupted”);
}
}
}
O/P- [Hello]
[Synchronized]
[World]
Example of locking object by synchronized
class callme
{
void call(String msg)
{
System.out.println(“[“+msg);
try
{
Thread.sleep(1000);
}catch(InterruptedException e)
{
system.out.println(“]”);
}
}
class caller implements Runnable
{
String msg;
callme target;
Thread t;
Deadlock- When two threads have a circular dependency on a pair of synchronized objects,
then there is deadlock .When two or more threads are waiting to gain control of resource. Due
to some reasons, the condition on which the waiting threads relay on to gain control does not
happen. The result is called as deadlock.
For example, suppose the thread A must access Method1 before it can release Method2,but
thread B can not release Method1 untill it gets hold of Method2.Because there are mutually
exclusive conditions, a deadlock occurs.
Deadlock is a difficult error to debug for two reasons:
i) In general it occurs only rarely,when two threads time-slice in just the
right away
Java implements strings as object of type string. When you create a string object,you
creating a string that cannot be changed that is once a string object has been
created,you cannot changed the characters that compromise the string.
Each time if you need an alter version of an existing string,new string object is created
the contains the modification. The original string is left unchanged.
For those cases in which a modifiable string is desired there is a companion class to
string called StringBuffer whose objects contain string that can be modified after they
are created.
Both string and StringBuffer class are defined in java.lang . thus they are available to
all programs automatically both are declared final which means that neither of these
classes may be subclasses.
String length:
The length of a string is the number of characters in it. To obtain this value the
length() function is used . It has following general form:
Int length()
Example: String s1=”ABCDEF”;
Int length=s1.length();
System.out.println.(“the length of string s1 is:”length);
o/p: the length of string is: 6
Character Extraction Method:
1) Char At():
To execute a single character from a string, you can refer directly to an
individual character via the char At() method. It has this general from:
Char char At (int where)
Here where is the index of the character that you want to obtain the value of
where must be non negative and specify a location within the string char At()
returns the character at the specified location for example.
Example: Char ch;
Ch=”abc”char At(1);
o/p: ch=b
2) getchars():
If you need to more than one character at a time, you us the getchars()
method. It has this general form:
Void getchars(int sourcestart,int sourceEnd,char target[],int target start);
Here sourcestrat specifies the index of the beginning of the substring,and
sourceEnd specifies the index of the desired substring. Array that will receive
the characters is specified by target. The index within target at which the
substring will be copied is passed in targetstart.
Example:
class getcharsDemo{
System.out.println(“s1+”equals”+s2+”->”+s1.equals (s2));
System.out.println(“s1+”equals”+s3+”->”+s1.equals(s3));
System.out.println(“s1+”equals”+s4+”->”+s1.eqauls(s4));
System.out.println(“s1+”equalsIgnoreCase”+s4+”->”+s1.
equalsIgnorecase(s4));
}
}
O/P:
Hello equals Hello -> true
Hello equals Good By->false
CompareTo():
This function checks whether the string is less than or greater than or equal to the
other string. It has general form:
int compare To (string str)
Here, str is string being compare with the invoking string. The result of the
comparison is returned and is interpreted as Shown below:
Value Meaning
Less than zero Thi invoking string is less than str
Greater than zero The invoking string is greater than str
Zero The two strings are equal.
EX: WAP in java to read 10 strings from console and then print the stored on console.
import.Java.io.*;
public class sort {
public static void main(String ar[]) {
int i, j;
try{
InputSystemReader in = new InputStreamReader(BufferedReader br=new
BufferedReader(System.in);
System.out.println(“Enter the strings to be sort:”);
for (i=o;i<10;i++)
str[i]=br.readline();
System.out.println(“sorted string are:”);
for(i=0;i<10;i++){
for(i=i+1; j<10; j++){
if(str[i].compareTo(str[j]<0)
{
String temp =str[j];
str[j]=str[i];
str[i]=temp;
}
}
System.out.println(str[j]);
}
catch(Exception e)
{
System.out.println(e);
} }
}
Searching strings:
The string class provides two methods that allows you to search a string for a
specified character or substring.
I). Index of(): searching the first occurrence of a character or substring.
II).lastIndex of(): searching for the last occurrence of a Character or substring.
These, two methods are overload in several different ways. In all case the methods
return the index at which the character or substring was or an failure.
To search for the first occurrence of character use int indexOf(int ch)
To search for last occurrence of a character use int lastIndexOf(int ch)
Here, ch is the character being sought.
To search for the first or last occurrence of a substring use.
int indexOf(string str)
int lastIndexOf(string str)
Here, str specifies the substring .
We can specify a starting point for the search using these forms:
Modifying a string:
Substring(): You can extract a substring using substring. It has two forms-
first is.
String substring (int startIndex)
Here, startIndex specifies the index at which the substring will begin. This
form returns a copy of the substring will begin. The form returns a copy of the
substring that begins at startIndex and runs to the end of the invoking string.
The second from of substring allows you to specify the beginning and ending
index of the substring.
String substring(int startIndex, int endIndex)
Here, startIndex specifies the beginning Index and endIndex specifies the
stoping point. The string returned contains all the characters from the
beginning index upto but not including the ending index.
Concat():
We can concatenate two string using concat()
String concat(string str)
This method creates a new object that contains the invoking string with the
contents of str append to the end. Contact() performs the same function as
For example:
String s1=”one”;
String s2=s1.concat(“two”);
Puts the string “onetwo” into s2. It generates the same result as the following
sequence.
String s1=”one”;
String s2=s1+”two”;
Replace():
The replace method replaces all the occurrence of the one character in the
invoking string with another character. It has the following general form:
String replace(char original, char replacement)
Here, original specifies the char be replaced by the character specified by the
replacement. The resulting string is return.
For example:
String s=”hello”.replace(‘1’,
Both methods returns a string a string object that contains the uppercase or
lowercase equivalent of the invoking string.
Ex: class changecase {
public static void main(String args[]) {
String s=”this is a test”;
System.out.println(“original:”+s);
String upper=s.toUppercase();
String lower=s.tolowercase();
System.out.println(“uppercase:”+upper);
System.out.println(“lowercase:”+lower);
} }
O/P: original: This is a test
Uppercase: THIS IS A TEST
Lowercase: this is a test.
StringBuffer:
StringBuffer is a class of string that provides much of the functionality of strings.
String represents fixed-length, immutable character sequences. In contrast
StringBuffer represents grow able and writable character sequences.
StringBuffer may have:character and substring inserted in the middle or appended to
the end. StringBuffer will automatically grow to make room for such additions and
after has more characters reallocated than are actually needed to allow room for
growth.
StringBuffer Constructors:
StringBuffer defines the constructors:
StringBuffer()
StringBuffer(int size)
StringBuffer(string str)
The default constructor reserves room for an integer argument that explicitly sets the
size of the buffer.
The third version accepts a string argument that sets the initial contacts of the
stringBuffer object and reverse room for 16 more characters without reallocation.
Methods of StringBuffer:
I). Length():
The current length of a stringBuffer can be found via the length() method.
The general form are:
int length()
int capacity()
Ex: class StringBufferDemo {
System.out.println(“buffer=”+sb);
System.out.println(“length=”+sb.length());
System.out.println(“capacity=”+sb.capacity());
}
}
O/P: buffer=Hello
Length=5
Capacity=21
II).Setlength():
To set the length of the buffer within a StringBuffer Object, use
setlength(). Its general form is:
void setlength(int len)
Here, len specifies the length of the buffer, this value must be non
negative.
When you increase the size of the buffer, null added to the end of the existing
buffer. If you call setlength() with a value less than the current value returned
by length(),than the characters stored beyond the new length will be lost.
IV): CharAt() and setcharAt():
The value of the single character can be obtained from a stringBuffer via the
charAt() method, we can set the value of a character within a stringBuffer
using setcharAt(). The general form is:
V): append:
The append() method concatenates the string representation of any other type
of data to the end of the invoking StringBuffer object. It has overloaded
version for all the built in type and for object. Here, are few forms:
StringBuffer append(String str)
StringBuffer append(int sum)
StringBuffer append (object obj).
System.out.println(s);
}
}
O/P: a=42 !
VI): insert():
The insert() methods insert one string into another. It is overload to accept
values of all the simple type plus strings and objects. Few forms of insert()
method:
StringBuffer insert(int index,string str)
String Buffer insert(int index, char ch)
StringBuffer insert(int index,object obj)
Here, index specifies the index at which point the string will be inserted into
the invoking StringBuffer object.
Sb.insert(2,”Like”);
System.out.println(sb);
}
}
VII): reverse():
We can reverse the characters within a StringBuffer object using
reverse(). The general form is :
StringBuffer reverse()
This method returns the reversed object on which it was called.
Ex: class ReverseDemo {
public static void main(String arg[])
{
StringBuffer s=new StringBuffer(“abcdef”);
System .out.println(s);
s.reverse();
System.out.println(s);
}
}
O/P: abcdef
fedcba
O/P:
after replace: this was a test
Wrapper Classes:
1. Many built in, Java classes work with only with objects and not on primitive
data types. Therefore wrapper classes are provided which have methods to
convert primitive datatype, to objects and vice-versa.. the wrapper classes also
provide method for converting string to the various data type and vice-versa.
2. Wrapper classes are contained in the java.lang package. The wrapper class are
method static methods therefore those can be invoked using class name,that is
there is no need to instantiate wrapper classes to invoke their methods.
3. Below tables shows the simple data types and their corresponding wrapper
class type.
The wrapper classes have a number of unique method for handling primitive
data and objects.
NOTE: All the parse methods throw a number format Exception of the
value of the str does not represent a number.