Comprehensive Guide to Java Programming: OOP, Exceptions, Threads, and More

Most Common Errors in Java

  • Method overloading
  • Comparing two objects (== and equals)
  • Using = sign rather than ==
  • Null pointer exception
  • Capitalization error
  • Incompatibility type
  • Expected
  • Unclosed string literal
  • Missing return statement

Operations in Java

  • Arithmetic operation
  • Relational operation
  • Bitwise operation
  • Logical operation
  • Assignment operation
  • Conditional operation
  • Misc operation

Major Concepts in OOP

  • Encapsulation: Bundle data and methods into a class; protect internal state.
  • Abstraction: Hide complex implementation details; expose only necessary parts.
  • Inheritance: Enable new classes to inherit properties and behaviors from existing ones; promote code reuse.
  • Polymorphism: Allow objects to be treated as instances of a common superclass; increase flexibility.
  • Modularity: Break down a program into smaller, manageable modules; enhance organization.
  • Reusability: Design classes for reuse across different programs; save development time.
  • Maintainability: Create easy-to-modify software; reduce update costs and effort.
  • Scalability: Ensure software can handle growth; accommodate more users and features easily.

Method Overloading

We define many methods with the same name but with different parameters; this process is called method overloading.

Example

public class Addition {
    // Method to add two integers
    public int sum(int x, int y) {
        return (x + y);
    }

    // Method to add three integers
    public int sum(int x, int y, int z) {
        return (x + y + z);
    }

    // Method to add two doubles
    public double sum(double x, double y) {
        return (x + y);
    }

    public static void main(String args[]) {
        Addition a = new Addition();
        System.out.println(a.sum(10, 20));
        System.out.println(a.sum(10, 20, 30));
        System.out.println(a.sum(10.5, 20.5));
    }
}

Copy Constructor

There is no copy constructor in Java like in C++. However, we can copy the value of one object to another.

Example

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Constructor to copy values from another Person object
    Person(Person other) {
        this.name = other.name;
        this.age = other.age;
    }

    public static void main(String[] args) {
        Person p1 = new Person("Alice", 30);
        Person p2 = new Person(p1); // Copying values from p1 to p2
        System.out.println(p1.name + ", " + p1.age);
        System.out.println(p2.name + ", " + p2.age);
    }
}

Constructors

Constructors initialize the variables of an object immediately after its creation. It simplifies the process of initializing variables while creating the object.

Types of Constructors

  • Default Constructors: A constructor that has no parameters is known as a default constructor.
  • Parameterized Constructors: A constructor that has parameters is known as a parameterized constructor.

Inheritance

Inheritance can be defined as the process or mechanism of acquiring all the properties and behavior of one class to another.

Types of Inheritance

  • Single Inheritance: When a single class is derived from its base class, this type of inheritance is termed single inheritance.
  • Multi-level Inheritance: In this type of inheritance, a derived class is created from another derived class and can have any number of levels. It is similar to the relation between grandfather, father, and child.
  • Hierarchical Inheritance: In this type, two or more classes inherit the properties of one existing class. When more than one class is derived from a single base class, such inheritance is known as Hierarchical Inheritance.

Packages

A Java package is a group of similar types of classes, interfaces, and sub-packages. We can say a package in Java is a mechanism to encapsulate a group of classes, interfaces, and sub-packages, which is used to provide access protection and namespace management.

Types of Packages

  • Built-in Packages: Existing Java packages, for example, java.io.*, java.lang, java.util, etc.
  • User-defined Package: Java packages created by users to categorize classes and interfaces.

Creating a Java Package

Creating a package in Java is quite easy. Simply include a package command followed by the name of the package as the first statement in the Java source file.

Example

package mypackage;

public class PackageDemo {
    public static void main(String args[]) {
        System.out.println("Welcome to package");
    }
}

Exception

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions are used for handling errors and other exceptional conditions in a controlled way.

Checked Exception

Checked exceptions in Java are exceptions that are checked at compile-time. These exceptions must be either caught using a try-catch block or declared in the method signature using the throws keyword.

Unchecked Exception

