0% found this document useful (0 votes)
2 views

java

The document is an assignment for a Computer Science course on Java, covering concepts such as classes and objects, multithreading, code reusability, data structures (arrays, ArrayLists, linked lists, vectors), garbage collection, and exception handling in Java. It includes explanations, code examples, and outputs demonstrating the functionality of various Java features. The assignment is authored by a student named Bankole Adebisi Tolulope under the guidance of Mr. Ayodele.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

java

The document is an assignment for a Computer Science course on Java, covering concepts such as classes and objects, multithreading, code reusability, data structures (arrays, ArrayLists, linked lists, vectors), garbage collection, and exception handling in Java. It includes explanations, code examples, and outputs demonstrating the functionality of various Java features. The assignment is authored by a student named Bankole Adebisi Tolulope under the guidance of Mr. Ayodele.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

FEDERAL POLYTECHNIC ILARO

(FPI)

PROGRAMME: COMPUTER SCIENCE


COURSE TITLE: JAVA II
COURSE CODE: COM211
LEVEL: ND2

ASSIGNMENT
NAME: BANKOLE ADEBISI TOLULOPE
MATRIC NUMBER: PN/CS/23/1892

BY MR. AYODELE
1. Write short note on object and class
Class:A class is a formal description of a group of entities that share common attributes and methods. It acts
as a programming template for creating objects.
Purpose: A class defines what an object is, what attributes it will have, and how it will behave.
Logical Entity: A class is a logical entity that exists in the code but does not allocate memory space.
Example: Consider a class named Car. It defines properties like make, model, and methods
like startEngine() and drive().
Object:An object is an instance of a class. It represents a physical entity created based on the class
blueprint.
Purpose: Objects are used to store data and perform actions. They encapsulate both data (attributes) and
behavior (methods).
Physical Entity: When you create an object, memory is allocated for its data members.
Example: If Car is the class, an object could be an actual car instance with specific values
for make and model.

2. Write a java program that will print a in the index of java program
public class Main {
public static void main(String[] args) {
System.out.print("Index of a:");
String index="Java Program";
for(int a=0;a<index.length();a++){
if(index.charAt(a)=='a'){
System.out.print(a + " ");
}
}

}
}

OUTPUT: Index of a:1 3 10


Code successful run!

3. Write a short note on multithreading and also a code on multithreading.


Java is a multi threaded programming language which means we can develop multi threaded program
using Java. A multi threaded program contains two or more parts that can run concurrently and each
part can handle different task at the same time making optimal use of the available resources specially
when your computer has multiple CPUs.
By definition multitasking is when multiple processes share common processing resources such as a
CPU. Multi threading extends the idea of multitasking into applications where you can subdivide
specific operations within a single application into individual threads. Each of the threads can run in
parallel. The OS divides processing time not only among different applications, but also among each
thread within an application.
Code Example

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running");
}

}
class Mynewtread extends MyThread {
@Override
public void run() {
System.out.println("Thread is isAlive");
}
}

public class Main {


public static void main(String[] args) {
MyThread t1 = new Mynewtread();
t1.start();

}
}

Output: Thread is isAlive


Code successful run!

4. How will achieve code reusability in java and retain ability in java
1. Reusability in Java

Java offers various mechanisms to promote code reuse:

1. Inheritance :You can extend a parent class to create a new class that inherits its properties
and behavior.

2. Interfaces and Abstract Classes


 Interfaces define a contract for classes to implement, allowing multiple inheritance and loose
coupling.
 Abstract classes allow partial implementation for reuse.

3. Polymorphism :Method overriding and overloading promote reusability by allowing


behavior to be changed or extended without modifying existing code.

4. Composition :Instead of inheritance, using objects of other classes inside a class promotes
flexible reusability.

2. Retainability in Java (Maintainability)

1. Encapsulation
o By hiding internal details and exposing only necessary methods, Java promotes
maintainable code.
o Use private variables and public getters/setters:
2. Modularity
 Divide code into small, independent modules or classes.
 This allows changes in one module without affecting others.

3. Consistent Coding Practices: Follow standard naming conventions and documentation for easier
readability and maintenance.
4. Exception Handling :Using proper try-catch blocks ensures that code handles errors gracefully
without breaking the entire system.

5. Write short note on array,arraylist, linked list and vector java

Array: A collection of fixed-size, homogeneous elements (same data type).

 Characteristics:
o Fixed Size: The size is defined when created and cannot be changed.
o Efficient Access: Direct access to any element using its index.

ArrayList :A resizable array from the java.util package.

 Characteristics:
o Dynamic Size: Can grow or shrink as needed.
o Random Access: Provides fast access to elements.
o Non-Synchronized: Not thread-safe, but more efficient.

Vector :A thread-safe, resizable array from the java.util package.

 Characteristics:
