Lab: launching the streaming platform¶
☕ Java 17 · Writing Your First main() Method · 3/3
Goal: boot our platform with a name and a region passed on the command line, without crashing when they're missing.
Setup: in src/, create the folders com/netflix/platform/ and the file StreamingPlatform.java inside. Open a terminal in src/.
Step 1 — Package and class¶
package com.netflix.platform;
public class StreamingPlatform {
private String platformName;
private String region;
}
The two fields belong to each object. main is static, so it can't use them without an object: we'll come back to that in a later section.
Step 2 — Guard the arguments¶
Add main inside the class:
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: <name> <region>");
return;
}
}
If fewer than two arguments are given, the program explains how to run it and return leaves main right away.
Step 3 — Read and print¶
After the if block:
String name = args[0]; // "Netflix"
String region = args[1]; // "France"
System.out.println("Launching " + name + " in " + region);
+ joins the text and the values into one message.
Step 4 — Compile and run¶
From src/, compile with the file path and run with the full class name (package included):
$ javac com/netflix/platform/StreamingPlatform.java
$ java com.netflix.platform.StreamingPlatform Netflix France
Launching Netflix in France
Now without arguments:
No crash: the guard caught the missing arguments before args[0] was read.
Final code¶
package com.netflix.platform;
public class StreamingPlatform {
private String platformName;
private String region;
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: <name> <region>");
return;
}
String name = args[0]; // "Netflix"
String region = args[1]; // "France"
System.out.println("Launching " + name + " in " + region);
}
}
← What breaks main · Back to the series
🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)