Java exp
Java exp
even.start();
odd.start();
}
}
Experiment – 5b(Output)
Even: 0
Odd: 1
Even: 2
Even: 4
Odd: 3
Even: 6
Even: 8
Odd: 5
Even: 10
Odd: 7
Odd: 9
Experiment – 6a
Create java program with the use of java packages
(a) Create a package named "Mathematics" and add a class "Matrix"
with methods to add and subtract matrices (2x2). Write a Java progrm
Importing the Mathematics package and use the classes defined in it
Package
Mathematics/
└── Matrix.java
MainApp.java
package Mathematics;
System.out.println("Matrix 1:");
m1.display();
System.out.println("\nMatrix 2:");
m2.display();
Matrix 2:
56
78
Sum of matrices:
68
10 12
Difference of matrices:
-4 -4
-4 -4
Experiment – 7a
Construct java program using Java /O package (a) Write a program in java to
take input from user by using all the following methods: Command Line
Arguments " DatalnputStream Class " BufferedReader Class Scanner Class "
Console Class
import java.io.*;
import java.util.Scanner;
public class InputMethodsDemo {
public static void main(String[] args) {
// 1. Command Line Arguments
if (args.length > 0) {
System.out.println("1. Command Line Argument:");
System.out.println("Hello, " + args[0]);
} else {
System.out.println("1. Command Line Argument:");
System.out.println("No command-line argument provided.");
}
try {
// 2. DataInputStream
System.out.println("\n2. DataInputStream:");
DataInputStream dis = new DataInputStream(System.in);
System.out.print("Enter your age (DataInputStream): ");
String ageStr = dis.readLine(); // Note: readLine() is deprecated but works
int age = Integer.parseInt(ageStr);
System.out.println("Your age is: " + age);
// 3. BufferedReader
System.out.println("\n3. BufferedReader:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter your city (BufferedReader): ");
String city = br.readLine();
System.out.println("Your city is: " + city);
// 4. Scanner
System.out.println("\n4. Scanner:");
Scanner sc = new Scanner(System.in);
System.out.print("Enter your favorite number (Scanner): ");
int favNum = sc.nextInt();
System.out.println("Your favorite number is: " + favNum);
// 5. Console
System.out.println("\n5. Console:");
Console console = System.console();
if (console != null) {
String name = console.readLine("Enter your name (Console): ");
System.out.println("Your name is: " + name);
} else {
System.out.println("Console is not available (usually in IDEs).");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output :
1. Command Line Argument:
Hello, User
2. DataInputStream:
Enter your age (DataInputStream): 20
Your age is: 20
3. BufferedReader:
Enter your city (BufferedReader): Delhi
Your city is: Delhi
4. Scanner:
Enter your favorite number (Scanner): 7
Your favorite number is: 7
5. Console:
Enter your name (Console): User
Your name is: User