0% found this document useful (0 votes)
5 views5 pages

Java Notes

This document provides an overview of Java programming, covering key concepts such as object-oriented programming, data types, control flow, methods, exception handling, and GUI basics. It includes examples of syntax for defining classes, methods, and handling exceptions, as well as best practices for coding in Java. Additionally, it touches on database connectivity using JDBC and common Java commands for compiling and running programs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views5 pages

Java Notes

This document provides an overview of Java programming, covering key concepts such as object-oriented programming, data types, control flow, methods, exception handling, and GUI basics. It includes examples of syntax for defining classes, methods, and handling exceptions, as well as best practices for coding in Java. Additionally, it touches on database connectivity using JDBC and common Java commands for compiling and running programs.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd

Java Notes

1. Basics
• Java: Object-Oriented Programming (OOP) language; platform-independent (Write
Once, Run Anywhere).

• File & Class Naming:


• File name must match the public class name.
public class MyClass { }

• Main Method: Entry point of a Java program.


public static void main(String[] args) {
[Link]("Hello, Java!");
}

• Comments:
// Single-line comment
/* Multi-line comment */
/** JavaDoc comment */

2. Data Types
• Primitive types:

Type Size Example


byte 1 byte 100
short 2 bytes 10000
int 4 bytes 100000
long 8 bytes 100000L
float 4 bytes 10.5f
double 8 bytes 10.5
char 2 bytes 'A'
boolean 1 bit true/false
• Non-primitive: String, Arrays, Classes, Objects, etc.

3. Variables
int age = 25;
String name = "John";
final double PI = 3.14159; // constant
• final → value cannot change.

• Variables can be local, instance, or static.

4. Operators
• Arithmetic: + - * / %

• Relational: == != > < >= <=

• Logical: && || !

• Assignment: = += -= *= /= %=

• Increment/Decrement: ++ --

5. Control Flow
If-Else
if (age > 18) {
[Link]("Adult");
} else {
[Link]("Minor");
}

Switch
switch(day) {
case 1: [Link]("Monday"); break;
default: [Link]("Other day");
}

Loops
for(int i=0; i<5; i++) { }
while(condition) { }
do { } while(condition);

6. Arrays
int[] numbers = {1,2,3,4};
String[] names = new String[3]; // size 3
names[0] = "Alice";

• Enhanced for loop:


for(int num : numbers) {
[Link](num);
}
7. Methods (Functions)
public int add(int a, int b) {
return a + b;
}

public static void greet() {


[Link]("Hello!");
}

• Method signature: access_modifier return_type


method_name(parameters)

8. Object-Oriented Programming (OOP)


Class & Object
class Person {
String name;
int age;

void display() {
[Link](name + " is " + age + " years old");
}
}

Person p = new Person();


[Link] = "John";
[Link] = 25;
[Link]();

Key OOP Concepts


• Encapsulation: Use private variables and getters/setters.
• Inheritance: class Child extends Parent

• Polymorphism: Overloading & overriding methods


• Abstraction: abstract class / interface

• Encapsulation Example
class Person {
private String name;

public String getName() { return name; }


public void setName(String n) { name = n; }
}

9. Exception Handling
try {
int x = 10 / 0;
} catch(ArithmeticException e) {
[Link]("Cannot divide by zero");
} finally {
[Link]("This always executes");
}

• Common Exceptions: NullPointerException,


ArrayIndexOutOfBoundsException, IOException, SQLException.

10. Java Packages & Import


import [Link];

Scanner sc = new Scanner([Link]);


int num = [Link]();

• [Link] is imported by default.

• Use packages to organize classes.

11. Java GUI Basics (Swing)


import [Link].*;

JFrame frame = new JFrame("My Window");


JButton button = new JButton("Click Me");

[Link](button);
[Link](300,200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](true);

• Event Handling
[Link](e -> [Link]("Button clicked!"));

12. JDBC (Database Connection Example)


import [Link].*;

public class DBExample {


public static void main(String[] args) {
try {
[Link]("[Link]");
Connection con = [Link](
"jdbc:mysql://localhost:3306/dbname", "user", "password"
);
Statement stmt = [Link]();
ResultSet rs = [Link]("SELECT * FROM users");
while([Link]()) {
[Link]([Link](1) + " " + [Link](2));
}
[Link]();
} catch(Exception e) {
[Link]();
}
}
}

13. Common Java Commands


javac [Link] # compile
java MyClass # run

14. Tips & Best Practices


• Always close resources (Scanner, DB connections, Files) after use.
• Use meaningful variable names.
• Follow CamelCase for classes and lowerCamelCase for variables/methods.
• Handle exceptions properly.
• For GUI apps, update UI only on Event Dispatch Thread (EDT).

Common questions

Powered by AI

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 .

You might also like