Java
Java Basics
Essential Java programming concepts and fundamentals
Java Basics
Java is a high-level, object-oriented programming language developed by Sun Microsystems (now Oracle). It's known for its "write once, run anywhere" philosophy.
Key Features
- Platform Independent: Java code runs on any platform with JVM
- Object-Oriented: Everything is an object (except primitives)
- Memory Management: Automatic garbage collection
- Strongly Typed: Type checking at compile time
- Multithreaded: Built-in support for concurrent programming
Basic Syntax
Hello World Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}Variables and Data Types
Primitive Data Types
// Integer types
byte myByte = 100; // 8-bit (-128 to 127)
short myShort = 5000; // 16-bit (-32,768 to 32,767)
int myInt = 100000; // 32-bit (-2^31 to 2^31-1)
long myLong = 15000000000L; // 64-bit (-2^63 to 2^63-1)
// Floating point types
float myFloat = 5.75f; // 32-bit IEEE 754
double myDouble = 19.99d; // 64-bit IEEE 754
// Other types
boolean myBool = true; // true or false
char myChar = 'A'; // 16-bit Unicode characterReference Types
String myString = "Hello Java";
int[] myArray = {1, 2, 3, 4, 5};
ArrayList<String> myList = new ArrayList<>();Control Structures
Conditional Statements
// if-else statement
int age = 18;
if (age >= 18) {
System.out.println("Adult");
} else if (age >= 13) {
System.out.println("Teenager");
} else {
System.out.println("Child");
}
// switch statement
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other day");
}Loops
// for loop
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
// enhanced for loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
// while loop
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
// do-while loop
int x = 0;
do {
System.out.println("x = " + x);
x++;
} while (x < 3);Object-Oriented Programming
Classes and Objects
public class Car {
// Instance variables
private String brand;
private String model;
private int year;
// Constructor
public Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
// Getter methods
public String getBrand() {
return brand;
}
public String getModel() {
return model;
}
public int getYear() {
return year;
}
// Setter methods
public void setBrand(String brand) {
this.brand = brand;
}
// Instance method
public void startEngine() {
System.out.println(brand + " " + model + " engine started!");
}
// Static method
public static void honk() {
System.out.println("Beep beep!");
}
}
// Using the class
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", "Camry", 2023);
myCar.startEngine();
Car.honk(); // Static method call
}
}Inheritance
// Parent class
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating");
}
}
// Child class
public class Dog extends Animal {
public Dog(String name) {
super(name); // Call parent constructor
}
public void bark() {
System.out.println(name + " is barking");
}
@Override
public void eat() {
System.out.println(name + " is eating dog food");
}
}Interfaces
public interface Drawable {
void draw(); // Abstract method
default void display() { // Default method
System.out.println("Displaying...");
}
}
public class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}Arrays and Collections
Arrays
// Array declaration and initialization
int[] numbers = new int[5];
int[] values = {1, 2, 3, 4, 5};
// Accessing elements
numbers[0] = 10;
int first = values[0];
// Array length
int length = numbers.length;
// 2D Array
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};Collections Framework
import java.util.*;
// ArrayList
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// HashMap
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
// HashSet
Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("John");
uniqueNames.add("Jane");Exception Handling
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("General error: " + e.getMessage());
} finally {
System.out.println("Finally block always executes");
}
}
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Division by zero!");
}
return a / b;
}
}Input/Output
import java.util.Scanner;
public class InputExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Hello " + name + ", you are " + age + " years old!");
scanner.close();
}
}Important Concepts
Method Overloading
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}Access Modifiers
- public: Accessible from anywhere
- protected: Accessible within package and subclasses
- default (no modifier): Accessible within package only
- private: Accessible within the same class only
String Operations
String str = "Hello World";
// Common string methods
int length = str.length();
String upper = str.toUpperCase();
String lower = str.toLowerCase();
boolean contains = str.contains("World");
String substring = str.substring(0, 5);
String[] words = str.split(" ");
// String concatenation
String greeting = "Hello" + " " + "World";
String formatted = String.format("Hello %s, you are %d years old", "John", 25);Best Practices
-
Naming Conventions:
- Classes: PascalCase (e.g.,
MyClass) - Methods/Variables: camelCase (e.g.,
myMethod) - Constants: UPPER_SNAKE_CASE (e.g.,
MAX_SIZE)
- Classes: PascalCase (e.g.,
-
Code Organization:
- One public class per file
- Package names in lowercase
- Meaningful variable and method names
-
Memory Management:
- Close resources (Scanner, FileReader, etc.)
- Avoid memory leaks
- Use appropriate data structures