Core Java Programs for Practice
Core Java Programs for Practice
Welcome to this post where we'll go through some core Java programs that are great for practice. Each program demonstrates fundamental concepts and provides a solid base for understanding core Java functionalities.
1.1 Hello World Program
This is the most basic Java program that prints "Hello, World!" to the console.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
1.2 Basic Calculator
This program performs basic arithmetic operations like addition, subtraction, multiplication, and division.
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.println("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.println("Enter operation (+, -, *, /): ");
char operator = scanner.next().charAt(0);
double result;
switch (operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
System.out.println("Invalid operator");
return;
}
System.out.println("Result: " + result);
}
}
2.1 Factorial Calculator
This program calculates the factorial of a number using a loop.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = scanner.nextInt();
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println("Factorial of " + num + " is " + factorial);
}
}
2.2 Fibonacci Series
This program generates the Fibonacci series up to a specified number of terms.
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of terms: ");
int terms = scanner.nextInt();
int first = 0, second = 1;
System.out.println("Fibonacci Series:");
for (int i = 1; i <= terms; i++) {
System.out.print(first + " ");
int next = first + second;
first = second;
second = next;
}
}
}
2.3 Prime Number Check
This program checks if a given number is prime.
import java.util.Scanner;
public class PrimeNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number: ");
int num = scanner.nextInt();
boolean isPrime = true;
if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}
3.1 Arithmetic Operators
This program demonstrates arithmetic operators in Java.
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 10;
int b = 5;
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
}
}
3.2 Boolean Operators
This program demonstrates boolean operators in Java.
public class BooleanOperators {
public static void main(String[] args) {
boolean x = true;
boolean y = false;
System.out.println("x && y = " + (x && y));
System.out.println("x || y = " + (x || y));
System.out.println("!x = " + (!x));
}
}
3.3 Logical Operators
This program demonstrates logical operators in Java.
public class LogicalOperators {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("a < b && b < 30 = " + (a < b && b < 30));
System.out.println("a < b || b < 15 = " + (a < b || b < 15));
System.out.println("!(a < b) = " + !(a < b));
}
}
3.4 Binary Operators
This program demonstrates binary operators in Java.
public class BinaryOperators {
public static void main(String[] args) {
int a = 10; // 00001010
int b = 5; // 00000101
System.out.println("a & b = " + (a & b));
System.out.println("a | b = " + (a | b));
System.out.println("a ^ b = " + (a ^ b));
System.out.println("a << 1 = " + (a << 1));
System.out.println("a >> 1 = " + (a >> 1));
System.out.println("a >>> 1 = " + (a >>> 1));
}
}
4.1 Branching Statements
This program demonstrates branching statements in Java.
public class BranchingStatements {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
System.out.println("Number is positive.");
} else if (number < 0) {
System.out.println("Number is negative.");
} else {
System.out.println("Number is zero.");
}
}
}
4.2 Iterative Statements
This program demonstrates iterative statements in Java.
public class IterativeStatements {
public static void main(String[] args) {
System.out.println("While Loop:");
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
System.out.println("For Loop:");
for (int j = 0; j < 5; j++) {
System.out.println(j);
}
System.out.println("Do-While Loop:");
int k = 0;
do {
System.out.println(k);
k++;
} while (k < 5);
}
}
4.3 Goto Statement
This program demonstrates the use of labels (goto-like behavior) in Java.
public class GotoStatement {
public static void main(String[] args) {
int count = 0;
label: while (true) {
while (true) {
if (count == 3) {
break label;
}
System.out.println("Count: " + count);
count++;
}
}
}
}
4.4 Break & Continue Statements
This program demonstrates break and continue statements in Java.
public class BreakContinueStatements {
public static void main(String[] args) {
System.out.println("Break Statement:");
for (int i = 0; i < 5; i++) {
if (i == 3) {
break;
}
System.out.println(i);
}
System.out.println("Continue Statement:");
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
}
}
5.1 Basics of OOPs
This program demonstrates basic concepts of Object-Oriented Programming (OOP) in Java.
public class BasicOOP {
public static void main(String[] args) {
Person person = new Person("John", 30);
person.display();
}
}
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
5.2 Constructors
This program demonstrates the use of constructors in Java.
public class Constructors {
public static void main(String[] args) {
Employee emp1 = new Employee("Alice", 50000);
Employee emp2 = new Employee("Bob");
emp1.display();
emp2.display();
}
}
class Employee {
String name;
double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
Employee(String name) {
this(name, 0);
}
void display() {
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}
}
6.1 Basics of Inheritance
This program demonstrates basic inheritance in Java.
public class InheritanceDemo {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
dog.display();
dog.bark();
}
}
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void display() {
System.out.println("Name: " + name);
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
void bark() {
System.out.println(name + " barks.");
}
}
7.1 Exception Handling
This program demonstrates exception handling in Java.
public class ExceptionHandling {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 100; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
} finally {
System.out.println("Finally block executed.");
}
}
}
8.1 Interfaces
This program demonstrates interfaces in Java.
public class InterfaceDemo {
public static void main(String[] args) {
Vehicle vehicle = new Car();
vehicle.start();
}
}
interface Vehicle {
void start();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car started.");
}
}
9.1 Multithreaded Programming
This program demonstrates multithreading in Java.
public class MultithreadedDemo {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());
thread1.start();
thread2.start();
}
}
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getId() + " Value: " + i);
}
}
}
10.1 Predefined Libraries
This program demonstrates the use of predefined libraries in Java.
import java.util.Date;
import java.text.SimpleDateFormat;
public class PredefinedLibraries {
public static void main(String[] args) {
// Using String class
String str = "Hello, World!";
System.out.println("Length of the string: " + str.length());
// Using java.lang package
int number = 123;
System.out.println("Number as a string: " + Integer.toString(number));
// Working with Date & Time
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("Current date: " + formatter.format(date));
}
}
10.2 Utility Framework
This program demonstrates the use of Java Utility Framework classes.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class UtilityFrameworkDemo {
public static void main(String[] args) {
// Using ArrayList
List list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println("ArrayList: " + list);
// Using HashMap
Map map = new HashMap<>();
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);
System.out.println("HashMap: " + map);
}
}
10.3 Collection Framework
This program demonstrates the use of Java Collection Framework classes.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.HashSet;
import java.util.TreeSet;
public class CollectionFrameworkDemo {
public static void main(String[] args) {
// Using ArrayList
ArrayList arrayList = new ArrayList<>();
arrayList.add("Red");
arrayList.add("Green");
arrayList.add("Blue");
System.out.println("ArrayList: " + arrayList);
// Using LinkedList
LinkedList linkedList = new LinkedList<>();
linkedList.add("Dog");
linkedList.add("Cat");
linkedList.add("Bird");
System.out.println("LinkedList: " + linkedList);
// Using HashSet
HashSet hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Apple"); // Duplicate value
System.out.println("HashSet: " + hashSet);
// Using TreeSet
TreeSet treeSet = new TreeSet<>();
treeSet.add("Pine");
treeSet.add("Oak");
treeSet.add("Maple");
System.out.println("TreeSet: " + treeSet);
}
}
10.4 I/O Framework
This program demonstrates basic file operations using the Java I/O framework.
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
public class IOFrameworkDemo {
public static void main(String[] args) {
File file = new File("example.txt");
// Writing to a file
try (FileWriter writer = new FileWriter(file)) {
writer.write("Hello, Java I/O Framework!");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
// Reading from a file
try (FileReader reader = new FileReader(file)) {
int ch;
while ((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}
}
These programs cover fundamental Java concepts and are great for practice. Feel free to modify them and try out more advanced variations as you progress in your learning journey!
Comments
Post a Comment