0% found this document useful (0 votes)
4 views61 pages

AI Java Lab Programs

Uploaded by

rgaru748
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views61 pages

AI Java Lab Programs

Uploaded by

rgaru748
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

LAB RECORD EXPERIMENTS

1. Write a java program to print Hello World.?


Program:
public class Main {
public static void main(String[] args) {
System.out.println("Hello World"); // Printing message to the console
}
}

1
output for 1st experiment:
Hello World

2
2. Write a java program to use various Data types.?
Program:
public class DataTypes {
public static void main(String[] args) {
// Primitive data types
byte b = 100; // 1 byte
short s = 30000; // 2 bytes
int i = 100000; // 4 bytes
long l = 15000000000L; // 8 bytes (use 'L' at the end for long values)

float f = 5.75f; // 4 bytes (use 'f' at the end for float values)
double d = 19.99; // 8 bytes

char c = 'A'; // 2 bytes (single character inside single quotes)


boolean bool = true; // 1 bit (true/false)

// Printing all data types


System.out.println("Byte value: " + b);
System.out.println("Short value: " + s);
System.out.println("Int value: " + i);
System.out.println("Long value: " + l);
System.out.println("Float value: " + f);
System.out.println("Double value: " + d);
System.out.println("Char value: " + c);
System.out.println("Boolean value: " + bool);
}
}

3
output for 2nd experiment:
Byte value: 100
Short value: 30000
Int value: 100000
Long value: 15000000000
Float value: 5.75
Double value: 19.99
Char value: A
Boolean value: true

4
3. Write a java program on Operators.?
Program:
public class OperatorsDemo {
public static void main(String[] args) {
int a = 10, b = 5;

// 1. Arithmetic Operators
System.out.println("Arithmetic Operators:");
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));

// 2. Relational Operators
System.out.println("\nRelational Operators:");
System.out.println("a > b = " + (a > b));
System.out.println("a < b = " + (a < b));
System.out.println("a == b = " + (a == b));
System.out.println("a != b = " + (a != b));

// 3. Logical Operators
System.out.println("\nLogical Operators:");
boolean x = true, y = false;
System.out.println("x && y = " + (x && y)); // AND
System.out.println("x || y = " + (x || y)); // OR
System.out.println("!x = " + (!x)); // NOT

// 4. Assignment Operators
System.out.println("\nAssignment Operators:");

5
int c = 10;
c += 5; // c = c + 5
System.out.println("c += 5: " + c);
c *= 2; // c = c * 2
System.out.println("c *= 2: " + c);

// 5. Unary Operators
System.out.println("\nUnary Operators:");
int d = 5;
System.out.println("d = " + d);
System.out.println("++d = " + (++d)); // pre-increment
System.out.println("d++ = " + (d++)); // post-increment
System.out.println("After d++ value: " + d);
System.out.println("--d = " + (--d)); // pre-decrement
}
}

6
output for 3rd experiment:
Arithmetic Operators:
a + b = 15
a-b=5
a * b = 50
a/b=2
a%b=0

Relational Operators:
a > b = true
a < b = false
a == b = false
a != b = true

Logical Operators:
x && y = false
x || y = true
!x = false

Assignment Operators:
c += 5: 15
c *= 2: 30

Unary Operators:
d=5
++d = 6
d++ = 6
After d++ value: 7
--d = 6

7
4.Write a Java program to find the largest among three given numbers.?
Program:
public class LargestNumber {
public static void main(String[] args) {
int a = 25, b = 40, c = 30; // Three numbers

// Check which number is largest


if (a >= b && a >= c) {
System.out.println("Largest number is: " + a);
} else if (b >= a && b >= c) {
System.out.println("Largest number is: " + b);
} else {
System.out.println("Largest number is: " + c);
}
}
}

8
output for 4th experiment:
Largest number is: 40

