You are on page 1of 48

GURU NANAK DEV ENGINEERING COLLEGE

LUDHIANA

DEPARTMENT OF INFORMATION TECHNOLOGY

JAVA LAB(LPCIT-109)
PRATICAL FILE

SUBMITTED TO: SUBMITTED BY:


Er. Kamaljeet kaur Dhillon Chahat jarewal
Assistant Professor(IT) URN-2104487
CRN-2121030
(I.T-A1)
Experiment no :1
Handling various data types

Code:- public class Main {


public sta c void main(String[] args) {
String Name= "Chahat Jarewal";
int Rollno =2104487;
int myNum = 500; // integer (whole number)
float myFloatNum = 6.89f; // floa ng point number
char myLe er = 'A'; // character
boolean myBool = true; // boolean
String myText = "heyaa"; // String
System.out.println(Name);

System.out.println(Rollno);
System.out.println(myNum);
System.out.println(myFloatNum);
System.out.println(myLe er);
System.out.println(myBool);
System.out.println(myText);
}
}

Output :-
Experiment no :2
Type casting

Code:- public class Main {


public sta c void main(String[] args) {
String Name= "Chahat Jarewal";
int Rollno =2104487;
int myInt = 9;
double myDouble = myInt; // Automa c cas ng: int to double
System.out.println(Name);
System.out.println(Rollno);
System.out.println(myInt);
System.out.println(myDouble);

}
}

Output:-
Experiment no :3
Arrays – 1D and 2 D
Code :- ARRAY -1D
public class Main {
public sta c void main(String[] args) {
String Name= "Chahat Jarewal";
int Rollno =2104487;
// Crea ng a 1D array
int[] array1D = new int[5];

// Accessing elements in the array


array1D[0] = 10;
array1D[1] = 20;
array1D[2] = 30;
array1D[3] = 40;
array1D[4] = 50;
// Prin ng elements in the array
System.out.println(Name);
System.out.println(Rollno);
for (int i = 0; i < array1D.length; i++){
System.out.println(array1D[i]);
}}}

Output :-
Code :- ARRAY -2D
public class Main {
public sta c void main(String[] args) {
String Name= "Chahat Jarewal";
int Rollno =2104487;
// Crea ng a 2D array
int[][] array2D = new int[3][3];
// Accessing elements in the array
array2D[0][0] = 1;
array2D[0][1] = 2;
array2D[0][2] = 3;
array2D[1][0] = 4;
array2D[1][1] = 5;
array2D[1][2] = 6;
array2D[2][0] = 7;
array2D[2][1] = 8;

array2D[2][2] = 9;
// Prin ng elements in the array
System.out.println(Name);
System.out.println(Rollno);
for (int i = 0; i < array2D.length; i++) {
for (int j = 0; j < array2D[i].length; j++) {
System.out.print(array2D[i][j] + " "); }
System.out.println();}}}

Output:-
Experiment no :4
Various control structures

Code :- 1.If-else statement:


public class Main {
public sta c void main(String[] args) {
String Name= "Chahat Jarewal";
int Rollno =2104487;
int num = 10;
// Prin ng elements in the array
System.out.println(Name);
System.out.println(Rollno);
if (num > 0) {
System.out.println("Posi ve number");} else if (num < 0) {
System.out.println("Nega ve number");} else {
System.out.println("Zero");}}}

Output :-

2. While loop:
public class Main {
public sta c void main(String[] args) {
String Name= "Chahat Jarewal";
int Rollno =2104487;
int i = 1;
while (i <= 5) {
// Prin ng elements in the array
System.out.println(i);
i++;}
System.out.println(i);
i++;

System.out.println(Name);
System.out.println(Rollno); }}

Output :-

3. Do-while loop:
public class Main {
public sta c void main(String[] args) {
String Name= "Chahat Jarewal";
int Rollno =2104487;
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
System.out.println(Name);
System.out.println(Rollno);}}

Output :-
4. Switch statement:
public class Main { public sta c void main(String[] args) {
String Name= "Chahat Jarewal";
int Rollno =2104487;
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");break;
case 2:
System.out.println("Tuesday");break;
case 3:
System.out.println("Wednesday");break;
default:
System.out.println("Invalid day");}
System.out.println(Name);
System.out.println(Rollno);}}

Output:-
Experiment no :5
Various decision structures

Code:- 1. If-else statement:


public class Main { public sta c void main(String[] args) {
String Name= "Chahat Jarewal";
int Rollno =2104487;
int num = 5;
if (num > 0) {
System.out.println("The number is posi ve.");} else if (num < 0) {
System.out.println("The number is nega ve.");} else {
System.out.println("The number is zero.");}
System.out.println(Name);
System.out.println(Rollno);} }

Output :-

2. Switch statement:
public class Main { public sta c void main(String[] args){
String Name= "Chahat Jarewal";
int Rollno =2104487;
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent!");break;
case 'B':
System.out.println("Good job!"); break;
case 'C':
System.out.println("You can do be er.");break;
default:

System.out.println("Invalid grade.")}
System.out.println(Name);
System.out.println(Rollno);}}

Output:-

3. Ternary operator:
public class Main { public sta c void main(String[] args){
String Name= "Chahat Jarewal";
int num1 = 10;
int num2 = 5;
int max = (num1 > num2) ? num1 : num2;
System.out.println("The maximum number is: " + max);
int Rollno =2104487;
System.out.println(Name);
System.out.println(Rollno);}}

Output:-
Experiment no :6
Recursion

Code:- public class Main {


public sta c void main(String[] args) {

String Name= "Chahat Jarewal";


int Rollno =2104487;
int result = sum(10);
System.out.println(result);
System.out.println(Name);
System.out.println(Rollno);
}
public sta c int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}}}

Output :-
Experiment no :7
Method Overloading by passing objects as arguments

Code :- public class Main {


sta c int plusMethodInt(int x, int y) {
return x + y;
}
sta c double plusMethodDouble(double x, double y) {
return x + y;
} public sta c void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
}

Output :-
Experiment no :8
Constructor Overloading by passing objects as arguments

Code:- class Student {


private int id;
private String name;
private int age;
// Constructor with no arguments
public Student() {
this.id = 0;
this.name = "Unknown";
this.age = 0; }
// Constructor with ID and name
public Student(int id, String name) {
this.id = id;
this.name = name;
this.age = 0; }
// Constructor with ID, name, and age
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age; }
// Constructor with another Student object as an argument
public Student(Student otherStudent) {
this.id = otherStudent.id;
this.name = otherStudent.name;
this.age = otherStudent.age; }
// Method to display student information
public void displayInfo() {
System.out.println("ID: " + id);
System.out.println("Name: " + name);
System.out.println("Age: " + age); }}
public class AnotherMain {
public static void main(String[] args) {
// Create students using different constructors
Student student1 = new Student();
Student student2 = new Student(101, "Alice");
Student student3 = new Student(102, "Bob", 20);
// Create a student by copying the information from another student
Student student4 = new Student(student3);
// Display student information
System.out.println("Student 1:");
student1.displayInfo();
System.out.println("\nStudent 2:");
student2.displayInfo();
System.out.println("\nStudent 3:");
student3.displayInfo();
System.out.println("\nStudent 4 (Copy of Student 3):");
student4.displayInfo(); }}

