A combination of Procedural and Object-oriented
My first dive into Java and the programming paradigms behind it.
The first lesson I’ve learned about Java is what its programming styles are. The first one is a very common one, which is Procedural. Think of traditional constructs such as functions, conditionals, loops and so on. You might wonder; does not every programming language has this? If I mention a couple of declarative languages you’ll immediately realize. Think of HTML, CSS, or SQL.
public class ProceduralExample {
static int countCompletedLessons(boolean[] lessons) {
int completed = 0;
for (boolean lessonCompleted : lessons) {
if (lessonCompleted) {
completed++;
}
}
return completed;
}
public static void main(String[] args) {
boolean[] lessons = {true, true, false, true};
int completed = countCompletedLessons(lessons);
System.out.println("Completed lessons: " + completed);
}
}
Then the other programming style used by Java is the Object-oriented one. When you talk about this you’ll rapidly run into Objects (duh!), classes, inheritance, polymorphism, etc. If you have a front-end background you might have been less in contact with these lately, but they are still present in the world of JavaScript.
public class CourseProgress {
private final int totalLessons;
private int completedLessons;
public CourseProgress(int totalLessons) {
this.totalLessons = totalLessons;
}
public void completeLesson() {
if (completedLessons < totalLessons) {
completedLessons++;
}
}
public void printProgress() {
System.out.println(
"Completed lessons: " + completedLessons + "/" + totalLessons
);
}
}