o Dynamic Size: Like ArrayList, it grows or shrinks automatically.
o Synchronized: All methods are synchronized, making it thread-safe but slower.
o Legacy Class: Often replaced by ArrayList in modern Java development.

6. Write short note on garbage collection


Garbage Collection (GC) in Java is a crucial process for managing memory dynamically during program
execution. Let’s explore how it works and its limitations:
1. Automatic Memory Management:
o In Java, GC automatically reclaims memory occupied by objects that are no longer needed.
o It prevents memory leaks by deallocating memory when objects become unreachable.
o GC ensures that developers don’t need to explicitly free memory (unlike languages like C or
C++).
2. How GC Works:
o Mark and Sweep Algorithm:
 The most common GC algorithm is the mark-and-sweep approach.
 It involves two phases:
1. Mark: The GC identifies all reachable objects (those still in use) by traversing the object
graph starting from known roots (e.g., static variables, method call stacks).
2. Sweep: The GC reclaims memory by freeing up space occupied by
unreachable objects.
o Generational GC:
 Java’s GC divides memory into generations (usually young and old generations).
 Most objects die quickly, so they start in the young generation.
 Objects surviving multiple GC cycles move to the old generation.
 Young generation GC is more frequent, while old generation GC is less frequent.
o GC Types:
 Minor (Young Generation) GC:

 Collects short-lived objects in the young generation.


 Frequent but efficient.

 Major (Old Generation) GC:

 Collects long-lived objects in the old generation.


 Less frequent but more time-consuming.

 Full GC:

 Collects the entire heap (both young and old generations).


 Rare and resource-intensive.

oTuning GC:
 Developers can tune GC parameters based on application requirements.
 Options include adjusting heap size, choosing GC algorithms, and setting thresholds.
 G1 (Garbage-First) GC is a popular choice for balancing throughput and latency.
3. GC Limitations:
o No Guarantee Against Out of Memory (OOM):
 GC does not guarantee that a program won’t run out of memory.
 If an application keeps references to objects (even unintentionally), GC cannot
reclaim their memory.
 Example: Infinite loops that keep adding objects to a list without releasing them.
o OutOfMemoryError (OOM):
 When memory is exhausted, an OOM error occurs.
 GC cannot prevent this if the application allocates more memory than available.
o Responsibility Lies with Developers:
 Developers must manage object references properly.
 Release unused objects explicitly (set references to null).
 Avoid circular references that prevent GC.
 Use tools (profilers) to identify memory leaks.
7. Write short note on Exception handling

EXCEPTION HANDLING

Exception handling is a mechanism in Java that allows you to handle runtime errors gracefully. In Java,
exceptions are objects that are thrown at runtime when an error occurs. Exception handling allows you to
catch these exceptions and take appropriate action.

Use Specific Exception Classes:


Different types of errors should be handled using specific exception classes. For instance, if you encounter a
file-not-found situation, catch a FileNotFoundException rather than a generic Exception.
This practice enhances code readability and helps you address specific issues appropriately
Clean Up Resources in a Finally Block or Use Try-With-Resource:
When using resources like InputStream, ensure proper cleanup.
Use a finally block to release resources explicitly or leverage the try-with-resource statement, which
automatically closes resources after use.
Be Careful What You Log:
Avoid logging sensitive information or stack traces that might expose security vulnerabilities.
Log relevant details without compromising security.
Don’t Bury Thrown Exceptions:
Avoid catching exceptions and ignoring them silently. Always handle exceptions appropriately.
If you catch an exception, ensure that you log it or take necessary actions.
Use Descriptive Messages When Throwing Exceptions:
When creating custom exceptions, provide clear and informative error messages.
These messages aid developers in understanding the issue and facilitate debugging.
Throw Early and Handle Exceptions Late:
Detect exceptions as early as possible in your code.
Handle them at a higher level in the call stack, closer to where you can take meaningful corrective actions.
Check for Suppressed Exceptions:
In Java, exceptions can have suppressed exceptions (e.g., when closing resources).
Use getSuppressed() to retrieve suppressed exceptions and handle them appropriately.
Explicitly Define Exceptions in the throws Clause:
When defining methods, explicitly declare the exceptions they can throw using the throws clause.
This informs callers about potential exceptions and helps them handle them correctly

example of exception handling in Java:

publicclassExceptionHandlingExample {
publicstaticvoidmain(String[] args) {
try {
int[] arr = newint[5];
arr[10] = 50;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
}
}

In this example, we are trying to access an array element that is out of bounds. This will cause an
ArrayIndexOutOfBoundsException to be thrown at runtime. To handle this exception, we have enclosed the
code that might throw the exception inside a try block. If an exception is thrown, it is caught by the catch
block, which prints a message to the console.

There are several other types of exceptions in Java, such as NullPointerException, ArithmeticException,
FileNotFoundException, etc. You can handle these exceptions in a similar way by enclosing the code that
might throw the exception inside a try block and catching the exception in a catch block.

You might also like