info@webounstraininghub.in
Java is a high-level, class-based, object-oriented programming language designed to be platform-independent. It follows the principle of "write once, run anywhere" and is used for developing various applications from mobile to enterprise systems.
Syntax:
public class Example {
public static void main(String[] args) {
// Code
}
}
The key features include portability, object-orientation, robustness, security, multithreading, and high performance. Java's platform independence is achieved through the Java Virtual Machine (JVM).
JVM is an engine that executes Java bytecode and provides a runtime environment. It handles tasks such as memory management and garbage collection.
JDK (Java Development Kit) includes JRE and tools for development. JRE (Java Runtime Environment) includes JVM and libraries required to run Java applications. JVM (Java Virtual Machine) executes Java bytecode.
A class is a blueprint for creating objects. It defines data members (fields) and methods to operate on the data.
Syntax:
public class MyClass {
// Fields and methods
}
An object is an instance of a class that holds state and behavior defined by its class.
Syntax:
MyClass obj = new MyClass();
OOP is a programming paradigm based on objects and classes. Key principles include encapsulation, inheritance, polymorphism, and abstraction.
Encapsulation is bundling the data (variables) and the methods (functions) that operate on the data into a single unit or class. It restricts direct access to some of an object’s components and can prevent the accidental modification of data. This is achieved using access modifiers: private, protected, and public.
Benefits:
Control: It allows the control of how data is accessed or modified.
Flexibility: The internal implementation of the class can be changed without affecting the classes that use it.
Increased Security: It protects the internal state of the object from unintended or harmful modifications.
Example:
public class Employee {
private String name; // Private variable
private int age; // Private variable
// Public getter for 'name'
public String getName() {
return name;
}
// Public setter for 'name'
public void setName(String name) {
this.name = name;
}
// Public getter for 'age'
public int getAge() {
return age;
}
// Public setter for 'age'
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
}
Inheritance is a mechanism that allows one class to inherit fields and methods from another class. The class that inherits is called the subclass or derived class, and the class from which it inherits is called the superclass or base class. It promotes code reusability and establishes a natural hierarchy.
Types:
Single Inheritance: A class inherits from one superclass.
Multilevel Inheritance: A class inherits from another class which is also a subclass of another class.
Hierarchical Inheritance: Multiple classes inherit from a single superclass.
Multiple Inheritance (through Interfaces): Java does not support multiple inheritance with classes but allows it through interfaces.
Example:
// Superclass
public class Animal {
public void eat() {
System.out.println("This animal eats food.");
}
}
// Subclass
public class Dog extends Animal {
public void bark() {
System.out.println("The dog barks.");
}
}
// Main class to test inheritance
public class TestInheritance {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method
myDog.bark(); // Subclass method
}
}
3. Polymorphism
Polymorphism means "many shapes" and allows objects to be treated as instances of their parent class rather than their actual class. It provides a way to perform a single action in different forms. There are two types of polymorphism in Java:
Abstraction is the concept of hiding the complex implementation details and showing only the necessary features of an object. It simplifies interaction by providing a clear interface while hiding the internal workings. Abstraction is achieved using abstract classes and interfaces in Java.
Abstract Class: A class that cannot be instantiated and may contain abstract methods (methods without a body) that must be implemented by subclasses.
Example:
public abstract class Vehicle {
abstract void start(); // Abstract method
public void stop() {
System.out.println("Vehicle stopped");
}
}
public class Car extends Vehicle {
@Override
void start() {
System.out.println("Car started");
}
}
// Main class to test abstraction
public class TestAbstraction {
public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start(); // Calls the overridden method in Car
myCar.stop(); // Calls the method in Vehicle
}
}
A reference type in Java that can contain only method signatures, default methods, static methods, and constants. It is used to achieve abstraction and multiple inheritance.
Example:
interface Drawable {
void draw(); // Interface method (does not have a body)
}
public class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing circle");
}
}
// Main class to test interface
public class TestInterface {
public static void main(String[] args) {
Drawable myCircle = new Circle();
myCircle.draw();
}
}
An interface can only contain method signatures and constants, whereas an abstract class can have both abstract and concrete methods. Interfaces support multiple inheritance, while abstract classes do not.
Syntax:
interface MyInterface {
void method();
}
abstract class MyAbstractClass {
abstract void method();
void concreteMethod() {}
}
== checks if two references point to the same memory location, while .equals() checks if the values of two objects are equivalent.
Access modifiers determine the visibility of classes, methods, and fields. They include public, protected, private, and default (package-private).
Syntax:
public class Example {
public int publicVar;
protected int protectedVar;
private int privateVar;
int defaultVar;
}
Method overloading allows multiple methods in the same class with the same name but different parameters (types, number).
Syntax:
public class MathOperations {
public int add(int a, int b) { return a + b; }
public double add(double a, double b) { return a + b; }
}
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass.
Syntax:
class Parent {
void method() {}
}
class Child extends Parent {
@Override
void method() {}
}
Super refers to the superclass of the current object and is used to access superclass methods, constructors, and fields.
Syntax:
class SuperClass {
void method() {}
}
class SubClass extends SuperClass {
void method() {
super.method();
}
}
A constructor is a special method that initializes objects. It has the same name as the class and no return type.
Syntax:
public class MyClass {
public MyClass() {
// Initialization code
}
}
Static methods belong to the class and can be called without creating an instance, while instance methods belong to objects and require an instance to be invoked.
Syntax:
public class Example {
static void staticMethod() {}
void instanceMethod() {}
}
Final can be used to define constants, prevent method overriding, and prohibit class inheritance.
Syntax:
final class FinalClass {}
Throw is used to explicitly throw an exception within a method, while throws is used in method signatures to declare that a method may throw exceptions.
Syntax:
void method() throws IOException {
throw new IOException();
}
Exception handling allows a program to deal with runtime errors using try, catch, finally, and throw keywords, preventing abrupt termination.
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Exception handler
} finally {
// Code that will always execute
}
The finally block is used to execute code after try and catch blocks, regardless of whether an exception was thrown or caught.
Syntax:
try {
// Code
} catch (ExceptionType e) {
// Handle exception
} finally {
// Cleanup code
}
A package is a namespace used to group related classes and interfaces, which helps avoid naming conflicts and controls access.
Syntax:
package com.example;
public class MyClass{};
Annotations provide metadata about the code and can be used to give information to the compiler or runtime.
Syntax:
@Override
public void method() {};
The this keyword refers to the current instance of a class and is used to access instance variables and methods.
Syntax:
public class MyClass {
private int value;
public void setValue(int value) {
this.value = value; // Accessing instance variable
}
}
The default keyword allows an interface to have methods with a body, providing a default implementation that classes can use or override.
Syntax:
interface MyInterface {
default void defaultMethod() {}
}
A static block is used to initialize static variables and is executed when the class is loaded.
Syntax:
class MyClass {
static {
// Initialization code
}
}
Serialization is the process of converting an object into a byte stream for storage or transmission. Deserialization is the reverse process.
Syntax:
import java.io.Serializable;
public class MyClass implements Serializable {
// Class implementation
}
The transient keyword prevents fields from being serialized. It is used to mark fields that should not be saved during serialization.
Syntax:
class MyClass implements Serializable {
private transient int value;
}
ArrayList uses a dynamic array for storage, which provides fast random access but slow insertions/removals. LinkedList uses a doubly linked list, which provides faster insertions/removals but slower random access.
Syntax:
ArrayList<Type> list = new ArrayList<>();
LinkedList<Type> linkedList = new LinkedList<>();
The synchronized keyword is used to control access to critical sections of code, ensuring that only one thread can execute a block of code at a time.
Syntax:
synchronized (object) {
// Synchronized block
}
HashMap stores elements in a hash table and does not maintain order. TreeMap stores elements in a red-black tree and maintains a sorted order.
Syntax:
HashMap<KeyType, ValueType> hashMap = new HashMap<>();
TreeMap<KeyType, ValueType> treeMap = new TreeMap<>();
A thread is a lightweight process that allows concurrent execution of code. Threads share the same memory space but execute independently.
Syntax:
public class MyThread extends Thread {
public void run() {
// Code
}
}
The Runnable interface represents a task that can be executed by a thread. It contains a single method, run(), which defines the code to be executed.
Syntax:
public interface Runnable {
void run();
}
An enum (short for enumeration) is a special class that represents a group of constants (unchangeable variables).
Syntax:
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
The volatile keyword ensures that a variable's value is always read from and written to the main memory, making it visible to all threads.
Syntax:
private volatile int counter;
The transient keyword is used to indicate that a field should not be serialized when an object is converted to a byte stream.
Syntax:
private transient int value;
The Java Collections Framework provides classes and interfaces for working with groups of objects. Key classes include ArrayList, HashSet, HashMap, and TreeMap.
Syntax:
ArrayList<Type> list = new ArrayList<>();
HashSet<Type> set = new HashSet<>();
HashMap<KeyType, ValueType> map = new HashMap<>();
TreeMap<KeyType, ValueType> treeMap = new TreeMap<>();
The instanceof keyword is used to test whether an object is an instance of a specific class or subclass.
Syntax:
if (object instanceof ClassName) {
// Code
}
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Player 1: Enter Rock, Paper, or Scissors:");
String player1 = scanner.nextLine().toLowerCase();
System.out.println("Player 2: Enter Rock, Paper, or Scissors:");
String player2 = scanner.nextLine().toLowerCase();
if (player1.equals(player2)) {
System.out.println("It's a tie!");
} else if (player1.equals("rock") && player2.equals("scissors") ||
player1.equals("scissors") && player2.equals("paper") ||
player1.equals("paper") && player2.equals("rock")) {
System.out.println("Player 1 wins!");
} else {
System.out.println("Player 2 wins!");
}
}
}
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a year:");
int year = scanner.nextInt();
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}
import java.util.Scanner;
public class NumberCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scanner.nextInt();
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.");
}
}
}
import java.util.Scanner;
import java.util.regex.Pattern;
public class EmailValidator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter an email address:");
String email = scanner.nextLine();
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
if (Pattern.matches(emailRegex, email)) {
System.out.println(email + " is a valid email address.");
} else {
System.out.println(email + " is not a valid email address.");
}
}
}
import java.util.Scanner;
public class Calculator {
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 op = scanner.next().charAt(0);
switch (op) {
case '+':
System.out.println("Result: " + (num1 + num2));
break;
case '-':
System.out.println("Result: " + (num1 - num2));
break;
case '*':
System.out.println("Result: " + (num1 * num2));
break;
case '/':
if (num2 != 0) {
System.out.println("Result: " + (num1 / num2));
} else {
System.out.println("Error: Division by zero.");
}
break;
default:
System.out.println("Invalid operation.");
break;
}
}
}
import java.util.Scanner;
public class DaysInMonth {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter year:");
int year = scanner.nextInt();
System.out.println("Enter month (1-12):");
int month = scanner.nextInt();
int daysInMonth;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
daysInMonth = 31;
break;
case 4: case 6: case 9: case 11:
daysInMonth = 30;
break;
case 2:
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
break;
default:
daysInMonth = 0;
System.out.println("Invalid month.");
break;
}
if (daysInMonth != 0) {
System.out.println("Number of days: " + daysInMonth);
}
}
}
import java.util.Scanner;
public class PerfectSquare {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number:");
int number = scanner.nextInt();
double sqrt = Math.sqrt(number);
if (sqrt == (int) sqrt) {
System.out.println(number + " is a perfect square. Square root: " + (int) sqrt);
} else {
System.out.println(number + " is not a perfect square.");
}
}
}
import java.time.LocalDate;
import java.time.Period;
import java.util.Scanner;
public class AgeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter birth year:");
int year = scanner.nextInt();
System.out.println("Enter birth month:");
int month = scanner.nextInt();
System.out.println("Enter birth day:");
int day = scanner.nextInt();
LocalDate birthDate = LocalDate.of(year, month, day);
LocalDate currentDate = LocalDate.now();
Period age = Period.between(birthDate, currentDate);
System.out.println("Age: " + age.getYears() + " years, " + age.getMonths() + " months, " + age.getDays() + " days");
}
}
import java.util.Scanner;
public class CharacterCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
int vowels = 0, consonants = 0, specialChars = 0;
for (char ch : sentence.toLowerCase().toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
} else if (!Character.isWhitespace(ch)) {
specialChars++;
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Special characters: " + specialChars);
}
}
import java.util.Scanner;
public class CharacterCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
int vowels = 0, consonants = 0, specialChars = 0;
for (char ch : sentence.toLowerCase().toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
} else if (!Character.isWhitespace(ch)) {
specialChars++;
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Special characters: " + specialChars);
}
}
import java.util.Scanner;
public class IncomeTaxCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter annual income:");
double income = scanner.nextDouble();
double tax;
if (income <= 250000) {
tax = 0;
} else if (income <= 500000) {
tax = (income - 250000) * 0.05;
} else if (income <= 1000000) {
tax = 12500 + (income - 500000) * 0.1;
} else {
tax = 12500 + 50000 + (income - 1000000) * 0.3;
}
System.out.println("Income Tax: " + tax);
}
}
public class PrimeNumbers {
public static void main(String[] args) {
for (int num = 2; num <= 100; num++) {
boolean isPrime = true;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(num);
}
}
}
}
public class SumOfSquares {
public static void main(String[] args) {
int sum = 0;
for (int i = 2; i <= 100; i += 2) {
sum += i * i;
}
System.out.println("Sum of squares of even numbers between 1 and 100: " + sum);
}
}
public class SumOfFirst100Primes {
public static void main(String[] args) {
int count = 0;
int num = 2;
int sum = 0;
while (count < 100) {
if (isPrime(num)) {
sum += num;
count++;
}
num++;
}
System.out.println("Sum of the first 100 prime numbers: " + sum);
}
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;
}
}
import java.util.Scanner;
public class PascalsTriangle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of rows:");
int rows = scanner.nextInt();
for (int i = 0; i < rows; i++) {
int number = 1;
for (int j = 0; j <= i; j++) {
System.out.print(number + " ");
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
public class ArmstrongNumbers {
public static void main(String[] args) {
for (int num = 1; num <= 1000; num++) {
int sum = 0;
int temp = num;
int digits = Integer.toString(num).length();
while (temp != 0) {
int digit = temp % 10;
sum += Math.pow(digit, digits);
temp /= 10;
}
if (sum == num) {
System.out.println(num);
}
}
}
}
import java.util.Scanner;
public class WordCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = scanner.nextLine();
String[] words = sentence.trim().split("\\s+");
System.out.println("Number of words: " + words.length);
}
}
import java.util.Scanner;
public class SecondSmallest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of elements:");
int n = scanner.nextInt();
int[] array = new int[n];
System.out.println("Enter elements:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
if (n < 2) {
System.out.println("Array should have at least two elements.");
return;
}
int first = Integer.MAX_VALUE;
int second = Integer.MAX_VALUE;
for (int num : array) {
if (num < first) {
second = first;
first = num;
} else if (num < second && num != first) {
second = num;
}
}
if (second == Integer.MAX_VALUE) {
System.out.println("No second smallest element.");
} else {
System.out.println("Second smallest element: " + second);
}
}
}
import java.util.Scanner;
public class RotateArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of elements:");
int n = scanner.nextInt();
int[] array = new int[n];
System.out.println("Enter elements:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
System.out.println("Enter number of steps to rotate:");
int k = scanner.nextInt();
rotateArray(array, k);
System.out.println("Rotated array:");
for (int num : array) {
System.out.print(num + " ");
}
}
public static void rotateArray(int[] array, int k) {
int n = array.length;
k = k % n; // In case the number of rotations exceeds the array size
reverse(array, 0, n - 1);
reverse(array, 0, k - 1);
reverse(array, k, n - 1);
}
public static void reverse(int[] array, int start, int end) {
while (start < end) {
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
}
import java.util.Arrays;
public class MergeSortedArrays {
public static void main(String[] args) {
int[] array1 = {1, 3, 5, 7};
int[] array2 = {2, 4, 6, 8};
merge(array1, array2);
System.out.println("Merged array: " + Arrays.toString(array1));
}
public static void merge(int[] array1, int[] array2) {
int n = array1.length;
int m = array2.length;
int i = n - 1;
int j = 0;
while (i >= 0 && j < m) {
if (array1[i] > array2[j]) {
array1[i] = array2[j];
array2[j] = array1[i];
j++;
}
i--;
}
Arrays.sort(array1);
Arrays.sort(array2);
}
}
import java.util.Arrays;
public class RemoveDuplicates {
public static void main(String[] args) {
int[] array = {4, 5, 9, 4, 2, 1, 2, 3, 5, 9};
Arrays.sort(array);
int length = removeDuplicates(array);
System.out.println("Array after removing duplicates:");
for (int i = 0; i < length; i++) {
System.out.print(array[i] + " ");
}
}
public static int removeDuplicates(int[] array) {
int n = array.length;
if (n == 0) return 0;
int uniqueIndex = 0;
for (int i = 1; i < n; i++) {
if (array[i] != array[uniqueIndex]) {
uniqueIndex++;
array[uniqueIndex] = array[i];
}
}
return uniqueIndex + 1;
}
}
import java.util.HashSet;
import java.util.Set;
public class ArrayIntersection {
public static void main(String[] args) {
int[] array1 = {1, 3, 5, 7};
int[] array2 = {5, 7, 9, 11};
Set<Integer> intersection = findIntersection(array1, array2);
System.out.println("Intersection: " + intersection);
}
public static Set<Integer> findIntersection(int[] array1, int[] array2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> intersection = new HashSet<>();
for (int num : array1) {
set1.add(num);
}
for (int num : array2) {
if (set1.contains(num)) {
intersection.add(num);
}
}
return intersection;
}
}
import java.util.Arrays;
public class RearrangeArray {
public static void main(String[] args) {
int[] array = {10, 5, 15, 7, 20, 3};
rearrange(array);
System.out.println("Rearranged array: " + Arrays.toString(array));
}
public static void rearrange(int[] array) {
Arrays.sort(array);
int[] result = new int[array.length];
int index = 0;
for (int i = array.length - 1; i >= 0; i -= 2) {
result[index++] = array[i];
}
for (int i = array.length - 2; i >= 0; i -= 2) {
result[index++] = array[i];
}
System.arraycopy(result, 0, array, 0, array.length);
}
}
public class SaddlePoint {
public static void main(String[] args) {
int[][] matrix = {
{3, 8, 7},
{4, 6, 5},
{9, 2, 1}
};
findSaddlePoint(matrix);
}
public static void findSaddlePoint(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
for (int i = 0; i < rows; i++) {
int minRow = matrix[i][0];
int minColIndex = 0;
for (int j = 1; j < cols; j++) {
if (matrix[i][j] < minRow) {
minRow = matrix[i][j];
minColIndex = j;
}
}
boolean isSaddlePoint = true;
for (int k = 0; k < rows; k++) {
if (matrix[k][minColIndex] > minRow) {
isSaddlePoint = false;
break;
}
}
if (isSaddlePoint) {
System.out.println("Saddle Point: " + minRow);
return;
}
}
System.out.println("No saddle point found.");
}
}
public class RotateMatrix {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
rotateMatrix(matrix);
System.out.println("Rotated matrix:");
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
public static void rotateMatrix(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n - j - 1][i];
matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];
matrix[j][n - i - 1] = temp;
}
}
}
}
public class MatrixMultiplication {
public static void main(String[] args) {
int[][] matrix1 = {
{1, 2},
{3, 4}
};
int[][] matrix2 = {
{5, 6},
{7, 8}
};
int[][] result = multiplyMatrices(matrix1, matrix2);
System.out.println("Resulting matrix:");
for (int[] row : result) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {
int rows1 = matrix1.length;
int cols1 = matrix1[0].length;
int rows2 = matrix2.length;
int cols2 = matrix2[0].length;
if (cols1 != rows2) {
throw new IllegalArgumentException("Matrices cannot be multiplied");
}
int[][] result = new int[rows1][cols2];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}
}
public class SpiralSum {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println("Sum in spiral order: " + spiralSum(matrix));
}
public static int spiralSum(int[][] matrix) {
int sum = 0;
int top = 0, bottom = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) {
sum += matrix[top][i];
}
top++;
for (int i = top; i <= bottom; i++) {
sum += matrix[i][right];
}
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) {
sum += matrix[bottom][i];
}
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) {
sum += matrix[i][left];
}
left++;
}
}
return sum;
}
}
public class MatrixTranspose {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
transpose(matrix);
System.out.println("Transposed matrix:");
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
public static void transpose(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
}
import java.util.Arrays;
public class Sort2DArray {
public static void main(String[] args) {
int[][] matrix = {
{3, 1, 2},
{9, 4, 6},
{7, 5, 8}
};
sortRows(matrix);
System.out.println("Row-wise sorted matrix:");
for (int[] row : matrix) {
System.out.println(Arrays.toString(row));
}
}
public static void sortRows(int[][] matrix) {
for (int[] row : matrix) {
Arrays.sort(row);
}
}
}
class Animal {
Animal() {
System.out.println("Animal constructor");
}
}
class Mammal extends Animal {
Mammal() {
System.out.println("Mammal constructor");
}
}
class Dog extends Mammal {
Dog() {
System.out.println("Dog constructor");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Dog dog = new Dog();
}
}
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
// Adding numbers 1 to 10
for (int i = 1; i <= 10; i++) {
list.add(i);
}
// Removing element at index 5 (6th element)
list.remove(5);
// Printing the ArrayList
System.out.println("ArrayList: " + list);
}
}
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
// Adding numbers 1 to 10
for (int i = 1; i <= 10; i++) {
list.add(i);
}
// Removing element at index 3 (4th element)
list.remove(3);
// Printing the LinkedList
System.out.println("LinkedList: " + list);
}
}
mport java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
// Adding numbers 1 to 10
for (int i = 1; i <= 10; i++) {
set.add(i);
}
// Removing element 5
set.remove(5);
// Printing the HashSet
System.out.println("HashSet: " + set);
}
}
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught an ArithmeticException: " + e.getMessage());
}
}
}
public class NullPointerExceptionExample {
public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length()); // This will throw NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught a NullPointerException: " + e.getMessage());
}
}
}
public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
int[] array = new int[5];
try {
array[10] = 1; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught an ArrayIndexOutOfBoundsException: " + e.getMessage());
}
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
import java.io.File;
public class FileExistenceCheck {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.exists()) {
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
}
}
}
import java.util.regex.Pattern;
public class PatternExample {
public static void main(String[] args) {
// Create a Pattern object with a regular expression
Pattern pattern = Pattern.compile("\\d+"); // Matches one or more digits
// Use the Pattern object (e.g., for matching)
System.out.println("Pattern created: " + pattern);
}
}
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
// Adding elements
for (int i = 1; i <= 10; i++) {
list.add(i);
}
// Iterating and printing
for (int num : list) {
System.out.println(num);
}
}
}
import java.util.ArrayList;
import java.util.Iterator;
public class RemoveEvenNumbers {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
// Adding elements
for (int i = 1; i <= 10; i++) {
list.add(i);
}
// Removing even numbers
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
if (iterator.next() % 2 == 0) {
iterator.remove();
}
}
// Printing the list
System.out.println("ArrayList after removing even numbers: " + list);
}
}
import java.util.ArrayList;
public class CombineArrayLists {
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
// Adding elements to list1
for (int i = 1; i <= 5; i++) {
list1.add(i);
}
// Adding elements to list2
for (int i = 6; i <= 10; i++) {
list2.add(i);
}
// Combining lists
list1.addAll(list2);
// Printing the combined list
System.out.println("Combined ArrayList: " + list1);
}
}
import java.util.ArrayList;
import java.util.Collections;
public class MinMaxArrayList {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
// Adding elements
for (int i = 1; i <= 10; i++) {
list.add(i);
}
// Finding maximum and minimum
int max = Collections.max(list);
int min = Collections.min(list);
// Printing results
System.out.println("Maximum value: " + max);
System.out.println("Minimum value: " + min);
}
}
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
// Adding entries
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);
// Retrieving and printing age of Bob
int age = map.get("Bob");
System.out.println("Age of Bob: " + age);
}
}
import java.util.HashMap;
public class RemoveHashMapEntry {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
// Adding entries
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);
// Removing entry with key "Bob"
map.remove("Bob");
// Printing the HashMap
System.out.println("HashMap after removal: " + map);
}
}
import java.util.HashMap;
public class CheckKeyInHashMap {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
// Adding entries
map.put("Alice", 30);
map.put("Bob", 25);
// Checking if key "Alice" exists
boolean exists = map.containsKey("Alice");
System.out.println("Key 'Alice' exists: " + exists);
}
}
import java.util.HashMap;
import java.util.Map;
public class IterateHashMap {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
// Adding entries
map.put("Alice", 30);
map.put("Bob", 25);
// Iterating through keys and values
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
import java.util.HashSet;
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
// Adding elements with duplicates
set.add("Apple");
set.add("Banana");
set.add("Apple");
set.add("Orange");
// Printing unique elements
System.out.println("HashSet: " + set);
}
}
import java.util.HashSet;
public class SetOperations {
public static void main(String[] args) {
HashSet<Integer> set1 = new HashSet<>();
HashSet<Integer> set2 = new HashSet<>();
// Adding elements
for (int i = 1; i <= 5; i++) {
set1.add(i);
}
for (int i = 3; i <= 7; i++) {
set2.add(i);
}
// Intersection
HashSet<Integer> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.println("Intersection: " + intersection);
// Union
HashSet<Integer> union = new HashSet<>(set1);
union.addAll(set2);
System.out.println("Union: " + union);
// Difference
HashSet<Integer> difference = new HashSet<>(set1);
difference.removeAll(set2);
System.out.println("Difference: " + difference);
}
}
import java.util.HashSet;
public class SubsetCheck {
public static void main(String[] args) {
HashSet<Integer> set1 = new HashSet<>();
HashSet<Integer> set2 = new HashSet<>();
// Adding elements
for (int i = 1; i <= 5; i++) {
set1.add(i);
}
for (int i = 3; i <= 7; i++) {
set2.add(i);
}
// Checking if set1 is a subset of set2
boolean isSubset = set2.containsAll(set1);
System.out.println("Set1 is a subset of Set2: " + isSubset);
}
}
import java.util.HashSet;
public class RemoveFromHashSet {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
// Adding elements
for (int i = 1; i <= 5; i++) {
set.add(i);
}
// Removing element 3
set.remove(3);
// Printing the HashSet
System.out.println("HashSet after removal: " + set);
}
}
import java.util.ArrayList;
import java.util.Collections;
public class SortArrayList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
// Adding elements
list.add("Banana");
list.add("Apple");
list.add("Cherry");
// Sorting the list
Collections.sort(list);
// Printing the sorted list
System.out.println("Sorted ArrayList: " + list);
}
}
import java.util.LinkedList;
public class LinkedListOperations {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
// Insertion
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Inserting at a specific position
list.add(1, "Blueberry");
// Deletion
list.remove("Banana");
// Searching
boolean exists = list.contains("Cherry");
// Printing the list and search result
System.out.println("LinkedList: " + list);
System.out.println("Contains 'Cherry': " + exists);
}
}
import java.util.ArrayList;
public class StackExample {
private ArrayList<Integer> stack = new ArrayList<>();
// Push operation
public void push(int value) {
stack.add(value);
}
// Pop operation
public int pop() {
if (stack.isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
return stack.remove(stack.size() - 1);
}
// Peek operation
public int peek() {
if (stack.isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
return stack.get(stack.size() - 1);
}
public static void main(String[] args) {
StackExample stack = new StackExample();
// Push operations
stack.push(1);
stack.push(2);
stack.push(3);
// Pop operation
System.out.println("Popped value: " + stack.pop());
// Peek operation
System.out.println("Top value: " + stack.peek());
}
}
We provide expert guidance, personalized support, and resources to help you excel in your digital marketing career.
Timing
9:00 am - 5:00 pm
info@webounstraininghub.in