output:
Experiment no :9
Program to show use various access control and usage of
static, final and finalise().
Code: hclass AccessDemo {
// Public variable
public int publicVariable = 42;
// Private variable
private int privateVariable = 10;
// Protected variable
protected int protectedVariable = 20;
// Package-private variable
int packageVariable = 30;
// Static variable
static int staticVariable = 50;
// Final variable
final int finalVariable = 60;
// Constructor
public AccessDemo() {
System.out.println("Constructor called.”); }
// Public method
public void publicMethod() {
System.out.println("publicMethod() called.");}
// Private method
private void privateMethod() {
System.out.println("privateMethod() called."); }
// Protected method
protected void protectedMethod() {
System.out.println("protectedMethod() called.");}
// Package-private method
void packageMethod() {
System.out.println("packageMethod() called."); }
// Static method
static void staticMethod() {
System.out.println("staticMethod() called."); }
// Finalize method (deprecated in Java 9)
protected void finalize() {
System.out.println("finalize() called.");}}
public class TestClass {
public static void main(String[] args) {
AccessDemo obj = new AccessDemo();
// Accessing fields and methods with different access control
System.out.println("Public Variable: " + obj.publicVariable);
// Private variable is not accessible directly
// System.out.println("Private Variable: " + obj.privateVariable);
System.out.println("Protected Variable: " + obj.protectedVariable);
System.out.println("Package Variable: " + obj.packageVariable);
obj.publicMethod();
// Private method is not accessible directly
// obj.privateMethod();
obj.protectedMethod();
obj.packageMethod();
System.out.println("Static Variable: " + AccessDemo.staticVariable);
AccessDemo.staticMethod();
System.out.println("Final Variable: " + obj.finalVariable);
// Call finalize() method (deprecated in Java 9, rarely used)
obj.finalize();
}
}

output:
Experiment no :10
Program to show use of command line arguments.

Code : public class Command {


public static void main(String[] args) {
// Check if any command-line arguments were provided
if (args.length == 0) {
System.out.println("No command-line arguments provided.");
} else {
System.out.println("Command-line arguments provided:");
// Iterate through the arguments and print each one
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
}
}
}

Output :
Experiment no :11
Various types of inheritance by applying various access
controls to its data members and methods

Code : // Base class with private and protected members


class Animal {
private String privateField = "I am a private field in Animal class";
protected String protectedField = "I am a protected field in Animal class";
private void privateMethod() {
System.out.println("This is a private method in Animal class”); }
protected void protectedMethod() {
System.out.println("This is a protected method in Animal class");}}
// Single Inheritance: Dog is a subclass of Animal
class Dog extends Animal {
public void display() {
// Access protected field and method from the base class
System.out.println(protectedField);
protectedMethod(); }}
// Multiple Inheritance (via interfaces): Cat inherits from two interfaces
interface Meow {
void meow();
}
interface Purr {
void purr();
}
class Cat implements Meow, Purr {
public void meow() {
System.out.println("Meow!");
}
public void purr() {
System.out.println("Purrr...");
}}
// Hierarchical Inheritance: Tiger and Lion both inherit from Animal
class Tiger extends Animal {
public void displayTiger() {
// Access protected field and method from the base class
System.out.println(protectedField);
protectedMethod();
}}
class Lion extends Animal {
public void displayLion() {
// Access protected field and method from the base class
System.out.println(protectedField);
protectedMethod(); }}
public class InheritanceDemo {
public static void main(String[] args) {
// Single Inheritance
Dog dog = new Dog();
dog.display();
// Multiple Inheritance (via interfaces)
Cat cat = new Cat();
cat.meow();
cat.purr();
// Hierarchical Inheritance
Tiger tiger = new Tiger();
tiger.displayTiger();
Lion lion = new Lion();
lion.displayLion();
}}
Output :
Experiment no :12
Method overriding
Code : class Grandfather{
int age;String name;
public Grandfather(){ }
public Grandfather(int age,String name){
this.name=name;
this.age=age;
}public void Print(){
System.out.println("Inside Grandfather class");
System.out.println("Hi I am "+name+" and I am "+age+" years old");
}}
class Father extends Grandfather{
int age; String name; float salary;
public Father(){
}
public Father(int age,String name){
this.name=name;
this.age=age;
}public void Print(){
System.out.println("Inside Father class");
System.out.println("Hi I am "+name+" and I am "+age+" years old");}
}
public class Methodoverriding {
public static void main(String [] args){
Father obj=new Father(45,"Father");
obj.Print();
}
}
Output :
Experiment no :13
Abstract class
Code : // Abstract class
abstract class Shape {
// Abstract method (to be implemented by subclasses)
public abstract double calculateArea();
// Concrete method
public void printArea() {
System.out.println("Area: " + calculateArea());
}
}
// Concrete subclass 1
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
// Concrete subclass 2
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double calculateArea() {
return width * height;
}
}
public class AbstractClassDemo {
public static void main(String[] args) {
// Create instances of concrete subclasses
Circle circle = new Circle(5.0);
Rectangle rectangle = new Rectangle(4.0, 6.0);
// Use abstract class methods
circle.printArea();
rectangle.printArea();
}
}

Output :
Experiment no :14
Nested class
Code : class OuterClass {
// Static nested class
static class StaticNestedClass {
void display() {
System.out.println("Static Nested Class");} }
// Inner (non-static) class
class InnerClass {
void display() {
System.out.println("Inner (Non-Static) Class"); } }}
public class NestedClassDemo {
public static void main(String[] args) {
// Accessing the static nested class
OuterClass.StaticNestedClass staticNestedObj = new
OuterClass.StaticNestedClass();
staticNestedObj.display();
// Accessing the inner (non-static) class
OuterClass outerObj = new OuterClass();
OuterClass.InnerClass innerObj = outerObj.new InnerClass();
innerObj.display(); }}

output:
Experiment no :15
Constructor chaining
Code : public class MyClass {
private int x;
private int y;
// Constructor with two parameters
public MyClass(int x, int y) {
this.x = x;
this.y = y; }
// Constructor with one parameter, chaining to the two-parameter constructor
public MyClass(int x) {
this(x, 0); // Calls the two-parameter constructor }
// Default constructor, chaining to the one-parameter constructor
public MyClass() {
this(0); // Calls the one-parameter constructor }
public void display() {
System.out.println("x: " + x + ", y: " + y); }
public static void main(String[] args) {
MyClass obj1 = new MyClass(10, 20);
MyClass obj2 = new MyClass(5);
MyClass obj3 = new MyClass();
obj1.display();
obj2.display();
obj3.display(); }}

output :
Experiment no :16
Importing classes from user defined package and creating
packages using access protection
Code : Package:
package mypackage;
public class MyClass {
public void displayMessage(String message) {
System.out.println("Message from MyClass: " + message);
}
}
Main class:
import mypackage.MyClass; // Import the MyClass from the user-defined package
public class Main {
public static void main(String[] args) {
MyClass myObject = new MyClass();
myObject.displayMessage("Hello, from MainClass!");
}
}

Output :
Experiment no :17
Interfaces, nested interfaces and use of extending interfaces

Code : // Define a simple interface


interface MyInterface {
void myMethod();}
// Define a nested interface within the MyInterface
interface NestedInterface {
void nestedMethod();}
// Create a class that implements MyInterface
class MyClass implements MyInterface {
public void myMethod() {
System.out.println("Inside MyClass - myMethod");
}}
// Create another class that implements both MyInterface and NestedInterface
class AnotherClass implements MyInterface, NestedInterface {
public void myMethod() {
System.out.println("Inside AnotherClass - myMethod");
}
public void nestedMethod() {
System.out.println("Inside AnotherClass - nestedMethod");
}}
public class Main {
public static void main(String[] args) {
MyClass obj1 = new MyClass();
obj1.myMethod();
AnotherClass obj2 = new AnotherClass();
obj2.myMethod();
obj2.nestedMethod(); }}
output :
Experiment no :18
Exception Handling - using predefined exception
Code : import java.util.*;
public class ExceptionHandling {
public static void main(String [] args){
int a,b;
float c;
Scanner scan =new Scanner(System.in);
System.out.println("Enter value for a: ");
a=scan.nextInt();
System.out.println("Enter value for b: ");
b=scan.nextInt();
try{
c=a/b;
System.out.println("Value of c= "+c);}
catch(Exception e){
System.out.println("Exception encountered: "+ e);
System.out.println("Exception Handled");
}}}

Output :
Experiment no :19
Exception Handling - creating user defined exceptions
Code : // Define a custom exception by extending the Exception class
class CustomException extends Exception {
public CustomException(String message) {
super(message); }}
public class UserDefinedExceptionExample {
public static void main(String[] args) {
try {
// Simulate a situation that triggers the custom exception
int age = 15;
if (age < 18) {
// Throw the custom exception with a descriptive message
throw new CustomException("You must be at least 18 years old to access
this content."); }
// If the age check passes, continue with the program
System.out.println("Access granted. You are over 18 years old.");
} catch (CustomException e) {
// Catch and handle the custom exception
System.out.println("Custom Exception caught: " + e.getMessage()); } }}

Output :
Experiment no :20
Multithreading by extending Thread Class

Code : class ExtendingThread extends Thread


{ String s[]={"Welcome","to","Java","Programming","Language"};
public static void main(String args[]){
ExtendingThread t=new ExtendingThread("Extending Thread Class");}
public ExtendingThread (String n){
super(n);
start();}
public void run(){
String name=getName();
for(int i=0;i<s.length;i++){
try{
sleep(500);}
catch(Exception e)
{
}
System.out.println(name+":"+s[i]);
}

Output :
Experiment no :21
Multithreading by implementing Runnable Interface
Code : // Custom class implementing Runnable interface
class CustomRunnable implements Runnable {
private String message;
// Constructor to set the message for the thread
public CustomRunnable(String message) {
this.message = message }
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread " + Thread.currentThread().getId() + ": " + message + " -
Count " + i);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage() } }}}
public class Main {
public static void main(String[] args) {
// Create instances of the custom runnable class with different messages
CustomRunnable customRunnable1 = new CustomRunnable("Hello");
CustomRunnable customRunnable2 = new CustomRunnable("World");
CustomRunnable customRunnable3 = new CustomRunnable("Java");
// Create threads using the custom runnable objects
Thread thread1 = new Thread(customRunnable1);
Thread thread2 = new Thread(customRunnable2);
Thread thread3 = new Thread(customRunnable3);
// Start the threads
thread1.start();
thread2.start();
thread3.start()}}
output :
Experiment no :22
Thread life cycle
Code : class A1 extends Thread
{
public void run ()
{
System.out.println ("Thread A");
System.out.println ("i in Thread A ");
for (int i = 1; i <= 5; i++)
{
System.out.println ("i = " + i);
try
{
Thread.sleep (1000);
}
catch (InterruptedException e)
{
e.printStackTrace ();
}
}
System.out.println ("Thread A Completed.");
}
}
class B extends Thread
{
public void run ()
{
System.out.println ("Thread B");
System.out.println ("i in Thread B ");
for (int i = 1; i <= 5; i++)
{
System.out.println ("i = " + i);
}
System.out.println ("Thread B Completed.");
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
A1 threadA = new A1();
B threadB = new B();
// Start threadA
threadA.start();
// Wait for threadA to complete before starting threadB
threadA.join();
// Start threadB
threadB.start();
System.out.println("Main Thread End");
}
}

Output :
Experiment no :23
Applet life cycle
Code : import java.applet.Applet;
import java.awt.Graphics;
@SuppressWarnings("serial")
public class AppletLifeCycle extends Applet {
public void init() {
System.out.println("1. I am init()");}
public void start() {
System.out.println("2. I am start()"); }
public void paint(Graphics g) {
System.out.println("3. I am paint()");
}
public void stop() {
System.out.println("4. I am stop()");
}
public void destroy() {
System.out.println("5. I am destroy()"); }}

Output :
Experiment no :24
Applet for configuring Applets by passing parameters
Code : import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{n = getParameter("name");
a = getParameter("age");}
public void paint(Graphics g)
{g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);}}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/

Output :
Experiment no :25
Event Handling
Code : import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
b.addActionListener(this);//passing current instance
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true); }
public void actionPerformed(ActionEvent e){
tf.setText("Welcome"); }
public static void main(String args[]){
new AEvent(); } }

output :
Experiment no :26
Reading and writing from a particular file
Code : import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class ReadWriteFile {
public static void main(String[] args) {
// File path
String filePath = "sample.txt";
// Read from the file
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
System.out.println("Contents of the file:");
while ((line = reader.readLine()) != null) {
System.out.println(line) }
reader.close();
} catch (IOException e) {
e.printStackTrack }
// Write to the file
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true)); //
Append mode
writer.newLine(); // Move to the next line
writer.write("This is a new line of text.");
writer.close();
System.out.println("Data has been written to the file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Output :
Experiment no :27
Database connectivity for various DDL and DML operations
Code : 1.DDL
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
class DDLExample {
public static void main(String[] args) {
try {
// Connect to the database
Connection connection = DriverManager.getConnection("jdbc:your-database-url",
"your-username", "your-password");
// Create a table (DDL)
createTable(connection);
// Close the connection
connection.close();
} catch (SQLException e) {
e.printStackTrace(); } }
private static void createTable(Connection connection) throws SQLException {
Statement statement = connection.createStatement();
String createTableSQL = "CREATE TABLE IF NOT EXISTS mytable (id INT
PRIMARY KEY, name VARCHAR(255))";
statement.execute(createTableSQL);
statement.close();}}

output :
2.DML
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
class SimpleDMLExample {
public static void main(String[] args) {
try {
// Connect to the database
Connection connection = DriverManager.getConnection("jdbc:your-database-url",
"your-username", "your-password");
// Insert data (DML)
insertData(connection, "John", 30);
// Close the connection
connection.close();
} catch (SQLException e) {
e.printStackTrace() }}
private static void insertData(Connection connection, String name, int age) throws
SQLException {
String insertSQL = "INSERT INTO mytable (name, age) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(insertSQL);
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
preparedStatement.executeUpdate();
preparedStatement.close() ; }}

output :
Experiment no :28
String class and its methods
Code : 1.Concat
Code:
public class Main {
public static void main(String[] args) {
String firstName = "CHA";
String lastName = "HAT";
System.out.println(firstName.concat(lastName));
}
}

Output :

2. Equals
Code:
public class Main {
public static void main(String[] args) {
String myStr1 = "Hello";
String myStr2 = "Hello";
String myStr3 = "Another String";
System.out.println(myStr1.equals(myStr2));
System.out.println(myStr1.equals(myStr3)); }}

Output :
3. Length
Code:
public class Main {
public static void main(String[] args) {
String txt = "DEFGHPQRWXYZ";
System.out.println(txt.length()); }}

Output :

4. ToLowerCase
Code:
public class Main {
public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());}}

Output :

5. Replace
Code:
public class Main {
public static void main(String[] args) {
String myStr = "Hello";
System.out.println(myStr.replace('l', 'p')); }}

Output :
Experiment no :29
StringBuffer class and its methods
Code : 1. append() method
import java.io.*;
class A {
public static void main(String args[])
{StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java"); // now original string is changed
System.out.println(sb); }}

Output :

2. insert() method
import java.io.*;
class A {
public static void main(String args[])
{ StringBuffer sb = new StringBuffer("Hello ");
sb.insert(1, "Java");
// Now original string is changed
System.out.println(sb); }}

Output :

3. replace() method
import java.io.*;
class A {
public static void main(String args[])
{StringBuffer sb = new StringBuffer("Hello");
sb.replace(1, 3, "Java");
System.out.println(sb); }}
Output :

4. delete() method
import java.io.*;
class A {
public static void main(String args[])
{ StringBuffer sb = new StringBuffer("Hello");
sb.delete(1, 3);
System.out.println(sb); }}

Output :

5. reverse() method
import java.io.* ;
class A {
public static void main(String args[])
{ StringBuffer sb = new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);}}

Output :

You might also like