9
5.Write a Java program to find factorial of a given number.?
Program:
public class FactorialNum {
public static void main(String[] args) {
int num = 5; // number to find factorial
long fact = 1; // factorial result (use long for large values)

// Loop from 1 to num


for (int i = 1; i <= num; i++) {
fact = fact * i; // multiply each value
}
System.out.println("Factorial of " + num + " is: " + fact);
}
}

10
output for 5th experiment:
Factorial of 5 is: 120

11
6.Write a java program to display Fibonacci series.?
Program:
public class FibonacciDemo {
public static void main(String[] args) {
int n = 10; // number of terms to display
int first = 0, second = 1;

System.out.println("Fibonacci Series up to " + n + " terms:");

for (int i = 1; i <= n; i++) {


System.out.print(first + " "); // print current term

// calculate next term


int next = first + second;
first = second;
second = next;
}
}
}

12
output for 6th experiment:
Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

13
7.Write a java program to find out the given number is palindrome or not.?
Program:
public class PalindromeDemo {
public static void main(String[] args) {
int num = 121; // number to check
int original = num; // store original number
int reversed = 0;

// Reverse the number


while (num != 0) {
int digit = num % 10; // get last digit
reversed = reversed * 10 + digit; // add digit to reversed
num = num / 10; // remove last digit
}

// Check palindrome
if (original == reversed) {
System.out.println(original + " is a Palindrome number.");
} else {
System.out.println(original + " is NOT a Palindrome number.");
}
}
}

14
output for 7th experiment:
121 a Palindrome number.

15
8.Write a java program on single and Multi-dimensional array.?
Program:
public class Array1 {
public static void main(String[] args) {
// ---------------- Single Dimensional Array ----------------
int[] numbers = {10, 20, 30, 40, 50}; // array declaration & initialization

System.out.println("Single Dimensional Array Elements:");


for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
// ---------------- Multi-Dimensional Array ----------------
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}; // 3x3 matrix

System.out.println("\nMulti-Dimensional Array Elements:");


for (int i = 0; i < matrix.length; i++) { // row
for (int j = 0; j < matrix[i].length; j++) { // column
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // new line for each row
}
}
}

16
output for 8th experiment:
Single Dimensional Array Elements:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

Multi-Dimensional Array Elements:


123
456
789

17
9.Write a Java program to find Sum of two matrices.?
Program:
public class MatrixAddition {
public static void main(String[] args) {
// First matrix
int[][] A = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Second matrix
int[][] B = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};

// Result matrix to store sum


int[][] sum = new int[3][3];

// Adding two matrices


for (int i = 0; i < 3; i++) { // row
for (int j = 0; j < 3; j++) { // column
sum[i][j] = A[i][j] + B[i][j];
}
}

// Printing result
System.out.println("Sum of two matrices:");

18
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
}
}

19
output for 9th experiment:
Sum of two matrices:
10 10 10
10 10 10
10 0 10

20
10.Write a Java program to demo String Class Methods.?
Program:
public class StringMethods {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = " World";
String str3 = "hello";

// 1. length()
System.out.println("Length of str1: " + str1.length());

// 2. concat()
System.out.println("Concatenation: " + str1.concat(str2));

// 3. equals()
System.out.println("str1 equals str3: " + str1.equals(str3));

// 4. equalsIgnoreCase()
System.out.println("str1 equalsIgnoreCase str3: " + str1.equalsIgnoreCase(str3));

// 5. toUpperCase()
System.out.println("Uppercase: " + str1.toUpperCase());

// 6. toLowerCase()
System.out.println("Lowercase: " + str1.toLowerCase());

// 7. charAt()
System.out.println("Character at index 1 in str1: " + str1.charAt(1));

// 8. substring()

21
System.out.println("Substring (1 to 4): " + str1.substring(1, 4));

// 9. replace()
System.out.println("Replace 'l' with 'p': " + str1.replace('l', 'p'));

// 10. trim()
String str4 = " Java Programming ";
System.out.println("Before trim: '" + str4 + "'");
System.out.println("After trim: '" + str4.trim() + "'");
}
}