Unchecked exceptions in Java are exceptions that are not checked at compile-time but are checked at runtime. They are subclasses of RuntimeException.

Exception Handling

Exception handling in Java allows you to manage and respond to unexpected situations that can occur during the execution of a program.

Example

public class ShortExceptionExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[4]); // Trying to access an element out of bounds
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Exception caught: Index is out of bounds");
        }
    }
}

Error

In Java, an Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Errors are typically external to the application and signal conditions that are generally unrecoverable.

Try Block

A try block is always followed by a catch block, which handles the exception that occurs in the associated try block.

Catch Block

It is where you handle the exception. This block must follow the try block.

String

It is probably the most commonly used class in the Java library. The String class is encapsulated under the java.lang package.

Java String Methods

  1. String length(): Returns the length of the string. String str = "Hello"; int len = str.length();
  2. String compareTo(): Compares two strings lexicographically. int result = str.compareTo("World");
  3. String toUpperCase(): Converts all characters of the string to uppercase. String upper = str.toUpperCase();
  4. String toLowerCase(): Converts all characters of the string to lowercase. String lower = str.toLowerCase();
  5. String isEmpty(): Checks if the string is empty (has a length of 0). String str = ""; boolean empty = str.isEmpty();
  6. String trim(): Removes whitespace from both ends of the string. String str = " Hello "; String trimmed = str.trim();
  7. String concat(): Concatenates the specified string to the end of this string. String str1 = "Hello"; String str2 = "World"; String str3 = str1.concat(str2);

Character Extraction

The process of extracting a particular character or any symbol from a given string is called character extraction.

Searching String

Searching a string for finding the location of either a character or a group of characters (substring) is a common task. We can search for a particular letter in a string using the indexOf() method of the String class.

Advantages of Exception Handling

  • In C, we need to check return values of every function call for error handling. if (read(buf, SIZE) == -1) This kind of error handling is very tedious, although necessary.
  • In Java, we can designate a separate exception handling region.
  • You try to run a block of code, which may throw exceptions. You catch the thrown exception in a designated area.
  • This makes reading, writing, and debugging code much clearer.

What is an Abstract Class? How is it Used in Java? Explain with a Suitable Example.

An abstract class in Java cannot be instantiated and is used to declare common characteristics for subclasses. It can contain both abstract methods (without implementation) and concrete methods (with implementation). Subclasses of an abstract class must implement all abstract methods unless they are also abstract. For example, an abstract class Animal might have an abstract method sound() and a concrete method eat(). Subclasses like Dog would implement the sound() method while inheriting the eat() method.

Program

abstract class Animal {
    abstract void sound();
    void eat() {
        System.out.println("Eating...");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Barks");
    }
}

What is Method Overriding? How is it Different from Method Overloading? Explain.

Method overriding occurs when a subclass provides a specific implementation for a method already defined in its superclass, using the same name, return type, and parameters. This allows a subclass to offer a specific behavior for a method that is also present in its parent class. Method overloading, on the other hand, happens when multiple methods in the same class share the same name but differ in their parameters (different number or type of parameters). Overloading allows a class to have multiple methods with the same name but different argument lists.

Example

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

class Test {
    void display(int a) {
        System.out.println("Display with int: " + a);
    }

    void display(String a) {
        System.out.println("Display with String: " + a);
    }
}

What is a Package in Java? Describe Their Types with a Suitable Example. How to Access a Package from Another Package? Explain with an Example.

A package in Java is a namespace that organizes related classes and interfaces, helping to avoid name conflicts and control access. Packages can be built-in (like java.util) or user-defined. Built-in packages are part of the Java API, while user-defined packages are created by developers to organize their code.

Example

package com.mycompany.mypackage;

public class MyClass {
    public void display() {
        System.out.println("Hello from MyClass in mypackage");
    }
}
package com.mycompany.anotherpackage;

import com.mycompany.mypackage.MyClass;

public class Test {
    public static void main(String[] args) {
        MyClass obj = new MyClass();
        obj.display();
    }
}

What are the Advantages of Using Inheritance in Java?

