1. import [Link].
Scanner;class
PrimeNumbers
{
public static void main(String[] args)
{
int n;
int p;
Scanner s=new Scanner([Link]);
[Link]("Enter a number: ");
n=[Link]();
for(int i=2;i<n;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
[Link](i);
}
}
}
Output:
Enter a number:
20
2
3
5
7
11
13
17
19
2. import [Link];
public class MatrixMultiplication { public static
void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of rows and columns of the firstmatrix:");
int rows1 = [Link]();int
cols1 = [Link]();
[Link]("Enter the elements of the first matrix:");int[][] matrix1 =
new int[rows1][cols1];
for (int i = 0; i < rows1; i++) { for (int
j = 0; j < cols1; j++) {
matrix1[i][j] = [Link]();
}
}
[Link]("Enter the number of rows and columns of the secondmatrix:");
int rows2 = [Link]();int
cols2 = [Link]();
if (cols1 != rows2) {
[Link]("Matrices cannot be multiplied!");return;
[Link]("Enter the elements of the second matrix:");int[][] matrix2 = new
int[rows2][cols2];
for (int i = 0; i < rows2; i++) { for (int
j = 0; j < cols2; j++) {
matrix2[i][j] = [Link]();
}
}
int[][] resultMatrix = multiplyMatrices(matrix1, matrix2);
[Link]("Result of matrix multiplication:");for (int i = 0; i
< rows1; i++) {
for (int j = 0; j < cols2; j++) { [Link](resultMatrix[i][j] + " ");
}
[Link]();
}
}
public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {int rows1 =
[Link];
int cols1 = matrix1[0].length;int
rows2 = [Link]; int cols2 =
matrix2[0].length;
int[][] resultMatrix = new int[rows1][cols2];
for (int i = 0; i < rows1; i++) { for (int
j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return resultMatrix;
}
}
Output
Enter the number of rows and columns of the first matrix:2 3
Enter the elements of the first matrix:
123
456
Enter the number of rows and columns of the second matrix:3 2
Enter the elements of the second matrix:7
8
9 10
11 12
Result of matrix multiplication:
58 64
139 154
3. import [Link].*;
class FileDemo
{
public static void main(String args[])
{
try
{
int lines=0,chars=0,words=0;int
code=0;
FileInputStream fis = new FileInputStream("[Link]");
while([Link]()!=0)
{
code = [Link]();
if(code!=10)
chars++;
if(code==32)
words++;
if(code==13)
{
lines++;
words++;
}
}
[Link]("[Link] characters = "+chars);
[Link]("[Link] words = "+(words+1));
[Link]("[Link] lines = "+(lines+1)); [Link]();
}
catch(FileNotFoundException e)
{
[Link]("Cannot find the specified file...");
}
catch(IOException i)
{
[Link]("Cannot read file...");
}
}
}
Output:
[Link] characters = 65
[Link] words = 14
[Link] lines = 4
Error message:
(assuming the file does not exist or cannot be accessed):
Cannot find the specified file...
(assuming there's an error reading the file):
Cannot read file...
4. import [Link];
public class RandomNumberGenerator {public
static void main(String[] args) {
// Define the lower and upper limitsint
lowerLimit = 1;
int upperLimit = 100;
// Create an instance of the Random classRandom
random = new Random();
// Generate a random number within the specified range
int randomNumber = [Link](upperLimit - lowerLimit + 1) +lowerLimit;
// Print the generated random number
[Link]("Generated Random Number: " + randomNumber);
// Print messages according to the range of the generated valueif
(randomNumber <= 25) {
[Link]("Random number is in the range 1-25.");
} else if (randomNumber <= 50) {
[Link]("Random number is in the range 26-50.");
} else if (randomNumber <= 75) {
[Link]("Random number is in the range 51-75.");
} else {
[Link]("Random number is in the range 76-100.");
}
}
}
Output:
Generated Random Number: 42 Random
number is in the range 26-50.
5. import [Link]; public class
StringManipulation {
public static void main(String[] args) { Scanner scanner =
new Scanner([Link]);
// Input two strings
[Link]("Enter the first string: "); String str1 =
[Link](); [Link]("Enter the second
string: ");String str2 = [Link]();
// Convert strings to character arrays char[]
charArray1 = [Link]();char[] charArray2
= [Link]();
// Perform string operations
int length1 = stringLength(charArray1);int
length2 = stringLength(charArray2);
[Link]("Length of string 1: " + length1); [Link]("Length of
string 2: " + length2); [Link]("Enter the position to find character in string
1: ");int position = [Link]();
char charAtPosition = findCharacter(charArray1, position);
if (charAtPosition != '\0') {
[Link]("Character at position " + position + " in string 1:" +
charAtPosition);
} else {
[Link]("Invalid position.");
String concatenatedString = concatenateStrings(charArray1,charArray2);
[Link]("Concatenated string: " + concatenatedString);
// Method to find the length of a string public static
int stringLength(char[] str) {
int length = 0; for
(char c : str) {
if (c == '\0') {
break;
length++;
return length;
}
// Method to find a character at a particular position in the stringpublic static char
findCharacter(char[] str, int position) {
if (position >= 1 && position <= [Link]) {return
str[position - 1];
} else {
return '\0'; // Null character indicating invalid position
// Method to concatenate two strings
public static String concatenateStrings(char[] str1, char[] str2) {char[] result =
new char[[Link] + [Link]];
int index = 0;
for (char c : str1) {if (c
== '\0') {
break;
result[index++] = c;
for (char c : str2) {if (c
== '\0') {
break;
}
result[index++] = c;
return new String(result);
}
Output:
Enter the first string: Hello Enter
the second string: WorldLength
of string 1: 5
Length of string 2: 5
Enter the position to find character in string 1: 3
Character at position 3 in string 1: l Concatenated
string: HelloWorld
6. import [Link]; public
class StringOperations {
public static void main(String[] args) { Scanner scanner =
new Scanner([Link]);
// Input two strings [Link]("Enter the first
string: ");String str1 = [Link]();
[Link]("Enter the second string: ");String str2 =
[Link]();
// Perform string concatenation
String concatenatedString = concatenateStrings(str1, str2);
[Link]("Concatenated string: " + concatenatedString);
// Perform substring search [Link]("Enter the
substring to search: ");String substring = [Link]();
boolean isSubstringFound = searchSubstring(concatenatedString,substring);
if (isSubstringFound) {
[Link]("Substring found in the concatenated string.");
} else {
[Link]("Substring not found in the concatenated string.");
}
// Perform substring extraction
[Link]("Enter the starting index to extract substring: ");
int startIndex = [Link]();
[Link]("Enter the ending index to extract substring: ");int endIndex =
[Link]();
String extractedSubstring = extractSubstring(concatenatedString,startIndex, endIndex);
[Link]("Extracted substring: " + extractedSubstring);
}
// Method to perform string concatenation
public static String concatenateStrings(String str1, String str2) {return
[Link](str2);
// Method to perform substring search
public static boolean searchSubstring(String str, String substring) {return
[Link](substring);
}
// Method to perform substring extraction
public static String extractSubstring(String str, int startIndex, intendIndex) {
return [Link](startIndex, endIndex);
}
}
Output:
Enter the first string: Hello Enter
the second string: World
Concatenated string: HelloWorld
Enter the substring to search: World Substring
found in the concatenated string. Enter the
starting index to extract substring: 3Enter the
ending index to extract substring: 7 Extracted
substring: loWo
7. import [Link];
public class StringBufferOperations { public static
void main(String[] args) {
// Define a string for string operationsString
mainString = "Hello, World!";
// Perform string length operation int length =
findLength(mainString);
[Link]("Length of the string: " + length);
// Perform string reversal operation
String reversedString = reverseString(mainString); [Link]("Reversed string: " +
reversedString);
// Perform substring deletion operationString
substringToDelete = "World";
String stringWithoutSubstring = deleteSubstring(mainString,substringToDelete);
[Link]("String after deleting substring '" +substringToDelete + "': "
+ stringWithoutSubstring);
}
// Method to find the length of a string using StringBufferpublic static
int findLength(String str) {
StringBuffer stringBuffer = new StringBuffer(str);return
[Link]();
}
// Method to reverse a string using StringBufferpublic static
String reverseString(String str) {
StringBuffer stringBuffer = new StringBuffer(str);return
[Link]().toString();
}
// Method to delete a substring from a given string using StringBufferpublic static String
deleteSubstring(String mainString, String
substringToDelete) {
StringBuffer stringBuffer = new StringBuffer(mainString);int index =
[Link](substringToDelete);
if (index != -1) {
[Link](index, index + [Link]());
}
return [Link]();
}
}
Output:
Length of the string: 13 Reversed
string: !dlroW ,olleH
String after deleting substring 'World': Hello, !
8. import [Link];
public class MultiThreadExample { public static
void main(String[] args) {
NumberGenerator numberGenerator = new NumberGenerator();SquareCalculator
squareCalculator = new SquareCalculator(); CubeCalculator cubeCalculator = new
CubeCalculator();
Thread thread1 = new Thread(numberGenerator);Thread thread2 =
new Thread(squareCalculator); Thread thread3 = new
Thread(cubeCalculator);
[Link]();
[Link]();
[Link]();
}
}
class NumberGenerator implements Runnable {Random
random = new Random();
@Override
public void run() {
while (true) {
int number = [Link](100); [Link]("Generated number:
" + number);
if (number % 2 == 0) {
synchronized ([Link]) {
[Link] = number;
[Link]();
}
} else {
synchronized ([Link]) {
[Link] = number;
[Link]();
}
}
try {
[Link](1000);
} catch (InterruptedException e) {[Link]();
}
}
}
}
class SquareCalculator implements Runnable {static final Object
lock = new Object();
static int number;
@Override
public void run() {
while (true) {
synchronized (lock) {try {
[Link]();
int square = number * number;
[Link]("Square of " + number + ": " + square);
} catch (InterruptedException e) {[Link]();
}
}
}
}
}
class CubeCalculator implements Runnable {static final
Object lock = new Object(); static int number;
@Override
public void run() {
while (true) {
synchronized (lock) {try {
[Link]();
int cube = number * number * number; [Link]("Cube of "
+ number + ": " + cube);
} catch (InterruptedException e) {[Link]();
}
}
}
}
}
Output:
Generated number: 68
Square of 68: 4624
Generated number: 35
Cube of 35: 42875
Generated number: 8
Square of 8: 64
Generated number: 26
Square of 26: 676
Generated number: 83
Cube of 83: 571787
Generated number: 77
Cube of 77: 456533
Generated number: 25
Cube of 25: 15625
Generated number: 84
Square of 84: 7056
Generated number: 23
Cube of 23: 12167
Generated number: 81
Square of 81: 6561
...
9. import [Link]; public
class ThreadExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new PrintNumbers(1, 10)); Thread thread2 =
new Thread(new PrintNumbers(90, 100));
[Link]();
[Link]();
}
}
class PrintNumbers implements Runnable {private int
start;
private int end;
public PrintNumbers(int start, int end) {[Link] = start;
[Link] = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
[Link]([Link]().getName() + ": " + i);try {
[Link](500); // Sleep for 500 milliseconds to simulateasynchronous behavior
} catch (InterruptedException e) {[Link]();
}
}
}
}
Output:
Thread-0: 1
Thread-1: 90
Thread-0: 2
Thread-1: 91
Thread-0: 3
Thread-1: 92
Thread-0: 4
Thread-1: 93
Thread-0: 5
Thread-1: 94
Thread-0: 6
Thread-1: 95
Thread-0: 7
Thread-1: 96
Thread-0: 8
Thread-1: 97
Thread-0: 9
Thread-1: 98
Thread-0: 10
Thread-1: 99
Thread-1: 100
10. import [Link];
public class ExceptionDemo {
public static void main(String[] args) {
// a) Arithmetic Exceptiontry {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception caught: " + [Link]());
}
// b) Number Format Exceptiontry {
String str = "abc";
int num = [Link](str); // String cannot be parsed to integer
} catch (NumberFormatException e) { [Link]("Number Format
Exception caught: " +
[Link]());
}
// c) Array Index Out of Bound Exceptiontry {
int[] arr = {1, 2, 3};
[Link](arr[5]); // Accessing index out of bounds
} catch (ArrayIndexOutOfBoundsException e) { [Link]("Array Index Out of
Bound Exception caught: " +
[Link]());
}
// d) Negative Array Size Exceptiontry {
int[] arr = new int[-5]; // Creating array with negative size
} catch (NegativeArraySizeException e) { [Link]("Negative Array Size
Exception caught: " +
[Link]());
}
}
}
Output:
Arithmetic Exception caught: / by zero
Number Format Exception caught: For input string: "abc"
Array Index Out of Bound Exception caught: Index 5 out of bounds for length 3Negative
Array Size Exception caught: -5
11. import [Link];
public class FileInfo {
public static void main(String[] args) {
// Read file name from the user
String fileName = "[Link]"; // Example file name, you can modifythis to read from
user input
// Create a File object with the specified file nameFile file = new
File(fileName);
// Check if the file existsif
([Link]()) {
[Link]("File exists.");
// Check if the file is readableif
([Link]()) {
[Link]("File is readable.");
} else {
[Link]("File is not readable.");
}
// Check if the file is writableif
([Link]()) {
[Link]("File is writable.");
} else {
[Link]("File is not writable.");
}
// Get the type of the fileif
([Link]()) {
[Link]("File type: Regular file");
} else if ([Link]()) { [Link]("File
type: Directory");
} else {
[Link]("File type: Unknown");
}
// Get the length of the file in bytes
[Link]("File length: " + [Link]() + " bytes");
} else {
[Link]("File does not exist.");
}
}
}
Output:
File exists.
File is readable.
File is writable.
File type: Regular file
File length: 12345 bytes
12. package practical;
import [Link].*;
import [Link].*;
import [Link];
import [Link];
public class TextStyler extends JFrame implements ActionListener {
private JTextField inputTextField;
private JLabel displayLabel;
private JComboBox<String>fontCombBox;
private JComboBox<Integer>sizeComboBox;
private JCheckBox boldCheckBox,italicCheckBox;
private static final String[]
FONTS=[Link]().getAvailableFontFamilyNames()
;
private static final Integer[]SIZES=
{8,10,12,14,16,18,20,22,24,26,28,30,32,34,36};
private TextStyler()
{
setTitle("Text Styler");
setSize(500,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
inputTextField=new JTextField(20);
displayLabel=new JLabel("your styled text will appear here");
[Link](new Font("Arial",[Link],14));
fontCombBox=new JComboBox<>(FONTS);
sizeComboBox=new JComboBox<>(SIZES);
boldCheckBox=new JCheckBox("Bold");
italicCheckBox=new JCheckBox("Italic");
JButton applyButton=new JButton("Apply");
[Link](this);
add(new JLabel("EnterText:"));
add(inputTextField);
add(new JLabel("Font"));
add(fontCombBox);
add(new JLabel("Size:"));
add(sizeComboBox);
add(boldCheckBox);
add(italicCheckBox);
add(applyButton);
add(displayLabel);
}
public void actionPerformed(ActionEvent e)
{
String text=[Link]();
String selectedFont=(String) [Link]();
int selectedsize=(Integer) [Link]();
int style=[Link];
if([Link]())
{
style |=[Link];
}
if([Link]()) {
style |=[Link];
}
Font font=new Font(selectedFont,style,selectedsize);
[Link](text);
[Link](font);
}
public static void main(String[] args) {
[Link](()->{
TextStyler frame=new TextStyler();
[Link](true);
});
}
}
Output:
13. import [Link].*;
import [Link].*;
import [Link].*;import
[Link].*;
class MouseEventPerformer extends JFrame implements MouseListener {JLabel l1;
public MouseEventPerformer() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 300);
setLayout(new FlowLayout([Link])); l1 = new
JLabel();
Font f = new Font("Verdana", [Link], 20);
[Link](f);
[Link]([Link]);add(l1);
addMouseListener(this);
setVisible(true);
public void mouseExited(MouseEvent m) {[Link]("Mouse Exited");
}
public void mouseEntered(MouseEvent m) {[Link]("Mouse
Entered");
public void mouseReleased(MouseEvent m) {
[Link]("Mouse Released");
public void mousePressed(MouseEvent m) {[Link]("Mouse
Pressed");
public void mouseClicked(MouseEvent m) {
[Link]("Mouse Clicked");
public static void main(String[] args) {
MouseEventPerformer mep = new MouseEventPerformer();
}
Output:
14. import [Link].*;
import [Link].*;
class Calculator implements ActionListener {
// Declaration of Objects
Frame f = new Frame();
Label l1 = new Label("First Number"); Label l2 =
new Label("Second Number");Label l3 = new
Label("Result");
TextField t1 = new TextField();
TextField t2 = new TextField();
TextField t3 = new TextField();
Button b1 = new Button("Add"); Button b2
= new Button("Sub"); Button b3 = new
Button("Mul"); Button b4 = new
Button("Div"); Button b5 = new
Button("Cancel");Calculator() {
// Giving Coordinates
[Link](100, 100, 150, 30);
[Link](100, 140, 150, 30);
[Link](100, 180, 150, 30);
[Link](300, 100, 150, 30);
[Link](300, 140, 150, 30);
[Link](300, 180, 150, 30);
[Link](50, 350, 60, 30);
[Link](110, 350, 60, 30);
[Link](170, 350, 60, 30);
[Link](230, 350, 60, 30);
[Link](290, 350, 60, 30);
// Adding components to the frame
[Link](l1);
[Link](l2);
[Link](l3);
[Link](t1);
[Link](t2);
[Link](t3);
[Link](b1);
[Link](b2);
[Link](b3);
[Link](b4);
[Link](b5);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](this);
[Link](null);
[Link](true);
[Link](500, 450);
public void actionPerformed(ActionEvent e) {int n1 =
[Link]([Link]());
int n2 = [Link]([Link]());
if ([Link]() == b1) { [Link]([Link](n1 +
n2));
if ([Link]() == b2) {
[Link]([Link](n1 - n2));
if ([Link]() == b3) {
[Link]([Link](n1 * n2));
if ([Link]() == b4) {
[Link]([Link](n1 / n2));
if ([Link]() == b5) {
[Link](0);
public static void main(String... s) {new
Calculator();
}
Output:
15. import [Link];
import [Link].*;
import [Link]; import
[Link];
import [Link].*;
class App extends JFrame implements ItemListener{JFrame
actualWindow;
JPanel messageContainer, lightsContainer;JLabel
message;
ButtonGroup btn_group;
JRadioButton rb_red, rb_yellow, rb_green;
App() {
Font myFont = new Font("Verdana",[Link], 50);
actualWindow = new JFrame("Traffic Lights"); messageContainer
= new JPanel();
lightsContainer = new JPanel(); message =
new JLabel(""); btn_group = new
ButtonGroup(); rb_red = new
JRadioButton("Red");
rb_yellow = new JRadioButton("Yellow");rb_green
= new JRadioButton("Green");
[Link](new GridLayout(2, 1));
[Link](myFont); rb_red.setForeground([Link]);
rb_yellow.setForeground([Link]);
rb_green.setForeground([Link]);
btn_group.add(rb_red);
btn_group.add(rb_yellow);
btn_group.add(rb_green);
rb_red.addItemListener(this);
rb_yellow.addItemListener(this); rb_green.addItemListener(this);
[Link](message); [Link](rb_red);
[Link](rb_yellow); [Link](rb_green);
[Link](messageContainer); [Link](lightsContainer);
[Link](300, 200);
[Link](true);
}
@Override
public void itemStateChanged(ItemEvent ie) {
JRadioButton selected = (JRadioButton) [Link]();String
textOnButton = [Link](); if([Link]("Red")) {
[Link]([Link]); [Link]("STOP");
} else if([Link]("Yellow")) {
[Link]([Link]);
[Link]("READY");
} else {
[Link]([Link]); [Link]("GO");
}
}
}
public class TrafficLight {
public static void main(String[] args) {new
App();
}
}
Output: