Avatar ·

How to work with strings in Java?

Hello everyone! I started learning Java and encountered a misunderstanding of working with strings. I read that String is an immutable object, but in practice questions arise.

Problem: There is a list of strings that need to be joined with commas, but some values can be null. I'm trying to do this in a loop, but I either get a NullPointerException or an extra comma at the end.

Here's what I tried (simplified code):

List<String> items = Arrays.asList("apple", null, "banana", "cherry");\nString result = "";\nfor (String item : items) {\n    if (item != null) {\n        result += item + ",";\n    }\n}\n// I get "apple,banana,cherry," — extra comma at the end\nSystem.out.println