Java Labs

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Java Labs Dr Benabderrezak

Part 1 : Basic data types

Code Output

class HelloWorld {
public static void main(String[] args) {
System.out.println("Try programiz.pro");
}
}
public class PrimitiveExample1 {
public static void main(String[] args) {
int a = 5;
int b = 10;
int sum = a + b;
System.out.println("Sum: " + sum);
}
}

public class PrimitiveExample2 {


public static void main(String[] args) {
double pi = 3.14;
double radius = 2.5;
double area = pi * radius * radius;
System.out.println("Area: " + area);
}
}

public class PrimitiveExample3 {


public static void main(String[] args) {
char grade = 'A';
boolean isPassed = true;
System.out.println("Grade: " + grade + ", Passed: " + isPassed);
}
}

public class PrimitiveExample4 {


public static void main(String[] args) {
float height = 5.9f;
float weight = 70.5f;
System.out.println("Height: " + height + ", Weight: " + weight);
}
}

public class PrimitiveExample5 {


public static void main(String[] args) {
byte age = 25;
short year = 2024;

1
Java Labs Dr Benabderrezak

System.out.println("Age: " + age + ", Year: " + year);


}
}

public class PrimitiveExample6 {


public static void main(String[] args) {
int x = 100;
int y = 256;
int product = x * y;
System.out.println("Product: " + product);
}
}

public class PrimitiveExample7 {


public static void main(String[] args) {
long distance = 123456789L;
System.out.println("Distance: " + distance);
}
}

public class PrimitiveExample8 {


public static void main(String[] args) {
boolean isSunny = false;
boolean isWeekend = true;
System.out.println("Is Sunny: " + isSunny);
System.out.println(" Is Weekend: " + isWeekend);
}
}

public class PrimitiveExample11 {


public static void main(String[] args) {
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
System.out.println("Max: " + max + ", Min: " + min);
}
}

public class PrimitiveExample12 {


public static void main(String[] args) {
float temperatureC = 37.0f;
float temperatureF = (temperatureC * 9/5) + 32;
System.out.println("Temperature in Fahrenheit: " + temperatureF);
}
}

public class PrimitiveExample13 {


public static void main(String[] args) {
byte smallNumber = 10;

2
Java Labs Dr Benabderrezak

smallNumber += 5;
System.out.println("Small Number: " + smallNumber);
}
}

public class PrimitiveExample14 {


public static void main(String[] args) {
short speed = 120;
short time = 2;
short distance = (short)(speed * time);
System.out.println("Distance: " + distance);
}
}

public class PrimitiveExample15 {


public static void main(String[] args) {
long population = 7800000000L;
System.out.println("Population: " + population);
}
}

public class PrimitiveExample16 {


public static void main(String[] args) {
boolean isRaining = true;
isRaining = !isRaining;
System.out.println("Is Raining: " + isRaining);
}
}

public class PrimitiveExample17 {


public static void main(String[] args) {
char letter = 'Z';
int asciiValue = letter;
System.out.println("ASCII Value: " + asciiValue);
}
}

public class PrimitiveExample18 {


public static void main(String[] args) {
float average = (float)(1 + 2 + 3 + 4 + 5) / 5;
System.out.println("Average: " + average);
}
}

public class PrimitiveExample19 {


public static void main(String[] args) {
int number = 9;
boolean isEven = (number % 2) == 0;

3
Java Labs Dr Benabderrezak

System.out.println("Is Even: " + isEven);


}
}

public class PrimitiveExample20 {


public static void main(String[] args) {
double side = 4.0;
double volume = side * side * side;
System.out.println("Volume: " + volume);
}
}

Homework
public class BankingSystem {
public static void main(String[] args) {
String accountHolder = "John Doe";
int accountNumber = 123456;
int balance = 0;
int depositAmount = 500;
int withdrawAmount = 200;
int exitChoice = 1;

balance += (depositAmount > 0) ? depositAmount : 0;


System.out.println((depositAmount > 0) ? "Deposited: $" + depositAmount : "Invalid deposit amount.");

balance -= (withdrawAmount > 0 && withdrawAmount <= balance) ? withdrawAmount : 0;


boolean cond =withdrawAmount > 0 && withdrawAmount <= balance;
System.out.print(cond ? "Withdrawn: $"+withdrawAmount : "Invalid withdrawal amount or insufficient balance.");
System.out.println("Current balance: $" + balance);

System.out.println((exitChoice == 1) ? "Exiting the Banking System. Thank you!" : "You chose to continue.");
}
}

Output

4
Java Labs Dr Benabderrezak

Part 2 : Loops
Code Output

public class SumNaturalNumbers {


public static void main(String[] args) {
int n = 5;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
System.out.println(sum);
}
}

public class Factorial {


public static void main(String[] args) {
int n = 5; // Factorial of 5
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println("Factorial of " + n + ": " + factorial);
}
}

public class CountDown {


public static void main(String[] args) {
int count = 5;
while (count > 0) {
System.out.println(count);
count--;
}
System.out.println("Blast off!");
}
}

public class SumEvenNumbers {


public static void main(String[] args) {
int n = 10;
int sum = 0;
int i = 0;
while (i <= n) {
sum += i;
i += 2;
}
System.out.println(sum);
}}

5
Java Labs Dr Benabderrezak

public class UserInputSimulation {


public static void main(String[] args) {
int number = 0;
int sum = 0;
do {
sum += number;
number++;
} while (number <= 5);
System.out.println("Sum of numbers from 0 to 5: " + sum);
}
}

public class MultiplicationTable {


public static void main(String[] args) {
int number = 3;
for (int i = 1; i <= 4; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
}
}
}

public class MultiplicationTable {


public static void main(String[] args) {
int number = 3; // Multiplication table for 3
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
}
}
}

public class CountDigits {


public static void main(String[] args) {
int number = 12345;
int count = 0;
while (number != 0) {
number /= 10;
count++;
}
System.out.println("Number of digits: " + count);
}
}

public class GuessingGame {


public static void main(String[] args) {
int secretNumber = 7;
int guess = 0;
int attempts = 0;
do {
6
Java Labs Dr Benabderrezak

attempts++;
guess++;
} while (guess != secretNumber);
System.out.println("Guessed the number in " + attempts + " attempts!");
}
}

public class FibonacciSeries {


public static void main(String[] args) {
int n = 10;
int a = 0, b = 1;
System.out.print("Fibonacci Series: " + a + ", " + b);
for (int i = 2; i < n; i++) {
int next = a + b;
System.out.print(", " + next);
a = b;
b = next;
}
}
}

public class LargestNumber {


public static void main(String[] args) {
int[] numbers = {3, 5, 7, 2, 8};
int largest = numbers[0];
int i = 1;
while (i < numbers.length) {
if (numbers[i] > largest) {
largest = numbers[i];
}
i++;
}
System.out.println("Largest number: " + largest);
}
}

public class CountOddNumbers {


public static void main(String[] args) {
int n = 20; // Count odd numbers up to 20
int count = 0;
for (int i = 1; i <= n; i += 2) {
count++;
}
System.out.println("Count of odd numbers up to " + n + ": " + count);
}
}

7
Java Labs Dr Benabderrezak

public class SumOfDigits {


public static void main(String[] args) {
int number = 12345;
int sum = 0;
do {
sum += number % 10;
number /= 10;
} while (number != 0);
System.out.println("Sum of digits: " + sum);
}
}

// Homework

public class PrimeNumbers {


public static void main(String[] args) {
int n = 30; // Print prime numbers up to 30
System.out.print("Prime numbers up to " + n + ": ");
for (int i = 2; i <= n; i++) {
boolean isPrime = true;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(i + " ");
}
}
}
}

// Homework

public class SumOddNumbers {


public static void main(String[] args) {
int n = 5; // Sum of first 5 odd numbers
int sum = 0;
int count = 0;
int i = 1;
while (count < n) {
sum += i;
i += 2;
count++;
}

8
Java Labs Dr Benabderrezak

System.out.println("Sum of first " + n + " odd numbers: " + sum);


}
}

Part 3 : Arrays
Code Output
public class OneDArray {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}

public class MaxElement {


public static void main(String[] args) {
int[] numbers = {3, 5, 7, 2, 8};
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Maximum element: " + max);
}
}

public class TwoDArray {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

9
Java Labs Dr Benabderrezak

public class SumTwoDArray {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int sum = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
}
System.out.println("Sum of all elements: " + sum);
}
}

public class ReverseArray {


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.print("Reversed array: ");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + " ");
}
}
}

import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
for (int number : numbers) {
System.out.println("Element: " + number);
}
}
}

import java.util.ArrayList;

public class RemoveElement {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
10
Java Labs Dr Benabderrezak

numbers.add(30);
numbers.remove(1);
System.out.println("After removal: " + numbers);
}
}

import java.util.ArrayList;

public class MaxInArrayList {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(3);
numbers.add(5);
numbers.add(7);
numbers.add(2);
numbers.add(8);

int max = numbers.get(0);


for (int i = 1; i < numbers.size(); i++) {
if (numbers.get(i) > max) {
max = numbers.get(i);
}
}
System.out.println("Maximum element: " + max);
}
}

import java.util.ArrayList;

public class TwoDArrayList {


public static void main(String[] args) {
ArrayList<ArrayList<Integer>> matrix = new ArrayList<>();
for (int i = 0; i < 3; i++) {
matrix.add(new ArrayList<>());
for (int j = 0; j < 3; j++) {
matrix.get(i).add(i * 3 + j + 1);
}
}
for (ArrayList<Integer> row : matrix) {
System.out.println(row);
}
}
}

import java.util.HashMap;

public class MapExample {


public static void main(String[] args) {
11
Java Labs Dr Benabderrezak

HashMap<String, Integer> map = new HashMap<>();


map.put("Alice", 25);
map.put("Bob", 30);
map.put("Charlie", 35);

for (String key : map.keySet()) {


System.out.println(key + ": " + map.get(key));
}
}
}

import java.util.HashMap;

public class CheckKeyInMap {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);

String keyToCheck = "Alice";


if (map.containsKey(keyToCheck)) {
System.out.println(keyToCheck + " exists in the map.");
} else {
System.out.println(keyToCheck + " does not exist in the map.");
}
}
}

public class CountOccurrences {


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 2, 4, 2, 5};
int count = 0;
int elementToCount = 2;
for (int number : numbers) {
if (number == elementToCount) {
count++;
}
}
System.out.println("Occurrences of " + elementToCount + ": " + count);
}
}

public class TransposeMatrix {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
12
Java Labs Dr Benabderrezak

};
int[][] transpose = new int[3][3];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
transpose[j][i] = matrix[i][j];
}
}
System.out.println("Transposed Matrix:");
for (int[] row : transpose) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}

import java.util.ArrayList;
import java.util.Collections;

public class SortArrayList {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(3);
numbers.add(8);
numbers.add(1);

Collections.sort(numbers);
System.out.println("Sorted ArrayList: " + numbers);
}
}

public class SumOfRows {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < matrix.length; i++) {
int sum = 0;
for (int j = 0; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
System.out.println("Sum of row " + i + ": " + sum);
}

13
Java Labs Dr Benabderrezak

}
}

import java.util.HashMap;

public class GetValueByKey {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);

String keyToGet = "Bob";


Integer value = map.get(keyToGet);
System.out.println(keyToGet + ": " + value);
}
}

public class SearchInTwoDArray {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int target = 5;
boolean found = false;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == target) {
found = true;
System.out.println("Found " + target + " at (" + i + ", " + j + ")");
}
}
}
if (!found) {
System.out.println(target + " not found in the matrix.");
}
}
}

import java.util.ArrayList;

public class MinInArrayList {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(3);
numbers.add(5);
numbers.add(7);
14
Java Labs Dr Benabderrezak

numbers.add(2);
numbers.add(8);

int min = numbers.get(0);


for (int i = 1; i < numbers.size(); i++) {
if (numbers.get(i) < min) {
min = numbers.get(i);
}
}
System.out.println("Minimum element: " + min);
}
}

import java.util.HashMap;

public class IterateMap {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
map.put("Charlie", 35);

System.out.println("Iterating over map:");


for (HashMap.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}

import java.util.HashMap;

public class CheckMapEmpty {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
System.out.println("Is the map empty? " + map.isEmpty());

map.put("Alice", 25);
System.out.println("Is the map empty after adding an element? " + map.isEmpty());
}
}

import java.util.HashMap;

public class RemoveElementFromMap {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
15
Java Labs Dr Benabderrezak

map.put("Charlie", 35);

System.out.println("Map before removal: " + map);


map.remove("Bob");
System.out.println("Map after removal: " + map);
}
}