22
output for 10th experiment:
Length of str1: 5
Concatenation: Hello World
str1 equals str3: false
str1 equalsIgnoreCase str3: true
Uppercase: HELLO
Lowercase: hello
Character at index 1 in str1: e
Substring (1 to 4): ell
Replace 'l' with 'p': Heppo
Before trim: ' Java Programming '
After trim: 'Java Programming'

23
11.Write a java program on interface.?
Program:
interface Animal {
void sound(); // abstract method
void eat(); // abstract method
}

// Class implementing the interface


class Dog implements Animal {
// Provide implementation for interface methods
public void sound() {
System.out.println("Dog barks");
}

public void eat() {


System.out.println("Dog eats bones");
}
}

public class InterfaceDemo {


public static void main(String[] args) {
Dog dog = new Dog(); // creating object of Dog class
dog.sound(); // calling sound method
dog.eat(); // calling eat method
}
}

24
output for 11th experiment:
Dog barks
Dog eats bones

25
12.Write java programs on various types of Inheritance.?
Program:
// Single Inheritance Example
class Parent {
void parentMethod() {
System.out.println("This is parent class method");
}
}

class Child extends Parent {


void childMethod() {
System.out.println("This is child class method");
}
}

public class SingleInheritance1 {


public static void main(String[] args) {
Child obj = new Child();
obj.parentMethod(); // inherited from Parent
obj.childMethod(); // own method
}
}

26
output for 12.1th experiment:
This is parent class method
This is child class method

27
Program:
// Multilevel Inheritance Example
class GrandParent {
void grandParentMethod() {
System.out.println("This is grandparent class method");
}
}

class Parent2 extends GrandParent {


void parentMethod() {
System.out.println("This is parent class method");
}
}

class Child2 extends Parent2 {


void childMethod() {
System.out.println("This is child class method");
}
}

public class MultilevelInheritance2 {


public static void main(String[] args) {
Child2 obj = new Child2();
obj.grandParentMethod();
obj.parentMethod();
obj.childMethod();
}
}

28
output for 12.2th experiment:
This is grandparent class method
This is parent class method
This is child class method

29
Program:
// Hierarchical Inheritance Example
class Parent3 {
void parentMethod() {
System.out.println("This is parent class method");
}
}

class ChildA extends Parent3 {


void childAMethod() {
System.out.println("This is child A method");
}
}

class ChildB extends Parent3 {


void childBMethod() {
System.out.println("This is child B method");
}
}

public class HierarchicalInheritance3 {


public static void main(String[] args) {
ChildA objA = new ChildA();
objA.parentMethod();
objA.childAMethod();

ChildB objB = new ChildB();


objB.parentMethod();
objB.childBMethod();
}

30
}
output for 12.3th experiment:
This is parent class method
This is child A method
This is parent class method
This is child B method

31
Program:
// Multiple Inheritance Example using Interface
interface Interface1 {
void method1();
}

interface Interface2 {
void method2();
}

class DemoClass implements Interface1, Interface2 {


public void method1() {
System.out.println("Method from Interface1");
}

public void method2() {


System.out.println("Method from Interface2");
}
}

public class MultipleInheritance4 {


public static void main(String[] args) {
DemoClass obj = new DemoClass();
obj.method1();
obj.method2();
}
}

32
output for 12.4th experiment:
Method from Interface1
Method from Interface2

33
Program: hybrid inheritance
// Parent class
class Animal {
void eat() {
System.out.println("Animal eats food");
}
}

// Child class 1 (single inheritance)


class Mammal extends Animal {
void walk() {
System.out.println("Mammal walks");
}
}

// Interface
interface Pet {
void play();
}

// Child class 2 implementing interface (multiple inheritance part)


class Dog extends Mammal implements Pet {
public void play() {
System.out.println("Dog plays with owner");
}
}

public class HybridInheritance5 {


public static void main(String[] args) {

34
Dog dog = new Dog();
dog.eat(); // inherited from Animal
dog.walk(); // inherited from Mammal
dog.play(); // implemented from Pet interface
}
}

