POO III
2 hours
Pass Arguments Via Command Line
In Java, you can pass and access arguments passed via the command line through the String[] args
parameter in the main method of your program.
public class ArgumentExample {
public static void main(String[] args) {
// Access command-line arguments here
System.out.println("Number of arguments: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
Running the Programm via CLI
java ArgumentExample This is a string argument! Another argument
Output
Number of arguments: 3
Argument 0: This
Argument 1: is
Argument 2: a string argument! Another argument
Java directories structure
project_name/
README.md # Project description and instructions
LICENSE # License file
src/ # Source code directory
main/
java/ # Java source code goes here, organized by package
com/
example/
... your project's java classes ...
resources/ # Resource files (images, configuration files, etc.)
test/ # Unit test source code (if applicable)
java/ # Similar structure for test code packages
pom.xml # Project configuration file (for Maven projects)
build.gradle # Project configuration file (for Gradle projects)
Processing User Input with Scanner
The Scanner class in Java provides a convenient way to read user input from the console. Here's a practical example that demonstrates using the Scanner class to calculate the area of a rectangle based on user-provided width and height.
import java.util.Scanner;
public class RectangleArea {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble(); // Read width as a double
System.out.print("Enter the height of the rectangle: ");
double height = scanner.nextDouble(); // Read height as a double
// Calculate and display the area
double area = width * height;
System.out.println("The area of the rectangle is: " + area);
scanner.close(); // Close the scanner (optional but good practice)
}
}
Exeption Handling
Exception handling in Java is a powerful mechanism
for managing errors that occur during program execution.
public class ExceptionExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3};
try {
System.out.println(numbers[10]); // This will cause an IndexOutOfBoundsException
} catch (IndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
} finally {
System.out.println("This code will always execute.");
}
}
}
Assertions
An assertion
is a statement you believe true during program execution. If the assertion evaluates to false, the program throws an AssertionError
.
Syntax Example:
int age = 20;
assert age >= 18 : "Person must be an adult";
Example:
public class Factorial {
public static long calculateFactorial(int n) {
// Assertion for non-negative input
assert n >= 0 : "Factorial is only defined for non-negative numbers";
long result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
// Valid input
long result = calculateFactorial(5);
System.out.println("5! = " + result); // Output: 5! = 120
// Invalid input (negative number) - throws AssertionError
try {
calculateFactorial(-2);
} catch (AssertionError e) {
System.out.println(e.getMessage()); // Output: Factorial is only defined for non-negative numbers
}
}
}
Abstract classes
Abstract classes cannot be instantiated directly. They serve as a base class to define a common structure
and behavior for subclasses.
public abstract class Shape {
public abstract double calculateArea(); // Abstract method
public void printInfo() {
System.out.println("This is a shape.");
} // Concrete method with implementation
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
Javadoc
Javadoc generates HTML documentation. These pages explain the classes
, methods
, and fields
in your code.
/**
* This class represents a simple calculator.
*
* @author Your Name Here
*/
public class Calculator {
/**
* Adds two numbers together.
*
* @param num1 the first number
* @param num2 the second number
* @return the sum of num1 and num2
*/
public int add(int num1, int num2) {
return num1 + num2;
}
}
For Each Loop
A simpler loop syntax compared to traditional for loops
.
for (dataType element : array/collection) {
// Code to be executed for each element
}
For Each vs For Loop
// For each loop
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
For Loop
int[] numbers = {1,2,3,4,5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Enum
An enum in Java is a special data type
that allows you to define a set of named constants.
They are commonly used to represent fixed values, like days of the week (MONDAY
, TUESDAY
, WEDNESDAY
) or compass directions (NORTH
, SOUTH
, EAST
, WEST
).
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day today = Day.FRIDAY;
if (today == Day.WEEKEND) {
System.out.println("Time to relax!");
}
Comparable vs Runnable vs Serializable Interfaces
Feature | Comparable | Runnable | Serializable |
---|---|---|---|
Purpose | Ordering objects | Defining a thread task | Object persistence |
Methods | compareTo | run | (none - marker interface) |
Return Value | int | void | non-applicable |
Use Case | Sorting | comparisons, multithreading | Saving/loading object state |
Comparable
Defines object ordering for sorting and comparisons.
public class Student implements Comparable<Student> {
int id;
String name;
int age;
// Constructor and other fields...
@Override
public int compareTo(Student other) {
return this.age - other.age; // Sort by age in ascending order
}
}
In this example, the compareTo
method compares the age of the current object (this)
with another Student object (other)
. It returns a negative integer if the current object is younger, zero if they have the same age, and a positive integer if the current object is older.
Runnable
Enables multithreading for concurrent task execution.
public class DownloadTask implements Runnable {
String url;
String filename;
public DownloadTask(String url, String filename) {
this.url = url;
this.filename = filename;
}
@Override
public void run() {
// Download logic using URL and filename
System.out.println("Downloaded: " + filename);
}
}
This DownloadTask
implements Runnable
and defines the run method. This method contains the code to download the file from the specified URL
and save it with the given filename
.
Serializable
Allows object persistence for data storage and sharing especially via network.
public class Person implements Serializable {
private String name;
private int age;
// Getters and setters omitted for brevity
}
With this implementation, you can create Person
objects and serialize them to files or transmit them over networks using streams.
Next
We will discuss vectors, arrays and strings, relational and non-relational databases with Java and Threads.