java practical
java practical
// Input string
System.out.print("Enter your name: ");
String name = sc.nextLine();
// Input integer
System.out.print("Enter your age: ");
int age = sc.nextInt();
// Input double
System.out.print("Enter your percentage: ");
double percentage = sc.nextDouble();
int value = 1;
System.out.println("Ragged Array:");
for (int i = 0; i < raggedArray.length; i++) {
for (int j = 0; j < raggedArray[i].length; j++) {
System.out.print(raggedArray[i][j] + " ");
}
System.out.println();
}
}
}
Arrays.sort(numbers);
System.out.println("Sorted array: " + Arrays.toString(numbers));
Arrays.fill(numbers, 3);
System.out.println("Array after fill(): " + Arrays.toString(numbers));
void displayDetails() {
System.out.println("Student Name: " + name);
System.out.println("Roll Number : " + rollNo);
System.out.println("Percentage : " + percentage + "%");
System.out.println();
}
}
void display(double a) {
System.out.println("Method with one double: " + a);
}
obj.display(10);
obj.display(10, 20);
obj.display(12.5);
obj.display("Hello Java");
}
}
Constructoroverloading() {
name = "Unknown";
age = 0;
}
Constructoroverloading(String n) {
name = n;
age = 0;
}
Constructoroverloading(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
obj1.display();
obj2.display();
obj3.display();
}
}
void displayStudentDetails() {
displayPersonDetails(); // Call method from parent class
System.out.println("Roll No: " + rollNo);
}
}
public class Singleinheritance {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Student s = new Student();
void display() {
System.out.println("Name: " + name);
System.out.println("Age : " + age);
}
}
void display() {
super.display();
System.out.println("Roll No: " + rollNo);
}
}
void displayPersonDetails() {
System.out.println("Name: " + name);
System.out.println("Age : " + age);
}
}
// Derived class
class Student extends Person {
int rollNo;
void displayStudentDetails() {
displayPersonDetails();
System.out.println("Roll No: " + rollNo);
}
}
void displayGraduateDetails() {
displayStudentDetails();
Tanushree Nair Page 18 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("Degree: " + degree);
}
}
// Main class
public class MultilevelInheritance {
public static void main(String[] args) {
GraduateStudent gs = new GraduateStudent();
Animal ref;
ref = new Dog();
ref.sound();
}
}
interface Showable {
void show();
}
class InnerClass {
String innerMessage = "This is Inner Class";
void displayMessages() {
// Accessing both inner and outer class members
System.out.println(outerMessage);
System.out.println(innerMessage);
}
}
inner.displayMessages();
}
}
void display() {
System.out.println("Inside outer method...");
class LocalClass {
void show() {
System.out.println("Hello from Local Inner Class!");
}
}
try {
System.out.println("Accessing element at index 5:");
System.out.println(numbers[5]); // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception Caught: " + e);
}
try {
String str = null;
try {
int num = 10, div = 0;
int result = num / div; // Will throw ArithmeticException
Tanushree Nair Page 27 of 78
MCA 208: Programming in Java MCA 2nd Semester
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
finally {
System.out.println("Finally block is always executed.");
}
}
}
try {
try {
System.out.println("Inner try block starts...");
int num = 10, div = 0;
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Outer catch block: ArrayIndexOutOfBoundsException caught: " +
e.getMessage());
}
}
}
27. WAJP To Create Your Own Exception Class And Display Corresponding Error
Message
class AgeException extends Exception {
try {
int age = 15; // Example of an invalid age
// Throwing the custom exception if age is less than 18
if (age < 18) {
throw new AgeException("Age is less than 18. Cannot proceed with registration.");
} else {
System.out.println("Age is valid. Proceeding with registration.");
}
} catch (AgeException e) {
}
}
28. WAJP For Creating And Executing Threads by extending the Thread class.
// Custom class extending the Thread class
} catch (InterruptedException e) {
System.out.println(threadName + " was interrupted.");
}
}
System.out.println(threadName + " has finished.");
}
}
public class ThreadExample {
public static void main(String[] args) {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n___________________________________________");
t2.start();
}
}
}
}
System.out.println(threadName + " has finished.");
}
}
this.name = name;
}
// Creating threads
Thread t1 = new Thread(new MyRunnable("Thread 1"));
Thread t2 = new Thread(new MyRunnable("Thread 2"));
Thread t3 = new Thread(new MyRunnable("Thread 3"));
Tanushree Nair Page 37 of 78
MCA 208: Programming in Java MCA 2nd Semester
} catch (InterruptedException e) {
System.out.println("t1 interrupted.");
}
t2.start();
try {
t2.join(); // Wait until t2 finishes
} catch (InterruptedException e) {
System.out.println("t2 interrupted.");
}
t3.start();
try {
t3.join(); // Wait until t3 finishes
} catch (InterruptedException e) {
System.out.println("t3 interrupted.");
}
e.printStackTrace();
}
dataReady = true;
System.out.println("Producer finished producing data.");
while (!dataReady) {
try {
wait(); // Wait until data is produced
} catch (InterruptedException e) {
e.printStackTrace();
}
}
consumer.start();
try {
Thread.sleep(500); // Ensure consumer starts first
} catch (InterruptedException e) {
e.printStackTrace();
}
producer.start();
}
}
// Concatenation
String combined = str1 + " " + str2;
System.out.println("Concatenation: " + combined);
// Length of a string
System.out.println("Length of str1: " + str1.length());
// charAt()
System.out.println("Character at index 1 of str1: " + str1.charAt(1));
// trim()
System.out.println("Before trim: '" + str3 + "'");
// substring()
System.out.println("Substring of str3 (start from 3): " + str3.substring(3));
// replace()
// contains()
System.out.println("Does str3 contain 'Java'? " + str3.contains("Java"));
// indexOf()
System.out.println("Index of 'o' in str2: " + str2.indexOf('o'));
// isEmpty()
String emptyStr = "";
try {
// Copying the file using Files.copy() method
Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + fileName);
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
}
}
}
// Serializable class
class Student implements Serializable {
String name;
int rollNo;
this.age = age;
}
}
}
}
}
Label label;
KeyboardEventExample() {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
label = new Label();
label.setBounds(50, 100, 300, 30);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose(); // close the window
}
});
}
// KeyListener methods
public void keyPressed(KeyEvent e) {
Label label;
MouseEventExample() {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
add(label);
addMouseListener(this);
addMouseMotionListener(this);
// MouseListener methods
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")");
}
}
catch (SQLException e)
{
System.out.println(" Error: Unable to connect to the database."); e.printStackTrace();
}
finally { try {
if (con != null)
{
con.close();
System.out.println("Database connection closed.");
}
} catch (SQLException e) {
System.out.println("Error while closing the connection.");
e.printStackTrace();
}
}
43. WAP to create a table named employee with feilds as emp_id, emp_name, age ,
dept.
import java.sql.*;
public class CreateEmployeeTable { public static void main(String[] args) {
try {
System.out.println("NAME : TANUSHREE NAIR\nCLASS : MCA IInd
Semester\n_____________________________________________________");
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe", " Tanushree ", " anjali123 "); Statement stmt = con.createStatement();
stmt.executeUpdate("create table employee1(emp_id number primary key,emp_name varchar(10),age
number,dept varchar(10))");
System.out.println(" Table 'employee1' created successfully!"); con.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
System.out.println(e);
}
}
}
System.out.println("Executing query...");
ResultSet rs = stmt.executeQuery("SELECT * FROM employee1");
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getInt(3) + " " + rs.getString(4));
}
if (!found) {
System.out.println("No records found in table.");
}
con.close();
} catch(Exception e) { System.out.println("Error: " + e);
}
}
}
countries.add("India");
countries.add("USA");
countries.add("UK");
countries.add("India"); // Duplicate
countries.remove("USA");
System.out.println("After removing USA: " + countries);
marks.put("Alice", 85);
marks.put("Bob", 90);
marks.put("Charlie", 78);
marks.put("Alice", 95); // Overwrites previous value
marks.remove("Charlie");
System.out.println("After removing Charlie: " + marks);
System.out.println("All entries:");
for (String name : marks.keySet()) {
System.out.println(name + " -> " + marks.get(name));
}
frame.setLayout(new FlowLayout());
frame.setLayout(new FlowLayout());
JToggleButton toggleButton = new JToggleButton("Off");
toggleButton.addActionListener(e -> {
if (toggleButton.isSelected()) {
toggleButton.setText("On");
} else {
toggleButton.setText("Off");
}
});