CSC 223 GUIDE
Object-Oriented (OO) Programming Answers
What is the main focus of Object-Oriented Programming?
The main focus is on using objects to design software.
How do objects communicate in Object-Oriented Programming?
Objects communicate through call statements, without needing to initialize objects first.
List three programming languages that support Object-Oriented Programming.
Java, C++, C.
Procedure-Oriented Programming (POP) Answers
What does Procedure-Oriented Programming emphasize more: data or procedures?
It emphasizes procedures (or functions) rather than data.
How can Object-Oriented languages be used in Procedure-Oriented Programming?
Object-Oriented languages can be used to create modular structures/programs in Procedure-Oriented Programming.
Is Python fully Object-Oriented, fully Procedure-Oriented, or a mix of both?
Python is a mix of both Object-Oriented and Procedure-Oriented programming.
Object-Based Programming Answers
What are the key features of Object-Based Programming?
It uses classes and supports encapsulation and object state but lacks certain object-oriented characteristics.
How does Object-Based Programming differ from fully Object-Oriented Programming?
Object-Based Programming lacks some object-oriented features like inheritance and polymorphism, which are present in fully Object-Oriented Programming.
Objects in Programming Answers
What is an object in programming?
An object is a region of memory that has a value.
What are the three key properties that every object must have?
An object must have a name, a behavior, and the ability to receive messages.
Types of Programs Answers
What are the three main types of programs based on programming paradigms?
Object-Oriented, Procedure-Oriented, and Object-Based programs.
Object Properties Answers
What are the two main properties of every object?
The state of the object and the behavior of the object.
How is the state of an object defined?
The state is defined by how the object appears, which includes its structure, creation, and how it is accessed.
What defines the behavior of an object?
The behavior is defined by how the object reacts to external messages.
Object State Answers
How is an object's state determined?
An object's state is determined by the class structure and object instances.
Write a simple code example (in Java or another language) that shows an object's state.
Example (Java):
class Example {
int a;
double b;
Example() {
a = 10;
b = 20;
}
}
Object Behavior Answers
What is the difference between internal behavior and external behavior of an object?
Internal behavior refers to the actual implementation of actions and modules, while external behavior is how the object interacts with the user or other systems without revealing its internal details.
How does external behavior benefit users interacting with a program?
External behavior allows users to interact with the program without needing to understand the internal workings, making the program easier to use.
Abstraction Answers
What is the purpose of abstraction in programming?
The purpose of abstraction is to separate the external behavior of an object from its internal implementation.
How does abstraction help separate external behavior from internal implementation?
Abstraction hides the complex internal details, allowing users to work with simpler external interfaces.
Runtime Errors Answers
What can cause runtime errors in Object-Oriented Programming?
Runtime errors can be caused by incorrect binding of methods or objects.
How does Java handle method calls to prevent runtime errors?
Java uses late binding to determine which method to call at runtime, which helps prevent errors.
What is the difference between early binding and late binding?
Early binding resolves method calls at compile time, while late binding resolves them at runtime.
Binding Answers
What are the four types of binding?
Dynamic Binding, Early Binding, Late Binding, Static Binding.
Define binding in the context of programming.
Binding is a modular structure that connects modules and transfers control between them.
What is static binding (early binding)?
Static binding refers to information that is available during compile time, where modules and functions are connected during compilation.
What is dynamic binding (late binding)?
Dynamic binding is when information is available during runtime, connecting modules/functions at execution.
Explain early binding and its significance.
Early binding occurs when the called method is found during compilation, allowing control to be transferred to the called module at that time.
What is late binding and when is it used?
Late binding (related to dynamic binding) occurs when information is found dynamically at runtime, waiting for methods/functions to be determined.
How does Java utilize late binding?
Java uses late binding to implement polymorphism, allowing the object being operated on to determine the method to be called.
Polymorphism Answers
What is the definition of polymorphism in programming?
Polymorphism is the ability for an object to take many forms, with operations differing based on the receiving object.
What are the two types of polymorphism?
Static Polymorphism and Dynamic Polymorphism.
Describe static polymorphism and provide an example.
Static polymorphism occurs when methods are overloaded with different signatures in the same class.
Example: public static void M1(int a, double b)
Describe dynamic polymorphism and provide an example.
Dynamic polymorphism occurs when methods are overloaded with the same signature in different classes.
Example: public static void M2(double b)
What are method signatures in the context of polymorphism?
Method signatures consist of the parameters and their amounts that distinguish one method from another.
Inheritance Answers
What is inheritance in object-oriented programming?
Inheritance allows objects from different classes to share common behavior, expressing relationships between specialized and general classes.
What are subclasses and how do they relate to base classes?
Subclasses are derived classes that inherit behaviors and properties from a base class, allowing for code reuse and extension.
Explain how subclasses can override base members.
Subclasses can provide specific implementations for methods or variables defined in the base class, effectively replacing the base class's behavior.
What is the syntax for declaring a subclass in Java?
public class DriveClassName extends BaseClassName
List and describe the types of inheritance.
Simple Inheritance: Involves a single base class from which subclasses can inherit methods/objects.
Multiple Inheritance: Involves more than one base class from which subclasses can inherit methods/objects (Note: Java does not support this).
Why does Java not support multiple inheritance?
Java does not support multiple inheritance to avoid complexity and ambiguity, such as the "Diamond Problem."
Access Modifiers Answers
What is the purpose of access modifiers in programming?
Access modifiers control the visibility and accessibility of classes, methods, and variables, protecting data from unauthorized access.
What access does the protected modifier provide?
The protected modifier allows access to child classes but restricts access from outside the class hierarchy.
How does the private modifier restrict access?
The private modifier restricts access to the declaring class only, preventing access from outside that class.
Abstraction and Encapsulation Answers
What is the purpose of abstraction in programming?
Abstraction separates the logical properties of an object from its implementation, allowing users to interact with the object's interface without knowing the details of its implementation.
What are the components of abstraction?
Definition: Defines methods and structures to operate on class variables.
Declaration: Declares class members and necessary objects.
Class definition follows class declaration, and methods are structured with a single entry and exit.
Define encapsulation and its significance in programming.
Encapsulation binds code and data together, preventing unauthorized access to the internal state of an object and ensuring that data can only be manipulated through formal interfaces/commands.
Factors Affecting Program Speed Answers
List the factors that can affect program speed.
Data structure, clock speed, instruction word length, memory structure and behavior.
Memory Allocation for Methods Answers
Why is memory management important in programming?
Memory management is vital as it impacts program speed and helps avoid memory leaks and gaps in memory allocation.
How does memory allocation differ across programming languages?
Different languages have varying approaches to memory allocation and deallocation, with some managing it manually and others automatically.
What role does the JVM play in memory management in Java?
The JVM manages memory allocation and deallocation automatically, helping to optimize resource usage and prevent memory leaks.
Types of Memory Answers
What is stack memory used for?
Stack memory stores specific types of data, primarily local variables and function call information.
What is heap memory, and how is it managed?
Heap memory stores instances of classes, is created by the OS, managed by the JVM, and is dynamically allocated during runtime.
How is memory allocated during runtime in object-oriented programs?
Memory is allocated dynamically in the heap for objects at runtime, allowing for flexible data structures.
Types of Methods Answers
What are static methods, and how do they access data?
Static methods receive all data/information as arguments and can access or modify shared variable objects without needing an instance of the class.
How are static methods identified in code?
Static methods are preceded by the class name when called. They can be identified in code as ClassName.methodName(arguments).
Where is memory allocated for static methods?
Memory for static methods is stored in the Permanent Generation Space (PGn) of the heap memory.
Provide an example of how a static method can be called externally and internally.
External call: Expl2.sum(); (from another class). Internal call: sum(); (within the same class).
What are strict methods (instance methods)?
Strict methods, or instance methods, receive parameters through objects and are called using the object of the class.
How do strict methods receive parameters?
Strict methods receive parameters through instances of the class, allowing them to work with the object's data.
How are strict methods called in code?
Strict methods are called using the syntax: objectName.methodName(arguments).
Where is memory allocated for strict methods?
Memory for strict methods is also stored in the Permanent Generation Space (PGn) of the heap, with local variables and arguments stored in stack memory.
Can strict methods be invoked from other classes? If so, how?
Yes, strict methods can be invoked from other classes if the class name is known and an instance of the class is created. The syntax is: ClassName objectName = new ClassName(); objectName.methodName(arguments);.
Types of Parameters Answers
What are value parameters?
Value parameters are arguments whose value is passed to the called method. The called method cannot change the original data of the object that was passed.
How does a called method interact with the original data of an object when using value parameters?
The called method does not have the authority to change the original data; it works with a copy of the data.
Define actual parameters. Where are they located?
Actual parameters are the arguments that are passed to a method when it is called. They are located in the calling method.
How are actual parameters transferred when a method call is made?
Actual parameters are transferred to the allocated storage by the called method when control is transferred to it.
What are reference parameters?
Reference parameters are address assessor methods, where the address of the data object is passed to the method instead of the object itself.
How does a method interact with data objects when using reference parameters?
When a method uses reference parameters, it can modify the original data object because it has access to the memory address of the object.
7. Write a code snippet that demonstrates the use of value parameters in a method.
java
Copy code
public void valueParameterExample(int num) {
num = num + 10; // This will not change the original value
}
8. Write a code snippet that shows how to define and call a method with actual parameters.
public void displayMessage(String message) {
System.out.println(message);
}
// Calling the method
displayMessage("Hello, World!"); // "Hello, World!" is the actual parameter
9. Provide a code example that demonstrates the use of reference parameters in a method.
public void referenceParameterExample(int[] arr) {
arr[0] = 100; // This will change the original array
}
// Calling the method
int[] myArray = {1, 2, 3};
referenceParameterExample(myArray);
// myArray[0] is now 100
10. What will happen to the original object if it is passed as a reference parameter and modified within the method? Write a code example to illustrate this.
public void modifyObject(MyClass obj) {
obj.value = 20; // This will change the original object's value
}
public class MyClass {
int value;
}
// Calling the method
MyClass myObj = new MyClass();
myObj.value = 10;
modifyObject(myObj);
// myObj.value is now 20
Garbage Collection and String Handling in Java Answers
What is garbage collection in programming?
Garbage collection is the process of automatically reclaiming unused memory from unreferenced objects to prevent memory shortages during runtime.
How does garbage collection occur when a pointer no longer points to an object?
When a pointer no longer points to an object, the object becomes unreferenced, leading to its memory being eligible for garbage collection and ultimately reclaimed by the JVM.
What happens when one object of a class is assigned to another object of the same class?
A copy of the object is created, causing the original object to lose its reference, making it eligible for garbage collection if no other references exist.
How does Java's JVM handle garbage collection?
Java's JVM automatically runs the garbage collection process to identify and release unused memory associated with unreferenced objects.
Explain how garbage collection works for strings in Java.
When a string literal is declared using the same pointer, a new string is created, and its address is assigned to the reference variable. The original string remains in memory, but its reference count decreases. Automatic garbage collection can remove the original object if it becomes unreferenced.
What is automatic dereferencing?
Automatic dereferencing is the process of obtaining an address from a reference variable, accessing that address, and retrieving the correct number of bytes for the object.
In Java, how is a string constant created?
In Java, a string constant is created as an object of either the String or StringBuffer class, and strings are stored as objects rather than primitive variables.
What does it mean for string objects to be immutable?
String objects being immutable means that once created, their value cannot be modified without creating a new string object.
List the seven constructors for string objects in Java.
String()
String(String value)
String(char[] array)
String(char[] array, int offset, int len)
String(StringBuffer)
String(byte[] array)
String(byte[] array, int offset, int count)
String Transfer and Manipulation in Java Answers
What is the purpose of string transfer in Java?
Strings can be transferred to and from a program using various Stream Classes to handle input.
Define InputStreamReader. How does it function in string transfer?
InputStreamReader reads bytes and decodes them into characters using a specified charset.
What role does BufferedReader play in handling input?
BufferedReader wraps InputStreamReader to read data more efficiently by buffering input.
Provide an example of reading a line of text from input using BufferedReader.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine(); // Reads a line of text from input
What is the function of the charAt() method? Provide an example of its usage.
The charAt() method retrieves individual characters from a string by its position.
char ch = str.charAt(3); // Retrieves the character at position 3
Explain the indexOf() and lastIndexOf() methods. How do they differ?
Both methods are used to find the position of a character or substring within a string. indexOf() finds the first occurrence, while lastIndexOf() finds the last occurrence.
Write examples of how to use the indexOf() method with different parameters.
int pos1 = str.indexOf("hello"); // Finds the position of "hello"
int pos2 = str.indexOf("hello", 5); // Finds "hello" starting at position 5
int pos3 = str.indexOf('a'); // Finds the position of character 'a'
int pos4 = str.indexOf('a', 3); // Finds 'a' starting from position 3
What does the .equals() method do when comparing two strings? Provide an example.
The .equals() method compares two strings for equality, returning true if they are equal and false otherwise. boolean isEqual = str1.equals(str2); // Returns true if str1 equals str2
How does the .compareTo() method work for string comparison? What values can it return?
The .compareTo() method compares two strings lexicographically based on Unicode value. It returns:
0 if the strings are equal,
A negative value if str1 comes before str2,
A positive value if str1 comes after str2.
Provide an example of using the .compareTo() method to compare two strings.
int comparison = str1.compareTo(str2); // Returns comparison result
Character Processing in Java Answers
What does the Character class provide for character processing?
The Character class provides methods like isDigit(), isLetter(), isLowerCase(), isUpperCase(), isWhiteSpace(), isSingleSpace(), toLowerCase(), and toUpperCase() for character processing.What does the isDigit(char ch) method do?
The isDigit(char ch) method checks if the character ch is a digit. It returns true if ch is a digit; otherwise, it returns false.What does the toLowerCase(char ch) method do?
The toLowerCase(char ch) method converts the character ch to lowercase and returns the converted character.What is the purpose of the StringBuffer class?
The StringBuffer class is used to modify String objects, which are immutable. It allows for character addition or text editing without creating new objects.
What does the append() method do in StringBuffer?
The append() method adds characters, strings, or primitive data types to the end of a StringBuffer object.
Example:
StringBuffer S1 = new StringBuffer("This is a new line to ");
S1.append("read");
How does StringBuffer differ from StringBuilder?
StringBuffer is synchronized (thread-safe), while StringBuilder is not. StringBuilder is better suited for single-threaded applications where frequent string modifications are needed.
6. What does the insert() method do in StringBuffer?
The insert() method allows for the insertion of a string, character, or data type at a specific position.
Example:
S1.insert(4, "not");
String Manipulation Answers
What are common classes used for string manipulation in Java?
Common classes used for string manipulation in Java include String, StringBuffer, and Character.How can you retrieve the character at a specific index in a string?
The character at a specific index in a string can be retrieved using the charAt(int index) method.What does the indexOf() method return?
The indexOf() method returns the index of the first occurrence of a specified character or substring within a string.What does the parse() method do?
The parse() method converts a string to a specified primitive type (e.g., int, double).
How does the delete(int start, int end) method work in StringBuffer?
The delete(int start, int end) method removes a substring from a StringBuffer, deleting characters from the start index up to, but not including, the end index.
Example:
s1.delete(5, 21); // deletes from index 5 up to 20
What does the deleteCharAt(int index) method do in StringBuffer?
The deleteCharAt(int index) method deletes the character at the specified index in the StringBuffer.What does the overloaded append() method do in StringBuffer?
The overloaded versions of the append() method in StringBuffer allow appending characters, strings, or the string representation of primitive data types.What is the purpose of the replace(int m, int n2, object) method in StringBuffer?
The replace(int m, int n2, object) method replaces characters in the string from position m to n2 - 1 with the specified object.
What is the valueOf() method used for?
The valueOf() method is used to convert a primitive data type to a String.
Example:
String.valueOf(double x);
How can you convert an array of characters to a string constant object?
The valueOf() method can convert an array of characters to a string constant object.
Example:
char d[] = {'a', 'b', 'c', 'd'};
String s = String.valueOf(d);
What does the valueOf() method with subarrays do?
The valueOf() method with subarrays allows operations on specific parts of an array.
Example:
String s = String.valueOf(d, 2, 2);
How can you convert a string constant to a primitive type?
To convert a string constant to a primitive type, you can use the Class.valueOf(String constant data object) method.
Example:
double x;
String s = "589.55";
double v = Double.valueOf(s);
x = v.doubleValue(); // Conversion to primitive double
File Stream Overview Answers
What is a file stream?
A file stream is a one-way path used to transfer information between a program and a file stored in secondary storage (e.g., hard drives).What is the purpose of a file stream?
It facilitates data movement between memory and storage devices in either direction: input stream for receiving data from a file to a program and output stream for writing data from a program to a file.What are the two types of file streams?
Input Stream: Transfers data from a file to a program.
Output Stream: Transfers data from a program to a file.
What determines the mode of a file stream?
The mode of a file stream determines the direction of the transfer.What happens to a file when it is transferred to memory?
When a file is transferred to memory, it becomes a data array, losing all its previous attributes.What is Direct Memory Access (DMA)?
Direct Memory Access (DMA) refers to the process where data is transferred directly between the file and memory.What does the redirection process do?
The redirection process changes the direction of the data transfer from the default setup (e.g., from keyboard to program or program to screen).What do System.in and System.out refer to?
System.in: Refers to input from the keyboard (an instance of java.io.BufferedInputStream, a subclass of InputStream).
System.out: Refers to output to the screen (an instance of java.io.PrintStream, a subclass of OutputStream).
How are standard stream objects instantiated?
Stream objects like System.in and System.out are automatically created by the compiler.What is the difference between character-based and byte-based files?
Character-Based Files: Data is stored and processed as characters.
Byte-Based Files: Data is stored and processed as raw bytes.
Character-Based File System (Text File) Answers
What is a character-based file?
A character-based file, also known as a text file, stores alphanumeric characters using individual character codes. These files are readable by word processors or text editors.
What are the primary stream classes used for character-based files?
The primary stream classes are FileReader for input streams and FileWriter for output streams.
What is the purpose of the FileReader class in Java?
The FileReader class is used to create an input stream object that connects the file to the program, allowing reading from a character-based file.
How do you create an input stream object to read from a character-based file?
An input stream object can be created using the following syntax: FileReader fr = new FileReader("filename");
What method is used to read one character at a time from a character-based file?
The read() method of FileReader is used to read one character at a time.
What happens when an output stream object is created using the FileWriter class?
When an output stream object is created, a new file is created with the specified name, or an existing file is overwritten.
What is the purpose of the write() method in the context of writing to a character-based file?
The write() method is used to output characters one at a time to the file.
Explain the process of establishing a connection between a file and a program.
A connection is established by creating a FileReader or FileWriter object, which maps the file's external name (e.g., "Exampleone.txt") to its internal name for program use.
What occurs if you create a FileWriter object for a file that already exists?
If the file already exists, it will be overwritten unless the FileWriter is created in append mode.
Can you explain the difference between reading from and writing to a character-based file?
Reading from a character-based file involves creating an input stream to retrieve data, while writing to a character-based file involves creating an output stream to send data to the file.
Character-Based File Example Answers
Write a code snippet to create a FileReader object for a file named "data.txt".
j
FileReader fr = new FileReader("data.txt");
How would you use the FileWriter class to append data to an existing file?
FileWriter fw = new FileWriter("data.txt", true); // 'true' enables append mode
Write a code snippet that reads all characters from a character-based file until the end of the file is reached.
int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
Provide a code example that demonstrates how to write a single character to a file using FileWriter.
fw.write('A'); // Writes the character 'A' to the file
Explain how you would handle an IOException when attempting to read from a character-based file.
try {
FileReader fr = new FileReader("data.txt");
// Reading code here
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + e.getMessage());
}
Append Mode and Buffered I/O Answers
What is the definition of append mode in file handling?
In append mode, data is added to the end of an existing file (EOF). If the file does not exist, a new file is created with the pointer initially at the beginning.What happens when you try to write to a file in append mode if the file does not exist?
A new file is created with the pointer initially at the beginning, and once the file is created, the mode switches to write mode for adding data.Define a buffer in the context of data transfers.
A buffer is a temporary storage space in memory used to facilitate incoming or outgoing data transfers in a system.What is the purpose of buffered I/O in data handling?
Buffered I/O reduces unnecessary calls to the operating system during I/O operations by buffering data, which minimizes hardware access and improves efficiency.How does buffering improve efficiency during I/O operations?
The buffer temporarily holds data, allowing a program to interact with it while the buffer handles the file access, reducing the number of interactions with the hardware.What is the role of a device driver in buffered I/O operations?
A device driver (DVDR) communicates between hardware and software, managing I/O transfer operations and synchronization due to speed differences in media.What is block size transfer in buffered streams?
Buffered streams transfer data in fixed block sizes (e.g., 512 bytes = ½ K on Unix systems).What is the first step to read data using BufferedReader?
Establish a connection to the file using FileReader.How do you create a BufferedReader object in Java?
You create a BufferedReader object by wrapping a FileReader object:
BufferedReader br = new BufferedReader(fr);What method is used to read a line of text from a BufferedReader?
The method br.readLine() is used to read a line of text.What is the first step to write data using BufferedWriter?
Establish a connection for writing using FileWriter.How do you create a BufferedWriter object in Java?
You create a BufferedWriter object by wrapping a FileWriter object:
BufferedWriter bw = new BufferedWriter(fw);What method is used to write data to a BufferedWriter?
The method bw.write("your text") is used to write data.
Zone and Numeric Field
What is the maximum value for Zone?
Answer: 3What is the maximum value for Field?
Answer: 4What does P (Error) represent between Zone and Numeric fields?
Answer: It represents the encoding that indicates the data structure or error handling.
PrintWriter Class
What is the purpose of the PrintWriter class?
Answer: To output data (byte representation of strings and primitive types) to a file.How do you create a FileWriter in Java?
Answer: FileWriter fw = new FileWriter("file");What is the role of BufferedWriter when using PrintWriter?
Answer: BufferedWriter buffers the output to improve writing efficiency.How do you create a PrintWriter object?
Answer: PrintWriter pr = new PrintWriter(bw);How do you print data using PrintWriter?
Answer: pr.print("argument");How would you write a message to a file using PrintWriter?
Answer: pr.write("The value of x is: " + x);
Interactive File Input Example
How do you read a filename from user input in Java?
Answer:
java
Copy code
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String filenameVar;
System.out.println("Enter a file name: ");
filenameVar = br.readLine();
StringTokenizer
What is the purpose of StringTokenizer?
Answer: To read data from a file line by line and tokenize each line into individual tokens for further processing.What is the first step to use StringTokenizer?
Answer: Create a FileReader object (e.g., FileReader fr = new FileReader("filename");).How do you read a line into a String variable using BufferedReader?
Answer:
String s;
s = br.readLine();
How do you create a StringTokenizer object?
Answer: StringTokenizer st = new StringTokenizer(s);How can you extract tokens from a StringTokenizer?
Answer: DataType v = st.nextToken();What methods are used for data conversion of tokens into required data types?
Answer: Use valueOf() and parse() methods.