Quickest Getting Started with Java
A quick refresher for Java. Not intended to be a comprehensive guide, but will help to recall/refresh your past Java experience or get insight into a few new concepts. Sometimes may help to get a light peek into the language conventions itself too. Enjoy!
1. Java Basics
Introduction to Java
Java is a high-level, class-based, object-oriented programming language designed to have as few implementation dependencies as possible. It is platform-independent, which means that once you write the code, it can run on any platform that supports Java.
Hello World Example
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
public class HelloWorld
: Defines a class namedHelloWorld
.public static void main(String[] args)
: The entry point of the Java application.System.out.println
: Prints the given string to the console.
Java Data Types
Java has two categories of data types:
- Primitive types: int, boolean, float, double, char, etc.
- Reference types: Objects (classes, arrays, etc.).
int number = 10;
boolean isJavaFun = true;
double pi = 3.14;
Control Flow Statements
Java supports control flow with:
- If-else:
if (number > 10) {
System.out.println("Number is greater than 10");
} else {
System.out.println("Number is 10 or less");
}
- Loops (for, while, do-while):
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
2. Object-Oriented Programming (OOP)
Java is fundamentally based on OOP principles:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
Classes and Objects
- Class: A blueprint for creating objects.
- Object: An instance of a class.
class Car {
String model;
int year;
void drive() {
System.out.println("Driving " + model);
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car(); // Creating an object
car.model = "Toyota";
car.year = 2020;
car.drive();
}
}
Encapsulation
Encapsulation means hiding the internal state and requiring all interactions to be performed through methods.
class Person {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Inheritance
Inheritance allows a new class to inherit properties and methods from an existing class.
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
Polymorphism
Polymorphism allows one interface to be used for a general class of actions, and different classes can implement methods in their own way.
Animal myDog = new Dog(); // Polymorphism in action
myDog.sound(); // Calls Dog's sound method
3. Concurrency
Concurrency allows multiple threads to execute simultaneously, potentially improving application performance.
Creating Threads
There are two primary ways to create threads in Java:
- Extend
Thread
class - Implement
Runnable
interface
Extending the Thread
class:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Starts the thread
}
}
Implementing the Runnable
interface:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
Thread Synchronization
When multiple threads access shared resources, synchronization ensures data consistency.
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
4. JDBC (Java Database Connectivity)
JDBC provides a way to interact with databases using Java.
Setting Up JDBC
- Load the JDBC driver:
Class.forName("com.mysql.jdbc.Driver");
- Establish a connection:
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
- Create a statement:
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
- Process the results:
while (rs.next()) {
System.out.println(rs.getString("username"));
}
- Close the connection:
connection.close();
Prepared Statements
For dynamic queries with user inputs, use prepared statements to avoid SQL injection attacks.
PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM users WHERE id = ?");
pstmt.setInt(1, 5);
ResultSet rs = pstmt.executeQuery();
5. Java Collections Framework
The Java Collections Framework (JCF) provides various data structures and algorithms to store and manipulate groups of objects.
Common Collection Interfaces
- List: An ordered collection (e.g.,
ArrayList
,LinkedList
). - Set: A collection that cannot contain duplicate elements (e.g.,
HashSet
,TreeSet
). - Map: A collection of key-value pairs (e.g.,
HashMap
,TreeMap
).
List Example (ArrayList
)
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");
for (String fruit : list) {
System.out.println(fruit);
}
}
}
Set Example (HashSet
)
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate, will not be added
for (String fruit : set) {
System.out.println(fruit);
}
}
}
Map Example (HashMap
)
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
for (Integer key : map.keySet()) {
System.out.println("Key: " + key + " Value: " + map.get(key));
}
}
}
Next Steps
- Practice OOP concepts: Build applications that follow object-oriented design principles.
- Dive deeper into Concurrency: Explore thread pools, executors, and advanced synchronization.
- Explore JDBC further: Understand database connection pooling and transaction management.
- Collections in depth: Learn more about
TreeMap
,PriorityQueue
, and other advanced data structures.