1. Basic Syntax
Java programs consist of classes and methods. Here's the basic structure:
// Java program structure public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
2. Variables and Data Types
Java supports various data types, and variables must be declared before use:
// Variable declaration and initialization int age = 25; double salary = 50000.50; char grade = 'A'; String name = "John Doe";
3. Control Flow Statements
Control the flow of your program using if-else, switch, while, for, and other statements:
// Example of if-else statement if (condition) { // code to be executed if the condition is true } else { // code to be executed if the condition is false } // Example of a for loop for (int i = 0; i < 5; i++) { // code to be repeated in the loop }
4. Object-Oriented Concepts
Java is an object-oriented language. Understand classes, objects, inheritance, polymorphism, encapsulation, and abstraction:
// Example of a class and object class Car { String brand; void start() { System.out.println("Car started"); } } Car myCar = new Car(); myCar.brand = "Toyota"; myCar.start();
5. Exception Handling
Handle exceptions using try, catch, finally, and throw:
// Example of exception handling try { // code that may throw an exception } catch (Exception e) { // handle the exception } finally { // code to be executed regardless of whether an exception is thrown or not }
6. Advanced Topics
Explore advanced concepts like multithreading, generics, lambda expressions, and Java Streams:
// Example of multithreading class MyThread extends Thread { public void run() { // code to be executed in the thread } } MyThread myThread = new MyThread(); myThread.start();
7. Networking in Java
Java provides classes for networking operations. Example of a simple socket client:
import java.net.Socket; import java.io.IOException; public class SimpleSocketClient { public static void main(String[] args) { try { Socket socket = new Socket("example.com", 80); // Perform networking operations socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
8. Database Connectivity in Java
Java Database Connectivity (JDBC) allows interaction with databases. Example of connecting to a MySQL database:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DatabaseConnection { public static void main(String[] args) { try { Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password"); // Perform database operations connection.close(); } catch (SQLException e) { e.printStackTrace(); } } }
0 Comment:
Post a Comment