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);
[Link]("int: " + myNum1);
[Link]("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() {
[Link] = 0;
[Link] = "Unknown";
[Link] = 0; }
// Constructor with ID and name
public Student(int id, String name) {
[Link] = id;
[Link] = name;
[Link] = 0; }
// Constructor with ID, name, and age
public Student(int id, String name, int age) {
[Link] = id;
[Link] = name;
[Link] = age; }
// Constructor with another Student object as an argument
public Student(Student otherStudent) {
[Link] = [Link];
[Link] = [Link];
[Link] = [Link]; }
// Method to display student information
public void displayInfo() {
[Link]("ID: " + id);
[Link]("Name: " + name);
[Link]("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
[Link]("Student 1:");
[Link]();
[Link]("\nStudent 2:");
[Link]();
[Link]("\nStudent 3:");
[Link]();
[Link]("\nStudent 4 (Copy of Student 3):");
[Link](); }}
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() {
[Link]("Constructor called.”); }
// Public method
public void publicMethod() {
[Link]("publicMethod() called.");}
// Private method
private void privateMethod() {
[Link]("privateMethod() called."); }
// Protected method
protected void protectedMethod() {
[Link]("protectedMethod() called.");}
// Package-private method
void packageMethod() {
[Link]("packageMethod() called."); }
// Static method
static void staticMethod() {
[Link]("staticMethod() called."); }
// Finalize method (deprecated in Java 9)
protected void finalize() {
[Link]("finalize() called.");}}
public class TestClass {
public static void main(String[] args) {
AccessDemo obj = new AccessDemo();
// Accessing fields and methods with different access control
[Link]("Public Variable: " + [Link]);
// Private variable is not accessible directly
// [Link]("Private Variable: " + [Link]);
[Link]("Protected Variable: " + [Link]);
[Link]("Package Variable: " + [Link]);
[Link]();
// Private method is not accessible directly
// [Link]();
[Link]();
[Link]();
[Link]("Static Variable: " + [Link]);
[Link]();
[Link]("Final Variable: " + [Link]);
// Call finalize() method (deprecated in Java 9, rarely used)
[Link]();
}
}
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 ([Link] == 0) {
[Link]("No command-line arguments provided.");
} else {
[Link]("Command-line arguments provided:");
// Iterate through the arguments and print each one
for (int i = 0; i < [Link]; i++) {
[Link]("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() {
[Link]("This is a private method in Animal class”); }
protected void protectedMethod() {
[Link]("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
[Link](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() {
[Link]("Meow!");
}
public void purr() {
[Link]("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
[Link](protectedField);
protectedMethod();
}}
class Lion extends Animal {
public void displayLion() {
// Access protected field and method from the base class
[Link](protectedField);
protectedMethod(); }}
public class InheritanceDemo {
public static void main(String[] args) {
// Single Inheritance
Dog dog = new Dog();
[Link]();
// Multiple Inheritance (via interfaces)
Cat cat = new Cat();
[Link]();
[Link]();
// Hierarchical Inheritance
Tiger tiger = new Tiger();
[Link]();
Lion lion = new Lion();
[Link]();
}}
Output :
Experiment no :12
Method overriding
Code : class Grandfather{
int age;String name;
public Grandfather(){ }
public Grandfather(int age,String name){
[Link]=name;
[Link]=age;
}public void Print(){
[Link]("Inside Grandfather class");
[Link]("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){
[Link]=name;
[Link]=age;
}public void Print(){
[Link]("Inside Father class");
[Link]("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");
[Link]();
}
}
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() {
[Link]("Area: " + calculateArea());
}
}
// Concrete subclass 1
class Circle extends Shape {
private double radius;
public Circle(double radius) {
[Link] = radius;
}
@Override
public double calculateArea() {
return [Link] * radius * radius;
}
}
// Concrete subclass 2
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
[Link] = width;
[Link] = 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
[Link]();
[Link]();
}
}
Output :
Experiment no :14
Nested class
Code : class OuterClass {
// Static nested class
static class StaticNestedClass {
void display() {
[Link]("Static Nested Class");} }
// Inner (non-static) class
class InnerClass {
void display() {
[Link]("Inner (Non-Static) Class"); } }}
public class NestedClassDemo {
public static void main(String[] args) {
// Accessing the static nested class
[Link] staticNestedObj = new
[Link]();
[Link]();
// Accessing the inner (non-static) class
OuterClass outerObj = new OuterClass();
[Link] innerObj = [Link] InnerClass();
[Link](); }}
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() {
[Link]("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();
[Link]();
[Link]();
[Link](); }}
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) {
[Link]("Message from MyClass: " + message);
}
}
Main class:
import [Link]; // Import the MyClass from the user-defined package
public class Main {
public static void main(String[] args) {
MyClass myObject = new MyClass();
[Link]("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() {
[Link]("Inside MyClass - myMethod");
}}
// Create another class that implements both MyInterface and NestedInterface
class AnotherClass implements MyInterface, NestedInterface {
public void myMethod() {
[Link]("Inside AnotherClass - myMethod");
}
public void nestedMethod() {
[Link]("Inside AnotherClass - nestedMethod");
}}
public class Main {
public static void main(String[] args) {
MyClass obj1 = new MyClass();
[Link]();
AnotherClass obj2 = new AnotherClass();
[Link]();
[Link](); }}
output :
Experiment no :18
Exception Handling - using predefined exception
Code : import [Link].*;
public class ExceptionHandling {
public static void main(String [] args){
int a,b;
float c;
Scanner scan =new Scanner([Link]);
[Link]("Enter value for a: ");
a=[Link]();
[Link]("Enter value for b: ");
b=[Link]();
try{
c=a/b;
[Link]("Value of c= "+c);}
catch(Exception e){
[Link]("Exception encountered: "+ e);
[Link]("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
[Link]("Access granted. You are over 18 years old.");
} catch (CustomException e) {
// Catch and handle the custom exception
[Link]("Custom Exception caught: " + [Link]()); } }}
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<[Link];i++){
try{
sleep(500);}
catch(Exception e)
{
}
[Link](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) {
[Link] = message }
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread " + [Link]().getId() + ": " + message + " -
Count " + i);
try {
[Link](1000); // Pause for 1 second
} catch (InterruptedException e) {
[Link]("Thread interrupted: " + [Link]() } }}}
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
[Link]();
[Link]();
[Link]()}}
output :
Experiment no :22
Thread life cycle
Code : class A1 extends Thread
{
public void run ()
{
[Link] ("Thread A");
[Link] ("i in Thread A ");
for (int i = 1; i <= 5; i++)
{
[Link] ("i = " + i);
try
{
[Link] (1000);
}
catch (InterruptedException e)
{
[Link] ();
}
}
[Link] ("Thread A Completed.");
}
}
class B extends Thread
{
public void run ()
{
[Link] ("Thread B");
[Link] ("i in Thread B ");
for (int i = 1; i <= 5; i++)
{
[Link] ("i = " + i);
}
[Link] ("Thread B Completed.");
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
A1 threadA = new A1();
B threadB = new B();
// Start threadA
[Link]();
// Wait for threadA to complete before starting threadB
[Link]();
// Start threadB
[Link]();
[Link]("Main Thread End");
}
}
Output :
Experiment no :23
Applet life cycle
Code : import [Link];
import [Link];
@SuppressWarnings("serial")
public class AppletLifeCycle extends Applet {
public void init() {
[Link]("1. I am init()");}
public void start() {
[Link]("2. I am start()"); }
public void paint(Graphics g) {
[Link]("3. I am paint()");
}
public void stop() {
[Link]("4. I am stop()");
}
public void destroy() {
[Link]("5. I am destroy()"); }}
Output :
Experiment no :24
Applet for configuring Applets by passing parameters
Code : import [Link].*;
import [Link].*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{n = getParameter("name");
a = getParameter("age");}
public void paint(Graphics g)
{[Link]("Name is: " + n, 20, 20);
[Link]("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 [Link].*;
import [Link].*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
[Link](60,50,170,20);
Button b=new Button("click me");
[Link](100,120,80,30);
[Link](this);//passing current instance
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true); }
public void actionPerformed(ActionEvent e){
[Link]("Welcome"); }
public static void main(String args[]){
new AEvent(); } }
output :
Experiment no :26
Reading and writing from a particular file
Code : import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class ReadWriteFile {
public static void main(String[] args) {
// File path
String filePath = "[Link]";
// Read from the file
try {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
[Link]("Contents of the file:");
while ((line = [Link]()) != null) {
[Link](line) }
[Link]();
} catch (IOException e) {
[Link] }
// Write to the file
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true)); //
Append mode
[Link](); // Move to the next line
[Link]("This is a new line of text.");
[Link]();
[Link]("Data has been written to the file.");
} catch (IOException e) {
[Link]();
}
}
}
Output :
Experiment no :27
Database connectivity for various DDL and DML operations
Code : [Link]
import [Link];
import [Link];
import [Link];
import [Link];
class DDLExample {
public static void main(String[] args) {
try {
// Connect to the database
Connection connection = [Link]("jdbc:your-database-url",
"your-username", "your-password");
// Create a table (DDL)
createTable(connection);
// Close the connection
[Link]();
} catch (SQLException e) {
[Link](); } }
private static void createTable(Connection connection) throws SQLException {
Statement statement = [Link]();
String createTableSQL = "CREATE TABLE IF NOT EXISTS mytable (id INT
PRIMARY KEY, name VARCHAR(255))";
[Link](createTableSQL);
[Link]();}}
output :
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
class SimpleDMLExample {
public static void main(String[] args) {
try {
// Connect to the database
Connection connection = [Link]("jdbc:your-database-url",
"your-username", "your-password");
// Insert data (DML)
insertData(connection, "John", 30);
// Close the connection
[Link]();
} catch (SQLException e) {
[Link]() }}
private static void insertData(Connection connection, String name, int age) throws
SQLException {
String insertSQL = "INSERT INTO mytable (name, age) VALUES (?, ?)";
PreparedStatement preparedStatement = [Link](insertSQL);
[Link](1, name);
[Link](2, age);
[Link]();
[Link]() ; }}
output :
Experiment no :28
String class and its methods
Code : [Link]
Code:
public class Main {
public static void main(String[] args) {
String firstName = "CHA";
String lastName = "HAT";
[Link]([Link](lastName));
}
}
Output :
2. Equals
Code:
public class Main {
public static void main(String[] args) {
String myStr1 = "Hello";
String myStr2 = "Hello";
String myStr3 = "Another String";
[Link]([Link](myStr2));
[Link]([Link](myStr3)); }}
Output :
3. Length
Code:
public class Main {
public static void main(String[] args) {
String txt = "DEFGHPQRWXYZ";
[Link]([Link]()); }}
Output :
4. ToLowerCase
Code:
public class Main {
public static void main(String[] args) {
String txt = "Hello World";
[Link]([Link]());
[Link]([Link]());}}
Output :
5. Replace
Code:
public class Main {
public static void main(String[] args) {
String myStr = "Hello";
[Link]([Link]('l', 'p')); }}
Output :
Experiment no :29
StringBuffer class and its methods
Code : 1. append() method
import [Link].*;
class A {
public static void main(String args[])
{StringBuffer sb = new StringBuffer("Hello ");
[Link]("Java"); // now original string is changed
[Link](sb); }}
Output :
2. insert() method
import [Link].*;
class A {
public static void main(String args[])
{ StringBuffer sb = new StringBuffer("Hello ");
[Link](1, "Java");
// Now original string is changed
[Link](sb); }}
Output :
3. replace() method
import [Link].*;
class A {
public static void main(String args[])
{StringBuffer sb = new StringBuffer("Hello");
[Link](1, 3, "Java");
[Link](sb); }}
Output :
4. delete() method
import [Link].*;
class A {
public static void main(String args[])
{ StringBuffer sb = new StringBuffer("Hello");
[Link](1, 3);
[Link](sb); }}
Output :
5. reverse() method
import [Link].* ;
class A {
public static void main(String args[])
{ StringBuffer sb = new StringBuffer("Hello");
[Link]();
[Link](sb);}}
Output :