AP Computer Science Exam Question:
Consider the following scenario: You are developing a file management system in Java and need to create a class to represent files. Design a File
class that meets the following requirements:
getSizeInKilobytes
that returns the size of the file in kilobytes (assuming the size is given in bytes).isValid
that returns true
if the file name has a valid extension, and false
otherwise. A valid extension is defined as either ".txt" or ".java".Implement the File
class according to the requirements above. Then, write a Java program that demonstrates the usage of the File
class by creating an instance of the File
class and performing the following operations:
getSizeInKilobytes
method.isValid
method.class File {
private String name;
private int size;
private String extension;
public File(String name, int size, String extension) {
this.name = name;
this.size = size;
this.extension = extension;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public int getSizeInKilobytes() {
return size / 1024;
}
public boolean isValid() {
return extension.equals(".txt") || extension.equals(".java");
}
}
public class Main {
public static void main(String[] args) {
File file = new File("exampleFile", 2048, ".txt");
System.out.println("File size in kilobytes: " + file.getSizeInKilobytes());
System.out.println("Is file valid? " + file.isValid());
}
}
Explanation:
File
class is created with three private instance variables: name
, size
, and extension
.getSizeInKilobytes
method returns the size of the file in kilobytes by dividing the size in bytes by 1024.isValid
method checks if the file extension is either ".txt" or ".java" and returns true
or false
accordingly.main
method, an instance of the File
class is created with the specified parameters: "exampleFile" as the name, 2048 as the size, and ".txt" as the extension.getSizeInKilobytes
method.isValid
method.