Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Assignment 4

Q1. "Write a program which accepts the values from console ,use method overloading and
overriding concept to display the results by calculating largest values from the variables

package Assignments;

import java.util.Scanner;

public class OverLoadingAndOverriding {

public static void main(String[] args) {


// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int a,b,c;
System.out.println("Enter 3 numbers");
a=sc.nextInt();b=sc.nextInt();c=sc.nextInt();
FindGreatestNo sum = new FindGreatestNo();
System.out.println(sum.GreatestNo(a, b));//gives output of 2 parameter GreatestNo
method
System.out.println(sum.GreatestNo(a, b, c));//gives output of 3 parameter GreatestNo
method
Animal n = new dog();//overRides eat method of Animal Class
n.eat();

public static class FindGreatestNo {


int a,b,c;

int GreatestNo(int a,int b) {


if(a>b)
return a;
else
return b;
}
int GreatestNo(int a,int b,int c) {
if(a>b&&a>c)
return a;
else if(b>c)
return b;
else
return c;
}
}

public static class Animal{


void eat() {
System.out.println("Animal is eating");
}
}
public static class dog extends Animal{
void eat() {
System.out.println("Dog is eating");
}
}

}
Output:
Enter 3 numbers
123
2
3
Dog is eating

Q. Reading and Writing Inputs from File

package files;

import java.io.File;

import java.io.FileNotFoundException;

import java.util.InputMismatchException;

import java.util.Scanner;

public class fileInput {

public static void main(String[] args) {

Scanner infile;

try {

infile = new Scanner(new File("input.txt"));


int input,sum=0;

while(infile.hasNext()) {

input=infile.nextInt();

sum+=input;

System.out.println(sum);

infile.close();

catch(FileNotFoundException ex) {

System.out.println("File not Found");

System.out.println(ex.getMessage());

catch(InputMismatchException ex) {

System.out.println("Error reading input");

System.out.println(ex.getMessage());

Q. Writing Files

package files;
import java.io.FileNotFoundException;

import java.io.PrintWriter;

public class FileOutput {

public static void main(String[] args) {

// TODO Auto-generated method stub

try {

PrintWriter pw = new PrintWriter("output.txt");

pw.print("Hello There!\n");

pw.print("My name is aftab");

pw.close();

catch(FileNotFoundException ex){

System.out.println("Couldn't write to the file");

You might also like