Armstrong Number Matrix Add mul transpose
int no, a,s=0; Public class setb3{
System.out.println(“Enter a number:”); Static int[][] m1;
no= sc.nextInt(); Static int[][] m2;
Num=no; Static int r ,c , I , j;
While(no>0){ Public static int[][] transpose( int
A=no%10; m[][]) {
S=s+a*a*a; Int[][] t = new int[c][r];
No=no/10;}
For(I = 0 ; I < r ; i++) {
If(num == s) print armstrong else no
For(j = 0 ; j < c ; j++){
Simple Date Format
T[j][i] = m[i][j];}}
Date dt = new Date();
Return t; }
String std;
SimpleDateFormat sdf = Public static int[][] multiply() {Int k;
new SimpleDateFormat("dd/MM/yyyy") Int[][] prod = new int[r][c];
std = sdf.format(dt); For(I = 0 ; I < r ; i++) {
System.out.println("Current date : " +st For(j = 0 ; j < c ; j++){
Check Negative positive through Prod[i][j] = 0;
commandline For(k = 0 ; k < c ; k++) {
Public class b2{ Prod[i][j] =
Int num; prod[i][j]+m1[i][k]*m2[k][j];}}}Return
Public MyNumber(){Num=0;} prod;}
Public int MyNumber(int void main Case 1 : int[][] sum =
num){This.num=num;} addition();
Public int isNegative(int num){
Case 2 : int[][] prod = multiply();
If(num<0)Return 1;Return-1;}
Public static void main(String args[]){ Case 3:print(“Transpose of the
If(args.length>0){ Matrix 1 :”);
Int n=Integer.parseInt(args[0]); Int[][] tr1 = transpose(m1);
MyNumber obj=new MyNumber(n);
Multiplication Table
If(obj.isNegative(n)==1)
println(n+” is Negative”);Else void main(String[] args) {
System.out.println(n+”is not Negative”) for (int i = 1; i <= 15; i++) {
Else{System.out.println(“Insufficient println("Table of " + i + ":");
Arguments”);}}} for (int j = 1; j <= 10; j++) {
println(i + " * " + j + " = " + (i * j));}
println(); } } }
Prime number function to check Interface ‘operations’,two
public static boolean isPrime(int num) { methods,calculate area and volume of
if (num <= 1) { cylinder
return false; } import java.util.Scanner;
for (int i = 2; i <= Math.sqrt(num); i++) interface operation{
if (num % i == 0) { double PI = 3.14;
return false; } } public double area();
return true;}} public double volume();}
To print n prime numbers class Cylinder implements operation{
for (int i = start; i <= end; i++) { double r, h;
if (isPrime(i)) {System.out.println(i); } } } public Cylinder(double r, double h) {
this.r = r;
Accept 5 nos using commandline this.h = h; }
Public class A3{
void main(String[] args){ public double area() {
Int I; return 2*PI*r*(r+h); }
If(args.length == 5){ public double volume(){
Int[] num = new int[5]; return PI*r*r*h; }
For(I = 0; i<args.length; i++){ public static void main(String[] args) {
Num[i] = Integer.parseInt(args[i]); } double r, h;
Arrays.sort(num); System.out.print("Enter radius: ");
System.out.println(“Sorted Numbers : “ Scanner sc = new Scanner(System.in);
For(i=0 ; i<num.length ; i++){ r = sc.nextDouble();
System.out.print(num[i]+” “);}} System.out.print("Enter Height: ");
Else{ h = sc.nextDouble();
System.out.println(“Provide exactly 5 operation p;
numbers”);} } } p = new Cylinder(r, h);
System.out.println("Area is:
"+p.area());System.out.println("Volum is:
"+p.volume());
}
}
Create employee class, define a default, use ‘this’ to initialise variable
Class employee{ Int id; String name; String deptName;Double salary;
Static int cnt = 0;
Employee(){ Cnt++;}
Employee(i id,name,deptName,salary){
This.id = id; This.name = name;
This.deptName = deptName; This.salary = salary;
Cnt++;
println(“object count after creation :” +cnt);}
Void display(){println(this.id+”\t\t”+this.name+”\t\t
+this.deptName+”\t\t”+ this.salary);}
void main(String[] args){
Scanner sc=new Scanner(System.in);
println(“Enter no of employes:”);
Int n = sc.nextInt();
Employee[] emp = new employee[n];
For( int i=0;i<n;i++){
println(“enter data for employee” +(i+1)+”:”);
System.out.println(“Enetr id:”);
Int id= sc.nextInt();
Sc.nextLine();
System.out.println(“Enter employee name:”);
String name = sc.nextLine();
System.out.println(“Enter dept name:”);
String deptName = sc.nextLine();
System.out.println(“Enter salary name:”);
Double salary = sc.nextDouble();
Emp[i] = new employee(id,name,deptName,salary);}
System.out.println(“Enter employee record:”);
System.out.println(“id\temployee Name \t\t dept name \t salary”);
For(int i=0;i<n;i++){Emp[i].display();}}}
Define class Student to create n objects, accept details, sort
import java.util.Scanner;
import java.util.Arrays;
class a2{int rno;String name;double pers;
a2(rno,name, pers){
this.rno = rno; this.name = name; this.pers=pers;}
void display(){
println(this.rno +"\t\t"+this.name +"\t\t"+ this.pers);}
static void sortStudent(a2[] student){
Arrays.sort(student,(s1,s2)-> Double.compare(s2.pers, s1.pers));}
void main(String[] args){
Scanner sc=new Scanner(System.in);
println("Enter no of student:");
int n = sc.nextInt();
sc.nextLine();
a2[] student = new a2[n];
for( int i=0;i<n;i++){
System.out.println("enter data for student" +(i+1)+":");
System.out.println("Enter roll no:");
int rno= sc.nextInt();
sc.nextLine();
System.out.println("Enter student name:");
String name = sc.nextLine();
System.out.println("Enter percentage:");
double pers = sc.nextDouble();
student[i] = new a2(rno, name, pers);}
a2.sortStudent(student);
System.out.println("Enter student record:");
System.out.println("rno\tstdent Name \t\t percentage");
for(a2 a2:student){
a2.display();}sc.close();}}
Define class cricket, calculate batting avg ,sort
import java.util.Scanner; public class Cricket{String name; int innings; int not_out;
int total_runs; double bat_avg;
public Cricket( name ,innings , not_out ,total_runs) {
this.name = name;this.innings = innings;this.not_out = not_out;
this.total_runs = total_runs;this.bat_avg = avg(total_runs , innings , not_out); }
public static double avg(total_runs , innings , not_out) {
if(innings - not_out > 0) return total_runs/(innings - not_out);
else return total_runs; }
public static void sort(Cricket[] players) {
int n , i , j; n = players.length;
for(i = 0 ; i < n-1 ; i++){ for(j = 0 ; j < n-i-1 ; j++){
if(players[j].bat_avg < players[j+1].bat_avg) {
Cricket temp = players[j];
players[j] = players[j+1];
players[j+1] = temp; } } } }
public void display() {
println("Name : "+name);and remaining details}
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int n , i , innings , not_out, total_runs;
String name;
print("Enter the number of players : ");
n = inp.nextInt();
Cricket[] players = new Cricket[n];
for(i = 0 ; i < n ; i++) {
println("Enter details for player "+(i+1)+":");
print("Name : "); name = inp.next();
print("No. of innings : "); innings = inp.nextInt();
print("No. of times not out : ");
not_out = inp.nextInt(); print("Total runs : ");
total_runs = inp.nextInt();
players[i] = new Cricket(name , innings, not_out , total_runs); }
Cricket.sort(players); println("\nPlayer Details in sorted order of batting average : ");
for(i = 0 ; i<n ; i++) { players[i].display(); } }}
TY,SYfolder calculate grade
TY File
package TY; public class TYMarks{
public int Theory;public int Practicals;
public TYMarks(int theory , int pract){
this.Theory = theory;
this.Practicals = pract; }}
SY File
package SY;
public class SYMarks{
public int ComputerTotal;
public int MathsTotal;
public int ElectronicsTotal;
public SYMarks(CompT,MathT,ElecT){
this.ComputerTotal = CompT;
this.MathsTotal = MathT;
this.ElectronicsTotal = ElecT;}
Main File
import java.util.Scanner;
import SY.*;
import TY.*;
public class Students{int rollno;String name;SYMarks sy;TYMarks ty;
public Students(rollno , name ,SYMarks sy ,TYMarks ty){
this.rollno = rollno;his.name = name;this.sy = sy;this.ty = ty;}
public void display() {int total = sy.ComputerTotal + ty.Theory;
String grade; if(total>=70)grade="A";else if(total>=60)grade="B";
elseif(total>=50)grade="C";else if(total>=40)grade="Pass";else grade="Fail";
println("\nRoll No. : "+rollno);println("Name : "+name);
println("Total Computer Marks : "+total);println("Grade : "+grade); }
public static void main(String[] args) {
Scanner inp = new Scanner(System.in); int n ,i,rollno;
String name; System.out.print("Enter number of students : ");
n = inp.nextInt(); inp.nextLine();
for(i = 0 ; i<n ; i++){
println("Enter details of Student "+(i+1)+":");
print("Roll No. : ");
rollno = inp.nextInt();
inp.nextLine();
System.out.print("Name : ");
name = inp.nextLine();
System.out.println("\nEnter SY Marks : ");
System.out.print("Computer : ");
int comp = inp.nextInt();
System.out.print("Math : ");
int math = inp.nextInt();
System.out.print("Electronics : ");
int elec = inp.nextInt();
SYMarks sy = new SYMarks(comp , math , elec);
System.out.println("\nEnter TY Marks : ");
System.out.print("Theory : ");
int theory = inp.nextInt();
System.out.print("Practical : ");
int pract = inp.nextInt();
TYMarks ty = new TYMarks(theory , pract);
Students stds = new Students(rollno , name , sy , ty);
stds.display(); } }}
Get Full name, reverse, First letter capital
import java.util.Scanner;
public class a4{
public static void main(String[] args) {
String name , fname , mname , lname , capt;
Scanner inp = new Scanner(System.in);
System.out.print("Enter your name (first middle last) : ");
name = inp.nextLine();
String[] nameparts = name.split(" ");
if(nameparts.length != 3){
System.out.println("ERROR- Enter name in the format 'first middle last' : ");
return; }
fname = nameparts[0];
mname = nameparts[1];
lname = nameparts[2];
capt = mname.substring(0,1).toUpperCase() + mname.substring(1).toLowerCase();
System.out.println("Name : "+ lname + " " + fname + " " + capt); }}
Read Text file and display content of file
import java.io.*;
public class a2{
public static void main(String[] args) {
File f = new File("sample.txt");
if (!f.exists()) {
System.out.println("File not found!");
System.exit(0); }
try {FileReader file_reader = new FileReader(f);
BufferedReader buf_reader = new BufferedReader(file_reader);
StringBuilder content = new StringBuilder();
String line;
System.out.println("Original content in UPPER CASE:");
while ((line = buf_reader.readLine()) != null) {
System.out.println(line.toUpperCase());
content.append(line).append("\n"); }
buf_reader.close();
System.out.println("\nContent in Reverse Order:");
System.out.println(content.reverse().toString()); } catch (IOException e) {
System.out.println("IO exception = " + e); } }}
Multilevel Inheritance country from continent
interface Continent {
String getContinentName();}
class Country implements Continent {
String continentName;
String countryName;
Country(String continentName, String countryName) {
this.continentName = continentName;
this.countryName = countryName; }
// @Override
public String getContinentName() {
return continentName; }
public String getCountryName() {
return countryName; }}
class State extends Country {
String stateName;
String placeName;
State(String continentName, String countryName, String stateName, String
placeName) {
super(continentName, countryName);
this.stateName = stateName;
this.placeName = placeName; }
public String getStateName() {return stateName; }
public String getPlaceName() {return placeName;}
public void displayDetails() {
System.out.println("Place: " + getPlaceName());
System.out.println("State: " + getStateName());
System.out.println("Country: " + getCountryName());
System.out.println("Continent: " + getContinentName()); }}
public class a1{
public static void main(String[] args) {
State place = new State("Asia", "India", "Maharashtra", "pune");
place.displayDetails(); } }
Abstract class Staff with protected details define one subclass
import java.util.Scanner;
abstract class Staff {
protected int id;
protected String name;
public Staff(int id, String name) {
this.id = id;
this.name = name; }
abstract void displayDetails();}
class OfficeStaff extends Staff {
private String department;
public OfficeStaff(int id, String name, String department) {
super(id, name);
this.department = department; }
@Override
void displayDetails() {
println("ID: " + id); println("Name: " + name);
println("Department: " + department); System.out.println("----"); }}
public class a2{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of OfficeStaff members: ");
int n = scanner.nextInt();
scanner.nextLine();
OfficeStaff[] staffArray = new OfficeStaff[n];
for (int i = 0; i < n; i++) {
System.out.println("Enter details for OfficeStaff " + (i + 1));
System.out.print("Enter ID: ");
int id = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Name: ");
String name = scanner.nextLine();
System.out.print("Enter Department: ");
String department = scanner.nextLine();
staffArray[i] = new OfficeStaff(id, name, department); }
System.out.println("\nDetails of OfficeStaff members:");
for (OfficeStaff staff : staffArray) { staff.displayDetails(); }scanner.close(); }}
Abstract class order, mem id, description, two sub classes,accept sale
purchase order define default parameterized constructor
import java.util.Scanner;
abstract class order{ int id;String description;abstract void accept();
abstract void display();}
class purchaseOrder extends order{
Scanner sc = new Scanner(System.in);
String customerName;
void accept() {
println("Enter Customer Name");
this.customerName = sc.nextLine();
println("Enter Customer id");
this.id = sc.nextInt();
sc.nextLine();
println("Enter Purchase Description:");
this.description = sc.nextLine(); }
void display() {
println("Customer Name:"+this.customerName);
println("Customer Id:"+this.id);
println("Description:"+this.description);
println(); } }
class salesOrder extends order{
Scanner sc = new Scanner(System.in);
String vendorName;
void accept(){ println("Enter Vendor Name");
this.vendorName = sc.nextLine();
println("Enter Vendor id"); this.id = sc.nextInt(); sc.nextLine();
println("Enter vendor Description:");
this.description = sc.nextLine(); }
void display() {
println("Vendor Name:"+this.vendorName);println("Vendor Id:"+this.id);
println("Description:"+this.description);println(); }}
public class b1{public static void main(String args[]) {
salesOrder o1,o2,o3 = new salesOrder();
purchaseOrder p1,p2,p3 = new purchaseOrder();
o1,o2,o3,p1,p2,p3.accept();println("Customer Info:"); o1,o2,o3.display();
System.out.println("Vendor Info: "); p1,p2,p3.display(); }}
Marker interface create class define constructor create obj and disp content
import java.util.*;
interface MarkerInt{}
class product implements MarkerInt{
int pid,pcost,quantity;String pname;static int cnt;
product(){ pid=1; pcost=10; quantity=1; pname="Pencil"; cnt++;}
product(int pid,String pname,int pcost,int quantity){
this.pid=pid; this.pname=pname; this.pcost=pcost; this.quantity=quantity;
cnt++;
System.out.println("Count of object is : "+cnt+"\n");}
void display(){
System.out.println("|\t"+pid+"\t"+pname+"\t"+pcost+"\t\t"+quantity+"\t|");}}
public class B2{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter no of Product : ");
int n=sc.nextInt();
product p[]=new product[n];
for(int i=0;i<n;i++){
System.out.println("Enter Product "+(i+1)+" Details:\n");
System.out.println("Enter Product ID : ");
int pid=sc.nextInt();
sc.nextLine();
System.out.println("Enter Product Name : ");
String pn=sc.nextLine();
System.out.println("Enter Product Cost : ");
int pc=sc.nextInt();
System.out.println("Enter Product Quantity : ");
int pq=sc.nextInt();
p[i]=new product(pid,pn,pc,pq);}
System.out.println("\n******************Product Details****************** \n");
System.out.println("|\tPID\tPname\tCost\tQuantity\t|");
for(int i=0;i<n;i++)
p[i].display();
sc.close();}}
Covid Exception Handeling
import java.util.Scanner;
class CovidPositiveException extends Exception {
CovidPositiveException(String message) {
super(message); }}
class Patient {
String patient_name; int patient_age;double patient_oxy_level;
int patient_HRCT_report;
Patient(String name, int age, double oxyLevel, int hrctReport) {
this.patient_name = name;
this.patient_age = age;
this.patient_oxy_level = oxyLevel;
this.patient_HRCT_report = hrctReport; }
void checkCondition() throws CovidPositiveException {
if (patient_oxy_level < 95.0 && patient_HRCT_report > 10) {
throw new CovidPositiveException("Patient has Covid and Needs to be admitted");
} else {displayInfo(); } }
void displayInfo() {
println("Patient Name: " + patient_name);
println("Patient Age: " + patient_age);
println("Oxygen Level: " + patient_oxy_level);
println("HRCT Report: " + patient_HRCT_report); }}
public class a1{public static void main(String[] args) {
Patient(patient_name,patient_age,patient_oxy_level,patient_HRCT_report);
Scanner sc = new Scanner(System.in);
System.out.println("enter name");
String name = sc.nextLine();
System.out.println("enter age");
int age = sc.nextInt();
System.out.println("enter oxy level");
double oxylevel = sc.nextInt();
System.out.println("enter hrtc report");
int HRCTreport = sc.nextInt();
try {Patient patient = new Patient(name,age,oxylevel,HRCTreport);
patient.checkCondition()} catch (CovidPositiveException e) {
System.out.println(e.getMessage());} finally {
System.out.println("Patient evaluation complete."); }}}
Accept two files and copy content of first to second
import java.io.*;
public class a3{
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: java FileCopyApp <source file> <destination file>");
System.exit(0); }
File sourceFile = new File(args[0]);
File destinationFile = new File(args[1]);
if (!sourceFile.exists()) {
System.out.println("Source file does not exist!");
System.exit(0); }
try {
FileReader file_reader = new FileReader(sourceFile);
BufferedReader buf_reader = new BufferedReader(file_reader);
FileWriter file_writer = new FileWriter(destinationFile);
BufferedWriter buf_writer = new BufferedWriter(file_writer);
String line;
while ((line = buf_reader.readLine()) != null) {
buf_writer.write(line);
buf_writer.newLine(); }
buf_writer.write("end of file");
buf_reader.close();
buf_writer.close();
System.out.println("File copied successfully with 'end of file' comment.");
} catch (IOException e) {
System.out.println("IO Exception: " + e); } } }
Email Id, username password, Exception invalid password
import java.util.*;import java.io.*;
class InvalidUsernameException extends Exception{
String msg="Invalid Username\nTry Again\n";
public String toString(){return msg;}}
class InvalidPasswordException extends Exception{
String msg="Invalid Password\nTry Again\n";
public String toString(){
return msg;}}
class Emailid{
String username;
String password;
Emailid(){username="MainHoonTanmay";
password="Tanmay@123";}
Emailid(String u,String p){
username=u;
password=p;}}//Emailid
public class b2{
public static void main(String[]args){
Emailid e1=new Emailid(args[0],args[1]);
Emailid e2=new Emailid();
String s1=e1.username;
String s2=e2.username;
String s3=e1.password;
String s4=e2.password;
try{ if(s1.equals(s2)){
System.out.println("Username Verified!");
}else{ throw new
InvalidUsernameException(); }
}catch(InvalidUsernameException e){
System.out.println(e);}
try{ if(s3.equals(s4)){
System.out.println("Password Verified!");
}else{throw new
InvalidPasswordException(); }
}catch(InvalidPasswordException e){
System.out.println(e);}}}
Class Mydate accept date, throw exception invalid date exception
import java.util.Scanner;
class InvalidDateException extends Exception{
String msg="Invalid date...\nTry Again\n";
public String toString(){
return msg;}}
class MyDate{ nt day,mon,yr;
MyDate(int d,int m,int y){day=d;mon=m; yr=y;}
void display(){
println("\n\t\tDate\n"); println("\t-------------");
println("\tDay\tMonth\tYear"); println("\t-------------");
println("\t"+day+"\t"+mon+"\t"+yr); println("\t-------------"); }}
public class b3{public static void main(String arg[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Date:dd mm yyyy");
int day=sc.nextInt();
int mon=sc.nextInt();
int yr=sc.nextInt();
int flag=0; try{
if(mon<=0||mon>12)
throw new InvalidDateException(); else{
if(mon==1||mon==3||mon==5||mon==7||mon==8||mon==10||mon==12){
if(day>=1&&day<=31)
flag=1; else
throw new InvalidDateException();
}else if(mon==2){
if(yr%4==00){
if(day>=1&&day<=29)
flag=1; else
throw new InvalidDateException();}
}else{if(mon==4||mon==6||mon==9||mon==11){
if(day>=1&&day<=30)
flag=1;else
throw new InvalidDateException();}}}if(flag==1){
MyDate dt=new MyDate(day,mon,yr);
dt.display(); }}catch(InvalidDateException e){
System.out.println(e); }}}
Calculator
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator {
private JFrame frame;
private JTextField textField;
private JPanel buttonPanel;
private String currentInput = "";
private double result = 0;
private char operation = ' ';
public SimpleCalculator() {
frame = new JFrame("Simple Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
textField = new JTextField(20);
textField.setEditable(false);
frame.add(textField, BorderLayout.NORTH);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 4));
addButton("7"); , 8,9,+,4,5,6,-,1,2,3,*,0,C,==,%
frame.add(buttonPanel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
private void addButton(String label) {
JButton button = new JButton(label);
button.addActionListener(new ButtonClickListener(label));
buttonPanel.add(button);
}
private void performOperation(char op) {
double currentValue = Double.parseDouble(currentInput);
switch (operation) {
case '+': result += currentValue; break;
case '-': result -= currentValue; break;
case '*': result *= currentValue; break;
case '%': result = result % currentValue; break;
Default: result = currentValue;}
textField.setText(Double.toString(result));
currentInput = ""; operation = op; }
private class ButtonClickListener implements ActionListener {
private String label;
public ButtonClickListener(String label) {
this.label = label;
}
@Override
public void actionPerformed(ActionEvent e) {
if (label.matches("[0-9]")) {
currentInput += label;
textField.setText(currentInput);
} else if (label.equals("C")) {
currentInput = "";
result = 0;
operation = ' ';
textField.setText("");
} else if (label.equals("=")) {
performOperation(operation);
} else { performOperation(label.charAt(0));} } }
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new SimpleCalculator()); }}