publicclassMain {
publicstaticvoidmain(String[] args) {
System.out.println("Hello, World. Lets Start");
// Initialise list of String(s)List<String> list = newArrayList<>();
// Add String elements to listlist.add("Johny");
list.add("Steve");
list.add("Barry");
list.add("Harry");
list.add("Barry");
// We can't add Int to a List of String//list.add(1);// And the same goes for Double//list.add(1.55)// Get all list elementsSystem.out.println(list);
// Get the first list elementStringfirst_list_element = list.get(0);
System.out.println("First element is: " + first_list_element);
// Get the second list elementStringsecond_list_element = list.get(1);
System.out.println("Second element is: " + second_list_element);
// Check list sizeSystem.out.println("List size is: " + list.size());
// Remove only the first occurrence of Object BarrySystem.out.println("\nRemoving the first occurrence of Barry");
list.remove("Barry");
System.out.println("List size is: " + list.size());
// Remove element (now Johny) by its index (position) 0 = firstSystem.out.println("\nRemoving element by index 0");
System.out.println(list);
list.remove(0);
// Get whole listSystem.out.println(list);
// Apply function toUpperCase to each List elementlist.replaceAll(String::toUpperCase);
System.out.println(list);
// Create a new list instance of lowered case elementsList<String> lower_list = list.stream().map(String::toLowerCase).collect(Collectors.toList());
System.out.println(lower_list);
}
}
publicclassMain {
publicstaticvoidmain(String[] args) {
System.out.println(divide(4, 0));
if (args.length > 1) {
// Convert a string to an integerintarg0 = Integer.parseInt(args[0]);
intarg1 = Integer.parseInt(args[1]);
System.out.println(divide(arg0, arg1));
}
}
privatestaticintdivide(inta, intb) {
if (b == 0) {
thrownewArithmeticException("You can\'t divide by zero!");
} else {
returna / b;
}
}
}
Try / Catch / Finally / Else
publicclassMain {
publicstaticvoidmain(String[] args) {
booleansuccess = true;
// Try define a block of code to be tested for errors while it is being executedtry {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
}
// Catch allows to define a block of code to be executed if an error occurs in the try blockcatch (Exceptione) {
System.out.println("Something went wrong.");
success = false;
}
// Finally lets you execute code, after try...catch, regardless of the resultfinally {
System.out.println("The 'try catch' is finished.");
}
if (success) {
System.out.println("Succeeded");
}
}
}