0% found this document useful (0 votes)
1 views35 pages

JAVA Sourcecode

The document contains multiple Java source code examples demonstrating various programming concepts, including prime number generation, matrix multiplication, text file analysis, random number generation, string manipulation, multithreading, and exception handling. Each code snippet is structured to perform specific tasks, such as calculating prime numbers, concatenating strings, or handling file operations. The examples illustrate fundamental programming techniques and Java's capabilities in handling user input, data structures, and error management.

Uploaded by

nawinrithishgp
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)
1 views35 pages

JAVA Sourcecode

The document contains multiple Java source code examples demonstrating various programming concepts, including prime number generation, matrix multiplication, text file analysis, random number generation, string manipulation, multithreading, and exception handling. Each code snippet is structured to perform specific tasks, such as calculating prime numbers, concatenating strings, or handling file operations. The examples illustrate fundamental programming techniques and Java's capabilities in handling user input, data structures, and error management.

Uploaded by

nawinrithishgp
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
You are on page 1/ 35

Source Code

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");

String str2= sc.nextLine();


System.out.println(" concatenated String : "+concat(str1,str2));
}
static String concat( String s1,String s2)
{
String s=s1+','+s2;
return s;
}
}
Output:
Source code
import java.util.Scanner;
public class Substrings
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
Substrings(inputString);
scanner.close();
}
private static void Substrings(String inputString)
{
int length = inputString.length();
System.out.println("All substrings of the given string:");
for (int i = 0; i < length; i++)
{
for (int j = i + 1; j <= length; j++)
{
String substring = inputString.substring(i, j);
System.out.println(substring);
}
}
}
output
Source code
public class Substringc
{
public static void main(String[] args)
{
String s1="Java programming";
String substr = s1.substring(0);
System.out.println(substr);
String substr2 = s1.substring(5,10);
System.out.println(substr2);
String substr3 = s1.substring(5,15);
}
}
Output
Source Code
import java.util.Scanner;
public class LengthofString {
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
StringBuffer stringBuffer = new StringBuffer(inputString);
int length = stringBuffer.length();
System.out.println("Length of the string: " + length);
scanner.close();
}
}
Output
Source code
import java.util.Scanner;
public class ReverseString
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
StringBuffer stringBuffer = new StringBuffer(inputString);
stringBuffer.reverse();
String reversedString = stringBuffer.toString();
System.out.println("Reversed string: " + reversedString);
scanner.close();
}
}
Output
Source Code:
import java.util.Scanner;
public class DeleteString
{
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 substring to delete: ");
String substringToDelete = scanner.nextLine();
StringBuffer stringBuffer = new StringBuffer(inputString);
int index = stringBuffer.indexOf(substringToDelete);
if (index != -1) {
stringBuffer.delete(index, index + substringToDelete.length());
String modifiedString = stringBuffer.toString();
System.out.println("Modified string: " + modifiedString);
}
else
{
System.out.println("Substring not found in the given string.");
}
scanner.close();
}
}

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);

JPanel buttonPanel = new JPanel();


buttonPanel.add(redButton);
buttonPanel.add(yellowButton);
buttonPanel.add(greenButton);
messageLabel = new JLabel();
messageLabel.setHorizontalAlignment(JLabel.CENTER);
messageLabel.setFont(new Font("Impact ", Font.BOLD, 30));
Container container = getContentPane();
container.setLayout(new BorderLayout());
container.add(buttonPanel, BorderLayout.CENTER);
container.add(messageLabel, BorderLayout.NORTH);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == redButton) {
messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED);
} else if (e.getSource() == yellowButton) {
messageLabel.setText("Ready");
messageLabel.setForeground(Color.YELLOW);
} else if (e.getSource() == greenButton) {
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TrafficLightSimulator1 trafficLightSimulator = new
TrafficLightSimulator1();
trafficLightSimulator.setVisible(true);
});
}
}
Output

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy