Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Java Fundamentals Recap

1. Introduction

Java is a versatile, high-level programming language that follows the Object-Oriented Programming paradigm. It was designed to have as few implementation dependencies as possible, making it a popular choice for developers.

2. Data Types

Java has two main categories of data types:

  • Primitive Data Types: Includes int, boolean, char, double, etc.
  • Reference Data Types: Includes objects and arrays.

Example of declaring variables:

int age = 25;
boolean isJavaFun = true;
char grade = 'A';

3. Control Structures

Control structures dictate the flow of the program. The main types include:

  1. Conditional Statements: if, if-else, switch.
  2. Loops: for, while, do-while.

Example of a conditional statement:

if (age >= 18) {
    System.out.println("Adult");
} else {
    System.out.println("Minor");
}

4. Object-Oriented Programming

Java is based on four main principles of Object-Oriented Programming:

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

Example of a simple class:

class Dog {
    String name;
    int age;

    void bark() {
        System.out.println("Woof!");
    }
}

5. Exception Handling

Exception handling in Java is managed via five keywords: try, catch, finally, throw, and throws. It enables graceful error handling.

Example:

try {
    int divideByZero = 5 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
} finally {
    System.out.println("This will always execute");
}

6. Best Practices

Following best practices enhances code quality and maintainability:

  • Use meaningful variable and method names.
  • Comment your code for clarity.
  • Follow Java naming conventions.
  • Avoid hardcoding values; use constants instead.

7. FAQ

What is the difference between JDK, JRE, and JVM?

JDK (Java Development Kit): A software development kit used to develop Java applications.

JRE (Java Runtime Environment): A part of the JDK that allows you to run Java applications.

JVM (Java Virtual Machine): An abstract machine that enables your computer to run Java programs.

What is a constructor in Java?

A constructor is a special method that is called when an object is instantiated. It typically initializes the object’s properties.

What are access modifiers in Java?

Access modifiers determine the visibility of classes, methods, and variables. The main types are public, private, protected, and default (package-private).