35
output for 12.5th experiment:
Animal eats food
Mammal walks
Dog plays with owner

36
13.Write a Java program to demo overloading of methods.?
Program:
class Calculator {

// Method to add two integers


int add(int a, int b) {
return a + b;
}

// Method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Method to add two double values


double add(double a, double b) {
return a + b;
}
}

public class MethodOverloading1 {


public static void main(String[] args) {
Calculator calc = new Calculator();

System.out.println("Sum of 10 + 20: " + calc.add(10, 20)); // calls int, int


method
System.out.println("Sum of 5 + 10 + 15: " + calc.add(5, 10, 15)); // calls int, int,
int method
System.out.println("Sum of 5.5 + 4.5: " + calc.add(5.5, 4.5)); // calls double,
double method

37
}
}

38
output for 13th experiment:
Sum of 10 + 20: 30
Sum of 5 + 10 + 15: 30
Sum of 5.5 + 4.5: 10.0

39
14.Write a Java program to demo ‘super’ keyword.?
Program:
// Parent class
class Parent {
int num = 100;

void display() {
System.out.println("Parent class display method");
}
}

// Child class
class Child extends Parent {
int num = 200;

void display() {
System.out.println("Child class display method");
}

void show() {
// Access parent class variable using super
System.out.println("Value of parent num: " + super.num);

// Access parent class method using super


super.display();

// Access child class variable and method


System.out.println("Value of child num: " + num);
display();

40
}
}

public class SuperDemo {


public static void main(String[] args) {
Child obj = new Child();
obj.show();
}
}

41
output for 14th experiment:
Value of parent num: 100
Parent class display method
Value of child num: 200
Child class display method

42
15.Write a Java program to demo ‘final’ keyword.?
Program:
class FinalDemo {

// Final variable (constant)


final int MAX_VALUE = 100;

// Final method
final void display() {
System.out.println("This is a final method.");
}
}

// Child class
class ChildFinal extends FinalDemo {
// Uncommenting below lines will cause compilation errors
// because final variable and final method cannot be changed/overridden

// void display() {
// System.out.println("Trying to override final method");
// }

// void changeMaxValue() {
// MAX_VALUE = 200; // Error: cannot assign a value to final variable
// }

void show() {
System.out.println("Final variable MAX_VALUE: " + MAX_VALUE);
}

43
}

public class FinalKeyword {


public static void main(String[] args) {
ChildFinal obj = new ChildFinal();
obj.show();
obj.display();
}
}

44
output for 15th experiment:
Final variable MAX_VALUE: 100
This is a final method.

45
16.Write a Java program to demo method overriding.?
Program:
class Parent {
void display() {
System.out.println("This is the parent class display method.");
}
}

// Child class
class Child extends Parent {
// Overriding the display method of Parent
@Override
void display() {
System.out.println("This is the child class display method.");
}
}

public class MethodOverriding {


public static void main(String[] args) {
Parent parent = new Parent();
Child child = new Child();

System.out.println("Calling parent class method:");


parent.display(); // calls parent method

System.out.println("Calling child class method:");


child.display(); // calls overridden child method
}
}

46
output for 16th experiment:
Calling parent class method:
This is the parent class display method.
Calling child class method:
This is the child class display method.

47
17.Write java programs on Packages.?
Program:
// Declare package
package mypackage;

// Class inside the package


public class Calculator {

// Method to add two numbers


public int add(int a, int b) {
return a + b;
}

// Method to multiply two numbers


public int multiply(int a, int b) {
return a * b;
}
}
Program:
// Import the package class
import mypackage.Calculator;

public class PackageDemo {


public static void main(String[] args) {
// Create object of Calculator class from mypackage
Calculator calc = new Calculator();

// Using package methods


int sum = calc.add(10, 20);

48
int product = calc.multiply(5, 4);

System.out.println("Sum of 10 and 20: " + sum);


System.out.println("Product of 5 and 4: " + product);
}
}

