Java Notes
Java Notes
Connecting a Java application to a MySQL database via JDBC involves loading the driver using Class.forName("com.mysql.cj.jdbc.Driver"); and establishing a connection with DriverManager.getConnection(), which requires the database URL, username, and password. Once connected, a Statement object is created to execute SQL queries, and a ResultSet object processes data retrieved from queries. Ensuring connections are closed after use is vital for resource management. JDBC's role is crucial for database interaction, enabling Java applications to perform CRUD operations on databases efficiently, integrating back-end data processing with Java logic .
Managing resources such as database connections and file streams in Java involves closing them once their tasks are complete to avoid resource leaks, as seen in try-catch-finally structures. Proper management is crucial because open resources consume system memory and file descriptors, hindering performance and risking application crashes. Practices include using try-with-resources for automatic closure, explicitly invoking close methods, and handling exceptions to ensure resources are released even when errors occur, reinforcing application stability and efficiency .
In a Java GUI program using Swing, a button is created with the JButton class. For example, JButton button = new JButton("Click Me"); creates a new button labeled "Click Me". It can be added to a frame using frame.add(button). To handle events, an action listener is added with button.addActionListener(e -> System.out.println("Button clicked!"));. This lambda expression responds to button clicks by printing a message, demonstrating event-driven programming in Java's graphical user interface applications .
The try-catch-finally block in Java handles exceptions by enclosing code that might throw an exception within a try block, catching the exception with a catch block, and a finally block that executes code after try and catch blocks, regardless of an exception being thrown. This construct promotes robust code by enabling the program to run error-handling mechanisms without crashing. It allows developers to specify recovery steps and ensure that certain cleanup operations, such as closing file streams or database connections, always execute, thus preserving resources and program stability .
Primitive data types in Java include byte, int, short, long, float, double, char, and boolean, which are predefined by the language and have a fixed size, leading to efficient memory management. Non-primitive types, such as Strings, Arrays, Classes, and Objects, are created by the programmer. They are references to a memory location, and their sizes can change, requiring Java's garbage collection mechanism to manage memory dynamically. The distinction affects how data is stored in memory and how it is accessed during the program's execution .
The main method in Java is the entry point for execution of a Java program. It must be declared as public, static, void, and accept a String array as an argument (String[] args). Its role is to serve as the starting point for program execution, allowing the Java runtime to locate and invoke it when the program is launched. The specific requirement of having it as static means it can be called without creating an instance of the class, facilitating the execution of the program directly by the Java Virtual Machine (JVM).
Method overloading in Java occurs when multiple methods within the same class have the same name but different parameter lists. It is used to perform different operations with similar inputs that need different processing. Method overriding involves a subclass providing a specific implementation of a method already defined in its superclass. It is used in polymorphism to define behavior specific to the subclass. Overloading enhances readability and reuse of code, while overriding allows specific behavior modification in inherited classes, supporting dynamic dispatch .
Java ensures platform independence through the use of the Java Virtual Machine (JVM). When a Java program is compiled, it is converted into bytecode, which is interpreted by the JVM on any platform. This allows the same Java program to run on different operating systems without modification, embodying the "Write Once, Run Anywhere" concept. For developers, this means reduced need for platform-specific code and broader reach of applications without additional adaptation effort .
Encapsulation in Java is the practice of restricting access to certain components of an object and establishing a controlled interface. It is implemented using private variables within a class and providing public getter and setter methods to access and modify these variables. For example, in class Person, the variable name can be accessed and modified using getName() and setName(String n). This control prevents unauthorized modification of the internal state and makes it easier to uphold invariants. Encapsulation thereby enhances software maintainability by decoupling component interfaces from their implementations, making code easier to manage, update, and understand .
The if-else statement in Java allows branching based on boolean expressions and can handle complex conditions. In contrast, the switch statement evaluates a single expression against multiple constant cases, utilizing labels and breaks. If-else is preferable for evaluating conditions requiring logical operators or ranges, while switch offers a cleaner syntax for mapping an expression to a specific case. Switch is more efficient when dealing with fixed integer or enumeration-based choices, whereas if-else excels with complex conditional logic involving different data types and computations .