Random number generator
package RandomNumberGenerator;
//public class [Link] {
//}
import [Link].*;
import [Link].*;
import [Link].*;
public class RandomNumberGenerator extends JFrame implements
ActionListener {
private JTextField textField;
private JButton button;
private JButton resetButton;
public RandomNumberGenerator() {
setTitle("Random Number Generator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(350, 200);
setLayout(new FlowLayout());
JPanel panel = new JPanel();
[Link](new BoxLayout(panel,
BoxLayout.Y_AXIS));
JLabel titleLabel = new JLabel("Click the button below
to generate a random number.");
[Link]([Link]);
add(titleLabel);
button = new JButton("Click here");
[Link]([Link]);
[Link]([Link]);
[Link](this);
add(button);
textField = new JTextField(20);
[Link](false);
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
add(textField);
resetButton = new JButton("Reset");
[Link](this);
add(resetButton);
}
public void actionPerformed(ActionEvent e) {
if ([Link]() == button) {
[Link]([Link]((int)
([Link]() * 1000000)));
} else if ([Link]() == resetButton) {
[Link]("");
}
}
public static void main(String[] args) {
RandomNumberGenerator randomNumberGenerator = new
RandomNumberGenerator();
[Link](true);
}
}
Table
package Table;
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class CSVTable {
public static void main(String[] args) {
String fileName = "[Link]";
List<String> headings = new ArrayList<>();
List<List<String>> data = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new
FileReader(fileName));
String line;
while ((line = [Link]()) != null) {
String[] values = [Link]("\\|");
if ([Link]()) {
for (String value : values) {
[Link]([Link]());
}
} else {
List<String> row = new ArrayList<>();
for (String value : values) {
[Link]([Link]());
}
[Link](row);
}
}
[Link]();
} catch (Exception e) {
[Link]();
}
[Link](() -> {
try {
[Link]([Link]
me());
} catch (Exception e) {
[Link]();
}
String[] columnNames = [Link](new
String[0]);
Object[][] rowData = new Object[[Link]()][];
for (int i = 0; i < [Link](); i++) {
rowData[i] = [Link](i).toArray();
}
DefaultTableModel model = new
DefaultTableModel(rowData, columnNames);
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("CSV Table");
[Link](JFrame.EXIT_ON_CLOSE);
[Link]().add(scrollPane);
[Link]();
[Link](null);
[Link](true);
});
}
}
[Link]
Name|Gender|Age|Preference
mrit Kumar|M|20|Veg
Arit Kumari|F|21|Non-Veg
Amit Kum|M|20|Veg
Amrt Kuma|M|10|Non-Veg
Sum of numbers in line
package PresentTheSum;
import [Link];
public class SumOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a line containing
numbers:");
String inputLine = [Link]();
try {
int sum = calculateSumOfNumbers(inputLine);
[Link]("Sum of numbers in the input
line: " + sum);
} catch (NumberFormatException e) {
[Link]("Error: Non-numeric characters
encountered. Ignoring them.");
}
}
private static int calculateSumOfNumbers(String inputLine)
throws NumberFormatException {
Scanner lineScanner = new Scanner(inputLine);
int sum = 0;
while ([Link]()) {
if ([Link]()) {
sum += [Link]();
} else {
// If the next token is not an integer, ignore
it
[Link]();
}
}
return sum;
}
}
Name Validator
package NameValidator;
import [Link].*;
import [Link].*;
class InvalidNameFormatException extends Exception {
public InvalidNameFormatException(String message) {
super(message);
}
}
public class NameValidator extends Frame implements
ActionListener {
TextField tf;
Button btn;
Label label;
public NameValidator() {
tf = new TextField(20);
btn = new Button("Validate");
label = new Label("");
setLayout(new FlowLayout());
add(tf);
add(btn);
add(label);
[Link](this);
}
public void actionPerformed(ActionEvent e) {
String name = [Link]();
try {
validateName(name);
[Link]("OK");
} catch (InvalidNameFormatException ex) {
[Link]("Invalid name");
}
}
public void validateName(String name) throws
InvalidNameFormatException {
if ([Link](".*\\d.*")) {
throw new InvalidNameFormatException("Invalid
name. It should not contain numbers.");
}
}
public static void main(String[] args) {
NameValidator frame = new NameValidator();
[Link]("Name Validator");
[Link](300, 100);
[Link](true);
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
});
}
}
Coffeemaker
AbstractCoffeeMaker
package CoffeeMaker;
import [Link];
import [Link];
public abstract class AbstractCoffeeMaker implements
CoffeeMaker {
private Map<String, Integer> ingredients;
public AbstractCoffeeMaker() {
ingredients = new HashMap<>();
}
protected void addIngredient(String name, int quantity) {
[Link](name, quantity);
}
protected boolean checkIngredients(String name, int
quantity) {
return [Link](name, 0) >= quantity;
}
public void brew() {
// default brewing process
}
public void serve() {
// default serving process
}
}
BlackCoffee
package CoffeeMaker;
public class BlackCoffee extends AbstractCoffeeMaker {
public BlackCoffee() {
addIngredient("coffee", 10);
}
@Override
public void brew() {
// brew black coffee recipe
}
@Override
public void serve() {
// serve black coffee
}
}
Cappuccino
package CoffeeMaker;
public class Cappuccino extends AbstractCoffeeMaker {
public Cappuccino() {
addIngredient("coffee", 10);
addIngredient("milk", 150);
addIngredient("foamed milk", 10);
}
@Override
public void brew() {
// brew cappuccino recipe
}
@Override
public void serve() {
// serve cappuccino
}
}
Interface Coffeemaker
package CoffeeMaker;
public interface CoffeeMaker {
void brew();
void serve();
}
Lattee
package CoffeeMaker;
public class Latte extends AbstractCoffeeMaker {
public Latte() {
addIngredient("coffee", 10);
addIngredient("milk", 150);
}
@Override
public void brew() {
// brew latte recipe
}
@Override
public void serve() {
// serve latte
}
}
Scientific calculator
AbstractScientificCalculator
package ScientificCalculator;
import [Link];
import [Link];
public abstract class AbstractScientificCalculator implements
ScientificCalculator {
protected Map<Integer, Double> factorialMap = new
HashMap<>();
@Override
public double logarithm(double number, double base) {
return [Link](number) / [Link](base);
}
@Override
public double exponential(double number, double power) {
return [Link](number, power);
}
@Override
public double root(double number, double degree) {
return [Link](number, 1.0 / degree);
}
@Override
public double factorial(int number) {
if (number == 0 || number == 1) {
return 1;
}
if ([Link](number)) {
return [Link](number);
}
double factorial = number * factorial(number - 1);
[Link](number, factorial);
return factorial;
}
}
BasicScientificCalculator
package ScientificCalculator;
public class BasicScientificCalculator extends
AbstractScientificCalculator {
public static void main(String[] args) {
BasicScientificCalculator calculator = new
BasicScientificCalculator();
double logarithm = [Link](100, 10);
double exponential = [Link](2, 3);
double root = [Link](8, 2);
double factorial = [Link](5);
[Link]("Logarithm: " + logarithm);
[Link]("Exponential: " + exponential);
[Link]("Root: " + root);
[Link]("Factorial: " + factorial);
}
}
Interface ScientificCalculator
package ScientificCalculator;
public interface ScientificCalculator {
double logarithm(double number, double base);
double exponential(double number, double power);
double root(double number, double degree);
double factorial(int number);
}
Shape
Circle
package Shape;
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
[Link] = radius;
}
@Override
void draw() {
[Link]("Drawing a circle with radius " +
radius);
}
@Override
double calculateArea() {
return [Link] * radius * radius;
}
}
Main
package Shape;
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape square = new Square(4);
Shape triangle = new Triangle(3, 2);
[Link]();
[Link]();
[Link]();
[Link]("Area of circle: " +
[Link]());
[Link]("Area of square: " +
[Link]());
[Link]("Area of triangle: " +
[Link]());
}
}
Abstract class Shape
package Shape;
public abstract class Shape {
abstract void draw();
abstract double calculateArea();
}
Square
package Shape;
public class Square extends Shape {
private double side;
public Square(double side) {
[Link] = side;
}
@Override
void draw() {
[Link]("Drawing a square with side length
" + side);
}
@Override
double calculateArea() {
return side * side;
}
}
Triangle
package Shape;
public class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
[Link] = base;
[Link] = height;
}
@Override
void draw() {
[Link]("Drawing a triangle with base " +
base + " and height " + height);
}
@Override
double calculateArea() {
return 0.5 * base * height;
}
}
String manipulation
package StringManipulation;
import [Link];
import [Link];
public class StringManipulationProgram {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
String input;
do {
[Link]("Select an option:");
[Link]("a. String compare");
[Link]("b. String compare ignoring
case");
[Link]("c. String reverse");
[Link]("d. Change to uppercase");
[Link]("e. Change to lowercase");
[Link]("f. END");
char choice = [Link]().charAt(0);
[Link](); // Consume the newline
character
switch (choice) {
case 'a':
[Link]("Enter the first
string:");
String str1 = [Link]();
[Link]("Enter the second
string:");
String str2 = [Link]();
compareStrings(str1, str2);
break;
case 'b':
[Link]("Enter the first
string:");
String str3 = [Link]();
[Link]("Enter the second
string:");
String str4 = [Link]();
compareStringsIgnoreCase(str3, str4);
break;
case 'c':
[Link]("Enter the string to
reverse:");
input = [Link]();
reverseString(input);
break;
case 'd':
[Link]("Enter the string to
convert to uppercase:");
input = [Link]();
toUpperCase(input);
break;
case 'e':
[Link]("Enter the string to
convert to lowercase:");
input = [Link]();
toLowerCase(input);
break;
case 'f':
[Link]("Program ended.
Goodbye!");
break;
default:
[Link]("Invalid option. Please
try again.");
}
} while ([Link]() && [Link]().charAt(0)
!= 'f');
[Link]();
}
private static void compareStrings(String str1, String
str2) {
if ([Link](str2)) {
[Link]("The strings are equal.");
} else {
[Link]("The strings are not equal.");
}
}
private static void compareStringsIgnoreCase(String str1,
String str2) {
if ([Link](str2)) {
[Link]("The strings are equal
(ignoring case).");
} else {
[Link]("The strings are not equal
(ignoring case).");
}
}
private static void reverseString(String str) {
StringBuilder reversed = new
StringBuilder(str).reverse();
[Link]("Reversed string: " + reversed);
}
private static void toUpperCase(String str) {
[Link]("Uppercase: " + [Link]());
}
private static void toLowerCase(String str) {
[Link]("Lowercase: " + [Link]());
}
}
Employee Salary
PayrollProcessor
package [Link];
import [Link].*;
public class PayrollProcessor {
public static void printEmployeeDetails(Employee employee)
{
[Link]("Employee Details:");
[Link]("Name: " + [Link]());
[Link]("Employee ID: " +
[Link]());
[Link]("Category: " +
[Link]());
[Link]("Basic Pay: " +
[Link]());
[Link]("HRA: " + [Link]());
[Link]("DA: " + [Link]());
[Link]("Gross Pay: " +
[Link]());
[Link]("Income Tax: " +
[Link]());
[Link]("Allowance: " +
[Link]());
}
public static void main(String[] args) {
// Example usage
Employee employee = new Employee("John Doe", 101,
"Permanent", 50000.0);
printEmployeeDetails(employee);
}
}
Employee
package [Link];
public class Employee {
private String name;
private int employeeId;
private String category;
private double basicPay;
public Employee(String name, int employeeId, String
category, double basicPay) {
[Link] = name;
[Link] = employeeId;
[Link] = category;
[Link] = basicPay;
}
public double calculateHRA() {
return 0.1 * basicPay;
}
public double calculateDA() {
return 0.05 * basicPay;
}
public double calculateGrossPay() {
return basicPay + calculateHRA() + calculateDA();
}
public double calculateIncomeTax() {
return 0.4 * calculateGrossPay();
}
public double calculateAllowance() {
return 0.02 * basicPay;
}
public String getName() {
return name;
}
public int getEmployeeId() {
return employeeId;
}
public String getCategory() {
return category;
}
public double getBasicPay() {
return basicPay;
}
}
Inner Class
package Innerclass;
// Outer class
class OuterClass {
// Member Inner class
class MemberInner {
void display() {
[Link]("Member Inner class");
}
}
// Anonymous Inner class
void anonymousInnerMethod() {
// Anonymous Inner class inside a method
Runnable runnable = new Runnable() {
@Override
public void run() {
[Link]("Anonymous Inner class");
}
};
new Thread(runnable).start();
}
// Local Inner class
void localInnerMethod() {
class LocalInner {
void display() {
[Link]("Local Inner class");
}
}
LocalInner localInner = new LocalInner();
[Link]();
}
// Static Nested class
static class StaticNested {
void display() {
[Link]("Static Nested class");
}
}
// Nested Interface
interface NestedInterface {
void show();
}
}
public class InnerClassExample {
public static void main(String[] args) {
// Creating an instance of the outer class
OuterClass outer = new OuterClass();
// Member Inner class
[Link] memberInner = [Link]
MemberInner();
[Link]();
// Anonymous Inner class
[Link]();
// Local Inner class
[Link]();
// Static Nested class
[Link] staticNested = new
[Link]();
[Link]();
// Nested Interface
[Link] nestedInterface = new
[Link]() {
@Override
public void show() {
[Link]("Nested Interface");
}
};
[Link]();
}
}
Relative Date of Birth
package RelativeLatest;
import [Link].*;
public class SortDates {
static Map<String, Integer> monthsMap = new HashMap<>();
// Function which initializes the monthsMap
static void sortMonths() {
[Link]("Jan", 1);
[Link]("Feb", 2);
[Link]("Mar", 3);
[Link]("Apr", 4);
[Link]("May", 5);
[Link]("Jun", 6);
[Link]("Jul", 7);
[Link]("Aug", 8);
[Link]("Sep", 9);
[Link]("Oct", 10);
[Link]("Nov", 11);
[Link]("Dec", 12);
}
static int cmp(String date) {
String[] dateParts = [Link](" ");
int day = [Link](dateParts[0]);
int month = [Link](dateParts[1]);
int year = [Link](dateParts[2]);
return year * 10000 + month * 100 + day;
}
// Utility function to print the contents
// of the array
static void printDates(String[] dates, int n) {
for (int i = 0; i < n; i++) {
[Link](dates[i]);
}
}
public static void main(String[] args) {
String[] dates = { "24 Jul 2017", "25 Jul 2017", "11
Jun 1996",
"01 Jan 2019", "12 Aug 2005", "01 Jan 1997" };
int n = [Link];
// Order the months
sortMonths();
// Sort the dates
[Link](dates, (a, b) -> cmp(a) - cmp(b));
// Print the sorted dates
printDates(dates, n);
}
}
// This code is contributed by Prince Kumar