0% found this document useful (0 votes)
23 views

Java 13

Java notes

Uploaded by

joykundu2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Java 13

Java notes

Uploaded by

joykundu2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

1. WRITE A JAVA PROGRAM TO PRINT THE HELLO WORLD.

class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
OUTPUT:
Hello World

2. WRITE A JAVA PROGRAM TO FIND THE LARGEST AND SMALLEST AMONG THREE
NUMBERS.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter the third number: ");
int num3 = scanner.nextInt();
int largest = num1;
if (num2 > largest) {
largest = num2;
}
if (num3 > largest) {
largest = num3;
}
int smallest = num1;
if (num2 < smallest) {
smallest = num2;
}
if (num3 < smallest) {
smallest = num3;
}
System.out.println("The largest number is: " + largest);
System.out.println("The smallest number is: " + smallest);
}
}
OUTPUT:
Enter the first number: 67 The largest number is: 89
Enter the second number: 89 The smallest number is: 0
Enter the third number:0
3.WRITE A JAVA PROGRAM TO CHECK WHETHE THE GIVEN YEAR IS LEAP YEAR OR NOT.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();
if (isLeapYear(year)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
public static boolean isLeapYear(int year) {
if (year % 4 == 0) {
if (year % 100 == 0) {
return year % 400 == 0;
} else {
return true;
}
}
return false;
}
}
OUTPUT:
Enter a year: 2000 Enter a year: 1900
2000 is a leap year. 1900 is not a leap year.

4. WRITE A JAVA PROGRAM IN JAVA TO CHECK WHETHER THE GIVEN NUMBER IS PRIME
OR NOT.
import java.util.Scanner;
public class PrimeNumberChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (isPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
public static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
OUTPUT:
Enter a number: 7 Enter a number: 10
7 is a prime number. 10 is not a prime number.

5. WRITE A JAVA PROGRAM TO CHECK WHETHER THE GIVEN NUMBER IS AN ARMSTRONG


NUMBER OR NOT.
import java.util.Scanner;
public class ArmstrongNumberChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}
public static boolean isArmstrong(int number) {
int originalNumber = number;
int result = 0;
int digits = String.valueOf(number).length();
while (number != 0) {
int digit = number % 10;
result += Math.pow(digit, digits);
number /= 10;
}
return result == originalNumber;
}
}
OUTPUT:
Enter a number: 153
153 is an Armstrong number.

6. WRITE A JAVA PROGRAM TO DISPLAY THE FOLLOWING PATTERN.


*
**
***
****
*****
****
***
**
*
public class Main {
public static void main(String[] args) {
int rows = 5;
for (int i = 1; i <= rows; i++) {
for (int j = rows; j > i; j--) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
for (int i = rows - 1; i >= 1; i--) {
for (int j = rows; j > i; j--) {
System.out.print(" ");
}
for (int k = 1; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}
OUTPUT:
*
**
***
****
*****
****
***
**
*

7. WRITE A JAVA PROGRAM TO SORT THE ARRAY ELEMENTS EITHER IN ASCENDING OR IN


DESCENDING ORDER (ARRAY ELEMENTS:4,1,7,3,2,0).

import java.util.Arrays;
import java.util.Scanner;
public class ArraySort {
public static void main(String[] args) {
int[] array = {4, 1, 7, 3, 2, 0};
Scanner scanner = new Scanner(System.in);
System.out.println("Original Array: " + Arrays.toString(array));
System.out.print("Enter '1' for Ascending order or '2' for Descending order: ");
int choice = scanner.nextInt();
if (choice == 1) {
sortAscending(array);
System.out.println("Array in Ascending Order: " + Arrays.toString(array));
} else if (choice == 2) {
sortDescending(array);
System.out.println("Array in Descending Order: " + Arrays.toString(array));
} else {
System.out.println("Invalid choice. Please enter 1 or 2.");
}
}
public static void sortAscending(int[] array) {
Arrays.sort(array);
}
public static void sortDescending(int[] array) {
Arrays.sort(array);
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = temp;
}
}
}
OUTPUT:
Original Array: [4, 1, 7, 3, 2, 0]
Enter '1' for Ascending order or '2' for Descending order: 1
Array in Ascending Order: [0, 1, 2, 3, 4, 7]

Original Array: [4, 1, 7, 3, 2, 0]


Enter '1' for Ascending order or '2' for Descending order: 2
Array in Descending Order: [7, 4, 3, 2, 1, 0]

8. WRITE A JAVA PROGRAM TO GENERATE THE FIBONACCI SERIES UP TO NTH


TERM USING RECURSION. [N IS THE USER INPUT]
import java.util.*;
public class File8 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number for FibonacciSeries :”);
int n = scanner.nextInt();
System.out.println("Fibonacci series up to " + n + " terms:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}}}

OUTPUT:
Enter the number for Fibonacci series: 10 Fibonacci
series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

9. WRITE A JAVA PROGRAM TO DEFINE A CLASS AND DEMONSTRATE HOW TO ACCESS


IT’S DATA MEMBERS AND METHODS.
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
void displayInfo() {
System.out.println("Student Name: " + name);
System.out.println("Student Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Student student1 = new Student("Kuheli Manna", 19);
System.out.println("Accessing data members directly:");
System.out.println("Name: " + student1.name);
System.out.println("Age: " + student1.age);
System.out.println("\nAccessing data members using a method:");
student1.displayInfo();
}}
OUTPUT:
Accessing data members directly:
Name: Kuheli Manna
Age: 19
Accessing data members using a method:
Student Name: Kuheli Manna
Student Age: 19

10. WRITE A JAVA PROGRAM TO EXPLAIN THE FUNCTIONALITY OF COMMAND LINE


ARGUMENT.
public class Cline {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No command line arguments provided.");
return;
}
System.out.println("Number of command line arguments: " + args.length);
System.out.println("Command line arguments:");
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
int sum = 0;
for (String arg : args) {
try {
sum += Integer.parseInt(arg);
} catch (NumberFormatException e) {
System.out.println("Invalid number format for argument: " + arg);
}
}
System.out.println("Sum of integer arguments: " + sum);
}
}
OUTPUT:
java Cline 5 10 15
Number of command line arguments: 3
Command line arguments:
Argument 1: 5
Argument 2: 10
Argument 3: 15
Sum of integer arguments: 30

11. WRITE A JAVA PROGRAM TO TAKE THE INPUT FROM THE USER USING SCANNER CLASS.
import java.util.*;
public class File11 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.print("Enter your favorite number: ");
double favoriteNumber = scanner.nextDouble();
System.out.println("\nUser Details:");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Favorite Number: " + favoriteNumber);
}}

OUTPUT:
Enter your name: Kuheli
Enter your age: 19
Enter your favorite number: 4

User Details:
Name: Kuheli
Age: 19
Favorite Number: 4.0

12. WRITE A JAVA PROGRAM TO IMPLEMENT AUTOBOXING AND UNBOXING(BOTH


IMPLICIT AND EXPLICIT).
public class AutoBoxingUnboxing {
public static void main(String[] args) {
int num = 10;
Integer obj = num;
System.out.println("AutoBoxing (Implicit): Integer value: " + obj);
int value = obj;
System.out.println("AutoUnboxing (Implicit): int value: " + value);
Double d = Double.valueOf(25.5);
System.out.println("AutoBoxing (Explicit): Double value: " + d);
double doubleValue = d.doubleValue();
System.out.println("AutoUnboxing (Explicit): double value: " + doubleValue);
java.util.ArrayList<Integer> list = new java.util.ArrayList<>();
list.add(15);
list.add(25);
System.out.println("ArrayList values (after auto-boxing and auto-unboxing): ");

for (Integer number : list) {


System.out.println("Value: " + number);
}
}
}
OUTPUT:
AutoBoxing (Implicit): Integer value: 10
AutoUnboxing (Implicit): int value: 10
AutoBoxing (Explicit): Double value: 25.5
AutoUnboxing (Explicit): double value: 25.5
ArrayList values (after auto-boxing and auto-unboxing):
Value: 15
Value: 25

13. WRITE A JAVA PROGRAM TO DEMONSTRATE THE USE OF STATIC KEYWORD.


public class StaticKeywordDemo {
static int count = 0;
static void incrementCount() {
count++;
System.out.println("Count: " + count);
}
void displayMessage() {
System.out.println("This is an instance method.");
}
public static void main(String[] args) {
StaticKeywordDemo.incrementCount();
StaticKeywordDemo.incrementCount();
System.out.println("Accessing static variable: " + StaticKeywordDemo.count);
StaticKeywordDemo obj = new StaticKeywordDemo();
obj.displayMessage();
}
}
OUTPUT:
Count: 1
Count: 2
Accessing static variable: 2
This is an instance method.

14. WRITE A JAVA PROGRAM TO IMPLEMENT THE USE OF THIS KEYWORD.


public class ThisKeyword {
int x;
ThisKeyword(int x) {
this.x = x;
}
void display() {
System.out.println("Value of x: " + this.x);
}
void setX(int x) {
this.x = x;
}
public static void main(String[] args) {
ThisKeyword obj = new ThisKeyword(10);
obj.display();
obj.setX(20);
obj.display();
}
}
OUTPUT:
Value of x: 10
Value of x: 20

15. WRITE JAVA PROGRAM TO ILLUSTRATE THE USE OF CONSTRUCTOR(DEFAULT AND


PARAMETERIZED CONSTRUCTOR).
public class ConstructorDemo {
String name;
int age;
ConstructorDemo() {
name = "KUHELI";
age = 19;
}
ConstructorDemo(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
ConstructorDemo obj1 = new ConstructorDemo();
obj1.display();
ConstructorDemo obj2 = new ConstructorDemo("John", 25);
obj2.display();
}
}
OUTPUT:
Name: KUHELI
Age: 19
Name: John
Age: 25

16. WRITE A JAVA PROGRAM TO IMPLEMENT THE CONCEPT OF METHOD OVERLOADING.


public class funOL{
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
funOL calculator = new funOL();
System.out.println("Sum : " + calculator.add(10, 10));
System.out.println("Sum2: " + calculator.add(10, 10, 15));
System.out.println("Sum of 5.5 and 10.5 (double): " + calculator.add(5.5, 10.5));
}}
OUTPUT:
Sum : 20
Sum2: 35
Sum of 5.5 and 10.5 (double): 16.0

17. WRITE A JAVA PROGRAM TO IMPLEMENTTYPES OF CONSTRUCTOR (DEFAULT AND


PARAMETERIZED CONSTRUCTOR).
public class File17 {
String name; int age;
public File17() {
age = 21;
name=”KuheliMnna”;
System.out.println("Default constructor called");
}
public File17(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Parameterized constructor called");
}
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
File17 person1 = new File17();
person1.displayDetails();
System.out.println();
File17 person2 = new File17("John", 20);
person2.displayDetails();
}}
OUTPUT:
Default constructor called
Name: KuhekiManna
Age: 21

Parameterized constructor called


Name: John
Age: 20

18. WRITE A JAVA PROGRAM TO IMPLEMENT COPY CONSTRUCTOR.