Inheritance in Java promotes code reusability by allowing a class to inherit fields and methods from another class, reducing code duplication. It also supports method overriding, enabling a subclass to provide specific implementations of methods defined in its superclass. Inheritance facilitates polymorphism, allowing a single method to operate differently based on the object it is acting upon. It enhances code maintainability and extensibility by enabling new functionalities to be added to existing code without modifying it.

How to Access a Package from Another Package? Explain with an Example.

To access a class from another package, use the import statement. For example, if you have a class MyClass in the package com.mycompany.mypackage, you can access it in another package com.mycompany.anotherpackage by importing it.

Example Above

What is Runtime Polymorphism or Dynamic Method Dispatch in Java?

Runtime polymorphism, or dynamic method dispatch, in Java occurs when the call to an overridden method is resolved at runtime rather than compile-time. This allows for dynamic behavior based on the object’s actual type. For example, if a superclass Animal has a method sound(), and its subclasses Dog and Cat override this method, the specific method that gets called depends on the actual object type at runtime, enabling flexible and dynamic method calls.

What are the Uses of the super Keyword in Java? Explain Their Uses with a Suitable Example.

The super keyword in Java is used to refer to the immediate parent class object. It can be used to access superclass methods, fields, and constructors. super helps call the superclass’s constructor, invoke a superclass’s method that has been overridden, and access a field of the superclass that is hidden by the subclass.

Example

class Animal {
    String color = "White";

    Animal() {
        System.out.println("Animal is created");
    }

    void display() {
        System.out.println("Animal method");
    }
}

class Dog extends Animal {
    String color = "Black";

    Dog() {
        super(); // Calling the constructor of the parent class
        System.out.println("Dog is created");
    }

    @Override
    void display() {
        super.display(); // Calling the display() method of the parent class
        System.out.println("Dog method");
    }

    void printColor() {
        System.out.println(super.color); // Accessing the color variable of the parent class
        System.out.println(color); // Accessing the color variable of the current class
    }
}

public class Test {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.display();
        d.printColor();
    }
}

Threads

Threads in Java are a powerful feature that allows for the concurrent execution of two or more parts of a program to maximize the utilization of CPU resources.

Methods of Threads

  1. public void start():

Threads Priority

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10).

Create a Thread by Implementing a Runnable Interface

If your class is intended to be executed as a thread, then you can achieve this by implementing a Runnable interface.

  • Step 1: As a first step, you need to implement a run() method provided by a Runnable interface. This method provides an entry point for the thread, and you will put your complete business logic inside this method. Following is a simple syntax of the run() method: public void run()
  • Step 2: As a second step, you will instantiate a Thread object using the following constructor: Thread(Runnable threadObj, String threadName); Where, threadObj is an instance of a class that implements the Runnable interface, and threadName is the name given to the new thread.
  • Step 3: Once a Thread object is created, you can start it by calling the start() method, which executes a call to the run() method. Following is a simple syntax of the start() method: void start();

Synchronization

At a time when more than one thread tries to access a shared resource, we need to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization.

Inter-Thread Communication

Java provides the benefits of avoiding thread pooling using inter-thread communication.

Thread Deadlock

Deadlock is a complete lock when no thread can complete its execution because of a lack of resources.

Java I/O Stream

Java I/O streams are flows of data that can either be read from or written to. They are used to process input and produce output.

Stream

A stream is a sequence of data. A stream is composed of bytes. It is called a stream because it is like a stream of water that continues to flow.

java.io Package

The package java.io contains the classes that handle fundamental input and output operations in Java. The I/O classes can be grouped as follows:

  • Classes for reading input from a stream of data.
  • Classes for writing output to a stream of data.

This package provides for system input and output through data streams, serialization, and the file system.

Java Byte Stream Classes

Byte stream classes are used to perform reading and writing of 8-bit bytes. Byte Stream Classes are used to read bytes from an input stream and write bytes to an output stream. Streams, being unidirectional in nature, can transfer bytes in one direction only, that is, either reading data from the source into a program or writing data from a program to the destination.

File Input Stream

This stream is used for reading data from files. Objects can be created using the keyword new, and there are several types of constructors available.

File Output Stream

FileOutputStream is used to create a file and write data into it. The stream would create a file if it doesn’t already exist before opening it for output.

Java Character Stream Classes

Character streams are also defined by using two abstract classes at the top of the hierarchy; they are Reader and Writer. Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java Character streams are used to perform input and output for 16-bit Unicode.

Reader Console Input

Scanner Class: Scanner is a class in the java.util package used for obtaining input of primitive types like int, double, etc., and strings.

Standard Stream Class

All programming languages provide support for standard I/O, where the user’s program can take input from a keyboard and then produce output on the computer screen.

Buffered Reader Class

BufferedReader reads text from a character-input stream, buffering characters to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

Serialization

Java provides a mechanism called object serialization, where an object can be represented as a sequence of bytes that includes the object’s data as well as information about the object’s type and the types of data stored in the object.

Serializing an Object

The ObjectOutputStream class is used to serialize an object. The following Serialize Demo program instantiates an Employee object and serializes it to a file. When the program is done executing, a file named employee.ser is created.

Deserialization

Deserialization in Java is the process of converting a byte stream back into a copy of the original object. This is the opposite of serialization, which converts an object into a byte stream to be stored or transmitted.

Package

A package in Java is a mechanism to encapsulate a group of classes, sub-packages, and interfaces.

Types of Packages

  1. Built-in Package
  2. User-defined Package

Built-in Package

These packages consist of a large number of classes which are a part of the Java API.

  • java.lang
  • java.io
  • java.util
  • java.applet
  • java.awt
  • java.net

User-defined Package

These are the packages that are defined by the user.

Wrapper Classes

A wrapper class is a class whose object wraps or contains a primitive data type. When we create an object of a wrapper class, it contains a field, and in this field, we can store a primitive data type.

Autoboxing

Autoboxing is the conversion of a primitive data type to the object of its corresponding wrapper class.

Unboxing

It is just the reverse process of autoboxing. Unboxing is converting an object of a wrapper class to its corresponding primitive type.

Features in Java

  • Compiled and interpreted
  • Platform-independent
  • Object-oriented
  • Robust and secure
  • Distributed
  • Multithreading and inheritance
  • Simple, small, and familiar
  • Portable
  • High performance

Why Java is OOP

Java is considered an Object-Oriented Programming (OOP) language because it incorporates and emphasizes the four fundamental principles of OOP: encapsulation, inheritance, polymorphism, and abstraction.

Why Use a Number Class Object Over Primitive Data?

  1. Constants defined by the Number class, such as MIN_VALUE and MAX_VALUE, that provide the upper and lower bounds of the data type are very much useful.
  2. The Number class object can be used as an argument of a method that expects an object (often used when manipulating collections of numbers).
  3. Class methods can be used for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, and binary).

Methods Common to All Subclasses of Number

  1. xxx xxxValue(): Here, xxx represents primitive number data types (byte, short, int, long, float, double). This method is used to convert the value of this Number object to the primitive data type specified.

Array

An array is a group of like-typed variables that are referred to by a common name.

One-Dimensional Arrays

A one-dimensional array in Java programming is an array with a bunch of values having been declared with a single index.

Creating an Array

An array is an object of a dynamically generated class. The Java array inherits the Object class and implements the Serializable as well as the Cloneable interface.

Instantiating an Array in Java

An array is declared; only a reference to the array is created. To actually create or give memory to the array, we create an array like this.

Array Literal

The size of the array and the variables of the array are already known as array literals.

Map Interface

The java.util.Map interface represents a mapping between a key and a value. The Map is not a subtype of the Collection interface.

Methods of Map Interface

  • public Object put(Object key, Object value): This method is used to insert an entry in this map.
  • public void putAll(Map map): This method is used to insert the specified map into this map.
  • public Object remove(Object key): This method is used to delete an entry for the specified key.
  • public Object get(Object key): This method is used to return the value for the specified key.
  • public boolean containsKey(Object key): This method is used to search for the specified key from this map.
  • public Set keySet(): This method is used to return the Set view containing all the keys.
  • public Set entrySet(): This method is used to return the Set view containing all the keys and values.

