0% found this document useful (0 votes)
6 views37 pages

Java Pratical 7-29

The document describes an experiment on constructor chaining in Java. It defines a MyClass with a two-parameter constructor, a one-parameter constructor that chains to the two-parameter constructor, and a no-argument constructor that chains to the one-parameter constructor. In the main method, it creates instances of MyClass using each constructor and calls the display method to print the x and y values initialized by the constructors.
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)
6 views37 pages

Java Pratical 7-29

The document describes an experiment on constructor chaining in Java. It defines a MyClass with a two-parameter constructor, a one-parameter constructor that chains to the two-parameter constructor, and a no-argument constructor that chains to the one-parameter constructor. In the main method, it creates instances of MyClass using each constructor and calls the display method to print the x and y values initialized by the constructors.
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

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 :

Common questions

Powered by AI

In Java, access modifiers control the visibility of class members (fields, methods) within different parts of a program. 'Private' restricts the visibility to the owning class only, meaning private members are not accessible to subclasses, enforcing encapsulation at the class level . 'Protected' extends access to subclasses (even if they are in different packages), allowing for more flexible program design where subclass functionalities build upon aspects of the parent class . 'Public' allows access from any other class, including from different packages, promoting extensive reuse of classes and methods across different parts of a program . The choice of access modifier impacts how subclasses interact with their superclass members, defining a hierarchy of permissions and control within object-oriented designs.

Java does not support multiple inheritance through classes to avoid complexity and ambiguity, commonly known as the 'diamond problem'. Instead, Java uses interfaces to achieve multiple inheritance. A class can implement multiple interfaces, thus inheriting the abstract behaviors defined by these interfaces. This approach allows a class to integrate multiple types and behaviors in a controlled manner, leveraging polymorphism without the complications of multiple class inheritance . By using interfaces, Java maintains a cleaner and more predictable inheritance model while enabling the extensibility of class behavior.

Java threads undergo several states during their lifecycle: new, runnable, running, blocked, and terminated. A thread starts in a 'new' state when it is created, transitioning to 'runnable' once the start method is invoked. The thread enters the 'running' state when the scheduler assigns it CPU time. If the thread encounters resource unavailability or performs wait() operation, it moves to the 'blocked' state, pausing operations temporarily. Finally, a thread enters the 'terminated' state upon completion of its run() method . Each state in the thread lifecycle is fundamental as it dictates the thread’s behavior and control, enabling effective multitasking by allowing synchronized resource access and efficient CPU utilization.

The 'main' method is critical in Java applications as it serves as the entry point for any standalone Java application. Signifying where program control starts, the main method adheres to a strict signature - "public static void main(String[] args)", which allows the JVM to invoke it. It can accept command-line arguments, enabling dynamic input during execution . In various application setups, particularly those that involve classes spread over packages, the main method facilitates the initialization of the program's execution flow, integrating different classes and components to execute the application's logic.

Constructor chaining in Java is a technique where a constructor is called within another constructor using 'this()' for calling constructors within the same class, or 'super()' for invoking a parent class constructor. This approach facilitates the initialization of an object with different sets of parameters while avoiding redundant code . It ensures that all constructors eventually call a common initialization code, leading to cleaner, more maintainable codebases and ensuring that object initialization is consistent across different scenarios, promoting code reuse and reducing the likelihood of errors or omissions in initialization logic.

Java handles method overriding to achieve dynamic polymorphism, allowing a subclass to provide a specific implementation of a method already defined in its superclass. This practice enables the invocation of overridden methods in an object-oriented manner, allowing base class references to refer to subclass objects and call overridden methods at runtime . Method overriding increases code flexibility, as customizable subclass behaviors can be incorporated without altering existing code structures in the base class, thus supporting the open/closed principle of software design, where systems can be extended without modifying their core structure.

Nested classes in Java are utilized to logically group classes that are used only in one place, increasing encapsulation. Static nested classes can be instantiated without an instance of the outer class and do not have access to instance variables of the outer class, where they function like top-level classes . In contrast, inner (non-static) classes are associated with an instance of the outer class and can access its instance variables. Static nested classes are often used to write cleaner code, encapsulate helper classes, and reduce namespace pollution, whereas inner classes are useful to handle events in GUI applications or to provide complex functionality tightly coupled with instances of the outer class.

The StringBuffer class in Java is designed for mutable sequences of characters, allowing for efficient modifications such as insertions, deletions, and reversals without creating new string instances. Methods like append(), insert(), replace(), delete(), and reverse() are provided to modify the content of the StringBuffer instance . These operations are synchronized, making StringBuffer thread-safe for use in multi-threaded environments. Their efficiency stems from the class’s ability to modify character sequences in place, avoiding the overhead associated with creating numerous immutable String objects during complex text manipulations.

Abstract classes in Java serve as a blueprint for other classes by allowing the definition of abstract methods that must be implemented by subclasses. An abstract class may include both abstract methods, which do not have a body, and concrete methods, offering a partial implementation that can be reused or overridden by subclasses . Abstract classes can include instance variables and constructors, enabling the initialization of common states for objects instantiated through subclasses. This construct allows for shared code and consistent interfaces across a family of subclasses while enforcing a design contract that ensures specific methods will be implemented by each subclass.

Java's exception handling is facilitated through a try-catch-finally construct, allowing developers to anticipate and handle runtime errors that would otherwise disrupt normal program execution. By using predefined exceptions, such as ArithmeticException or NullPointerException, Java provides a set of tools to elegantly manage common error scenarios. Developers can also define custom exceptions by extending the Exception class, which enhances error management by allowing specific error messages or handling pathways tailored to the situation . Custom exceptions deepen error handling by addressing application-specific mistakes, improving debugging processes, and ensuring that errors are handled consistently throughout the application's lifecycle.

You might also like