public class CopyConstructorDemo {
String name;
int age;
CopyConstructorDemo(String name, int age) {
this.name = name;
this.age = age;
}
CopyConstructorDemo(CopyConstructorDemo other) {
this.name = other.name;
this.age = other.age;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
CopyConstructorDemo obj1 = new CopyConstructorDemo("KUHELI", 19);
obj1.display();
CopyConstructorDemo obj2 = new CopyConstructorDemo(obj1);
obj2.display();
}
}
OUTPUT:
Name: KUHELI
Age: 19
Name: KUHELI
Age: 19
19. WRITE A JAVA PROGRAM TO DEMONSTRATE CONSTRUCTOR OVERLOADING.
public class File19 {
String name;
int age;
public File19() {
name = "KUHELI";
age = 0;
System.out.println("Default constructor called");
}
public File19(String name) {
this.name = name;
this.age = 0;
System.out.println("Constructor with one parameter called");
}
public File19(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Constructor with two parameters called");
}
public void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
File19 person1 = new File19();
person1.displayDetails();
System.out.println();
File19 person2 = new File19("JOHN");
person2.displayDetails();
System.out.println();
File19 person3 = new File19("ALICE", 20);
person3.displayDetails();
}}
OUTPUT:
Default constructor called
Name:KUHELI
Age: 0
Constructor with one parameter called
Name: JOHN
Age: 0
Constructor with two parameters called
Name: ALICE
Age: 20

20. WRITE A JAVA PROGRAM TO IMPLEMENTS


A.SINGLE INHERITANCE :
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class SingleInheritance {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}
OUTPUT:
Animal is eating
Dog is barking

B. MULTILEVEL INHERITANCE :
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
class Puppy extends Dog {
void play() {
System.out.println("Puppy is playing");
}
}
public class MultilevelInheritance {
public static void main(String[] args) {
Puppy puppy = new Puppy();
puppy.eat();
puppy.bark();
puppy.play();
}}
OUTPUT:
Animal is eating
Dog is barking
Puppy is playing

C.HIERARCHICAL INHERITANCE:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat is meowing");
}
}
public class HierarchicalInheritance {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();

Cat cat = new Cat();


cat.eat();
cat.meow();
}
}
OUTPUT:
Animal is eating
Dog is barking
Animal is eating
Cat is meowing

21. WRITE A JAVA PROGRAM TO IMPLEMENT METHOD OVERRIDING.


class Bank {
int getRateOfInterest() {
return 0;
}
}
class SBI extends Bank {
@Override
int getRateOfInterest() {
return 5;
}
}
class ICICI extends Bank {
@Override
int getRateOfInterest() {
return 6;
}
}
class AXIS extends Bank {
@Override
int getRateOfInterest() {
return 7;
}
}
class DisplayResult {
public static void main(String args[]) {
SBI s = new SBI();
ICICI i = new ICICI();
AXIS a = new AXIS();
System.out.println("Rate of Interest in SBI is " + s.getRateOfInterest() + "%");
System.out.println("Rate of Interest in ICICI is " + i.getRateOfInterest() + "%");
System.out.println("Rate of Interest in AXIS is " + a.getRateOfInterest() + "%");
}
}
OUTPUT:
Rate of Interest in SBI is 5%
Rate of Interest in ICICI is 6%
Rate of Interest in AXIS is 7%

22. WRITE A JAVA PROGRAM TO DEMONSTRATE ABSTRACT METHOD AND ABSTRACT


CLASS.
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("This animal is sleeping");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}
public class AbstractDemo {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
dog.sleep();
Cat cat = new Cat();
cat.sound();
cat.sleep();
}
}
OUTPUT:
Dog barks
This animal is sleeping
Cat meows
This animal is sleeping

23. WRITE A JAVA PROGRAM TO IMPLEMENT INTERFACE INHERITANCE.


interface Animal {
void sound();
}
interface Pet {
void play();
}
class Dog implements Animal, Pet {
public void sound() {
System.out.println("Dog barks");
}
public void play() {
System.out.println("Dog plays with a ball");
}
}
public class InterfaceInheritance {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
dog.play();
}
}
OUTPUT:
Dog barks
Dog plays with a ball

24. WRITE A JAVA PROGRAM TO IMPLEMENT MULTIPLE INHERITANCE USING INTERFACE.


interface Animal {
void sound();
}
interface Pet {
void play();
}
class Dog implements Animal, Pet {
public void sound() {
System.out.println("Dog barks");
}
public void play() {
System.out.println("Dog plays with a ball");
}
}
class Cat implements Animal, Pet {
public void sound() {
System.out.println("Cat meows");
}
public void play() {
System.out.println("Cat plays with yarn");
}
}
public class MultipleInheritanceUsingInterface {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
dog.play();
Cat cat = new Cat();
cat.sound();
cat.play();
}
}
OUTPUT:
Dog barks Cat meows
Dog plays with a ball Cat plays with yarn
25. WRITE A JAVA PROGRAM TO DEMONSTRATE SUPER KEYWORD.
class Vehicle {
int maxSpeed = 130;
}
class Car extends Vehicle {
int maxSpeed = 180;
void display()
{
System.out.println("Maximum Speed: "
+ super.maxSpeed);
}}
class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}}

OUTPUT:
Maximum Speed: 130

26. WRITE A JAVA PROGRAM TO DEMONSTRATE FINAL KEYWORD.


final class FinalClass {
final int finalVariable = 100;
final void display() {
System.out.println("This is a final method in a final class.");
}
}
class RegularClass {
final int number;
RegularClass(int num) {
this.number = num;
}
void showFinalParameter(final int finalParameter) {
System.out.println("The final parameter value is: " + finalParameter);
}
}
class FinalKeywordDemo {
public static void main(String[] args) {
FinalClass fc = new FinalClass();
fc.display();
RegularClass rc = new RegularClass(10);
System.out.println("The final variable value is: " + rc.number);
rc.showFinalParameter(30);
}}
OUTPUT:
This is a final method in a final class.
The final variable value is: 10
The final parameter value is: 30

27. WRITE A JAVA PROGRAAM TO CREATE A MUTABLE STRING USING STRINGBUFFER OR


STRINGBUILDER CLASS.
public class MutableString {
public static void main(String[] args) {
// Using StringBuilder
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
sb.insert(5, " Beautiful");
sb.reverse();
System.out.println("StringBuilder output: " + sb.toString());

// Using StringBuffer
StringBuffer sbf = new StringBuffer("Hello");
sbf.append(" World");
sbf.insert(5, " Beautiful");
sbf.reverse();
System.out.println("StringBuffer output: " + sbf.toString());
}
}
OUTPUT:
StringBuilder output: dlroW lufituaeH
StringBuffer output: dlroW lufituaeH

28. WRITE A JAVA PROGRAM TO DEMONSTRATE THE FOLLOWING METHODS: CHARAT(),