HashMap Class Methods

  • void clear(): It removes all the key and value pairs from the specified Map.
  • Object clone(): It returns a copy of all the mappings of a map and is used for cloning them into another map.
  • boolean containsKey(Object key): It is a boolean function that returns true or false based on whether the specified key is found in the map.
  • boolean containsValue(Object value): Similar to the containsKey() method, however, it looks for the specified value instead of the key.
  • Value get(Object key): It returns the value for the specified key.
  • boolean isEmpty(): It checks whether the map is empty. If there are no key-value mappings present in the map, then this function returns true else false.
  • Set keySet(): It returns the Set of the keys fetched from the map.
  • value put(Key k, Value v): Inserts key-value mapping into the map. Used in the above example.

List Interface

The java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored.

Set Interface

A collection that contains no duplicate elements. More formally, Set contains no pair of elements e1 and e2 such that e1.equals(e2) and at most one null element.

Collection Classes

  • Array List: It is a part of the collection framework and is present in the java.util package. It provides us with dynamic arrays in Java.
  • Linked List: A linked list is a linear data structure where the elements are not stored in contiguous locations, and every element is a separate object with a data part and an address part.
  • Hash Set: The HashSet class implements the Set interface backed by a hash table, which is actually a HashMap instance.
  • Tree Set: This class implements the TreeSet interface backed by a TreeMap. This class guarantees that the Set will be in ascending element order, stored according to the natural order of the elements or by the comparator provided at TreeSet creation time, depending on which constructor is used.

AWT

The Abstract Window Toolkit (AWT) is Java’s original platform-dependent windowing, graphics, and user-interface widget toolkit, preceding Swing.

What is an Interface? How is it Different from a Class? Explain.

An interface in Java is a reference type used to define a set of abstract methods that a class must implement. Interfaces provide a way to achieve abstraction and multiple inheritance since a class can implement multiple interfaces. Unlike classes, interfaces cannot have instance fields or constructors and cannot be instantiated. Interfaces are meant to specify what a class should do, not how it should do it. In contrast, a class can have fields, methods with implementations, and constructors, and can be instantiated to create objects.

Difference Between Synchronized Keyword and Synchronized Block

Synchronized Keyword

  • Locks the entire method.
  • Instance methods: locks the instance (this).
  • Static methods: locks the class object (ClassName.class).
  • Simple to implement.
  • Suitable when the entire method needs to be synchronized.
  • Less efficient if only part of the method needs synchronization.
  • Syntax: public synchronized void synchronizedMethod() { ... }

Synchronized Block

  • Locks only a specific block of code within a method.
  • Can lock any specified object.
  • More flexible and fine-grained control.
  • Suitable for synchronizing only critical sections of code.
  • More efficient by reducing the amount of synchronized code.
  • Syntax: public void method() { synchronized(lockObject) { ... } }

Difference Between Java AWT and Java Swing

Java AWT

  • AWT components are platform-dependent.
  • AWT components are heavyweight.
  • AWT doesn’t support a pluggable look and feel.
  • AWT provides fewer components than Swing.
  • AWT does not follow MVC, where the model represents data, the view represents presentation, and the controller acts as an interface between the model and view.

Java Swing

  • Java Swing components are platform-independent.
  • Swing components are lightweight.
  • Swing supports a pluggable look and feel.
  • Swing provides more powerful components such as tables, lists, scroll panes, color choosers, tabbed panes, etc.
  • Swing follows MVC.

Difference Between Java Applet and Java Application

Java Application

  • Java applications are stand-alone programs that can be executed independently.
  • Java applications must have a main() method for them to execute.
  • Java applications just need the JRE.
  • Java applications do not need to extend any class unless required.
  • Java applications can execute code from the local system.
  • Java applications have access to all the resources available in our system.

Java Applet

  • Java applets are small Java programs that are designed to exist within HTML web documents.
  • Java applets do not need main() for execution.
  • Java applets cannot run independently and require APIs.
  • Java applets must extend the java.applet.Applet class, while Java applications do not.
  • Java applets cannot execute code from the local system, while Java applications can.
  • Java applets have access only to the browser-specific services.

