




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
OOP with java past gtu paper question with solutions
Typology: Study notes
1 / 164
This page cannot be seen from the preview
Don't miss anything!
Paper CO Question
JRE (Java Runtime Environment) JRE provides the environment required to run Java applications. It includes the JVM (Java Virtual Machine) , libraries, and other components necessary to execute Java programs. JRE does not include development tools like the compiler (javac). JDK (Java Development Kit) JDK is a complete software development kit for Java application development. It includes JRE + development tools like javac (Java compiler), debugger, and other utilities. Different versions of JDK are available, such as JDK 8, JDK 11, and JDK 17 (LTS versions). JIT (Just-In-Time Compiler) JIT is a part of JVM that improves performance by compiling bytecode into native machine code at runtime. Instead of interpreting each line, JIT translates frequently executed code into faster machine code. This reduces execution time and improves efficiency.
Static Keyword in Java The static keyword in Java is used for memory management. It can be applied to variables, methods, blocks, and nested classes.
1. Static Variable A static variable belongs to the class, not to any specific object. It is shared among all objects of the class. 2. Static Method A static method can be called without creating an object of the class. It can only access static variables and static methods directly. 3. Static Block The static block is executed only once when the class is loaded into memory. Example Program class StaticExample { static int count = 0; // Static variable // Static method static void displayCount() { System.out.println("Count: " + count); } // Constructor StaticExample() { count++;
// Static block static { System.out.println("Static block executed."); } public static void main(String[] args) { StaticExample obj1 = new StaticExample(); StaticExample obj2 = new StaticExample(); StaticExample.displayCount(); // Calling static method without object } } Output: Static block executed. Count: 2 Explanation:
Inheritance in Java
System.out.println("Model: " + model); } } // Main class public class InheritanceExample { public static void main(String[] args) { Car myCar = new Car(); myCar.showBrand(); // Accessing parent class method myCar.showDetails(); // Accessing child class method } }
Brand: Toyota Model: Corolla Key Benefits of Inheritance:
this.height = h; } void area() { System.out.println("Triangle Area: " + (0.5 * base * height)); } } // Subclass Rectangle class Rectangle extends Shape { double length, width; Rectangle(double l, double w) { this.length = l; this.width = w; } void area() { System.out.println("Rectangle Area: " + (length * width)); } } // Subclass Circle class Circle extends Shape { double radius; Circle(double r) { this.radius = r; } void area() { System.out.println("Circle Area: " + (Math.PI * radius * radius)); } } // Main class public class ShapeDemo { public static void main(String[] args) { Shape t = new Triangle(5, 10); Shape r = new Rectangle(4, 6); Shape c = new Circle(7); t.area(); r.area(); c.area(); } } Output Triangle Area: 25. Rectangle Area: 24. Circle Area: 153. Explanation
Definition of Interface in Java An interface in Java is a blueprint of a class that contains only abstract
inheritance.
What is Run-Time Polymorphism? Run-time polymorphism in Java occurs when a method is overridden in a subclass and the method to be executed is determined at run time based on the object’s reference. This is achieved using method overriding and dynamic method dispatch. Key Features of Run-Time Polymorphism ✔ Achieved through method overriding (same method name, different behavior in child class) ✔ Uses parent class reference to call overridden method in child class ✔ Decided at run-time, not compile-time Java Program Demonstrating Run-Time Polymorphism // Parent class class Animal { void makeSound() { // Method to be overridden System.out.println("Animal makes a sound"); } } // Child class 1 class Dog extends Animal { void makeSound() { // Overriding method System.out.println("Dog barks"); } } // Child class 2 class Cat extends Animal { void makeSound() { // Overriding method System.out.println("Cat meows"); } } // Main class public class RuntimePolymorphismExample { public static void main(String[] args) { Animal a; // Parent class reference a = new Dog(); // Dog object a.makeSound(); // Calls Dog's method a = new Cat(); // Cat object a.makeSound(); // Calls Cat's method } }
Output Dog barks Cat meows Explanation
Difference Between Text I/O and Binary I/O in Java Feature Text I/O Binary I/O Data Format Stores data as human- readable text (characters) Stores data in raw binary format (bytes) Classes Used Uses FileReader, FileWriter, BufferedReader, PrintWriter Uses FileInputStream, FileOutputStream, DataInputStream, DataOutputStream File Size Larger, as text encoding (like UTF-8) is used Smaller, as it stores data in compact binary format Performa nce Slower because of encoding/decoding Faster as no conversion is needed Usage Used for text-based files (.txt, .csv, .json) Used for images, audio, video, and object files (.jpg, .mp3, .dat) Example of Text I/O import java.io.; public class TextIOExample { public static void main(String[] args) throws IOException { FileWriter writer = new FileWriter("textfile.txt"); writer.write("Hello, World!"); writer.close(); } } Example of Binary I/O import java.io.; public class BinaryIOExample { public static void main(String[] args) throws IOException { FileOutputStream fos = new FileOutputStream("binaryfile.dat"); fos.write(65); // Writing a single byte (ASCII of 'A') fos.close(); } }
What is an Exception in Java? An exception in Java is an unexpected event that occurs during the execution of a program and disrupts the normal flow of the program. Exceptions typically occur due to: Invalid user input Dividing by zero Accessing an array element out of bounds Attempting to open a file that does not exist Network connectivity failures Java provides a built-in mechanism to handle such errors and prevent the program from crashing. This is done using exception handling techniques. Types of Exceptions in Java
1. Checked Exceptions (Compile-time Exceptions) These exceptions must be handled using try-catch or declared using throws, otherwise the program will not compile. They occur due to external factors like file handling or database operations. Examples: IOException (File not found, read/write error) SQLException (Database access issues) ClassNotFoundException (Class not found in runtime) 2. Unchecked Exceptions (Runtime Exceptions) These exceptions occur due to logical programming errors and do not need to be handled explicitly. The program will compile but fail at runtime if not handled properly. Examples: ArithmeticException (Dividing by zero) NullPointerException (Accessing a null object) ArrayIndexOutOfBoundsException (Accessing an invalid array index) NumberFormatException (Invalid conversion of string to a number) 3. Errors (Serious Issues) Errors are not exceptions but critical problems that cannot be recovered from. They indicate issues that should not be handled by normal exception handling techniques. Examples: StackOverflowError (Infinite recursion) OutOfMemoryError (Insufficient memory) VirtualMachineError (JVM internal error) Common Built-in Exceptions in Java Exception Name Description ArithmeticException Occurs when dividing by zero NullPointerException Occurs when accessing an object reference that is null
ArrayIndexOutOfBoundsException Occurs when trying to access an index outside the array range FileNotFoundException Occurs when a file does not exist IOException General Input/Output exception NumberFormatException Occurs when converting an invalid string to a number ClassNotFoundException Occurs when JVM cannot find the specified class Explaining ArithmeticException with Example The ArithmeticException occurs when a mathematical operation is not allowed , such as dividing by zero. Example: Handling Divide by Zero using try-catch public class ArithmeticExceptionExample { public static void main(String[] args) { try { int num1 = 10; int num2 = 0; int result = num1 / num2; // This will cause an exception System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Error: Cannot divide by zero!"); } } } Output Error: Cannot divide by zero! Explanation of Code
(like Integer, String, etc.). data is a variable of type T. The constructor initializes data, and getData() returns the value of data. Example: Using a Generic Class public class GenericExample { public static void main(String[] args) { GenericClass
Java Program to Read and Display Content of student.txt File This program reads the content of a file named student.txt using FileReader and BufferedReader , then displays its content on the console. Java Code: import java.io.*; public class ReadStudentFile { public static void main(String[] args) { try { // Open the file for reading FileReader fileReader = new FileReader("student.txt"); BufferedReader bufferedReader = new BufferedReader(fileReader); String line; System.out.println("Contents of student.txt:"); // Read and display the file content line by line while ((line = bufferedReader.readLine()) != null) { System.out.println(line); }
// Close the reader bufferedReader.close(); } catch (FileNotFoundException e) { System.out.println("File not found! Please check if 'student.txt' exists."); } catch (IOException e) { System.out.println("Error reading the file."); } } } Explanation:
Thread Life Cycle in Java A thread in Java goes through different stages in its life cycle. The Thread Life Cycle consists of the following states:
1. New (Created) State A thread is in the new state when it is created but not yet started. It is created using the Thread class but has not been executed using start(). Example: Thread t = new Thread(); 2. Runnable State When the start() method is called, the thread enters the runnable