Вы находитесь на странице: 1из 47

JAVA practice questions and example answers

Question 1:-

//Code for question 1


class Student{ int age=0; char gender; double maths; double stat; double cs; //double avg; double calAvg(){ return (this.maths+this.stat+this.cs)/3; } } class Driver1{ public static void main(String[]arg){ Student st1=new Student(); st1.age=30; st1.gender='M'; st1.maths=45; st1.stat=78; st1.cs=90; System.out.println("Student 1 :"+st1.calAvg()); Student st2=new Student(); st2.age=80; st2.gender='F'; st2.maths=90; st2.stat=7; st2.cs=36; System.out.println("Student 2 :"+st2.calAvg()); } }

//A advanced code for question 1


import java.util.*; class Student{ int age=0; String gender; double maths; double stat; double cs; //double avg; double calAvg(){ return (this.maths+this.stat+this.cs)/3; } } class Driver1_extend{ public static void main(String[]arg){ Scanner sc=new Scanner(System.in); Student st1=new Student(); System.out.print("Enter the age of first Student...."); st1.age=sc.nextInt(); sc.nextLine();/*For fix a logical error*/ System.out.print("Enter the gender of first Student...."); st1.gender=sc.nextLine(); System.out.print("Enter the mathamatics marks of of first Student...."); st1.maths=sc.nextDouble(); System.out.print("Enter the stat marks of first Student...."); st1.stat=sc.nextDouble(); System.out.print("Enter the computer science marks of first Student...."); st1.cs=sc.nextDouble(); System.out.println("Student 1 :"+st1.calAvg()); Student st2=new Student(); st2.age=80; //st2.gender='F'; st2.maths=90; st2.stat=7; st2.cs=36; System.out.println("Student 2 :"+st2.calAvg()); } }

Question 2

Code for question 2:import java.util.*; class Calculator{ double num1; double num2; } class GetNumbers{ void getting(){ Scanner sc=new Scanner(System.in); Calculator cal=new Calculator(); System.out.print("Enter the first no...."); cal.num1=sc.nextDouble(); System.out.print("Enter the second no...."); cal.num2=sc.nextDouble(); Choice ch=new Choice(); ch.choose(cal.num1,cal.num2); }

} class Choice{ void choose(double num1,double num2){ Scanner sc=new Scanner(System.in); int choice; System.out.println("1- Addition\n 2-Substraction \n 3-Division \n 4-Multiplication"); System.out.print("Enter the choice No....."); choice=sc.nextInt(); if(choice==1){ Addition add=new Addition(); System.out.println(add.add(num1,num2)); } if(choice==2){ Substraction sub=new Substraction(); System.out.println(sub.sub(num1,num2)); } if(choice==3){ Division div=new Division(); System.out.println(div.div(num1,num2)); }

if(choice==4){ Multiplication mul=new Multiplication(); System.out.println(mul.mul(num1,num2)); } } }

class Addition{ double add(double num1,double num2){ return num1+num2; } } class Substraction{ double sub(double num1,double num2){ return num1-num2; } } class Division{ double div(double num1,double num2){ return num1+num2; } } class Multiplication{ double mul(double num1,double num2){ return num1*num2; } }

class Driver2{ public static void main(String[]arg){ GetNumbers gn=new GetNumbers(); gn.getting(); } }

Question 3:-

Code for question 3:import java.util.*; class InsertValues{ private double length=1; private double width=1; private double height=1; public void setValues(double length,double width,double height){ this.length=length; this.width=width; this.height=height; } public void cubeVolume(){ System.out.println("Volume of the cube is...."+length*height*width); } public void cubeArea(){ System.out.println("Area of the cube is..."+(length*width)*6); } } class Driver3{ public static void main(String[]arg){ for(int count=1;count>0;count++){ Scanner sc=new Scanner(System.in); InsertValues val=new InsertValues(); System.out.print("Enter the values for height..."); double height=sc.nextDouble(); System.out.print("Enter the values for width..."); double width=sc.nextDouble(); System.out.print("Enter the values for length..."); double length=sc.nextDouble(); val.setValues(length,width,height); val.cubeVolume(); val.cubeArea(); } } }

Question 4:-

Code for question 4:class FindAverage{ int average(int val1,int val2){ return (val1+val2)/2; } int average(int val1,int val2,int val3){ return (val1+val2+val3)/3; } float average(int val1,float val2){ return (val1+val2)/2; } float average(int val1,int val2,float val3){ return (val1+val2+val3)/3; } float average(float val1,float val2,float val3){ return (val1+val2+val3)/3; } double average(double val1,double val2){ return (val1+val2)/2; } double average(int val1,float val2,double val3){ return (val1+val2+val3)/3; } } class Driver5{ public static void main(String[]arg){ FindAverage fA=new FindAverage(); System.out.println(fA.average(2,4)); System.out.println(fA.average(2,4,5)); System.out.println(fA.average(2,5f)); System.out.println(fA.average(2,4,5.4f)); System.out.println(fA.average(2.56f,4.5f,5f)); System.out.println(fA.average(2.54,4.3)); System.out.println(fA.average(2,4f,5.34)); } }

Question 5:-

Code for Question 5:import java.util.*; class StudentMarks{ public void markPanal(int stu){ int marks[]=new int[5]; int value=0; Scanner sc=new Scanner(System.in); for(int markIndex=0;markIndex<marks.length;markIndex++){ System.out.print("Enter the Student"+(stu+1)+" subject "+(markIndex+1)+" ....."); value=sc.nextInt(); marks[markIndex]=value; //markIndex++; } } } class Driver4{ public static void main(String[]arg){ int markIndex=0; StudentMarks sm[]=new StudentMarks[5]; for(int count=0;count<sm.length;count++){ sm[count]=new StudentMarks(); sm[count].markPanal(count); } } }

Question 6:

Code for question 6:import java.util.*; class StudentInfo{ int age; String gender; int mathematics; int stat; int cs; } class Driver6{ public static void main(String[]arg){ Scanner sc=new Scanner(System.in); StudentInfo si[]=new StudentInfo[2]; for(int count=0;si.length>count;count++){ si[count]=new StudentInfo(); System.out.print("Enter the age......."); si[count].age=sc.nextInt(); System.out.print("Enter the gender......."); si[count].gender=sc.nextLine(); sc.nextLine(); System.out.print("Enter the mathematics marks......."); si[count].mathematics=sc.nextInt(); System.out.print("Enter the stat marks......."); si[count].stat=sc.nextInt(); System.out.print("Enter the cs marks......."); si[count].cs=sc.nextInt(); } } }

Question 7:-

Code for question 7:class MultiplicationTbl{ int values[][]=new int[12][12]; } class Driver7{ public static void main(String[]arg){ MultiplicationTbl mTbl=new MultiplicationTbl(); for(int row=0;row<12;row++){ for(int col=0;col<12;col++){ mTbl.values[row][col]=(col+1)*(row+1); } } for(int row=0;row<12;row++){ for(int col=0;col<12;col++){ System.out.print(mTbl.values[row][col]+"\t"); } System.out.println(""); } } }

Question 8:The given JAVA program represents the details of the members in a family. The class 'FamilyMember is the class defined to store information of the family members and class defined as Family is the driver class of the program. Each family member has a first name, middle initial and a last name which is common to all the family members. The title is the prefix that uses in front of the name such as Mr., Ms,Mrs. Some of the members in the family have an occupation. Hence they also have a basic salary. There are two constructors in the JAVA program one of which is to assign the values of the members who have an occupation and the other one is for the members who do not have an occupation. There are two methods which are defined in the FamilyMember class. The method defined as displayPersonalData is to display the personal information of the family members and the method called displayProfessionalData is to display the professional details.

The following table shows the information of 4 members in the family. i. Correct the errors which will appear when the program is compiled. ii. Store details of Mother, Son and Daughter and display them. iii. Modify the method displayPersonalData to display the gender in words (Female or Male). iv. Modify the method displayProfessionalData, so that it does not display the basic salary for the members who do not have an occupation. v. Define a new method to calculate the total monthly income of the family. vi. Define a new method to calculate the tax, based on the following criteria. If total monthly income of the family is, Less than or equal to Rs. 10000/=, then no tax is calculated

In between Rs. 10000/= and Rs. 30000/=, then the tax is 5% of the total monthly income of the family. Greater than Rs. 30000/=, then 7.5% of the total monthly income is calculated as the tax.

Code for question 8:class FamilyMember { char gender; String firstName; char middleInitial; static String lastName; String title; String occupation; double basicSalary; static double totalIncome; FamilyMember(String fName, char midInit, String title, char gender, String occupation, double basicSalary) { this.firstName=fName; this.middleInitial=midInit; this.title=title; this.occupation=occupation; this.basicSalary=basicSalary; this.gender=gender; }

FamilyMember(String fName, char midInit, String title, char gender) { this.firstName=fName; this.middleInitial=midInit; this.title=title; this.occupation="No occupation"; this.gender=gender; } void displayPersonalData() { System.out.println("\tFull Name: "+this.title+" "+this.firstName+" "+this.middleInitial+" "+FamilyMember.lastName); if(this.gender=='M'){ System.out.println("\n\tGender: "+"Male"); } if(this.gender=='F'){ System.out.println("\n\tGender: "+"FeMale"); }

} double displayProfessionalData() { System.out.println("\n\tOccupation: "+this.occupation); if(this.occupation!="No occupation"){ System.out.println("\n\tBasic salary: "+this.basicSalary); } return basicSalary; } static double totalIncome(){ return totalIncome; } static void taxCal(){ if(totalIncome<=10000){ System.out.println("No Income Tax"); } if(totalIncome>10000 && totalIncome<30000){ System.out.println("Income tax amount is...."+totalIncome*(5/100)); } if(totalIncome>30000){ System.out.println("Income tax amount is..."+totalIncome*(7.5/100)); } } } class Family { public static void main(String[]arg){ FamilyMember father=new FamilyMember("Upali",'K',"Mr.",'M', "Engineer", 35000); FamilyMember mother=new FamilyMember("Kanthi",'M',"Mrs.",'F'); FamilyMember daughter=new FamilyMember("Sumali",'D',"Ms.",'F', "Doctor", 45000); FamilyMember son=new FamilyMember("Mahesh",'L',"Mr.",'M'); FamilyMember.lastName="Perera"; System.out.println("\n\n\n\t***** Details of Father *****\n\n");

father.displayPersonalData(); father.displayProfessionalData(); System.out.println("\n\n\n\t***** Details of Mother *****\n\n"); mother.displayPersonalData(); mother.displayProfessionalData(); System.out.println("\n\n\n\t***** Details of Son *****\n\n"); son.displayPersonalData(); son.displayProfessionalData(); System.out.println("\n\n\n\t***** Details of Daughter *****\n\n"); daughter.displayPersonalData(); daughter.displayProfessionalData(); FamilyMember.totalIncome=father.basicSalary+daughter.basicSalar y; System.out.println("Toatal income of the family is...."+FamilyMember.totalIncome()); FamilyMember.taxCal(); }

Question 9:-

Code for question 9:import java.io.*; import java.util.*; class ReadFile{ Scanner reader; String userName; String pwd; boolean grant; String a; String b; String c; public void openFile(){ try{ reader=new Scanner(new File("login.txt")); } catch(Exception e){ System.out.println("Could not read file"); } } public void displayLogin(){ Scanner sc=new Scanner(System.in); System.out.println("**************LOG IN*************"); System.out.print("Enter User ID...."); userName=sc.nextLine(); System.out.print("Enter User password...."); pwd=sc.nextLine(); } public void readFile(){ while(reader.hasNext()){ a=reader.next(); b=reader.next(); c=reader.next(); if(a.equals(userName)&&b.equals(pwd)){ grant=true; showLogin(); }

} } void showLogin(){ if(grant==true){ System.out.println("*************Welcome : "+c+"*************"); }else{ System.out.println("Authentication Fail"); } } public void closeFile(){ reader.close(); } } class Driver10{ public static void main(String[]arg){ ReadFile rF=new ReadFile(); rF.openFile(); rF.displayLogin(); rF.readFile(); rF.closeFile(); } }

Question 10:-

Code(without using vector) for question 10:class ItemList{ String itemName[]={"Ice cream","Yogurt","Chicken","Orange juice","Chips","Bananas","Macaroni & cheese"}; int itemPrice[]={450,90,400,90,175,90,630}; } class Driver8{ public static void main(String[]arg){ ItemList iL=new ItemList(); int totalPrice=0; for(int count=0;count<iL.itemPrice.length;count++){ totalPrice=totalPrice+iL.itemPrice[count]; } System.out.println("Total cost......"+totalPrice); int max=iL.itemPrice[0]; int maxPriceIndex=0; for(int count=0;count<iL.itemPrice.length;count++){ if(max<iL.itemPrice[count]){ max=iL.itemPrice[count]; maxPriceIndex=count; } } System.out.println("High cost item is....."+iL.itemName[maxPriceIndex]+". its cost is..."+max); int min=iL.itemPrice[0]; int minPriceIndex=0; for(int count=0;count<iL.itemPrice.length;count++){ if(min>iL.itemPrice[count]){ min=iL.itemPrice[count]; minPriceIndex=count; } } System.out.println("High cost item is....."+iL.itemName[minPriceIndex]+". its cost is..."+min); int noOfEvent=0; int maxNoOfEvents=0; int maxEventIndex=0; for(int count=0;iL.itemPrice.length>count;count++){ noOfEvent=0;

for(int count2=0;iL.itemPrice.length>count2;count2++){ if(iL.itemPrice[count]==iL.itemPrice[count2]){ noOfEvent++; } if(maxNoOfEvents<noOfEvent){ maxNoOfEvents=noOfEvent; maxEventIndex=count; } } } System.out.println("Maximum appearance...."iL.itemPrice[maxEventIndex]); } }

Code(using vector) for question 10:import java.util.Iterator; import java.util.Vector; public class NewClass1 { public static void main(String[] args) { Vector v=new Vector(); v.add("Ice Cream"); v.add("Yoghurt"); v.add("Chiken"); v.add("Orange juice"); v.add("Chipe"); v.add("Banana"); v.add("Maca"); Vector v1=new Vector(); v1.add(450); v1.add(300); v1.add(400); v1.add(175); v1.add(175); v1.add(90); v1.add(630); int max=(Integer)v1.firstElement(); int index=0; int index1=0; int min=(Integer)v1.firstElement(); // int total=0; // int max=(Integer)v1.firstElement(); Iterator i=v1.iterator(); while(i.hasNext()){ int value=(Integer)i.next(); // total +=(Integer)i.next(); if(max<value){ max=value; index=v1.indexOf(max); } if(min>value){ min=value; index1=v1.indexOf(min); }

} System.out.println("Maximum Item "+v.elementAt((index))); System.out.println("Minimum Item "+v.elementAt((index1))); //System.out.println(v.elementAt(v1.indexOf((Object)max))); }

Code for the part (d) of the question 10(using vectors):import java.util.Iterator; import java.util.Vector; public class NewClass2 { public static void main(String[] args) { Vector v=new Vector(); v.add("Ice Cream"); v.add("Yoghurt"); v.add("Chiken"); v.add("Orange juice"); v.add("Chipe"); v.add("Banana"); v.add("Maca"); Vector v1=new Vector(); v1.add(450); v1.add(300); v1.add(400); v1.add(175); v1.add(175); v1.add(90); v1.add(630); int count=0; int value=0; int value2=0; int mode=0; int elementer=0; Iterator i=v1.iterator(); Iterator i2=v1.iterator(); while(i.hasNext()){ value=(Integer)i.next(); while(i2.hasNext()){ value2=(Integer)i2.next(); if(value==value2){ count++;

} } if(mode<count){ elementer=(Integer)i.next(); mode=count; } count=0; } System.out.println(elementer); // System.out.println("hjgfjsdfhkhf"); } }

Question 11:-

Code for question11:class Vehicle{ int identificationNo; int time; double speed; Vehicle(){} Vehicle(int time,int id){ this.identificationNo=id; this.time=time; this.speed=200/time; System.out.println("Speed of the vehicle "+id+" is "+this.speed); } } class Driver9{ public static void main(String[]arg){ Vehicle v1=new Vehicle(4,1); Vehicle v2=new Vehicle(5,2); } }

A way to write to a file using java:import java.io.*; //import java.io.FileWriter; public class NewClass4 { public static void main(String[] args) { try{ File f=new File("C:\\Users \\A.txt"); f.createNewFile(); FileWriter fr=new FileWriter(f); fr.write("Udara"); fr.write(" Chathuranga"); fr.flush(); fr.close(); char ch[]=new char[1000]; FileReader fRead=new FileReader(f); fRead.read(ch); for(char a:ch){ System.out.print(a); } fr.flush(); fr.close(); } catch(Exception ex){ } } }

Question 11:-

Answer code for question 11:-

import java.util.*; class ElectricityCustomer{ private int id; private String name; private int code; private int previous; private int current; private int unitsConsumed; private double amountDue;

ElectricityCustomer(int id,String name,int code){ setInfo(id,name,code); } void setInfo(int id,String name,int code){ this.id=id; this.name=name; this.code=code; } void setReadings(int previous,int current){ this.previous=previous; this.current=current; calUnitConsumed(); } void calUnitConsumed(){ this.unitsConsumed=this.current-this.previous; calAmountDue(); } void calAmountDue(){ if(this.code==1){ this.amountDue=this.unitsConsumed*30;

} if(this.code==2){ this.amountDue=this.unitsConsumed*50; } if(this.code==3){ this.amountDue=this.unitsConsumed*60; } if(this.code==4){ this.amountDue=this.unitsConsumed*25; } } void displayBill(String customerCategory){ System.out.println("**************Electricity Bill*****************"); System.out.println("Customer Id: "+this.id); System.out.println("Customer Name: "+this.name); System.out.println("Customer code: "+this.code+" "+customerCategory); System.out.println("Units Consumed: "+this.unitsConsumed); System.out.println("Amount Due: "+this.amountDue); } } class ElectricityBill{ public static void main(String[]arg){ ElectricityCustomer electricityCustomer=new ElectricityCustomer(1001,"Kamal",1); electricityCustomer.setReadings(450,500); //electricityCustomer.displayBill(); FeedInfo fI=new FeedInfo(); fI.billInfo(); } } class FeedInfo{ String billInfo[]=new String[5]; void billInfo(){ Scanner sc=new Scanner(System.in); System.out.println("*************Enter the bill information*************"); System.out.print("Enter the customer Id:"); billInfo[0]=sc.nextLine(); System.out.print("Enter the customer Name:"); billInfo[1]=sc.nextLine();

System.out.print("Enter the customer Code:"); billInfo[2]=sc.nextLine(); System.out.print("Enter the Previous reading:"); billInfo[3]=sc.nextLine(); System.out.print("Enter the Current reading:"); billInfo[4]=sc.nextLine(); parseInfo(); } void parseInfo(){ int id=Integer.parseInt(billInfo[0]); int code=Integer.parseInt(billInfo[2]); int previous=Integer.parseInt(billInfo[3]); int current=Integer.parseInt(billInfo[4]); String customerCategory=""; if(code==1){ customerCategory="Domestic"; } if(code==2){ customerCategory="Business"; } if(code==3){ customerCategory="Industrial"; } if(code==4){ customerCategory="School"; }

ElectricityCustomer ec=new ElectricityCustomer(id,billInfo[1],code); ec.setReadings(previous,current); ec.displayBill(customerCategory); } }

Question 12:-

Answer code for question 12:import java.util.*; abstract class Employee{ private String name; String type; double totalPayment; Employee(){} Employee(String name){ this.name=name; } abstract void earnings(); void display(){ System.out.println("*******Employee Details********"); System.out.println("Name: "+this.name); System.out.println("Type: "+this.type); System.out.println("Total payment: "+this.totalPayment); } } class SalariedEmployee extends Employee{ private double fixedWeekSalary; SalariedEmployee(double fixedWeekSalary,String name){ super(name); this.fixedWeekSalary=fixedWeekSalary; } @Override void earnings(){ this.totalPayment=this.fixedWeekSalary; } } class CommisionEmployee extends Employee{ double valueOfSales; double commisionRate; CommisionEmployee(){}

CommisionEmployee(double valueOfSales,double commisionRate,String name){ super(name); this.valueOfSales=valueOfSales; this.commisionRate=commisionRate; } @Override void earnings(){ this.totalPayment=this.valueOfSales*this.commisionRate; } }

class HourlyEmployee extends Employee{ private int noOfWorkingHours; private double normalPaymentForHour; private double overTimePaymentForHour; private double noOfAdditionalHours; HourlyEmployee(int noOfWorkingHours,double normalPaymentForHour,double overTimePaymentForHour,double noOfAdditionalHours,String name){ super(name); this.noOfWorkingHours=noOfWorkingHours; this.normalPaymentForHour=normalPaymentForHour; this.overTimePaymentForHour=overTimePaymentForHour; this.noOfAdditionalHours=noOfAdditionalHours; } @Override void earnings(){ if(this.noOfWorkingHours<=40){ this.totalPayment=this.noOfWorkingHours*this.normalPaymentForHour; } if(this.noOfWorkingHours>40){ this.totalPayment=(40*this.normalPaymentForHour)+(this.noOfAdditionalHours*this.overTi mePaymentForHour); } } } class BaseCommisionEmployee extends CommisionEmployee{ private double baseSalary;

BaseCommisionEmployee(double baseSalary,double valueOfSales,double commisionRate,String name){ super(valueOfSales,commisionRate,name); this.baseSalary=baseSalary; } @Override void earnings(){ this.totalPayment=(this.valueOfSales*this.commisionRate)+this.baseSalary; }

} class Uwuiit100038{ Employee emp[]=new Employee[3]; int empType=0; public static void main(String[]arg){ Uwuiit100038 employee=new Uwuiit100038(); employee.displayDialog(); } void displayDialog(){ Scanner sc=new Scanner(System.in); for(int count=0;count<emp.length;count++){ System.out.println("*******Employee types********"); System.out.println("1. Salaried Employee"); System.out.println("2. Hourly Employees"); System.out.println("3. Commision employees"); System.out.println("4. Base-commision employees"); System.out.print("Enter the Employee Category No:"); empType=sc.nextInt(); if(empType==1){ sc.nextLine(); System.out.print("Enter Name:"); String empName=sc.nextLine(); System.out.print("Enter Salary:"); double fixedWeekSalary=sc.nextDouble(); emp[count]=new SalariedEmployee(fixedWeekSalary,empName); } if(empType==2){ sc.nextLine(); System.out.print("Enter Name:"); String empName=sc.nextLine();

System.out.print("No of working hours:"); int noOfWorkingHours=sc.nextInt(); System.out.print("Enter normal payment for hour:"); double normalPaymentForHour=sc.nextDouble(); System.out.print("Enter over time payment for hour:"); double overTimePaymentForHour=sc.nextDouble(); System.out.print("Enter number of additional hours:"); double noOfAdditionalHours=sc.nextDouble(); emp[count]=new HourlyEmployee(noOfWorkingHours,normalPaymentForHour,overTimePaymentForHour,noOfAdditi onalHours,empName); } if(empType==3){ sc.nextLine(); System.out.print("Enter Name:"); String empName=sc.nextLine(); System.out.print("Enter value of sales:"); double valueOfSales=sc.nextDouble(); System.out.print("Enter commision Rate:"); double commisionRate=sc.nextDouble(); emp[count]=new CommisionEmployee(valueOfSales,commisionRate,empName); } if(empType==4){ sc.nextLine(); System.out.print("Enter Name:"); String empName=sc.nextLine(); System.out.print("Enter base salary:"); double baseSalary=sc.nextDouble(); System.out.print("Enter value of sales:"); double valueOfSales=sc.nextDouble(); System.out.print("Enter comission rate:"); double commisionRate=sc.nextDouble(); emp[count]=new BaseCommisionEmployee(baseSalary,valueOfSales,commisionRate,empName); } emp[count].earnings(); } for(int count=0;count<emp.length;count++){ emp[count].display(); } }

Вам также может понравиться