Difference Between Throw and Throws

Throw

  • It is used to create a new Exception object and throw it.
  • Using the throw keyword, you can declare only one exception at a time.
  • The throw keyword is used to throw an exception explicitly.
  • The throw keyword is used within the method.
  • Syntax-wise, the throw keyword is followed by the instance variable.
  • A checked exception cannot be propagated using throw only. An unchecked exception can be propagated using throw.
  • Example: throw new IOException("Cannot open connection");

Throws

  • It is used in the method definition to declare that a risky method is being called.
  • Using the throws keyword, you can declare multiple exceptions at a time.
  • The throws keyword is used to declare one or more exceptions, separated by commas.
  • The throws keyword is used with the method signature.
  • Syntax-wise, the throws keyword is followed by exception class names.
  • For the propagation of a checked exception, you must use the throws keyword followed by the specific exception class name.
  • Example: throws IOException, ArrayIndexOutOfBoundsException

Difference Between Error and Exception

Error

  • Errors in Java are of type java.lang.Error. All errors in Java are of the unchecked type.
  • Errors happen at runtime. They will not be known to the compiler.
  • It is impossible to recover from errors.
  • Errors are mostly caused by the environment in which the application is running.
  • Examples: java.lang.StackOverflowError, java.lang.OutOfMemoryError

Exception

  • Exceptions in Java are of type java.lang.Exception. Exceptions include both checked and unchecked types.
  • Checked exceptions are known to the compiler, whereas unchecked exceptions are not known to the compiler because they occur at runtime.
  • We can recover from exceptions by handling them through try-catch blocks.
  • Exceptions are mainly caused by the application itself.
  • Examples:
    • Checked Exceptions: SQLException, IOException
    • Unchecked Exceptions: ArrayIndexOutOfBoundsException, ClassCastException, NullPointerException

Difference Between Abstract Class and Final Class

Abstract Class

  • Should be subclassed to override the functionality of abstract methods.
  • Abstract class methods’ functionality can be altered in subclasses.
  • Cannot be instantiated.
  • For later use, all the abstract methods should be overridden.
  • Can be inherited.
  • Can contain abstract methods.
  • A few methods can be implemented, and a few cannot.
  • Cannot create immutable objects (in fact, no objects can be created).
  • It is an incomplete class (for this reason only, designers do not allow objects to be created).

Final Class

  • Can never be subclassed as final does not permit it.
  • Final class methods should be used as is by other classes.
  • Can be instantiated.
  • The overriding concept does not arise as it is a final class.
  • Cannot be inherited.
  • Cannot contain abstract methods.
  • All methods should have an implementation.
  • Immutable objects can be created (e.g., String class).
  • It is a complete class (in the sense that all methods have complete functionality or meaning).

Abstract Class and Interface

–  Abstract :  Abstract class can have abstract and non-abstract methods.  –Abstract class doesn’t support multiple inheritance. —Abstract class can have final, non-final, static and non-static variables. –Abstract class can provide the  implementation of interface.  –The abstract keyword is used to declare abstract class. –An abstract class can be extended using keyword “extends”. –A Java abstract class can have class members like private, protected, etc.

Example: //public abstract class Shape //{// public abstract void draw(); //}

Interface:  –Interface can have only abstract methods. –Interface supports multiple inheritance.  —Interface has only static and final variables. –Interface can’t provide the implementation of abstract class. —The interface keyword is used to declare interface –An interface can be implemented using keyword “implements”. —Members of a Java interface are public by default. —Example: public interface Shape //{ //void draw(); // }


Different Between Method Overloading and Method overriding:

Method Overloading:  –Method overloading is a feature that allows a class to have more than one method having the same name, but different type of arguments and number of arguments. –Method overloading is used to increase the readability of the program. –Method overloading is performed within class. –In case of method overloading, parameter must be different. –Method overloading is of compile time polymorphism.  –In java, method overloading can’t be performed by changing return type of the r method only. 