49
output for 17th experiment:
Sum of 10 and 20: 30
Product of 5 and 4: 20

50
18.Write a java program on Multi-Threading.?
Program:
// Thread 1: prints numbers 1 to 5
class NumberThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("NumberThread: " + i);
}
}
}

// Thread 2: prints letters A to E


class LetterThread extends Thread {
public void run() {
for (char c = 'A'; c <= 'E'; c++) {
System.out.println("LetterThread: " + c);
}
}
}

public class SampleMultithreading {


public static void main(String[] args) {
NumberThread t1 = new NumberThread();
LetterThread t2 = new LetterThread();

t1.start(); // start first thread


t2.start(); // start second thread
}
}

51
output for 18th experiment:
NumberThread: 1
LetterThread: A
NumberThread: 2
LetterThread: B
NumberThread: 3
LetterThread: C
NumberThread: 4
LetterThread: D
NumberThread: 5
LetterThread: E

52
19.Write java programs on various types Exceptions.?
Program:
import java.io.*;
public class AllExceptions {
public static void main(String[] args) {

// 1. ArithmeticException
try {
int a = 10 / 0; // division by zero
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
}

// 2. ArrayIndexOutOfBoundsException
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " +
e.getMessage());
}

// 3. NullPointerException
try {
String str = null;
System.out.println(str.length()); // null object
} catch (NullPointerException e) {
System.out.println("NullPointerException caught: " + e.getMessage());
}

53
// 4. NumberFormatException
try {
String numStr = "abc";
int num = Integer.parseInt(numStr); // invalid number
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: " + e.getMessage());
}

// 5. FileNotFoundException
try {
FileReader file = new FileReader("nonexistent.txt");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException caught: " + e.getMessage());
}

// 6. Finally block demo


try {
int x = 10 / 2;
System.out.println("Division Result: " + x);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught");
} finally {
System.out.println("Finally block executed for division example");
}
}
}

54
output for 19th experiment:
ArithmeticException caught: / by zero
ArrayIndexOutOfBoundsException caught: 5
NullPointerException caught: null
NumberFormatException caught: For input string: "abc"
FileNotFoundException caught: nonexistent.txt (No such file or directory)
Division Result: 5
Finally block executed for division example

55
20.Write a Java Program to write and read from a file.?
Program:
import java.io.*;
public class File {
public static void main(String[] args) {
String filename = "example.txt"; // file name
String content = "Hello, this is a sample file content!";

// 1. Writing to a file
try {
FileWriter writer = new FileWriter(filename);
writer.write(content);
writer.close(); // close the file
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("Error writing file: " + e.getMessage());
}

// 2. Reading from the file


try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);

String line;
System.out.println("File content:");
while ((line = br.readLine()) != null) {
System.out.println(line); // print each line
}

56
br.close(); // close the file
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}

57
output for 20th experiment:
File written successfully.
File content:
Hello, this is a sample file content!

58
21.Write an Applet program to draw a Rectangle.?
Program:
import java.applet.Applet;
import java.awt.*;

// <applet code="RectangleApplet" width=400 height=300></applet>


public class RectangleApplet extends Applet {

public void paint(Graphics g) {


// Set color for the rectangle
g.setColor(Color.BLUE);

// Draw a rectangle: x=50, y=50, width=200, height=100


g.drawRect(50, 50, 200, 100);

// Fill the rectangle with color


g.setColor(Color.CYAN);
g.fillRect(50, 50, 200, 100);

// Draw some text inside the rectangle


g.setColor(Color.RED);
g.drawString("This is a rectangle", 80, 100);
}
}

Prepare html document:


<html>
<body>
<applet code="RectangleApplet" width=400 height=300></applet>

59
<\body>
<\html>

60
output for 21th experiment:
+----------------------------+
| |
| This is a rectangle |
| |
+----------------------------+

61

You might also like