A simple Java program consists of at least one class and a main method. Let's start with the most basic Java program:
javaCopy code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}- public class HelloWorld: This defines a class named
HelloWorld. In Java, every application must have at least one class. - public static void main(String[] args): This is the
mainmethod, which is the entry point of any Java application. The JVM looks for this method to start the program. - System.out.println("Hello, World!");: This line prints the text "Hello, World!" to the console.
- Open a text editor or an Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse.
- Copy the above code into a new file named
HelloWorld.java. - Compile the program using
javac HelloWorld.javaand run it usingjava HelloWorldin the terminal.
Variables store data that can be used and manipulated in your program. Let's learn about different data types and how to declare variables.
javaCopy code
public class VariablesExample {
public static void main(String[] args) {
int number = 10; // Integer (whole number)
double price = 19.99; // Floating point number
char letter = 'A'; // Character
boolean isJavaFun = true; // Boolean (true/false)
String greeting = "Hello"; // String (sequence of characters)
System.out.println("Number: " + number);
System.out.println("Price: " + price);
System.out.println("Letter: " + letter);
System.out.println("Is Java Fun: " + isJavaFun);
System.out.println("Greeting: " + greeting);
}
}- int number = 10;: Declares an integer variable named
numberand initializes it to 10. - double price = 19.99;: Declares a double variable named
priceand initializes it to 19.99. - char letter = 'A';: Declares a char variable named
letterand initializes it to 'A'. - boolean isJavaFun = true;: Declares a boolean variable named
isJavaFunand initializes it to true. - String greeting = "Hello";: Declares a String variable named
greetingand initializes it to "Hello".
- Create a new file named
VariablesExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
Now, let's learn how to perform basic arithmetic operations.
javaCopy code
public class BasicOperations {
public static void main(String[] args) {
int a = 10;
int b = 5;
int sum = a + b; // Addition
int difference = a - b; // Subtraction
int product = a * b; // Multiplication
int quotient = a / b; // Division
int remainder = a % b; // Modulus (remainder)
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
System.out.println("Remainder: " + remainder);
}
}- int sum = a + b;: Adds
aandb, and stores the result insum. - int difference = a - b;: Subtracts
bfroma, and stores the result indifference. - int product = a * b;: Multiplies
aandb, and stores the result inproduct. - int quotient = a / b;: Divides
abyb, and stores the result inquotient. - int remainder = a % b;: Calculates the remainder when
ais divided byb, and stores the result inremainder.
- Create a new file named
BasicOperations.java. - Copy the above code into this file.
- Compile and run the program to see the output.
Control structures allow you to control the flow of your program. Let's start with if statements.
javaCopy code
public class IfStatements {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
}
}- if (number > 0): Checks if
numberis greater than 0. - else if (number < 0): If the previous condition is false, checks if
numberis less than 0. - else: If none of the above conditions are true, this block is executed.
- Create a new file named
IfStatements.java. - Copy the above code into this file.
- Change the value of
numberand observe how the output changes. - Compile and run the program to see the output.
Loops allow you to execute a block of code multiple times. Let's start with for loops and while loops.
A for loop is useful when you know in advance how many times you want to execute a statement or a block of statements.
javaCopy code
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println("i is: " + i);
}
}
}- for (int i = 0; i < 5; i++): Initializes
ito 0, checks ifiis less than 5, and incrementsiby 1 after each iteration. - System.out.println("i is: " + i);: Prints the value of
i.
- Create a new file named
ForLoopExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
A while loop is useful when you want to repeat a block of code as long as a condition is true.
javaCopy code
public class WhileLoopExample {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println("i is: " + i);
i++;
}
}
}- int i = 0;: Initializes
ito 0. - while (i < 5): Checks if
iis less than 5. - System.out.println("i is: " + i);: Prints the value of
i. - i++;: Increments
iby 1.
- Create a new file named
WhileLoopExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
Methods are reusable blocks of code that perform a specific task. They help you organize your code and make it more readable and maintainable.
javaCopy code
public class MethodsExample {
public static void main(String[] args) {
printHello();
int result = add(5, 3);
System.out.println("Sum: " + result);
}
// Method to print a message
public static void printHello() {
System.out.println("Hello!");
}
// Method to add two numbers and return the result
public static int add(int a, int b) {
return a + b;
}
}- printHello(): This method prints "Hello!" to the console.
- add(int a, int b): This method takes two integers as parameters, adds them, and returns the result.
- Create a new file named
MethodsExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try adding more methods to perform different operations, like subtraction, multiplication, etc.
In Java, classes are blueprints for creating objects. An object is an instance of a class. Let's create a simple class and create objects from it.
javaCopy code
class Person {
String name;
int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display the person's details
public void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class ClassesAndObjects {
public static void main(String[] args) {
// Creating objects
Person person1 = new Person("Alice", 30);
Person person2 = new Person("Bob", 25);
// Calling methods on objects
person1.display();
person2.display();
}
}- class Person: Defines a class named
Person. - String name; int age;: Declares instance variables for the class.
- public Person(String name, int age): A constructor to initialize the instance variables.
- public void display(): A method to display the person's details.
- Person person1 = new Person("Alice", 30);: Creates an object of the
Personclass. - person1.display();: Calls the
displaymethod on theperson1object.
- Create a new file named
ClassesAndObjects.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try creating more objects and calling methods on them.
Inheritance allows a class to inherit fields and methods from another class. This promotes code reusability.
javaCopy code
class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("The dog barks.");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method
myDog.bark(); // Method from Dog class
}
}- class Animal: A base class with a method
eat. - class Dog extends Animal: A derived class that inherits from
Animaland adds a new methodbark. - Dog myDog = new Dog();: Creates an object of the
Dogclass. - myDog.eat();: Calls the inherited
eatmethod. - myDog.bark();: Calls the
barkmethod of theDogclass.
- Create a new file named
InheritanceExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try creating more classes and using inheritance to add functionality.
An interface is a reference type in Java, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields or constructors.
javaCopy code
interface Animal {
void eat();
void makeSound();
}
class Dog implements Animal {
@Override
public void eat() {
System.out.println("The dog eats bones.");
}
@Override
public void makeSound() {
System.out.println("The dog barks.");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.makeSound();
}
}- interface Animal: Declares an interface named
Animalwith two abstract methods. - class Dog implements Animal: The
Dogclass implements theAnimalinterface and provides implementations for theeatandmakeSoundmethods. - myDog.eat();: Calls the
eatmethod on themyDogobject. - myDog.makeSound();: Calls the
makeSoundmethod on themyDogobject.
- Create a new file named
InterfaceExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try creating more classes that implement the
Animalinterface.
An abstract class cannot be instantiated and may contain abstract methods, which must be implemented by subclasses.
abstract class Animal {
abstract void eat();
abstract void makeSound();
}
class Dog extends Animal {
@Override
public void eat() {
System.out.println("The dog eats bones.");
}
@Override
public void makeSound() {
System.out.println("The dog barks.");
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat();
myDog.makeSound();
}
}- abstract class Animal: Declares an abstract class named
Animalwith two abstract methods. - class Dog extends Animal: The
Dogclass extends theAnimalclass and provides implementations for theeatandmakeSoundmethods. - Dog myDog = new Dog();: Creates an object of the
Dogclass. - myDog.eat();: Calls the
eatmethod on themyDogobject. - myDog.makeSound();: Calls the
makeSoundmethod on themyDogobject.
- Create a new file named
AbstractClassExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try creating more classes that extend the
Animalabstract class.
Exception handling in Java is managed via try, catch, finally, and throw keywords. It allows you to handle runtime errors, ensuring the normal flow of the program.
javaCopy code
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int division = divide(10, 0);
System.out.println("Result: " + division);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} finally {
System.out.println("This block always executes.");
}
}
public static int divide(int a, int b) throws ArithmeticException {
return a / b;
}
}- try: The block of code to be tested for errors.
- catch: The block of code to be executed if an error occurs in the
tryblock. - finally: The block of code that always executes, regardless of whether an exception is thrown or not.
- throws ArithmeticException: Declares that the
dividemethod may throw anArithmeticException.
- Create a new file named
ExceptionHandlingExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try modifying the values to see different outcomes.
Reading from and writing to files is a common task. Java provides several classes for file operations.
javaCopy code
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFileExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, world!");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}- FileWriter writer = new FileWriter("output.txt");: Creates a
FileWriterobject to write to a file namedoutput.txt. - writer.write("Hello, world!");: Writes the string to the file.
- writer.close();: Closes the file writer.
- Create a new file named
WriteToFileExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Check the directory for the
output.txtfile to see the written content.
javaCopy code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFromFileExample {
public static void main(String[] args) {
try {
File file = new File("output.txt");
Scanner reader = new Scanner(file);
while (reader.hasNextLine()) {
String data = reader.nextLine();
System.out.println(data);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}- File file = new File("output.txt");: Creates a
Fileobject for the file namedoutput.txt. - Scanner reader = new Scanner(file);: Creates a
Scannerobject to read from the file. - reader.hasNextLine(): Checks if the file has another line to read.
- String data = reader.nextLine();: Reads the next line from the file.
- Create a new file named
ReadFromFileExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Ensure
output.txtexists in the same directory with some content to read.
The Java Collections Framework provides a set of classes and interfaces to store and manipulate groups of data as a single unit. Let's look at some commonly used collections: ArrayList, HashMap, and HashSet.
An ArrayList is a resizable array that can contain elements of a specific type.
javaCopy code
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
// Adding elements to the ArrayList
list.add("Apple");
list.add("Banana");
list.add("Orange");
// Accessing elements
System.out.println("First element: " + list.get(0));
// Removing an element
list.remove(1);
// Iterating through the ArrayList
System.out.println("Elements in the list:");
for (String fruit : list) {
System.out.println(fruit);
}
}
}- Create a new file named
ArrayListExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try adding more elements, removing elements, and iterating in different ways.
A HashMap is a collection that stores key-value pairs. It allows you to map keys to values.
javaCopy code
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
// Adding key-value pairs to the HashMap
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 3);
// Accessing a value by key
System.out.println("Value for 'Apple': " + map.get("Apple"));
// Removing a key-value pair
map.remove("Banana");
// Iterating through the HashMap
System.out.println("Elements in the map:");
for (String key : map.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
}
}- Create a new file named
HashMapExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try adding more key-value pairs, removing pairs, and iterating in different ways.
A HashSet is a collection that contains no duplicate elements. It's useful for storing unique elements.
javaCopy code
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
// Adding elements to the HashSet
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Apple"); // Duplicate element
// Iterating through the HashSet
System.out.println("Elements in the set:");
for (String fruit : set) {
System.out.println(fruit);
}
}
}- Create a new file named
HashSetExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try adding more elements and observing how duplicates are handled.
Generics allow you to write flexible, reusable code by parameterizing types. Let's look at a simple example of a generic class.
javaCopy code
public class GenericBox<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
public static void main(String[] args) {
GenericBox<String> stringBox = new GenericBox<>();
stringBox.setContent("Hello, Generics!");
System.out.println("String content: " + stringBox.getContent());
GenericBox<Integer> integerBox = new GenericBox<>();
integerBox.setContent(123);
System.out.println("Integer content: " + integerBox.getContent());
}
}- GenericBox: Declares a generic class with a type parameter
T. - setContent(T content): Sets the content of the box.
- getContent(): Returns the content of the box.
- GenericBox stringBox = new GenericBox<>();: Creates a
GenericBoxobject forStringtype. - GenericBox integerBox = new GenericBox<>();: Creates a
GenericBoxobject forIntegertype.
- Create a new file named
GenericBox.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try creating more
GenericBoxobjects with different types.
Multi-threading allows you to perform multiple operations simultaneously. Let's look at creating and running threads in Java.
javaCopy code
public class MultiThreadExample extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
try {
Thread.sleep(500); // Sleep for 500 milliseconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
public static void main(String[] args) {
MultiThreadExample thread1 = new MultiThreadExample();
MultiThreadExample thread2 = new MultiThreadExample();
thread1.start();
thread2.start();
}
}- extends Thread: The
MultiThreadExampleclass extends theThreadclass. - run(): The
runmethod contains the code that will be executed by the thread. - thread1.start();: Starts the first thread.
- thread2.start();: Starts the second thread.
- Create a new file named
MultiThreadExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try creating more threads and observing how they run concurrently.
Let's look at more advanced exception handling, including creating custom exceptions.
javaCopy code
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
try {
validateAge(15);
} catch (CustomException e) {
System.out.println("Caught the exception");
System.out.println(e.getMessage());
}
}
static void validateAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be 18 or above");
} else {
System.out.println("Valid age");
}
}
}- class CustomException extends Exception: Declares a custom exception class.
- validateAge(int age) throws CustomException: A method that throws a custom exception if the age is less than 18.
- throw new CustomException("Age must be 18 or above");: Throws a custom exception with a message.
- Create a new file named
CustomExceptionExample.java. - Copy the above code into this file.
- Compile and run the program to see the output.
- Try modifying the age to see different outcomes.
- Write a Java program that prints your name, age, and favorite hobby to the console.
- Create a program that declares variables of different data types (int, double, boolean, char, String) and prints their values.
- Write a program that takes two numbers as input and performs addition, subtraction, multiplication, and division. Print the results.
- Create a program that checks if a number is positive, negative, or zero using an
if-elsestatement. - Write a program that takes a score as input and prints the corresponding grade (A, B, C, D, F) using an
if-elseladder.
- Write a program that prints the numbers from 1 to 100 using a
forloop. - Create a program that prints the even numbers between 1 and 50 using a
whileloop.
- Write a program with a method that takes two integers as parameters and returns their sum. Call this method from the
mainmethod and print the result. - Create a method that checks if a given string is a palindrome.
- Define a
Personclass with fields for name, age, and address. Create an object of this class and print its details. - Create a
Carclass with methods for starting, stopping, and displaying the car's details. Instantiate an object of this class and call its methods.
- Create a base class
Animalwith a methodmakeSound(). Create derived classesDogandCatthat overridemakeSound(). Test the classes by creating objects and calling their methods.
- Define an interface
Shapewith methodscalculateArea()andcalculatePerimeter(). Implement this interface in classesCircleandRectangle. Create objects of these classes and call their methods.
- Create an abstract class
BankAccountwith methodsdeposit()andwithdraw(). Extend this class inSavingsAccountandCurrentAccountclasses. Implement the methods and test the classes.
- Write a program that handles an
ArrayIndexOutOfBoundsExceptionand prints an appropriate message. - Create a method that throws a custom exception
InsufficientFundsExceptionwhen a withdrawal amount exceeds the account balance.
- Write a program to write "Hello, world!" to a file named
hello.txt. - Create a program that reads from a file named
data.txtand prints its contents to the console.
- Write a program that uses an
ArrayListto store and print a list of fruits. - Create a program that uses a
HashMapto store and print student names and their corresponding grades. - Write a program that uses a
HashSetto store and print unique cities.
- Create a generic class
Boxthat can store objects of any type. Test this class with different data types. - Write a generic method that takes an array of any type and prints its elements.
- Write a program that creates two threads. Each thread should print numbers from 1 to 5, pausing for 1 second between each number.
- Create a program where two threads share a common resource (e.g., a counter). Ensure that the resource is accessed safely using synchronization.
- Create a custom exception
InvalidAgeExceptionand write a program that throws this exception if an invalid age (negative or over 150) is entered. - Write a program that demonstrates the use of multiple catch blocks for different exception types.
- Write a complete program that includes reading data from a file, processing it using collections, and handling any exceptions that may occur.
- Create a mini-banking application with classes for accounts, transactions, and customers. Include features like deposit, withdrawal, and balance inquiry. Use exception handling for error scenarios and collections to manage multiple accounts.
- Print name, age, and favorite hobby:
javaCopy code
public class PrintDetails {
public static void main(String[] args) {
System.out.println("Name: John Doe");
System.out.println("Age: 25");
System.out.println("Favorite Hobby: Reading");
}
}- Declare and print variables of different data types:
javaCopy code
public class DataTypesExample {
public static void main(String[] args) {
int age = 25;
double height = 5.9;
boolean isStudent = true;
char grade = 'A';
String name = "John Doe";
System.out.println("Age: " + age);
System.out.println("Height: " + height);
System.out.println("Is Student: " + isStudent);
System.out.println("Grade: " + grade);
System.out.println("Name: " + name);
}
}- Perform basic arithmetic operations:
javaCopy code
import java.util.Scanner;
public class BasicOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.println("Sum: " + (num1 + num2));
System.out.println("Difference: " + (num1 - num2));
System.out.println("Product: " + (num1 * num2));
System.out.println("Quotient: " + (num1 / num2));
}
}- Check if a number is positive, negative, or zero:
javaCopy code
import java.util.Scanner;
public class CheckNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
}
}- Print grade based on score:
javaCopy code
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your score: ");
int score = scanner.nextInt();
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else if (score >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
}
}- Print numbers from 1 to 100 using a
forloop:
javaCopy code
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
System.out.println(i);
}
}
}- Print even numbers between 1 and 50 using a
whileloop:
javaCopy code
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 50) {
if (i % 2 == 0) {
System.out.println(i);
}
i++;
}
}
}- Method to sum two integers:
javaCopy code
public class SumMethod {
public static int sum(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = sum(10, 20);
System.out.println("Sum: " + result);
}
}- Method to check if a string is a palindrome:
javaCopy code
public class PalindromeCheck {
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String word = "radar";
System.out.println(word + " is a palindrome: " + isPalindrome(word));
}
}- Person class:
javaCopy code
class Person {
String name;
int age;
String address;
Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
}
}
public class PersonExample {
public static void main(String[] args) {
Person person = new Person("John Doe", 25, "123 Main St");
person.displayDetails();
}
}- Car class:
javaCopy code
class Car {
String make;
String model;
int year;
Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
void start() {
System.out.println("The car is starting.");
}
void stop() {
System.out.println("The car is stopping.");
}
void displayDetails() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}
public class CarExample {
public static void main(String[] args) {
Car car = new Car("Toyota", "Camry", 2020);
car.start();
car.displayDetails();
car.stop();
}
}- Animal inheritance example:
javaCopy code
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Meow");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.makeSound();
cat.makeSound();
}
}- Shape interface example:
javaCopy code
interface Shape {
double calculateArea();
double calculatePerimeter();
}
class Circle implements Shape {
private double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
@Override
public double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle implements Shape {
private double length;
private double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
public double calculateArea() {
return length * width;
}
@Override
public double calculatePerimeter() {
return 2 * (length + width);
}
}
public class InterfaceExample {
public static void main(String[] args) {
Circle circle = new Circle(5);
Rectangle rectangle = new Rectangle(4, 6);
System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Circle Perimeter: " + circle.calculatePerimeter());
System.out.println("Rectangle Area: " + rectangle.calculateArea());
System.out.println("Rectangle Perimeter: " + rectangle.calculatePerimeter());
}
}- BankAccount abstract class example:
javaCopy code
abstract class BankAccount {
double balance;
BankAccount(double balance) {
this.balance = balance;
}
abstract void deposit(double amount);
abstract void withdraw(double amount);
}
class SavingsAccount extends BankAccount {
SavingsAccount(double balance) {
super(balance);
}
@Override
void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount + ", New Balance: " + balance);
}
@Override
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrew: " + amount + ", New Balance: " + balance);
} else {
System.out.println("Insufficient funds");
}
}
}
class CurrentAccount extends BankAccount {
CurrentAccount(double balance) {
super(balance);
}
@Override
void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount + ", New Balance: " + balance);
}
@Override
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrew: " + amount + ", New Balance: " + balance);
} else {
System.out.println("Insufficient funds");
}
}
}
public class AbstractClassExample {
public static void main(String[] args) {
SavingsAccount savingsAccount = new SavingsAccount(1000);
savingsAccount.deposit(200);
savingsAccount.withdraw(500);
CurrentAccount currentAccount = new CurrentAccount(2000);
currentAccount.deposit(500);
currentAccount.withdraw(1000);
}
}- Handle
ArrayIndexOutOfBoundsException:
javaCopy code
public class ArrayExceptionHandling {
public static void main(String[] args) {
int[] array = {1, 2, 3};
try {
System.out.println(array[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds");
}
}
}- Custom exception
InsufficientFundsException:
javaCopy code
class InsufficientFundsException extends Exception {
InsufficientFundsException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
BankAccount(double balance) {
this.balance = balance;
}
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds for withdrawal");
} else {
balance -= amount;
System.out.println("Withdrawn: " + amount + ", New Balance: " + balance);
}
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
BankAccount account = new BankAccount(500);
try {
account.withdraw(600);
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
}
}
}- Write to a file:
javaCopy code
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("hello.txt");
writer.write("Hello, world!");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}- Read from a file:
javaCopy code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFromFile {
public static void main(String[] args) {
try {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String data = scanner.nextLine();
System.out.println(data);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}- ArrayList of fruits:
javaCopy code
import java.util.ArrayList;
public class FruitList {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}- HashMap of students and grades:
javaCopy code
import java.util.HashMap;
import java.util.Map;
public class StudentGrades {
public static void main(String[] args) {
HashMap<String, String> grades = new HashMap<>();
grades.put("John", "A");
grades.put("Jane", "B");
grades.put("Jack", "C");
for (Map.Entry<String, String> entry : grades.entrySet()) {
System.out.println("Student: " + entry.getKey() + ", Grade: " + entry.getValue());
}
}
}- HashSet of unique cities:
javaCopy code
import java.util.HashSet;
public class UniqueCities {
public static void main(String[] args) {
HashSet<String> cities = new HashSet<>();
cities.add("New York");
cities.add("Los Angeles");
cities.add("Chicago");
cities.add("New York"); // Duplicate entry
for (String city : cities) {
System.out.println(city);
}
}
}- Generic
Boxclass:
javaCopy code
class Box<T> {
private T value;
Box(T value) {
this.value = value;
}
T getValue() {
return value;
}
void setValue(T value) {
this.value = value;
}
}
public class GenericBoxExample {
public static void main(String[] args) {
Box<Integer> intBox = new Box<>(123);
System.out.println("Integer value: " + intBox.getValue());
Box<String> strBox = new Box<>("Hello");
System.out.println("String value: " + strBox.getValue());
}
}- Generic method to print array elements:
javaCopy code
public class GenericMethodExample {
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
String[] strArray = {"A", "B", "C", "D", "E"};
System.out.println("Integer array:");
printArray(intArray);
System.out.println("String array:");
printArray(strArray);
}
}- Two threads printing numbers:
javaCopy code
class NumberThread extends Thread {
private String threadName;
NumberThread(String threadName) {
this.threadName = threadName;
}
public void run() {
try {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(threadName + " interrupted.");
}
}
}
public class MultiThreadExample {
public static void main(String[] args) {
NumberThread thread1 = new NumberThread("Thread 1");
NumberThread thread2 = new NumberThread("Thread 2");
thread1.start();
thread2.start();
}
}- Threads sharing a common resource:
javaCopy code
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
class CounterThread extends Thread {
private Counter counter;
CounterThread(Counter counter) {
this.counter = counter;
}
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
public class SynchronizedExample {
public static void main(String[] args) {
Counter counter = new Counter();
CounterThread thread1 = new CounterThread(counter);
CounterThread thread2 = new CounterThread(counter);
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final count: " + counter.getCount());
}
}- Custom exception
InvalidAgeException:
javaCopy code
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
public class AgeCheck {
public static void checkAge(int age) throws InvalidAgeException {
if (age < 0 || age > 150) {
throw new InvalidAgeException("Invalid age: " + age);
} else {
System.out.println("Valid age: " + age);
}
}
public static void main(String[] args) {
try {
checkAge(200);
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
}
}
}- Multiple catch blocks:
javaCopy code
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] array = new int[5];
array[10] = 30 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException: " + e.getMessage());
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
}