Example: //class Overloading //{//static int add(int a, int b) //{  //return a+b; //} //static int add(int a, int b, int c) //{  //return a+b+c;}//}

Method Overriding:  —Method overriding is the process of redefining exactly same method (same signature) of parent class to their child class. –Method overriding is used to provide the specific implementation of the method that is already provided by its super class. —Method overriding occurs in two classes that have IS-A (inheritance) relationship. –In case of method overriding, parameter must be same. —Method overriding is the example of run time polymorphism. –Return type must be same or covariant in method overriding. Example: class Outer //{ //void Display() { } System.out.println(“Class outer”); //}  //class Child extends Outer //{ //void Display() { } System.out.println(“Child class”); //}

Different Between Application and Applet:

Application:  —Java applications have full access to local file system and network. –It requires a main() method for its execution. —Applications can run programs from the local system. –An application program is used to perform some task directly for the user. –It can access all kinds of resources available on the system. –It doesn’t require any Graphical User Interface (GUI). –It is a trusted application and doesn’t require much security. –It requires Java Runtime Environment (JRE) for its successful execution.

Applet:   –Applets have no disk and network access. –It does not require a main() method for its execution. –Applets cannot run programs from the local machine. –An applet program is used to perform small tasks or part of it. –It can only access the browser specific services. –It must run within GUI. –It requires high-security constraints as applets are un-trusted. —It requires a web browser like Chrome, Firefox, etc for its successful execution.

Different BEtween Procedural Oriented Programming And  Object Oriented Programminng;

Procedural Oriented Programming:  –In procedural programming, program is divided into small parts called functions. –Procedural programming follows top down approach. –There is no access specifier in procedural programming. –Adding new data and function is not easy.–Procedural programming does not have any proper way for hiding data so it is less secure. –In procedural programming, overloading is not possible. –In procedural programming, function is more important than data.

Object oriented programming: –In object oriented programming, program is divided into small parts called objects. –Object oriented programming follows bottom up approach. –Object oriented programming have access specifiers like private, public, protected etc. –Adding new data and function is easy. –Object oriented programming provides data

hiding so it is more secure. –Overloading is possible in object oriented programming. —In object oriented programming, data is more important than function.

Different Between Checked And Unchecked Exception in java: 

Checked : —Checked at compile-time –IOException, ClassNotFoundException, etc. —Must be caught or declared using throws keyword –Handled using try-catch blocks or throws keyword —Program flow is interrupted and transferred to catch block —File operations, database operations, etc

Unchecked:  —Not checked at compile-time —NullPointerException, ArrayIndexOutOfBoundsException, etc. —Optional to catch or declare using throws keyword —Not required to handle explicitly —Program execution is halted with an error message —Logical errors, invalid arguments, etc

Different between Wait() and sleep()

Wait():  -called for synchronized block. -monitor is released. -gets awake when notify ( ) or notify all ( ) method is called. -not a static method. -wait( ) is generaly used on condition. 

Sleep( ):  -no such requirement. -monitor is not released. -does not get awake when notify ( ) or notifyAll( ) method is called. -static method. -sleep() method is simply used to put your thread on sleep. 

How to Create a Sub-package in Java? Explain. Compare Interface and Multiple Inheritance.

To create a sub-package in Java, define it within another package. For example, if you have a package com.mycompany.mypackage, you can create a sub-package com.mycompany.mypackage.subpackage. This helps organize code logically.

Interfaces in Java allow a class to implement multiple sets of behaviors by implementing multiple interfaces, providing a way to achieve multiple inheritance. Java does not support multiple inheritance of classes directly due to the complexity and ambiguity it can introduce, such as the “Diamond Problem.” Interfaces solve this issue by allowing a class to adopt multiple behaviors without inheriting the implementation from multiple classes.

major character extraction method in java: 

CharAt()= The java string char =At (int index ) method returns the character at the specific index in a string.  2 getChars()=  if you need to extract more than one character at a time, you can use the getChars(0 method.  3 toCharArray()= It is an alternative of getchars() method. toCharArray(0 convert all the characters in the string. 4 getBytes()= it is extract characters from string object and then convert the character in a byte array.