import java.util.HashMap;

public class SizeOfMap {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);
map.put("Charlie", 35);

System.out.println("Size of the map: " + map.size());


}
}

import java.util.HashMap;

public class MergeMaps {


public static void main(String[] args) {
HashMap<String, Integer> map1 = new HashMap<>();
map1.put("Alice", 25);
map1.put("Bob", 30);

HashMap<String, Integer> map2 = new HashMap<>();


map2.put("Charlie", 35);
map2.put("Dave", 40);

map1.putAll(map2);
System.out.println("Merged Map: " + map1);
}
}

import java.util.HashMap;

public class ReplaceValueInMap {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Alice", 25);
map.put("Bob", 30);

System.out.println("Map before replacement: " + map);


map.replace("Bob", 32);
16
Java Labs Dr Benabderrezak

System.out.println("Map after replacement: " + map);


}
}

Part 4 : Strings
Code Output
public class ConcatenateStrings {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = " World";
String result = str1 + str2;
System.out.println("Concatenated String: " + result);
}
}

public class StringLength {


public static void main(String[] args) {
String str = "Hello World";
int length = str.length();
System.out.println("Length of the String: " + length);
}
}

public class ReplaceCharacter {


public static void main(String[] args) {
String str = "Hello World";
String replaced = str.replace('o', '0');
System.out.println("Replaced String: " + replaced);
}
}

public class ContainsSubstring {


public static void main(String[] args) {
String str = "Hello World";
boolean contains = str.contains("World");
System.out.println("Contains 'World': " + contains);
}
}

public class TrimWhitespace {


public static void main(String[] args) {
String str = " Hello World ";
String trimmed = str.trim();
System.out.println("Trimmed String: '" + trimmed + "'");
}
}
17
Java Labs Dr Benabderrezak

public class CountWords {


public static void main(String[] args) {
String str = "Hello World, this is a test.";
String[] words = str.split("\\s+");
System.out.println("Number of words: " + words.length);
}
}

import java.util.Arrays;

public class AnagramCheck {


public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
boolean isAnagram = Arrays.equals(
str1.chars().sorted().toArray(),
str2.chars().sorted().toArray()
);
System.out.println("Are anagrams: " + isAnagram);
}
}

public class ReverseString {


public static void main(String[] args) {
String str = "Hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println("Reversed String: " + reversed);
}
}

public class PalindromeCheck {


public static void main(String[] args) {
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
boolean isPalindrome = str.equals(reversed);
System.out.println("Is palindrome: " + isPalindrome);
}
}

public class CountVowels {


public static void main(String[] args) {
String str = "Hello World";
int count = 0;
for (char c : str.toCharArray()) {
if ("AEIOUaeiou".indexOf(c) != -1) {
count++;
}
}
18
Java Labs Dr Benabderrezak

System.out.println("Number of vowels: " + count);


}
}

public class ConvertToUppercase {


public static void main(String[] args) {
String str = "hello";
String upperStr = str.toUpperCase();
System.out.println("Uppercase String: " + upperStr);
}
}

import java.util.LinkedHashSet;

public class RemoveDuplicates {


public static void main(String[] args) {
String str = "programming";
LinkedHashSet<Character> set = new LinkedHashSet<>();
for (char c : str.toCharArray()) {
set.add(c);
}
StringBuilder result = new StringBuilder();
for (char c : set) {
result.append(c);
}
System.out.println("String after removing duplicates: " + result);
}
}

import java.util.LinkedHashMap;

public class FirstNonRepeatingCharacter {


public static void main(String[] args) {
String str = "swiss";
LinkedHashMap<Character, Integer> charCount = new LinkedHashMap<>();

for (char c : str.toCharArray()) {


charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}

for (char c : charCount.keySet()) {


if (charCount.get(c) == 1) {
System.out.println("First non-repeating character: " + c);
break;
}
}
}
}
19
Java Labs Dr Benabderrezak

public class ReverseWords {


public static void main(String[] args) {
String str = "Hello World";
String[] words = str.split(" ");
StringBuilder reversed = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
reversed.append(words[i]).append(" ");
}
System.out.println("Reversed Words: " + reversed.toString().trim());
}
}

public class LongestPalindrome {


public static void main(String[] args) {
String str = "babad";
String longest = "";

for (int i = 0; i < str.length(); i++) {


for (int j = i; j < str.length(); j++) {
String substring = str.substring(i, j + 1);
String reversed = new StringBuilder(substring).reverse().toString();
if (substring.equals(reversed) && substring.length() > longest.length()) {
longest = substring;
}
}
}
System.out.println("Longest Palindromic Substring: " + longest);
}
}

public class StringCompression {


public static void main(String[] args) {
String str = "aaabbccdde";
StringBuilder compressed = new StringBuilder();

int count = 1;
for (int i = 1; i < str.length(); i++) {
if (str.charAt(i) == str.charAt(i - 1)) {
count++;
} else {
compressed.append(str.charAt(i - 1)).append(count);
count = 1;
}
}
compressed.append(str.charAt(str.length() - 1)).append(count);

System.out.println("Compressed String: " + compressed);

20
Java Labs Dr Benabderrezak

}
}

import java.util.Arrays;

public class LongestCommonPrefix {


public static void main(String[] args) {
String[] strs = {"flower", "flow", "flight"};
if (strs.length == 0) return;

String prefix = strs[0];


for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return;
}
}
System.out.println("Longest Common Prefix: " + prefix);
}
}

import java.util.HashSet;

public class StringPermutations {


public static void main(String[] args) {
String str = "abc";
HashSet<String> permutations = new HashSet<>();
permute("", str, permutations);
System.out.println("Permutations: " + permutations);
}

private static void permute(String prefix, String str, HashSet<String> permutations) {


int n = str.length();
if (n == 0) {
permutations.add(prefix);
} else {
for (int i = 0; i < n; i++) {
permute(prefix + str.charAt(i), str.substring(0, i) + str.substring(i + 1, n), permutations);
}
}
}
}

21
Java Labs Dr Benabderrezak

Part 5 : Functions
code Output
public class SimpleFunction {
public static int add(int a, int b) {
return a + b;
}

public static void main(String[] args) {


System.out.println("Sum: " + add(5, 3));
}
}

public class EvenOddCheck {


public static boolean isEven(int num) {
return num % 2 == 0;
}

public static void main(String[] args) {


System.out.println("Is 4 even? " + isEven(4));
}
}

public class MaxOfThree {


public static int maxOfThree(int x, int y, int z) {
return Math.max(x, Math.max(y, z));
}

public static void main(String[] args) {


System.out.println("Maximum: " + maxOfThree(5, 10, 3));
}
}

public class CelsiusToFahrenheit {


public static double convert(double celsius) {
return (celsius * 9/5) + 32;
}

public static void main(String[] args) {


System.out.println("Fahrenheit: " + convert(25));
}
}

public class CelsiusToFahrenheit {


public static double convert(double celsius) {
return (celsius * 9/5) + 32;
}

22
Java Labs Dr Benabderrezak

public static void main(String[] args) {


System.out.println("Fahrenheit: " + convert(25));
}
}

public class Factorial {


public static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}

public static void main(String[] args) {


System.out.println("Factorial of 5: " + factorial(5));
}
}

public class CountVowels {


public static int countVowels(String str) {
int count = 0;
for (char c : str.toCharArray()) {
if ("AEIOUaeiou".indexOf(c) != -1) {
count++;
}
}
return count;
}

public static void main(String[] args) {


System.out.println("Number of vowels: " + countVowels("Hello World"));
}
}

public class ReverseString {


public static String reverse(String str) {
if (str.isEmpty()) {
return str;
}
return str.charAt(str.length() - 1) + reverse(str.substring(0, str.length() - 1));
}

public static void main(String[] args) {


System.out.println("Reversed String: " + reverse("Hello"));
}
}

23
Java Labs Dr Benabderrezak

public class PrimeCheck {


public static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}

public static void main(String[] args) {


System.out.println("Is 7 prime? " + isPrime(7));
}
}

public class SumArray {


public static int sum(int[] arr) {
int total = 0;
for (int num : arr) {
total += num;
}
return total;
}

public static void main(String[] args) {


int[] numbers = {1, 2, 3, 4, 5};
System.out.println("Sum of Array: " + sum(numbers));
}
}

import java.util.function.BiFunction;

public class LambdaAddition {


public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println("Sum using lambda: " + add.apply(5, 3));
}
}

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FilterEvenNumbers {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
List<Integer> evenNumbers = numbers.stream()
.filter(num -> num % 2 == 0)
.collect(Collectors.toList());
24
Java Labs Dr Benabderrezak

System.out.println("Even Numbers: " + evenNumbers);


}
}

public class GCD {


public static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}

public static void main(String[] args) {


System.out.println("GCD of 48 and 18: " + gcd(48, 18));
}
}

import java.util.Arrays;
import java.util.List;

public class SortStrings {


public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Alice", "Bob");
names.sort((s1, s2) -> s1.compareTo(s2));
System.out.println("Sorted Names: " + names);
}
}

public class Power {


public static int power(int base, int exp) {
if (exp == 0) return 1;
return base * power(base, exp - 1);
}

public static void main(String[] args) {


System.out.println("2 to the power of 3: " + power(2, 3));
}
}

import java.util.function.Function;

public class LambdaFactorial {


public static void main(String[] args) {
Function<Integer, Integer> factorial = new Function<>() {
@Override
public Integer apply(Integer n) {
return (n == 0) ? 1 : n * apply(n - 1);
}
};
System.out.println("Factorial using lambda: " + factorial.apply(5));
25
Java Labs Dr Benabderrezak

}
}

import java.util.function.BiFunction;

public class ConcatenateStrings {


public static void main(String[] args) {
BiFunction<String, String, String> concatenate = (s1, s2) -> s1 + " " + s2;
System.out.println("Concatenated String: " + concatenate.apply("Hello",
"World"));
}
}

public class CountDigits {


public static int count(int n) {
if (n == 0) return 0;
return 1 + count(n / 10);
}

public static void main(String[] args) {


System.out.println("Number of digits in 12345: " + count(12345));
}
}

import java.util.Arrays;
import java.util.List;

public class MaxInList {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Integer max = numbers.stream().max(Integer::compare).orElse(null);
System.out.println("Maximum Value: " + max);
}
}

public class PalindromeCheck {


public static boolean isPalindrome(String str) {
String reversed = new StringBuilder(str).reverse().toString();
return str.equals(reversed);
}

public static void main(String[] args) {


System.out.println("Is 'madam' a palindrome? " + isPalindrome("madam"));
}
}

26
Java Labs Dr Benabderrezak

Part 6 : OOP
Code Output
class Dog {
String name;
int age;

void bark() {
System.out.println(name + " says Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.name = "Buddy";
dog.age = 3;
dog.bark();
}
}

class Rectangle {
int length;
int width;

// Constructor with no parameters


Rectangle() {
length = 1;
width = 1;
}

// Constructor with parameters


Rectangle(int l, int w) {
length = l;
width = w;
}
int area() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle(5, 3);
System.out.println("Area of rect1: " + rect1.area());
System.out.println("Area of rect2: " + rect2.area());
}
}

27
Java Labs Dr Benabderrezak

class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

class Cat extends Animal {


void meow() {
System.out.println("Cat says Meow!");
}
}

public class Main {


public static void main(String[] args) {
Cat cat = new Cat();
cat.eat();
cat.meow();
}
}

class Vehicle {
void start() {
System.out.println("Vehicle is starting.");
}
}

class Car extends Vehicle {


@Override
void start() {
System.out.println("Car is starting with a key.");
}
}

public class Main {


public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start();
}
}

class BankAccount {
private double balance;

public void deposit(double amount) {


if (amount > 0) {
balance += amount;
}

28
Java Labs Dr Benabderrezak

public double getBalance() {


return balance;
}
}

public class Main {


public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(100);
System.out.println("Balance: " + account.getBalance());
}
}

class Shape {
void draw() {
System.out.println("Drawing a shape.");
}
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing a circle.");
}
}

class Square extends Shape {


@Override
void draw() {
System.out.println("Drawing a square.");
}
}

public class Main {


public static void main(String[] args) {
Shape shape1 = new Circle();
Shape shape2 = new Square();
shape1.draw();
shape2.draw();
}
}

abstract class Animal {


abstract void sound();
}

29
Java Labs Dr Benabderrezak

class Dog extends Animal {


void sound() {
System.out.println("Dog barks.");
}
}

public class Main {


public static void main(String[] args) {
Animal myDog = new Dog();
myDog.sound();
}
}

interface Drawable {
void draw();
}

class Rectangle implements Drawable {


public void draw() {
System.out.println("Drawing a rectangle.");
}
}

public class Main {


public static void main(String[] args) {
Drawable rect = new Rectangle();
rect.draw();
}
}

class OuterClass {
private String outerField = "Outer field";

class InnerClass {
void display() {
System.out.println("Accessing: " + outerField);
}
}
}

public class Main {


public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display();
}

30
Java Labs Dr Benabderrezak

class Counter {
static int count = 0;

Counter() {
count++;
}

static void displayCount() {


System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
Counter.displayCount();
}
}

import java.util.ArrayList;

class Employee {
private String name;
private ArrayList<Employee> subordinates;

public Employee(String name) {


this.name = name;
this.subordinates = new ArrayList<>();
}

public void addSubordinate(Employee employee) {


subordinates.add(employee);
}

public void displayHierarchy(int level) {


System.out.println(" ".repeat(level) + name);
for (Employee subordinate : subordinates) {
subordinate.displayHierarchy(level + 1);
}
}
}

public class Main {


public static void main(String[] args) {
Employee ceo = new Employee("John");

31
Java Labs Dr Benabderrezak

Employee manager1 = new Employee("Alice");


Employee manager2 = new Employee("Bob");
Employee employee1 = new Employee("Charlie");
Employee employee2 = new Employee("David");

manager1.addSubordinate(employee1);
manager1.addSubordinate(employee2);
ceo.addSubordinate(manager1);
ceo.addSubordinate(manager2);

System.out.println("Employee Hierarchy:");
ceo.displayHierarchy(0);
}
}

import java.util.ArrayList;

class Student {
private String name;
private int age;

public Student(String name, int age) {


this.name = name;
this.age = age;
}

public String getDetails() {


return "Name: " + name + ", Age: " + age;
}
}

class StudentManagement {
private ArrayList<Student> students;

public StudentManagement() {
students = new ArrayList<>();
}

public void addStudent(Student student) {


students.add(student);
}

public void displayStudents() {


for (Student student : students) {
System.out.println(student.getDetails());
}
}

32
Java Labs Dr Benabderrezak

public class Main {


public static void main(String[] args) {
StudentManagement management = new StudentManagement();
management.addStudent(new Student("Alice", 20));
management.addStudent(new Student("Bob", 22));
management.addStudent(new Student("Charlie", 19));

System.out.println("Student List:");
management.displayStudents();
}
}

import java.util.HashMap;

class PhoneBook {
private HashMap<String, String> contacts;

public PhoneBook() {
contacts = new HashMap<>();
}

public void addContact(String name, String phoneNumber) {


contacts.put(name, phoneNumber);
}

public String searchContact(String name) {


return contacts.getOrDefault(name, "Contact not found");
}

public void displayAllContacts() {


for (String name : contacts.keySet()) {
System.out.print("Name: " + name );
System.out.println(",Phone Number: " + contacts.get(name));
}
}
}
public class Main {
public static void main(String[] args) {
PhoneBook phoneBook = new PhoneBook();
phoneBook.addContact("Alice", "123-456-7890");
phoneBook.addContact("Bob", "098-765-4321");
phoneBook.addContact("Charlie", "555-555-5555");
System.out.println("Searching for Alice: " + phoneBook.searchContact("Alice"));
System.out.println("Searching for David: " + phoneBook.searchContact("David"));

33
Java Labs Dr Benabderrezak

System.out.println("\nAll Contacts:");
phoneBook.displayAllContacts();
}
}

Challenge 1 : Create a Social Media Management System like Facebook

- You are tasked with developing a simplified social media management system for a Facebook-like

platform using JAVA with OOP

- The system should allow users to create, edit, delete, and view posts.

- Each post can have comments, likes, and shares.

- The system should also allow users to manage their profiles and view their posts.

- The system should allow users to send friend requests, accept or reject requests

- The system should allow users to view their friend list.

- Each user should also be able to manage their profile and view information about their friends.

Challenge 2 : Create a Family Relationship Management System

- You are tasked with developing a family relationship management system that represents familial

relationships using a graph structure.

- Each person in the family will be a node, and relationships (such as parent-child, sibling, and

spouse) will be represented as edges between these nodes.

- The system should allow users to add family members, define relationships, and query

relationships between family members.

34

You might also like