Java
#3
TIOBE#4
PYPL#2
GitHub#8
RedMonk#3
IEEESpectrum#2
JetBrains#5
Programming Language
Java
Overview
Java is an object-oriented programming language with the concept of "write once, run anywhere".
Details
Java is an object-oriented programming language developed by Sun Microsystems (now Oracle) in 1995. Based on the philosophy of "Write Once, Run Anywhere" (WORA), it enables platform-independent application development by running on the Java Virtual Machine (JVM). It features strong typing, automatic memory management (garbage collection), and rich standard libraries, and is used in a wide range of fields including enterprise development, web applications, Android app development, and big data processing. Major companies such as Oracle, IBM, Google, and LinkedIn use Java for critical systems, and it is known for its stability and reliability.
Code Examples
Hello World
// Basic Hello World
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
// Output using variables
String message = "Hello, Java!";
System.out.println(message);
// String concatenation
String name = "John";
int age = 25;
System.out.println("My name is " + name + " and I am " + age + " years old.");
// printf-style output
System.out.printf("My name is %s and I am %d years old.%n", name, age);
}
}
// Example using packages
package com.example.hello;
public class HelloJava {
public static void main(String[] args) {
System.out.println("Hello from Java package!");
}
}
Variables and Data Types
public class Variables {
public static void main(String[] args) {
// Primitive data types
int number = 42;
long bigNumber = 1234567890L;
float price = 99.99f;
double pi = 3.14159;
char initial = 'J';
boolean isActive = true;
byte smallNumber = 100;
short mediumNumber = 30000;
// Reference types
String name = "John Smith";
String nullString = null;
// Arrays
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3];
names[0] = "Smith";
names[1] = "Johnson";
names[2] = "Brown";
// Constants (final)
final double TAX_RATE = 0.1;
final String COMPANY_NAME = "ABC Corporation";
// Type inference (Java 10+)
var message = "This is a string"; // Inferred as String
var count = 10; // Inferred as int
var items = new String[]{"Item1", "Item2"}; // Inferred as String[]
// Output examples
System.out.println("Number: " + number);
System.out.println("Big number: " + bigNumber);
System.out.println("Price: " + price);
System.out.println("Pi: " + pi);
System.out.println("Initial: " + initial);
System.out.println("Active: " + isActive);
System.out.println("Name: " + name);
// Array output
System.out.println("Number array: " + java.util.Arrays.toString(numbers));
System.out.println("Name array: " + java.util.Arrays.toString(names));
// Null check
if (nullString == null) {
System.out.println("nullString is null");
}
}
}
Methods
public class Methods {
// Basic method
public static int add(int a, int b) {
return a + b;
}
// Method overloading
public static double add(double a, double b) {
return a + b;
}
public static String add(String a, String b) {
return a + b;
}
// Variable arguments
public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
// Void method
public static void printMessage(String message) {
System.out.println("Message: " + message);
}
// Method with array parameter
public static void printArray(String[] array) {
for (String item : array) {
System.out.println("- " + item);
}
}
// Recursive method
public static int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
// Method calls
System.out.println("5 + 3 = " + add(5, 3));
System.out.println("2.5 + 3.7 = " + add(2.5, 3.7));
System.out.println("Hello + World = " + add("Hello", "World"));
// Variable arguments
System.out.println("Sum: " + sum(1, 2, 3, 4, 5));
System.out.println("Sum: " + sum(10, 20));
// Void method
printMessage("Hello, Java!");
// Passing arrays
String[] fruits = {"Apple", "Banana", "Orange"};
printArray(fruits);
// Recursive method
System.out.println("Factorial of 5: " + factorial(5));
}
}
Classes and Objects
// Basic class
class Person {
// Fields (private)
private String name;
private int age;
private String email;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Overloaded constructor
public Person(String name, int age, String email) {
this(name, age); // Call other constructor
this.email = email;
}
// Getters
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
// Setters
public void setAge(int age) {
if (age >= 0) {
this.age = age;
}
}
public void setEmail(String email) {
this.email = email;
}
// Methods
public void introduce() {
System.out.println("My name is " + name + " and I am " + age + " years old.");
if (email != null) {
System.out.println("Email: " + email);
}
}
// Static method
public static Person createDefaultPerson() {
return new Person("No name", 0);
}
// Override toString method
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + ", email='" + email + "'}";
}
}
// Abstract class
abstract class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public abstract void makeSound();
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
// Inheritance
class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name);
this.breed = breed;
}
@Override
public void makeSound() {
System.out.println(name + " (" + breed + ") is barking.");
}
public void fetch() {
System.out.println(name + " fetched the ball.");
}
}
// Interface
interface Drawable {
void draw();
// Default method (Java 8+)
default void info() {
System.out.println("This is a drawable object.");
}
// Static method (Java 8+)
static void showVersion() {
System.out.println("Drawable interface v1.0");
}
}
// Interface implementation
class Circle implements Drawable {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius);
}
public double getArea() {
return Math.PI * radius * radius;
}
}
public class ClassExample {
public static void main(String[] args) {
// Object creation
Person person1 = new Person("John Smith", 25);
Person person2 = new Person("Jane Doe", 30, "[email protected]");
// Method calls
person1.introduce();
person2.introduce();
// Using setters
person1.setEmail("[email protected]");
person1.introduce();
// Using toString
System.out.println(person1);
// Static method call
Person defaultPerson = Person.createDefaultPerson();
defaultPerson.introduce();
// Inheritance example
Dog dog = new Dog("Buddy", "Golden Retriever");
dog.makeSound();
dog.fetch();
dog.sleep();
// Interface example
Circle circle = new Circle(5.0);
circle.draw();
circle.info();
System.out.println("Circle area: " + circle.getArea());
// Static method call
Drawable.showVersion();
}
}
Collection Framework
import java.util.*;
import java.util.stream.Collectors;
public class Collections {
public static void main(String[] args) {
// ArrayList
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Apple"); // Duplicates allowed
System.out.println("Fruit list: " + fruits);
System.out.println("First element: " + fruits.get(0));
System.out.println("Size: " + fruits.size());
// Enhanced for loop (for-each)
System.out.println("Each fruit:");
for (String fruit : fruits) {
System.out.println("- " + fruit);
}
// HashSet (no duplicates)
Set<String> uniqueFruits = new HashSet<>(fruits);
System.out.println("Unique fruits: " + uniqueFruits);
// HashMap
Map<String, Integer> fruitPrices = new HashMap<>();
fruitPrices.put("Apple", 100);
fruitPrices.put("Banana", 80);
fruitPrices.put("Orange", 120);
System.out.println("Fruit prices:");
for (Map.Entry<String, Integer> entry : fruitPrices.entrySet()) {
System.out.println(entry.getKey() + ": $" + entry.getValue());
}
// Stream API (Java 8+)
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// Filtering
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println("Even numbers: " + evenNumbers);
// Mapping
List<Integer> doubled = numbers.stream()
.map(n -> n * 2)
.collect(Collectors.toList());
System.out.println("Doubled: " + doubled);
// Sum
int sum = numbers.stream()
.mapToInt(Integer::intValue)
.sum();
System.out.println("Sum: " + sum);
// Finding elements matching condition
Optional<String> expensiveFruit = fruitPrices.entrySet().stream()
.filter(entry -> entry.getValue() > 100)
.map(Map.Entry::getKey)
.findFirst();
if (expensiveFruit.isPresent()) {
System.out.println("Expensive fruit: " + expensiveFruit.get());
}
// Grouping
List<String> words = Arrays.asList("apple", "banana", "apricot", "cherry", "avocado");
Map<Character, List<String>> groupedWords = words.stream()
.collect(Collectors.groupingBy(word -> word.charAt(0)));
System.out.println("Grouped by first letter: " + groupedWords);
}
}
Exception Handling
// Custom exception classes
class ValidationException extends Exception {
public ValidationException(String message) {
super(message);
}
}
class AgeOutOfRangeException extends RuntimeException {
public AgeOutOfRangeException(String message) {
super(message);
}
}
public class ExceptionHandling {
// Method that throws checked exception
public static void validateEmail(String email) throws ValidationException {
if (email == null || !email.contains("@")) {
throw new ValidationException("Invalid email address: " + email);
}
}
// Method that throws unchecked exception
public static void validateAge(int age) {
if (age < 0 || age > 150) {
throw new AgeOutOfRangeException("Age must be between 0 and 150: " + age);
}
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
public static void main(String[] args) {
// try-catch statement
try {
int result = divide(10, 2);
System.out.println("10 ÷ 2 = " + result);
} catch (ArithmeticException e) {
System.out.println("Arithmetic error: " + e.getMessage());
}
// Catching multiple exceptions
try {
validateEmail("invalid-email");
} catch (ValidationException e) {
System.out.println("Validation error: " + e.getMessage());
}
// Catching unchecked exception
try {
validateAge(-5);
} catch (AgeOutOfRangeException e) {
System.out.println("Age error: " + e.getMessage());
}
// Multi-catch (Java 7+)
try {
int[] array = {1, 2, 3};
System.out.println(array[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException | NullPointerException e) {
System.out.println("Array or null error: " + e.getMessage());
}
// finally clause
try {
System.out.println("Executing process...");
// Some processing
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
} finally {
System.out.println("Cleanup process (always executed)");
}
// try-with-resources (Java 7+)
try (Scanner scanner = new Scanner(System.in)) {
// Resources are automatically closed
System.out.println("Scanner will be automatically closed");
} catch (Exception e) {
System.out.println("Scanner error: " + e.getMessage());
}
// Exception re-throwing with throw statement
try {
handleException();
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
private static void handleException() throws Exception {
try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println("Caught internally: " + e.getMessage());
throw new Exception("Processing failed", e); // Preserve original exception
}
}
}
Generics
import java.util.*;
// Generic class
class Box<T> {
private T content;
public void set(T content) {
this.content = content;
}
public T get() {
return content;
}
@Override
public String toString() {
return "Box{content=" + content + "}";
}
}
// Multiple type parameters
class Pair<T, U> {
private T first;
private U second;
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
public T getFirst() { return first; }
public U getSecond() { return second; }
@Override
public String toString() {
return "Pair{first=" + first + ", second=" + second + "}";
}
}
// Bounded type parameters
class NumberBox<T extends Number> {
private T number;
public NumberBox(T number) {
this.number = number;
}
public double getDoubleValue() {
return number.doubleValue();
}
}
public class Generics {
// Generic method
public static <T> void swap(T[] array, int i, int j) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
// Generic method with multiple type parameters
public static <T, U> void printPair(T first, U second) {
System.out.println("Pair: " + first + " and " + second);
}
// Wildcards
public static void printList(List<?> list) {
for (Object item : list) {
System.out.println("- " + item);
}
}
// Upper bounded wildcard
public static double sumOfNumbers(List<? extends Number> numbers) {
double sum = 0.0;
for (Number num : numbers) {
sum += num.doubleValue();
}
return sum;
}
// Lower bounded wildcard
public static void addNumbers(List<? super Integer> list) {
list.add(1);
list.add(2);
list.add(3);
}
public static void main(String[] args) {
// Using generic classes
Box<String> stringBox = new Box<>();
stringBox.set("Hello, Generics!");
System.out.println("String box: " + stringBox.get());
Box<Integer> numberBox = new Box<>();
numberBox.set(42);
System.out.println("Number box: " + numberBox.get());
// Multiple type parameters
Pair<String, Integer> nameAge = new Pair<>("John", 25);
System.out.println("Name and age: " + nameAge);
// Bounded type parameters
NumberBox<Integer> intBox = new NumberBox<>(100);
NumberBox<Double> doubleBox = new NumberBox<>(3.14);
System.out.println("Integer box: " + intBox.getDoubleValue());
System.out.println("Double box: " + doubleBox.getDoubleValue());
// Generic methods
String[] words = {"Hello", "World", "Java"};
System.out.println("Before swap: " + Arrays.toString(words));
swap(words, 0, 2);
System.out.println("After swap: " + Arrays.toString(words));
// Multiple type parameters
printPair("Name", "John");
printPair(100, 200);
// Wildcards
List<String> stringList = Arrays.asList("Apple", "Banana", "Orange");
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
System.out.println("String list:");
printList(stringList);
System.out.println("Integer list:");
printList(intList);
// Upper bounded wildcard
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
List<Double> doubles = Arrays.asList(1.1, 2.2, 3.3);
System.out.println("Sum of integers: " + sumOfNumbers(integers));
System.out.println("Sum of doubles: " + sumOfNumbers(doubles));
// Lower bounded wildcard
List<Number> numbers = new ArrayList<>();
addNumbers(numbers);
System.out.println("Added numbers: " + numbers);
}
}
Versions
Version | Release Date | Major Features |
---|---|---|
Java 21 (LTS) | 2023-09 | Virtual Threads, Pattern Matching, Record Patterns |
Java 17 (LTS) | 2021-09 | Sealed Classes, Pattern Matching for switch |
Java 11 (LTS) | 2018-09 | Local-Variable Syntax for Lambda, HTTP Client API |
Java 8 (LTS) | 2014-03 | Lambda Expressions, Stream API, Optional |
Java 7 | 2011-07 | Try-with-resources, Diamond operator |
Java 6 | 2006-12 | Scripting API, Compiler API |
Java 5 | 2004-09 | Generics, Annotations, Autoboxing |
Reference Links
Official Documentation
- Java Official Site - Official website
- Oracle Java Documentation - Oracle official documentation
- OpenJDK - Open source implementation
Learning Resources
- Oracle Java Tutorials - Oracle official tutorials
- Java Code Geeks - Resources for Java developers
- Baeldung - Comprehensive Java and Spring learning site
Development Tools
- IntelliJ IDEA - Popular Java IDE
- Eclipse - Open source Java IDE
- Maven - Project management and build tool
- Gradle - Modern build tool