COMPARETO(), EQUALS(), EQUALSIGNORECASE(), INDEXOF(), LENGTH(), SUBSTRING(),
TOCHARARRAY(), TOLOWERCASE(), TOSTRING(), TOUPPERCASE(), TRIM(), VALUEOF(),
APPEND(), CAPACITY(), CHARAT(), DELETE(), DELETECHARAT(), ENSURECAPACITY(),
GETCHARS(), INDEXOF(), INSERT(), LENGTH(), SETCHARAT(), SETLENGTH(), SUBSTRING(),
TOSTRING().
public class StringMethodsDemo {
public static void main(String[] args) {
String str = " Hello World ";
System.out.println("charAt(1): " + str.charAt(1));
System.out.println("compareTo('Hello World'): " + str.compareTo("Hello World"));
System.out.println("equals('Hello World'): " + str.equals("Hello World"));
System.out.println("equalsIgnoreCase('hello world'): " + str.equalsIgnoreCase("hello
world"));
System.out.println("indexOf('o'): " + str.indexOf('o'));
System.out.println("length(): " + str.length());
System.out.println("substring(2, 5): " + str.substring(2, 5));
System.out.println("toCharArray(): " + java.util.Arrays.toString(str.toCharArray()));
System.out.println("toLowerCase(): " + str.toLowerCase());
System.out.println("toString(): " + str.toString());
System.out.println("toUpperCase(): " + str.toUpperCase());
System.out.println("trim(): " + str.trim());
System.out.println("valueOf(123): " + String.valueOf(123));
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println("append(): " + sb);
System.out.println("capacity(): " + sb.capacity());
System.out.println("charAt(1): " + sb.charAt(1));

sb.delete(0, 5);
System.out.println("delete(0, 5): " + sb);

sb.deleteCharAt(0);
System.out.println("deleteCharAt(0): " + sb);

sb.ensureCapacity(50);
System.out.println("ensureCapacity(50): " + sb.capacity());

char[] chars = new char[5];


sb.getChars(0, 5, chars, 0);
System.out.println("getChars(): " + java.util.Arrays.toString(chars));

sb.insert(0, "Goodbye ");


System.out.println("insert(0, 'Goodbye '): " + sb);

sb.setCharAt(0, 'H');
System.out.println("setCharAt(0, 'H'): " + sb);

sb.setLength(5);
System.out.println("setLength(5): " + sb);

System.out.println("substring(0, 3): " + sb.substring(0, 3));


System.out.println("toString(): " + sb.toString());
}
}
OUTPUT:
charAt(1): e
compareTo('Hello World'): 0
equals('Hello World'): false
equalsIgnoreCase('hello world'): true
indexOf('o'): 4
length(): 15
substring(2, 5): llo
toCharArray(): [ , H, e, l, l, o, , W, o, r, l, d, , ]
toLowerCase(): hello world
toString(): Hello World
toUpperCase(): HELLO WORLD
trim(): Hello World
valueOf(123): 123
append(): Hello World
capacity(): 34
charAt(1): e
delete(0, 5): World
deleteCharAt(0): orld
ensureCapacity(50): 50
getChars(): [o, r, l, d, ]
insert(0, 'Goodbye '): Goodbye orld
setCharAt(0, 'H'): Hoodbye orld
setLength(5): Hood
substring(0, 3): Hoo
toString(): Hood

29. WRITE A JAVA PROGRAM TO CREATE A PACKAGE AND ACCESS IT FROM ANOTHER
PACKAGE.
Step 1: Create the mypackage package
Create a directory named mypackage, and inside it, create a Java file named MyClass.java.
mypackage/MyClass.jav
a package mypackage;
public class MyClass {
public void displayMessage() {
System.out.println("Hello from MyClass in mypackage!");
}}
Step 2: Create the testpackage package
Create another directory named testpackage, and inside it, create a Java file named
TestClass.java. This file will import mypackage and use MyClass.
testpackage/TestClass.jav
a package testpackage;
import
mypackage.MyClass;
public class TestClass {
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.displayMessage();
}}
Step 3: Compile and Run the Program
1. Open a terminal or command prompt and navigate to the
directory containing mypackage and testpackage folders.
2. Compile MyClass.java and TestClass.java: javac
mypackage/MyClass.java javac -cp .
testpackage/TestClass.java 3. Run TestClass from
testpackage:
java -cp . testpackage.TestClass

OUTPUT:
Hello from MyClass in mypackage!
This demonstrates how to create and access a package from another package in Java.

30. WRITE A JAVA PROGRAM TO DEMONSTRATE THE USE OF TRY,CATCH AND FINALLY
BLOCKS.
public class TryCatchFinallyDemo {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("This is the 'finally' block, executed after try/catch.");
}
System.out.println("Program continues after try-catch-finally.");
}
}
OUTPUT:
Exception caught: java.lang.ArithmeticException: / by zero
This is the 'finally' block, executed after try/catch.
Program continues after try-catch-finally.

KUHELI MANNA
ROLL:123221103078

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy