You are currently viewing Java Program Cheat Sheet With Examples

Java Program Cheat Sheet With Examples

This article is all about Java Program CheatSheet. We have covered all Java Topics in Short so that you can revise complete java quickly for your interview preparation.

Table of Contents

What is Java?

Java is a programming language that is used to develop web applications, web servers, mobile apps, embedded systems applications, etc. It was first released in 1995 and was created by James Gosling. The main aim to develop this language was to provide a platform-independent language for building software applications. Later in 2010, it was acquired by Oracle Corporation.

Basic Java Program

import java.time.LocalDate;
public class Main {
  public static void main(String[] args) {
    System.out.println("Hello World");
    System.out.println("Today date: " + LocalDate.now());
  }
}

Above Syntax Explanations

  • import – used to import java libraries
  • class keyword – to declare a class in java.
  • public keyword – access modifier represents visibility. Public is visible to all.
  • static keyword – no need to create an object to invoke the static method. There is no need to create an object to invoke the main method and it’s invoked by JVM and saves memory.
  • void – return type of the method. it doesn’t return any value.
  • main – starting point of the program.
  • String[] args – for command line arguments.
  • System.out.println() – used to print statement.

Steps to compile and run java program

Go to Command prompt and navigate to the folder where java files are stored

To Compile

javac Main.java

To Run Java program

java Main

Data Type In Java

1). Primitive Data Type

Primitive data types are the basic data types in the Java language. They are used to store simple values.

In Java, there are eight primitive data types

  1. byte: Represents a signed 8-bit integer.
    byte a = 99;
  2. short: Represents a signed 16-bit integer.
    short b = 999;
  3. int: Represents a signed 32-bit integer.
    int c = 99;
  4. long: Represents a signed 64-bit integer.
    long d = 99999999999L;
  5. float: Represents a 32-bit floating-point number.
    float e = 99.99f;
  6. double: Represents a 64-bit floating-point number.
    double e = 99.99d;
  7. char: Represents a single 16-bit Unicode character.
    char g = ‘A’;
  8. boolean: Represents either true or false.
    boolean f = true;

2). Non-Primitive Data Types

Non-primitive data types, also known as reference types or objects,. These are used to store complex data and provide more functionality. They are created using predefined classes or custom-defined classes.
Some common non-primitive data types include:

  1. String: Represents a sequence of characters

String str = “java”

  1. Arrays: Represents a collection of elements of the same type

int[] arr = {12, 4, 5, 2, 5};

  1. Classes: Represents user-defined data types
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello World");
    }
}

  1. Interfaces: Represents a collection of abstract methods
interface printable {
    void print();
}
  1. Enums: Represents a fixed set of constants
enum Level {
   LOW,
   MEDIUM,
   HIGH
}

Variables in Java

data-type variable-name = value;

Variable naming convention

Java variable names should follow certain conventions to improve code readability and maintain consistency.

1). Camel Case

Variable names should be written in camel case, starting with a lowercase letter and using uppercase letters to separate words.
For example:

int studentAge;
double averageGrade;
String firstName;

2). Meaningful Names

Choose descriptive names that convey the purpose or meaning of the variable. Avoid using single-character names or generic names like temp, x, or data.

For example:

int numberOfStudents;
double piValue;
String customerName;

3). Lowercase Constants

If a variable is declared as a constant using the final keyword, its name should be written in uppercase letters with underscores (_) separating words.

For example:

final double PI_VALUE = 3.14159;
final int MAXIMUM_ATTEMPTS = 5;

4). Class Member Variables

Class member variables (instance variables or fields) should be prefixed with this keyword to differentiate them from local variables and method parameters.

For example:

private int age;
private String name;
public void setName(String name) {
   this.name = name;
}

5). Acronyms
If an acronym is used in a variable name, it should be written in camel case.

For example:

String htmlContent;
int userID;

6). Packages

When a variable is declared in a package, it is recommended to use the package name as a prefix to avoid naming conflicts.

For example:

com.example.myapp.Student student;

Short Points on Java Naming Convention

  • Name should be Case sensitive.
  • keywords cannot be used as variable names
  • Must should begin with a lower case letter. For second word should be a capital like this: firstName, pinCode etc.
  • Cannot contain white spaces like first name.
  • Special characters like $ and _ can be used to begin a variable name

These conventions help make code more readable and understandable, especially when working collaboratively or when revisiting code in the future. Following consistent naming conventions improves code maintainability and reduces confusion for developers.

Types of Variables

There are three types of variables:

  1. local variables
  2. instance variables
  3. static variables

1). Local Variables

Local variables are declared inside a method, constructor, or block. They are accessible only within the block or method where they are declared and do not exist outside that scope. Local variables are not initialized by default and must be assigned a value before they can be used.

Example:

public void method() {
   int x = 10; // x is a local variable
   // do something with x
}

2). Instance Variables

Instance variables are declared inside a class but outside a method, constructor, or block. They are also called fields or attributes. Instance variables are accessible throughout the class and are used to represent the state of an object. They are initialized to a default value depending on their type.

Example:

public class MyClass {
   int x; // x is an instance variable
   String name;
}

3). Static Variables

Static variables are declared using the static keyword and are also known as class variables. They are shared among all instances of a class and can be accessed without creating an instance of the class. Static variables are initialized to a default value depending on their type and retain their value throughout the program’s execution.

Example:

public class MyClass {
   static int count = 0; // count is a static variable
   String name;
}

In Java program, variable names should follow Java naming conventions which is described above. Variable name and variable type depends on the context and requirements of the program. Local variables are used to represent temporary values, while instance variables are used to represent the state of an object. Static variables are used to represent values shared among all instances of a class. You should clear the understanding of these variable types to write efficient and maintainable code.

Comments in Java

Comments is very essential key elements in Java. It is used to provide explanations, documentation, or clarification within the code. Comments are ignored by the compiler and do not affect the execution of the program.

Three types of Comments

  1. Single-Line Comments
  2. Multi-Line Comments
  3. Documentation Comments

1. Single-Line Comments
Single-line comments begin with // and continue until the end of the line. They are used to comment on a single line or provide short explanations.

Example

int age = 25; // Initializing age variable

2. Multi-Line Comments

Multi-line comments, also known as block comments, start with /* and end with */. They can span multiple lines and are used for longer explanations or to comment out a block of code.

Example:

/*
This is a multi-line comment.
It can span multiple lines and is used
to provide detailed explanations.
*/

3. Documentation Comments

Documentation comments begin with /** and end with */. They are used to generate documentation using tools like Javadoc. These comments typically appear immediately before a class, method, or field declaration and provide information for API documentation. They can include tags like @param, @return, and @throws to describe parameters, return values, and exceptions.

Example:

/**
* This method calculates the sum of two numbers.
* @param a The first number.
* @param b The second number.
* @return The sum of a and b.
*/
public int calculateSum(int a, int b) {
  return a + b;
}

Comments are an essential to add the code explanation in the program. They improve code readability and assist the othere developers in understanding the code. Also it helps in documenting the purpose and functionality of different parts of the program.

Data Conversions in java

In Java, data conversions, also known as type conversions or type casting. It allow us to convert values from one data type to another.

There are two types of data conversions in Java  

  • implicit conversions (widening)
  • explicit conversions (narrowing)

1). Implicit Conversions (Widening)

Implicit conversions occur when you assign a value of a smaller data type to a variable of a larger data type. Java performs these conversions automatically without the need for explicit casting. It is considered safe because it does not result in any loss of information.

Example 1:

int x = 10;
long y = x; // Implicit conversion from int to long

Example 2:

double a = 3.14;
float b = a; // Implicit conversion from double to float

2). Explicit Conversions (Narrowing)

Explicit conversions, also known as casting, occur when you assign a value of a larger data type to a variable of a smaller data type. These conversions require explicit casting because there is a potential loss of information. You need to indicate to the compiler that you are aware of the potential loss and want to perform the conversion.

Example 1:

double pi = 3.14159;
int approxPi = (int) pi; // Explicit conversion from double to int

Example 2:

long largeNumber = 1234567890;
int smallNumber = (int) largeNumber; // Explicit conversion from long to int

When performing explicit conversions, be cautious of potential data loss or precision issues. For example, when converting from a floating-point type (e.g., double) to an integer type (e.g., int), the fractional part is truncated, potentially leading to loss of precision.

It’s important to note that not all data types can be implicitly or explicitly converted. For incompatible types, you may need to use conversion methods or constructors provided by the classes to convert the data.

It’s generally recommended to use implicit conversions when possible to ensure safety and minimize potential errors. Explicit conversions should only be used when necessary and when you are aware of the consequences.

Operators in Java

  • Arithmetic Operator + , – , * , / , %
  • Comparision Operator < , > , <= , >=, != , ==
  • Bitwise Operator & , ^ , |, <<, >>, >>>
  • Logical Operator && , ||, !
  • Assignment Operator = , += , -= , *= , /= , %=
  • Auto-increment and Auto-decrement Operators ++ , —
  • Ternary Operator ? :

Conditional Statements

In Java, conditional statements allow you to control the flow of execution based on certain conditions. It means that only execute the code block when condition satisfy.
There are three types of conditional statements

  • if statement
  • if-else statement
  • if-else-if ladder statement
  • Nested-If ladder statement
  • switch statement

1). If Statement

In Java, if statement is used when you wanted to execute a block of code only if a certain condition is true. If the given condition is evaluated to true, the code written inside the if block will be execute otherwise that code will be skipped.

Syntax of the if Statement

if (condition1) {
   // Code block to be executed if condition1 is true
}

2). If-else Statement

The if-else statement is the extends version of if statement. It allows you to execute different blocks of code based on different conditions. Here there are two block one is inside if block and another is inside else block. If the condition written in the if statement is true, the code inside the if block will be executed. If the condition written in if returns false then else block will be executed.

Syntax of the If-else Statement

if (condition1) {
   // Executed if condition1 is true
} else (condition2) {
   // Executed if condition1 is false
}

3). if-else-if ladder

The if-else-if ladder in Java is an extension of the if-else statement, allowing you to check multiple conditions and execute different blocks of code based on those conditions. It provides a way to chain multiple if-else statements together.

Syntax of the if-else-if ladder

if (condition1) {
// Executed if condition1 is true
} else if (condition2) {
// Executed if condition1 is false and condition2 is true
} else if (condition3) {
// Executed if condition1 and condition2 are false and condition3 is true
} else {
// Executed if all conditions are false
}

4). Nested-If ladder

A nested if ladder in Java refers to the situation where an if statement is nested within another if statement. It allows for more complex decision-making by evaluating multiple conditions and executing different blocks of code based on those conditions.

Syntax of a nested if ladder

if (condition1) {
  // Outer if block
  if (condition2) {
    // Inner if block
    // Code to be executed if condition1 and condition2 are true
  } else {
    // Inner else block
    // Code to be executed if condition1 is true but condition2 is false
  }
} else {
  // Outer else block
  // Code to be executed if condition1 is false
}

5). Switch Statement

The switch statement allows you to select one of many code blocks to be executed based on the value of a variable or an expression. It provides an alternative to using multiple if-else statements. The value of the variable or expression is compared with the values specified in various case labels, and the corresponding code block is executed. If no case matches, the code block specified in the default label is executed (if present).

Syntax of Switch Statement

switch (expression) {
case value1:
  // Code block to be executed if expression matches value1
  break;
case value2:
  // Code block to be executed if expression matches value2
  break;
case value3:
  // Code block to be executed if expression matches value3
  break;
  // …
default:
  // Code block to be executed if expression doesn't match any case
}

Loops In Java

In Java, loops are used to execute a block of code repeatedly.
There are three main types of loops in Java

1). For Loop

The for loop is used when the number of iterations is known in advance.

Syntax of For Loop

for (initialization; condition; iteration) {
// code to be executed
}

Example of For Loop

for (int i = 1; i <= 5; i++) {
  System.out.println("Iteration: " + i);
}

Output

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

2). While Loop

The while loop is used when the number of iterations is not known in advance, and the loop continues until a certain condition becomes false.

Syntax of while

while (condition) {
// code to be executed
}

Example of while

int i = 1;
while (i <= 5) {
  System.out.println("Iteration: " + i);
  i++;
}

Output

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

3). Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once because the condition is evaluated at the end of the loop.

Syntax of do-while loop

do {
// code to be executed
} while (condition);

Example of do-while loop

int i = 1;
do {
  System.out.println("Iteration: " + i);
  i++;
} while (i <= 5);

Output

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

These loop structures allow you to repeat a block of code multiple times, providing flexibility in handling different scenarios in Java programs.

Array in java

In Java, an array is a collection of elements having same data type. It takes and stores the data in a contiguous memory location.

Syntax for declaring an array in Java

1). One dimensional array

// one dimensional array
datatype[] arrayName = new datatype[arraySize];
datatype arrayName[] = new datatype[arraySize];

2). Two dimensional array

// two dimensional array
datatype[][] arrayName;

Here, datatype is the type of data that the array will hold, arrayName is the name of the array, and arraySize is the number of elements that the array can hold.

For example
To declare an integer array of size 5, we would write

int[] numbers = new int[5];

Collections In Java

1). Set – Set is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc.

2). List – List is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors.

3). Queue –FIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.

4). Stack – LIFO approach, last in first out structutre, stack is a sub ordinate of vector which helps in performing different functions.

5). Deque – Deque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail).

6). Map – Map contains key-values pairs which don’t have any duplicates. Map is implemented in HashMap, TreeMap etc.

Collections in java with syntax and example

Some of the commonly used collection types in Java, along with their syntax and examples:

1). List

List is a ordered collection of elements which can have duplicates values. Lists are classified into ArrayList, LinkedList, Vectors

Syntax of List

List listName = new ArrayList<>();

Example of List

import java.util.List;
import java.util.ArrayList;
List names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names);

Output

[Alice, Bob, Charlie]

2). Set

Set is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc.

Syntax of Set

Set setName = new HashSet<>();

Example of Set

import java.util.Set;
import java.util.HashSet;
Set numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(10); // Duplicate value
System.out.println(numbers);

Output

[10, 20, 30]

3). Map

Syntax of Map

Map mapName = new HashMap<>();

Example of Map

import java.util.Map;
import java.util.HashMap;
Map scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 90);
scores.put("Charlie", 95);
System.out.println(scores);

Output

{Alice=85, Bob=90, Charlie=95}

4). Queue

FIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.

Syntax of Queue

Queue queueName = new LinkedList<>();

Example of Queue

import java.util.Queue;
import java.util.LinkedList;
Queue queue = new LinkedList<>();
queue.add("Alice");
queue.add("Bob");
queue.add("Charlie");
System.out.println(queue);

Output
[Alice, Bob, Charlie]

5). Stack

LIFO approach, last in first out structutre, stack is a sub ordinate of vector which helps in performing different functions.

Syntax of Stack

Stack stackName = new Stack<>();

Example of Stack

import java.util.Stack;
Stack stack = new Stack<>();
stack.push("Alice");
stack.push("Bob");
stack.push("Charlie");
System.out.println(stack);

Output

[Alice, Bob, Charlie]

These are just a few examples of collection types available in Java. The Java Collections framework provides a wide range of interfaces and classes to handle various data structures and operations efficiently.

Collection Class Implementation

1). ArrayList (List implementation)

ArrayList is an implementation of the List interface, which allows duplicate elements and maintains the insertion order. In this example, we create an ArrayList of Strings, add elements to it using the add() method, and print the list.

Example of ArrayList

import java.util.List;
import java.util.ArrayList;
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names);

Output

[Alice, Bob, Charlie]

2). HashSet(Set implementation)

HashSet is an implementation of the Set interface, which stores unique elements in no particular order. In this example, we create a HashSet of Integers, add elements to it using the add() method (where duplicate value is ignored), and print the set.

Example of HashSet

import java.util.Set;
import java.util.HashSet;
Set<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(10); // Duplicate value
System.out.println(numbers);

Output

[10, 20, 30]

3). HashMap(Map implementation)

HashMap is an implementation of the Map interface, which stores key-value pairs. Each key is unique, and values can be accessed using the corresponding key. In this example, we create a HashMap with String keys and Integer values, add entries using the put() method, and print the map.

Example of HashMap

import java.util.Map;
import java.util.HashMap;
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 85);
scores.put("Bob", 90);
scores.put("Charlie", 95);
System.out.println(scores);

Output:

{Alice=85, Bob=90, Charlie=95}

4. LinkedList (Queue implementation)

LinkedList is an implementation of the Queue interface, which represents a FIFO (First-In-First-Out) data structure. In this example, we create a LinkedList as a Queue, add elements to it using the add() method, and print the queue.

Example of LinkedList

import java.util.Queue;
import java.util.LinkedList;
Queue<String> queue = new LinkedList<>();
queue.add("Alice");
queue.add("Bob");
queue.add("Charlie");
System.out.println(queue);

Output:

[Alice, Bob, Charlie]

String in Java 

String class represents a sequence of characters. It is widely used to store and manipulate text data. 

Methods of the String Class

1). length()

Returns the length of the string.

Example of length()

String name = "Alice";
int length = name.length();
System.out.println(length);

Output

5

2. charAt(int index)

Returns the character at the specified index.

Example of charAt(int index)

String name = "Alice";
char firstChar = name.charAt(0);
System.out.println(firstChar);

Output

A

3. substring(int startIndex)

Returns a new string that is a substring of the original string starting from the specified index.

Example of substring(int startIndex)

String name = "Alice";
String substring = name.substring(2);
System.out.println(substring);

Output

ice

4. substring(int startIndex, int endIndex)

Returns a new string that is a substring of the original string starting from the startIndex and ending at the endIndex (exclusive).

Example of substring(int startIndex, int endIndex)

String name = "Alice";
String substring = name.substring(1, 4);
System.out.println(substring);

Output:

lic

5. toLowerCase() and toUpperCase()

Converts the string to lowercase or uppercase.

Example of toLowerCase() and toUpperCase()

String name = "Alice";
String lowercase = name.toLowerCase();
String uppercase = name.toUpperCase();
System.out.println(lowercase);
System.out.println(uppercase);

Output:

alice

ALICE

6. concat(String str)

Concatenates the specified string to the end of the original string.

Example of concat(String str)

String firstName = "John";
String lastName = "Doe";
String fullName = firstName.concat(" ").concat(lastName);
System.out.println(fullName);

Output:

John Doe

7. equals(Object obj)

Compares the string with the specified object for equality.

String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2);
System.out.println(isEqual);

Output:

false

8. startsWith(String prefix) and endsWith(String suffix)

Checks if the string starts with the specified prefix or ends with the specified suffix.

String name = "Alice";
boolean startsWithA = name.startsWith("A");
boolean endsWithC = name.endsWith("c");
System.out.println(startsWithA);
System.out.println(endsWithC);

Output:

true

false

9. indexOf(String str) and lastIndexOf(String str)

Returns the index of the first occurrence or last occurrence of the specified string within the original string.

String sentence = "I love Java, Java is great!";
int firstIndex = sentence.indexOf("Java");
int lastIndex = sentence.lastIndexOf("Java");
System.out.println(firstIndex);
System.out.println(lastIndex);

Output:

7

18

10. isEmpty()

Checks if the string is empty (contains no characters).

String str1 = "";
String str2 = "Hello";
boolean isEmpty1 = str1.isEmpty();
boolean isEmpty2 = str2.isEmpty();
System.out.println(isEmpty1);
System.out.println(isEmpty2);

Output:

true

false

11. replace(char oldChar, char newChar) and replace(CharSequence target, CharSequence replacement)

Replaces occurrences of a specified character or sequence of characters with another character or sequence of characters.

String sentence = "Java is fun!";
String replaced1 = sentence.replace('a', 'o');
String replaced2 = sentence.replace("fun", "awesome");
System.out.println(replaced1);
System.out.println(replaced2);

Output:

Java is fun!

Java is awesome!

12. split(String regex)

Splits the string into an array of substrings based on the specified regular expression.

String sentence = "Java is awesome!";
String[] words = sentence.split(" ");
for (String word : words) {
    System.out.println(word);
}

Output:

Java

is

awesome!

13. trim()

Removes leading and trailing whitespaces from the string.

String str = " Hello, World! ";
String trimmed = str.trim();
System.out.println(trimmed);

Output:

Hello, World!

14. compareTo(String anotherString)

Compares the string lexicographically (based on the Unicode value of each character) with another string.

String str1 = "apple";
String str2 = "banana";
int result = str1.compareTo(str2);
System.out.println(result);

Output:

-1

15. valueOf(datatype value)

Converts different types of values to their string representation.

int number = 42;

String strNumber = String.valueOf(number);

System.out.println(strNumber);

Output:

42

OPPs (Object Oriented Programing Language)

Classes and Objects in Java

Classes

A class is a blueprint or a template that defines the structure and behavior of objects. It represents a collection of related data (variables) and methods (functions) that operate on that data. It serves as a blueprint for creating individual objects of that class.

Here’s an example of a class called “Car” that represents the blueprint for creating car objects:

public class Car {

    // Instance variables

    String brand;

    String color;

    int year;

    // Constructor

    public Car(String brand, String color, int year) {

        this.brand = brand;

        this.color = color;

        this.year = year;

    }

    // Method

    public void startEngine() {

        System.out.println("The " + brand + " car's engine is started.");

    }

}

In this example, the Car class has three instance variables brand, color, and year, that represent the state of a car object. It also has a constructor that is used to initialize the state of the object when it is created. The class also contains a method called startEngine() that defines the behavior of a car object.

An object, on the other hand, is an instance of a class. It is created using the new keyword and the class’s constructor. Each object has its own set of instance variables and can invoke the methods defined in its class.

Here’s an example of creating objects of the Car class:

public class Main {

    public static void main(String[] args) {

        // Creating car objects

        Car car1 = new Car("Toyota", "Red", 2022);

        Car car2 = new Car("BMW", "Black", 2021);

        // Accessing object properties

        System.out.println(car1.brand);  // Output: Toyota

        System.out.println(car2.color);  // Output: Black

        // Invoking object methods

        car1.startEngine();  // Output: The Toyota car's engine is started.

        car2.startEngine();  // Output: The BMW car's engine is started.

    }

}

In the above example, two car objects (car1 and car2) are created using the new keyword and the Car class’s constructor. The objects are assigned with specific values for their instance variables. Then, the properties of the objects are accessed using the dot (.) notation, and the startEngine() method is invoked on each object, which produces the corresponding output.

This demonstrates how classes and objects work together in Java to model real-world entities and their behaviors. Objects allow you to create multiple instances of a class, each with its own unique state and behavior.

Abstraction

Abstraction is a fundamental concept in object-oriented programming (OOP) that allows you to represent complex systems by focusing on the essential features and hiding unnecessary details. It helps in creating modular, maintainable, and reusable code. In Java, abstraction is achieved through abstract classes and interfaces.

Abstract Classes

An abstract class is a class that cannot be instantiated and is meant to be subclassed. It can contain both abstract and non-abstract methods. Abstract methods are declared without any implementation and are meant to be overridden by the subclasses. Abstract classes provide a way to define common behavior and attributes for a group of related classes.

Example of Abstract Class

abstract class Shape {

    protected String color;

    public Shape(String color) {

        this.color = color;

    }

    public abstract void draw();

}

class Circle extends Shape {

    private double radius;

    public Circle(String color, double radius) {

        super(color);

        this.radius = radius;

    }

    @Override

    public void draw() {

        System.out.println("Drawing a circle with radius " + radius + " and color " + color);

    }

}

class Rectangle extends Shape {

    private double length;

    private double width;

    public Rectangle(String color, double length, double width) {

        super(color);

        this.length = length;

        this.width = width;

    }

    @Override

    public void draw() {

        System.out.println("Drawing a rectangle with length " + length + ", width " + width + ", and color " + color);

    }

}

public class Main {

    public static void main(String[] args) {

        Shape circle = new Circle("Red", 5.0);

        circle.draw();

        Shape rectangle = new Rectangle("Blue", 10.0, 7.0);

        rectangle.draw();

    }

}

In the above example, the abstract class Shape defines a common behavior, draw(), that is expected to be implemented by its subclasses. The Circle and Rectangle classes inherit from the Shape class and provide their own implementation of the draw() method.

Encapsulation In Java

Encapsulation is a fundamental principle of object-oriented programming (OOP) in Java. It refers to the bundling of data (attributes) and methods (behavior) together as a single unit, known as a class. Encapsulation provides a way to hide the internal implementation details of an object and expose only the necessary functionality through public methods.

By encapsulating the internal state of an object, you ensure that the object’s data is accessed and modified only through controlled mechanisms, maintaining data integrity and preventing direct access to sensitive information.

Example of Encapsulation in Java

public class Employee {

    private String name;

    private int age;

    private double salary;

    public Employee(String name, int age, double salary) {

        this.name = name;

        this.age = age;

        this.salary = salary;

    }

    // Getter methods

    public String getName() {

        return name;

    }

    public int getAge() {

        return age;

    }

    public double getSalary() {

        return salary;

    }

    // Setter methods

    public void setName(String name) {

        this.name = name;

    }

    public void setAge(int age) {

        this.age = age;

    }

    public void setSalary(double salary) {

        this.salary = salary;

    }

}

In the above example, the Employee class encapsulates the attributes name, age, and salary by making them private. This prevents direct access to these attributes from outside the class. To access or modify these attributes, public getter and setter methods are provided.

The getter methods (getName(), getAge(), getSalary()) allow other classes to retrieve the values of the private attributes. The setter methods (setName(), setAge(), setSalary()) allow other classes to modify the values of the private attributes. By encapsulating the attributes and providing controlled access, the Employee class ensures that the data is accessed and modified in a controlled manner.

Example of using the Employee class

public class Main {

    public static void main(String[] args) {

        Employee emp = new Employee("John Doe", 30, 50000.0);       

        // Accessing attributes through getter methods

        System.out.println("Name: " + emp.getName());

        System.out.println("Age: " + emp.getAge());

        System.out.println("Salary: " + emp.getSalary());       

        // Modifying attributes through setter methods

        emp.setName("Jane Smith");

        emp.setAge(35);

        emp.setSalary(60000.0);

        // Accessing modified attributes

        System.out.println("Modified Name: " + emp.getName());

        System.out.println("Modified Age: " + emp.getAge());

        System.out.println("Modified Salary: " + emp.getSalary());

    }

}

In this example, we create an Employee object and use the getter and setter methods to access and modify its attributes. The encapsulation ensures that the attributes are not directly accessed or modified from outside the class, maintaining the integrity and control over the object’s state.

Encapsulation provides several benefits, including data hiding, modularity, code reusability, and improved maintainability. It allows you to protect the internal state of an object and control its interactions with the outside world, promoting better design and encapsulating complexity within classes.

Polymorphism

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. It enables you to write code that can work with objects of various types, providing flexibility, code reuse, and extensibility.

There are two types of polymorphism in Java: compile-time polymorphism (method overloading) and runtime polymorphism (method overriding).

1). Compile-Time Polymorphism (Method Overloading)

Method overloading allows you to define multiple methods with the same name but different parameter lists within a class. The appropriate method to execute is determined by the compiler based on the number, type, and order of the arguments passed.

Here’s an example of method overloading in Java

public class Calculator {

    public int add(int a, int b) {

        return a + b;

    }

    public double add(double a, double b) {

        return a + b;

    }

    public int add(int a, int b, int c) {

        return a + b + c;

    }

}

public class Main {

    public static void main(String[] args) {

        Calculator calculator = new Calculator();

        int result1 = calculator.add(5, 10);

        double result2 = calculator.add(2.5, 3.7);

        int result3 = calculator.add(1, 2, 3);

        System.out.println("Result 1: " + result1);

        System.out.println("Result 2: " + result2);

        System.out.println("Result 3: " + result3);

    }

}

In this example, the Calculator class defines three add methods with different parameter lists. The appropriate method is called based on the arguments passed during method invocation. The compiler determines which method to invoke based on the parameter types.

2). Runtime Polymorphism (Method Overriding)

Method overriding allows a subclass to provide a different implementation of a method that is already defined in its superclass. The subclass overrides the method by using the @Override annotation and providing its own implementation. At runtime, the JVM determines which version of the overridden method to execute based on the actual object’s type.

Here’s an example of method overriding in Java

class Animal {

    public void makeSound() {

        System.out.println("The animal makes a sound");

    }

}

class Dog extends Animal {

    @Override

    public void makeSound() {

        System.out.println("The dog barks");

    }

}

class Cat extends Animal {

    @Override

    public void makeSound() {

        System.out.println("The cat meows");

    }

}

public class Main {

    public static void main(String[] args) {

        Animal animal1 = new Dog();

        Animal animal2 = new Cat();

        animal1.makeSound();  // Calls the overridden method in Dog class

        animal2.makeSound();  // Calls the overridden method in Cat class

    }

}

In this example, the Animal class defines a makeSound method, and the Dog and Cat classes override this method with their own implementations. When creating objects of Dog and Cat and referencing them with the Animal type, the appropriate overridden makeSound method is executed at runtime based on the actual object’s type.

Polymorphism allows you to write generic code that can operate on objects of different types, making your code more flexible, reusable, and extensible. It promotes code modularity, simplifies code maintenance, and enables you to work with objects at a higher level of abstraction.

Constructor in java  

In Java, a constructor is a special method that is used to initialize objects of a class. It is called when an object is created using the new keyword and is responsible for setting initial values to the object’s attributes or performing any necessary setup.

Here are some key points about constructors

The constructor has the same name as the class and does not have a return type, not even void.

Constructors can be overloaded, meaning a class can have multiple constructors with different parameter lists.

If a class does not explicitly define any constructors, a default constructor (with no arguments) is automatically provided by the compiler.

Constructors can invoke other constructors within the same class using the this() keyword for constructor chaining.

Constructors can also call the constructor of the superclass using the super() keyword.

Here’s a program to demonstrates the usage of constructors

public class Employee {

    private String name;

    private int age;

    // Default constructor

    public Employee() {

        name = "Unknown";

        age = 0;

    }

    // Parameterized constructor

    public Employee(String name, int age) {

        this.name = name;

        this.age = age;

    }

    // Getter and setter methods

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public int getAge() {

        return age;

    }

    public void setAge(int age) {

        this.age = age;

    }

}

public class Main {

    public static void main(String[] args) {

        // Creating objects using constructors

        Employee emp1 = new Employee(); // Default constructor

        Employee emp2 = new Employee("John Doe", 30); // Parameterized constructor

        // Accessing object attributes

        System.out.println("Employee 1: " + emp1.getName() + ", " + emp1.getAge());

        System.out.println("Employee 2: " + emp2.getName() + ", " + emp2.getAge());

        // Modifying object attributes

        emp1.setName("Jane Smith");

        emp1.setAge(35);

        System.out.println("Modified Employee 1: " + emp1.getName() + ", " + emp1.getAge());

    }

}

In the above example, the Employee class has two constructors: a default constructor with no arguments and a parameterized constructor that takes the name and age as parameters. The default constructor sets the initial values to “Unknown” and 0, while the parameterized constructor initializes the attributes with the provided values.

In the Main class, objects of the Employee class are created using both constructors. The object attributes are accessed and modified using the getter and setter methods.

Constructors are essential for initializing objects and ensuring that the necessary setup is performed before the object is used. They help in maintaining the object’s integrity and providing a consistent state. Constructors allow for flexibility by supporting different ways of creating objects with varying initialization requirements.

Inheritance in java

 Inheritance is a key concept in object-oriented programming (OOP) that allows you to create new classes (subclasses) based on existing classes (superclasses). The subclass inherits the properties and behaviors (methods) of the superclass, promoting code reuse, extensibility, and modularity.

In Java, inheritance is implemented using the extends keyword, where a subclass extends a single superclass. The subclass inherits all the non-private members (attributes and methods) of the superclass and can add its own additional members or override inherited members.

Example to demonstrates inheritance in Java

class Vehicle {

    protected String brand;

    public Vehicle(String brand) {

        this.brand = brand;

    }

    public void start() {

        System.out.println("The vehicle starts.");

    }

    public void stop() {

        System.out.println("The vehicle stops.");

    }

}

class Car extends Vehicle {

    private int numOfSeats;

    public Car(String brand, int numOfSeats) {

        super(brand);

        this.numOfSeats = numOfSeats;

    }

    public void drive() {

        System.out.println("The car is driving.");

    }

    @Override

    public void stop() {

        System.out.println("The car stops by applying brakes.");

    }

}

public class Main {

    public static void main(String[] args) {

        Car car = new Car("Toyota", 5);

        car.start();

        car.drive();

        car.stop();

    }

}

In this example, the Vehicle class is the superclass, and the Car class is the subclass that extends the Vehicle class. The Vehicle class has a constructor and two methods: start() and stop(). The Car class has an additional attribute numOfSeats and a method drive(). The Car class also overrides the stop() method inherited from the Vehicle class to provide its own implementation.

In the Main class, an object of the Car class is created. The object can access and invoke the methods inherited from the Vehicle class, such as start() and stop(). It can also access its own methods, such as drive(). The Car class can provide specialized behavior and extend the functionality of the Vehicle class while inheriting and reusing the common attributes and methods.

Inheritance allows you to create a hierarchy of classes, with subclasses inheriting from superclasses. It promotes code reuse, modularity, and extensibility. Inherited members can be overridden, allowing subclasses to provide their own implementations. Inheritance is a powerful mechanism in OOP that helps in creating well-structured and organized code.

Excpetion Handling  in java

Exception handling in Java allows you to handle and manage unexpected or exceptional situations that may occur during the execution of a program.  In Simple word we can say that exception is a condition that terminate the program from the normal execution.

The key components of exception handling in Java are

try: The try block is used to enclose the code that may throw an exception. If an exception occurs within the try block, it is caught and handled by the corresponding catch block.

catch: The catch block is used to catch and handle specific types of exceptions if exception occurred in try blog. Catch block has the code that to execute when that exception occurs.

finally: The finally block is an optional block. It follows the try and catch blocks. It contains code that will execute always either exception occurred or not. It is typically used to release resources or perform cleanup operations.

Example to demonstrates Exception Handling in Java

public class ExceptionHandlingExample {

    public static void main(String[] args) {

        try {

            int result = divide(10, 0);

            System.out.println("Result: " + result);

        } catch (ArithmeticException ex) {

            System.out.println("An exception occurred: " + ex.getMessage());

        } finally {

            System.out.println("Finally block executed.");

        }

    }

    public static int divide(int dividend, int divisor) {

        return dividend / divisor;

    }

}

In the above example, the divide() method attempts to divide the dividend by the divisor. However, since division by zero is not allowed, it will throws an ArithmeticException. The try block in the main() method contains the division operation. If an exception occurs within the try block, it is caught by the corresponding catch block that handles ArithmeticException. The message from the exception is printed to the console.

The finally block is executed regardless of whether an exception occurred or not. In this example, the “Finally block executed.” message is always printed.

Exception handling allows you to gracefully handle exceptional situations, providing a way to recover from errors or terminate the program in a controlled manner. It prevents abrupt termination of the flow of program, allows for error reporting and logging, and enables the execution of cleanup code. By catching and handling exceptions, you can handle errors and ensure the smooth execution of your Java programs.

Multithreading in java

In Java, Multithreading allows you to execute multiple threads concurrently. This multithreading helps to improve the performance of your application by leveraging the capabilities of modern multi-core processors.

Here are a few examples of how you can use multithreading in Java

Program 1: Extending the Thread class

class MyThread extends Thread {

    public void run() {

        System.out.println("Thread is running");

    }

}

public class Main {

    public static void main(String[] args) {

        MyThread thread = new MyThread();

        thread.start(); // Starts the new thread

    }

}

Example 2: Implementing the Runnable interface

class MyRunnable implements Runnable {

    public void run() {

        System.out.println("Runnable is running");

    }

}

public class Main {

    public static void main(String[] args) {

        MyRunnable runnable = new MyRunnable();

        Thread thread = new Thread(runnable);

        thread.start(); // Starts the new thread

    }

}

In the Above examples you have seen different ways to create and run threads in Java. You have seen how to create threads by either extending the Thread class or implementing the Runnable interface.

Serialization in java

Java Serialization is a mechanism in Java that allows you to convert objects into a byte stream to store and transmit it remotly. It enables you to save the state of an object and recreate it later, ensuring that the object’s structure and data are preserved. Serialization is widely used in scenarios such as saving objects to files, sending objects over a network, or storing objects in a database.

To make a class serializable, you need to implement the java.io.Serializable interface. This interface serves as a marker interface, indicating that the class can be serialized. It doesn’t have any methods to implement, but it acts as a contract that the class agrees to be serialized.

Example to demonstrates serialization and deserialization

import java.io.*;

class Employee implements Serializable {

    private String name;

    private String department;

    private transient double salary; // Marked as transient, won't be serialized

    public Employee(String name, String department, double salary) {

        this.name = name;

        this.department = department;

        this.salary = salary;

    }

    public void printDetails() {

        System.out.println("Name: " + name);

        System.out.println("Department: " + department);

        System.out.println("Salary: " + salary);

    }

}

public class SerializationExample {

    public static void main(String[] args) {

        Employee emp = new Employee("John Doe", "Engineering", 5000.0);

        // Serialization

        try {

            FileOutputStream fileOut = new FileOutputStream("employee.ser");

            ObjectOutputStream out = new ObjectOutputStream(fileOut);

            out.writeObject(emp);

            out.close();

            fileOut.close();

            System.out.println("Serialized data is saved in employee.ser");

        } catch (IOException e) {

            e.printStackTrace();

        }

        // Deserialization

        try {

            FileInputStream fileIn = new FileInputStream("employee.ser");

            ObjectInputStream in = new ObjectInputStream(fileIn);

            Employee deserializedEmp = (Employee) in.readObject();

            in.close();

            fileIn.close();

            System.out.println("Deserialized data:");

            deserializedEmp.printDetails();

        } catch (IOException e) {

            e.printStackTrace();

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        }

    }

}

In the above example, we have a Employee class that implements the Serializable interface. It has a few fields, including name, department, and salary. The salary field is marked as transient, which means it won’t be serialized.

The main method demonstrates serialization and deserialization. First, we create an Employee object. We then serialize the object by creating a FileOutputStream and an ObjectOutputStream. The writeObject method is used to write the object to the output stream. The serialized data is saved in a file named “employee.ser”.

For deserialization, we read the serialized data from the file using FileInputStream and ObjectInputStream. The readObject method is used to read the object from the input stream. We cast the deserialized object to an Employee and print its details using the printDetails method.

It’s important to note that both serialization and deserialization can throw IOException if there are issues with the input/output streams. Additionally, deserialization can throw ClassNotFoundException if the class being deserialized is not found in the classpath.

Serialization in Java provides a convenient way to store and transmit objects. However, it’s worth considering the compatibility and security aspects while using serialization, as changes to the serialized class structure or potential security vulnerabilities can impact deserialization.