JAVA Sourcecode
JAVA Sourcecode
import java.util.Scanner;
public class PrimeNumbersList
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int limit = scanner.nextInt();
System.out.println("Prime numbers up to " + limit + ":");
for (int num = 2; num <= limit; num++) {
if (isPrime(num)) {
System.out.print(num + " ");
}
}
scanner.close();
}
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Output:
Source code
import java.util.Scanner;
public class MatrixMultiplicationExample
{
public static void main(String args[])
{
int row1, col1, row2, col2;
Scanner s = new Scanner(System.in);
// Input dimensions of First Matrix: A
System.out.print("Enter number of rows in first matrix: ");
row1 = s.nextInt();
System.out.print("Enter number of columns in first matrix: ");
col1 = s.nextInt();
// Input dimensions of second matrix: B
System.out.print("Enter number of rows in second matrix: ");
row2 = s.nextInt();
System.out.print("Enter number of columns in second matrix: ");
col2 = s.nextInt();
// Requirement check for matrix multiplication
if (col1 != row2) {
System.out.println("Matrix multiplication is not possible");
return;
}
int a[][] = new int[row1][col1];
int b[][] = new int[row2][col2];
int c[][] = new int[row1][col2];
// Input the values of matrices
System.out.println("\nEnter values for matrix A : ");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) a[i][j] = s.nextInt();
}
System.out.println("\nEnter values for matrix B : ");
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) b[i][j] = s.nextInt();
}
// Perform matrix multiplication
// Using for loop
System.out.println("\nMatrix multiplication is : ");
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
// Initialize the element C(i,j) with zero
c[i][j] = 0;
// Dot product calculation
for (int k = 0; k < col1; k++) {
c[i][j] += a[i][k] * b[k][j];
}
System.out.print(c[i][j] + " ");
}
System.out.println();
}
OUTPUT
Source Code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class TextAnalyzer {
public static void main(String[] args) {
String fileName = "D:/AAA/sample.txt"; // Replace "input.txt" with the
path to your input file
try (BufferedReader br = new BufferedReader(new
FileReader(fileName))) {
String line;
int charCount = 0;
int lineCount = 0;
int wordCount = 0;
while ((line = br.readLine()) != null) {
charCount += line.length();
lineCount++;
StringTokenizer tokenizer = new StringTokenizer(line);
wordCount += tokenizer.countTokens();
}
System.out.println("Number of characters: " + charCount);
System.out.println("Number of lines: " + lineCount);
System.out.println("Number of words: " + wordCount);
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
}
}
}
Output
Source Code
import java.util.Random;
public class RandomNumberGenerator
{
public static void main(String[] args)
{
int lowerLimit = 10;
int upperLimit = 50;
Random random = new Random();
int randomNumber = random.nextInt(upperLimit - lowerLimit + 1) +
lowerLimit;
System.out.println("Generated Random Number: " + randomNumber);
if (randomNumber < 20)
{
System.out.println("The number is less than 20.");
}
else if (randomNumber >= 20 && randomNumber < 40)
{
System.out.println("The number is between 20 and 40 (inclusive).");
}
else
{
System.out.println("The number is greater than or equal to 40.");
}
}
}
Output
Source Code
import java.util.Scanner;
public class StringLengthManipulation
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
char[] charArray = inputString.toCharArray();
int length = charArray.length;
System.out.println("Length of the string: " + length);
scanner.close();
}
}
Output
Source code
import java.util.Scanner;
public class StringPositionManipulation
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
System.out.print("Enter the position (0-indexed): ");
int position = scanner.nextInt();
if (position >= 0 && position < inputString.length())
{
char[] charArray = inputString.toCharArray();
char character = charArray[position];
System.out.println("Character at position " + position + ": " +
character);
} else
{
System.out.println("Invalid position.");
}
scanner.close();
}
}
Output
Source Code
import java.util.Scanner;
public class StringConcatenating {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String firstString = scanner.nextLine();
System.out.print("Enter the second string: ");
String secondString = scanner.nextLine();
char[] firstCharArray = firstString.toCharArray();
char[] secondCharArray = secondString.toCharArray();
int totalLength = firstCharArray.length + secondCharArray.length;
char[] concatenatedCharArray = new char[totalLength];
int index = 0;
for (char c : firstCharArray) {
concatenatedCharArray[index++] = c;
}
for (char c : secondCharArray) {
concatenatedCharArray[index++] = c;
}
String concatenatedString = new String(concatenatedCharArray);
System.out.println("Concatenated string: " + concatenatedString);
scanner.close();
}
}
Output
Source Code
import java.util.Scanner;
class strcon
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string1");
String str1= sc.nextLine();
System.out.println("Enter the string2");
Output
Source code
import java.util.*;
class EvenNum implements Runnable
{
public int a;
public EvenNum(int a)
{
this.a = a;
}
public void run()
{
System.out.println("The Thread "+ a +" is EVEN and Square of " + a + "
is : " + a * a);
}
}
class OddNum implements Runnable
{
public int a;
public OddNum(int a)
{
this.a = a;
}
public void run()
{
System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: "
+ a * a * a);
}
}
class RandomNumGenerator extends Thread
{
public void run()
{
int n = 0;
Random rand = new Random();
try {
for (int i = 0; i < 10; i++)
{
n = rand.nextInt(20);
System.out.println("Generated Number is " + n);
if (n % 2 == 0)
{
Thread thread1 = new Thread(new EvenNum(n));
thread1.start();
}
else {
Thread thread2 = new Thread(new OddNum(n));
thread2.start();
}
Thread.sleep(1000);
System.out.println("------------------------------------");
}
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
public class MultiThreadRandOddEven
{
public static void main(String[] args)
{
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}
Output
Source Code
import java.util.*;
class PrintNumbers implements Runnable
{
private int start;
private int end;
public PrintNumbers(int start, int end)
{
this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++)
{
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
public class ThreadingProgram
{
public static void main(String[] args)
{
// Create two threads for printing numbers asynchronously
Thread thread1 = new Thread(new PrintNumbers(1, 10));
Thread thread2 = new Thread(new PrintNumbers(90, 100));
// Start the threads
thread1.setName("Thread1");
thread2.setName("Thread2");
thread1.start();
thread2.start();
}
}
Output
Source code
import java.util.Scanner;
public class ExceptionDemo
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
try
{
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
Output
Source code
import java.util.Scanner;
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null;
System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println("NullPointerException..");
}
}
}
Output
Source code
import java.util.Scanner;
public class ArrayIndexOutOfBoundException
{
public static void main(String[] args)
{
String[] arr = {"One","Two","Three","Four"};
for(int i=0;i<=arr.length;i++)
{
System.out.println(arr[i]);
}
}
}
Output
Source Code
import java.util.Scanner;
public class NegativeArraySizeExceptionDemo {
public static void main(String[] args) {
try {
// Attempt to create an array with negative size
int[] negativeArray = new int[-5];
} catch (NegativeArraySizeException e) {
System.out.println("Negative Array Size Exception occurred: " +
e.getMessage());
}
}
}
Output
Source Code
import java.util.*;
import java.io.File;
public class FileInformation
{
public static void main(String[] args)
{
// Read file name from the user
String fileName = "D:/demo/sample.txt"; // Provide a default file path if
needed
// You can use Scanner to read input from the user if you're running this
program in a console environment
// Create a File object with the provided file name
File file = new File(fileName);
// Check if the file exists
boolean exists = file.exists();
System.out.println("File exists: " + exists);
// Check if the file is readable
boolean readable = file.canRead();
System.out.println("File is readable: " + readable);
// Check if the file is writable
boolean writable = file.canWrite();
System.out.println("File is writable: " + writable);
// Get the type of file (directory or regular file)
String fileType = "Unknown";
if (file.isDirectory()) {
fileType = "Directory";
} else if (file.isFile()) {
fileType = "Regular file";
}
System.out.println("File type: " + fileType);
// Get the length of the file in bytes
long length = file.length();
System.out.println("File length (bytes): " + length);
}
}
Output
Source code
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextEditorWithFormatting extends JFrame {
private JTextArea textArea;
private JSlider sizeSlider;
private JCheckBox boldCheckBox;
private JCheckBox italicCheckBox;
public TextEditorWithFormatting() {
// Set up the frame
setTitle("Text Editor with Formatting");
setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Create and add text area
textArea = new JTextArea("Type your text here...");
textArea.setFont(new Font("Arial", Font.PLAIN, 14));
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
// Create and add controls panel
JPanel controlsPanel = new JPanel();
sizeSlider = new JSlider(8, 36, 14);
boldCheckBox = new JCheckBox("Bold");
italicCheckBox = new JCheckBox("Italic");
sizeSlider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
int newSize = sizeSlider.getValue();
Font currentFont = textArea.getFont();
textArea.setFont(new Font(currentFont.getFontName(),
currentFont.getStyle(), newSize));
}
});
boldCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
applyFontStyle();
}
});
italicCheckBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
applyFontStyle();
}
});
controlsPanel.add(new JLabel("Font Size:"));
controlsPanel.add(sizeSlider);
controlsPanel.add(boldCheckBox);
controlsPanel.add(italicCheckBox);
add(controlsPanel, BorderLayout.SOUTH);
}
private void applyFontStyle() {
int style = Font.PLAIN;
if (boldCheckBox.isSelected()) {
style |= Font.BOLD;
}
if (italicCheckBox.isSelected()) {
style |= Font.ITALIC;
}
Font currentFont = textArea.getFont();
textArea.setFont(new Font(currentFont.getFontName(), style,
currentFont.getSize()));
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TextEditorWithFormatting app = new TextEditorWithFormatting();
app.setVisible(true);
}
});
}
}
Output
Source Code
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame {
String event;
public MyFrame(String title) {
super(title);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
event = "Mouse Clicked";
repaint();
}
public void mousePressed(MouseEvent e) {
event = "Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e) {
event = "Mouse Released";
repaint();
}
public void mouseEntered(MouseEvent e) {
event = "Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent e) {
event = "Mouse Exited";
repaint();
}
});
setSize(400, 400);
setVisible(true);
}
public void paint(Graphics g) {
// Clear the previous event
g.clearRect(0, 0, getWidth(), getHeight());
// Get the center coordinates of the window
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
// Set font and color for displaying the event name
g.setFont(new Font("Times New Roman", Font.BOLD, 30));
g.setColor(Color.RED);
// Draw the event name at the center of the window
g.drawString(event, centerX - 50, centerY);
}
}
public class MouseEventDemo {
public static void main(String[] args) {
new MyFrame("Mouse Event Demo");
}
}
Output
Source Code
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Cal" width=300 height=300>
</applet>
*/
public class Cal extends Applet
implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}
Output
Source code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TrafficLightSimulator1 extends JFrame implements ActionListener
{
private JRadioButton redButton, yellowButton, greenButton;
private JLabel messageLabel;
public TrafficLightSimulator1()
{
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");
ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(yellowButton);
group.add(greenButton);
redButton.addActionListener(this);
yellowButton.addActionListener(this);
greenButton.addActionListener(this);