0% found this document useful (0 votes)
1 views27 pages

Java_Notes

The document provides an overview of Java programming, covering its history, features, and core concepts such as libraries, data types, object-oriented programming, and access modifiers. It explains the structure of Java programs, including classes, objects, constructors, inheritance, and method overloading. Additionally, it discusses Java's runtime environment, command-line arguments, and the use of packages to organize code.

Uploaded by

Aryan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
1 views27 pages

Java_Notes

The document provides an overview of Java programming, covering its history, features, and core concepts such as libraries, data types, object-oriented programming, and access modifiers. It explains the structure of Java programs, including classes, objects, constructors, inheritance, and method overloading. Additionally, it discusses Java's runtime environment, command-line arguments, and the use of packages to organize code.

Uploaded by

Aryan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

JAVA Programming Notes

History of JAVA
• Java was developed by James Gosling at Sun Microsystems, Inc.
• Java originated at Sun Microsystems, Inc. in 1991.
• Vinod Khosla was the co-founder of Sun Microsystems.
• On January 27, 2010, Sun was acquired by Oracle Corporation for USS7.4 billion ;

Java is Everywhere(slogan)
• JAVA resides in mobiles, client machines, server machines, embedded devices, smart
phones, cloud, etc.
• It shares the same basic features of the language and libraries.
• Principle of Java: Write Once, Run Anywhere (WORA)

What is Library?
• Java Library is a collection of predefined classes.
• You can use these classes either by inheriting them or by instantiating them.

Java flavours
• JAVA SE (core java)
• JAVA EE (Advance Java)
• JAVA ME (Micro Edition for mobiles)
• Many more...

Features of JAVA
1. Simple
2. Object Oriented Language
3. Interpreted
4. Robust
5. Secure
6. Portable
7. Multi-threaded
8. Garbage Collector
Compile and Run
JDK
• Java Developer Kit contains tools needed to develop the Java programs
• These tools could be Compiler (javac.exe), Application Launcher (java.exe), etc
JRE
• Java Runtime Environment.
• It contains JVM (Java Virtual Machine) and Java Package Classes(Java Library)

JVM
• JVM is platform dependent.
• The Java Virtual Machine provides a platform-independent way of executing code
• Java Virtual Machine interprets the byte code into the machine code depending upon the
underlying operating system and hardware combination. ‘

Remember
• Java is a case sensitive language like C and C++
• Java is nearly 100% object oriented language
• In java, it is not possible to make a function which is not a member of any class (as we
can do in C++)

First Program
public class HelloWorld{
public static void main(String [] args){
System.out.printIn(“Hello World”);
}
}

keywords
Java keywords are also known as reserved words. Keywords are particular words that act as a
key to a code. These are predefined words by Java so they cannot be used as a variable or object
name or class name.
Eg : abstract, default, break, Boolean, byte…..etc.
Data Types
• A type identifies a set of values (and their representation in memory) and a set of
operations that transform these values into other values of that set.
• Java is strongly typed language.

Types
Primitive Types: byte, short, int, long, float, double, char and boolean.
User-defined Types: such as String , Arrays and Classes

Comments
• Block style comments begin with /* and terminate with */ that spans multiple lines.
• Line style comments begin with // and terminate at the end of the line.
• Documentation style comments begin with /** and terminate with */ that spans multiple
lines They are generally created using the automatic documentation generation tool, such
as java.

Conversion
Every expression written in the Java programming language has a type that can be deduced from
the structure of the expression and the types of the literals, variables, and methods mentioned in
the expression.
implementation with code
Widening Conversion / Implicit conversion
int y=3.
float x=y; //Widening Conversion, no error

Narrowing Conversion / Explicit conversion


• float x=3.4f.
• int y=x; //narrowing conversion, error
• int y=(int)x; //no error
• float k=3.5; //narrowing conversion, error
• float k=3.5f; //no error

Permitted Conversions
• byte to short, int, long, float, or double
• char to int, long, float, or double
• int to long, float, or double
• long to float or double
• float to double

OOP In JAVA:
• OOP stand for object-oriented programming.
• The main aim of OOP is to bind together the data & the function that operate on them so
that no other part of the code can access this data except this function.

Advantage of OOP
• OOP is faster & easier to execute.
• Provide a clear structure for the program.
• OOP helps to keep the JAVA code DRY (Don’t Repeat Yourself) & make the code easier
to maintain, modify & debug.

Class

Creating class is as good as creating data type

Class is defining a category of data.

It is user define data types which holds its own data members & member function which
can be accessed & used by creating an instance of that class.
SYNTAX
public class ClassName {
//Data member variable
//member function
}
Eg:
Public Class Person {
Private String name.
Private int age.
}

Object
• Object is a real-world entity.
• Object is an instance of a class.
• When a class is defined no memory is allocated but when it is instantiated (an object is
created) memory is allocated.

SYNTAX
Class Name objectName = new className();
E.g.:
Person obj = new Person();

Static member In Java


• Static member variable
• Static member function
• ..and not static variable in methods
• ...but we can have static inner class.

public class Example{


int x; //Instance variable
static int y; //static member variable
public void fun1() { } //instance member function
public static void fun2() { } //static member function
}

Static variables
1. Static variables are declared in the class using static keyword.
2. Static variables are by default initialized to its default value.
3. Static variable has a single copy for the whole class and does not depend on the object.

Static functions
• Static functions defined inside the class are qualified with the keyword static
• Static function can only access static members of the same class
• Static function can be invoked using class name and dot operator.
Implementation With Code

Static class
We can have a class inside a class which is known as inner class
Inner class can be qualified with the keyword static

wrapper class in java


In Java, a wrapper class is a class that serves as a "wrapper" around a primitive data type,
allowing you to treat primitive values as objects. This is necessary in situations where objects are
required, such as when using Java collections, generics, or when you need to perform certain
operations that are available only for objects.
Java provides wrapper classes for each of its primitive data types:
1. Integer: Wraps int.
2. Double: Wraps double.
3. Float: Wraps float.
4. Long: Wraps long.
5. Short: Wraps short.
6. Byte: Wraps byte.
7. Character: Wraps char.
8. Boolean: Wraps boolean.
For example, if you want to use an int in a context that requires an object, you can use the Integer
wrapper class:

int primitiveInt = 42;


Integer wrappedInt = Integer.valueOf(primitiveInt); // Wrapping
int unwrappedInt = wrappedInt.intValue(); // Unwrapping

Wrapper classes also provide methods to convert between primitive types and their wrapped
object counterparts. Additionally, wrapper classes offer utility methods for working with the
wrapped values, such as parsing strings into primitive values, comparing values, and more.
Here's an example of parsing an integer from a string using Integer wrapper class:
String numberStr = "123";
int parsedInt = Integer.parseInt(numberStr);
With the introduction of autoboxing and unboxing in Java, the conversion between
primitive types and their corresponding wrapper classes can happen implicitly in most
cases:
Integer autoWrappedInt = 42; // Autoboxing
int autoUnwrappedInt = autoWrappedInt; // Unboxing
Wrapper classes are especially useful when working with Java collections that require objects or
when dealing with generic types that don't support primitive types. However, it's important to
note that using wrapper classes adds a slight overhead in terms of memory and performance
compared to using primitive types directly.

Command-line arguments in Java


Command-line arguments in Java allow you to provide input parameters to a Java program when
you run it from the command line or terminal. These arguments are specified after the name of
the Java class you are running. Command-line arguments are stored in the args parameter of the
main method of your program.
Here's how you can work with command-line arguments in Java:

public class CommandLineArgumentsExample {


public static void main(String[] args) {
// The 'args' parameter contains the command-line arguments
// args[0] is the first argument, args[1] is the second, and so on
// args.length holds the total number of arguments

System.out.println("Number of arguments: " + args.length);

// Printing all the arguments


for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
To compile and run this program, follow these steps:
Open a command prompt or terminal.
Navigate to the directory where your Java file is located.
Compile the Java file using the command: javac CommandLineArgumentsExample.java
Run the compiled program with command-line arguments: java
CommandLineArgumentsExample arg1 arg2 arg3
Replace arg1, arg2, and arg3 with the actual values you want to pass as command-line
arguments.
For example, if you run: java CommandLineArgumentsExample John 25 true, the output
will be:
Number of arguments: 3
Argument 0: John
Argument 1: 25
Argument 2: true

NOTE: Keep in mind that the command-line arguments are always passed as strings. If you need
to convert them to other data types (e.g., integers, booleans), you'll need to perform appropriate
parsing or conversion operations within your program.

Java Packages
• Packages are nothing more than the way we organize files into different directories
according to their functionality, usability as well as category they should belong to
• Files in one directory (or package) would have different functionality from those of
another directory.

Name Collision
• Packaging also helps us to avoid class name collision when we use the same class name
as that of others.
• The benefits of using package reflect the ease of maintenance, organization, and increase
collaboration among developers

How to create packages?


Suppose we have a file called HelloWorld.java, and we want to put this file in a package world
How to create packages?
package world;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Now compile this file as
path -> javac –d . HelloWorld.java
Implementation With code

Remember
• We can have only one public class in a single java file.
• Name of the file should be same as the name of public class
• In absence of public class, any class name can be given to the file name

Use of import
• import is a keyword in Java
• It is used to import classes of other packages

access modifiers
In Java, access modifiers are keywords used to control the visibility and accessibility of classes,
methods, fields, and other members within a program. There are four main access modifiers in
Java

1. public: Members with this modifier are accessible from anywhere, both within the same
package and from other packages.
2. protected: Members with this modifier are accessible within the same package and by
subclasses (even if they are in different packages).
3. default (no modifier): Also known as package-private, members with no explicit access
modifier are accessible only within the same package.
4. private: Members with this modifier are accessible only within the same class.
Here's a breakdown of how these access modifiers can be applied to various elements in Java:
Class Access Modifiers:
public: The class is accessible from anywhere.
default: The class is accessible only within the same package.
Field and Method Access Modifiers:
public: The field or method is accessible from anywhere.
protected: The field or method is accessible within the same package and by subclasses (even in
different packages).
default: The field or method is accessible only within the same package.
private: The field or method is accessible only within the same class.

public class MyClass {


public int publicField;
protected int protectedField;
int defaultField; // package-private
private int privateField;

public void publicMethod() {


// ...
}

protected void protectedMethod() {


// ...
}
void defaultMethod() {
// ...
}
private void privateMethod() {
// ...
}
}
Keep in mind the following principles:
• you can't use a more restrictive access modifier when overriding a method. For instance,
if a method is declared as protected in a superclass, the overriding method in a subclass
can't be declared as private.
• Top-level classes can only have public or default access. Nested classes (inner and static
nested classes) can have all access modifiers.
• Interface methods are implicitly public.
• Fields in an interface are implicitly public, static, and final.
• It's a best practice to use the most restrictive access modifier possible to encapsulate your
code and ensure good encapsulation principles.
Access modifiers play a crucial role in encapsulation and controlling the visibility of your code's
components. They help in creating well-structured and maintainable Java programs.

Constructors In Java
• Constructor is a member function of a class
• The name of constructor is same as the name of the class.
• Constructor has no return type.
Implementation With Code

Constructor is special
• A constructor is a special method that is used to initialize a newly created object and is
called implicitly, just after the memory is allocated for the object
• It is not mandatory for the coder to write a constructor for the class
• When there is no constructor defined in the class by programmer, compiler implicitly
provide a default constructor for the class

Constructor Overloading
• Constructors can be parameterized
• Constructors can be overloaded
Inheritance In java
Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the mechanism in
Java by which one class is allowed to inherit the features(fields and methods) of another class. In
Java, Inheritance means creating new classes based on existing ones. A class that inherits from
another class can reuse the methods and fields of that class. In addition, you can add new fields
and methods to your current class as well.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends keyword indicates you
are derived from an existing class. In other words, “extends” refers to increased functionality.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Implentation With Code

Types of inheritance in java


Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if
you inherit 2 classes. So whether you have same method or different, there will be compile
time error.

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output:
Compile Time Error
Method overloading in Java
Method overloading in Java allows you to define multiple methods in the same
class with the same name but different parameter lists. These methods must have
different parameter types, a different number of parameters, or both. Java
determines which method to invoke based on the arguments provided during the
method call.
Key points about method overloading:
1. Method Name: Overloaded methods must have the same name.
2. Parameter Lists: Overloaded methods must have different parameter lists, which
includes differences in the number and/or types of parameters.
3. Return Type: The return type of the method is not considered when determining which
overloaded method to call. Two methods with the same name and parameter types but
different return types are not valid overloads.
4. Access Modifier and Exceptions: The access modifiers and exceptions thrown by
overloaded methods can be different.

Here's an example to illustrate method overloading:


public class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b;
}

// Method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Method to add two doubles


public double add(double a, double b) {
return a + b;
}
}
In this example, the Calculator class has three add methods with different parameter lists. You
can call these methods with different argument combinations to perform addition:
Calculator calculator = new Calculator();
int result1 = calculator.add(2, 3); // Calls the first add method
int result2 = calculator.add(1, 2, 3); // Calls the second add method
double result3 = calculator.add(2.5, 3.5); // Calls the third add method

Java determines the correct method to call based on the provided arguments' types and numbers.
Keep in mind that while overloading can make your code more readable and intuitive, excessive
overloading can lead to confusion. Use method overloading judiciously and ensure that the
methods' behavior is logically consistent to avoid unexpected results.

Method overriding in Java


Method overriding in Java allows a subclass to provide a specific implementation for a method
that is already defined in its superclass. The overriding method in the subclass has the same
name, return type, and parameter list as the method in the superclass. Method overriding is a way
to implement polymorphism and dynamic method dispatch in object-oriented programming.

class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
final keyword
In Java, the final keyword is used to indicate that a particular entity (class, method, or variable)
cannot be changed or further extended, depending on where it's applied. It enforces various
forms of immutability and restrictions in the Java programming language.
Here's how the final keyword is used in different contexts:
Final Instance Variables: When applied to a variable, it means that the variable's value cannot
be changed after it's assigned a value. This is often used for constants.
final int myConstant = 42;
// myConstant = 100; // This would result in a compilation error

Final Methods: When applied to a method, it means that the method cannot be overridden by
subclasses. This is often used to ensure that the behavior of a method remains consistent across
subclasses.
class Parent {
final void doSomething() {
// ...
}
}
class Child extends Parent {
// Cannot override doSomething() here
}

Final Classes: When applied to a class, it means that the class cannot be extended. This is used
to prevent further inheritance from that class.
final class MyFinalClass {
// ...
}
// Cannot create subclasses of MyFinalClass
Final Arguments: When applied to method arguments, it means that the value of the argument
cannot be modified within the method.
void process(final int value) {

// value = 10; // This would result in a compilation error


}

this keyword
• The this object reference is a local variable in instance member methods referring the
caller object
• this keyword is used as a reference to the current object which is an instance of the
current class
• The this reference to the current object is useful in situations where a local variable hides,
or shadows, a field with the same name.
Implementation With Code

super keyword
In Java, the super keyword is used to refer to the immediate parent class of a subclass. It's
primarily used to access members (fields, methods, constructors) of the superclass when there is
a name conflict between the subclass and superclass or to explicitly call the superclass's
constructor from the subclass's constructor.
Here are the main ways the super keyword is used:
Accessing Superclass Members: If a subclass has a member (field or method) with the same
name as a member in its superclass, the super keyword can be used to refer to the superclass's
member.

class Parent {
int value = 10;
void display() {
System.out.println("Value in parent: " + value);
}
}
class Child extends Parent {
int value = 20;
void display() {
System.out.println("Value in child: " + value); // Child's value
System.out.println("Value in parent: " + super.value); // Parent's value
}
}

Invoking Superclass Constructors: In the constructor of a subclass, you can use super() to
explicitly call a constructor from the superclass. This is used for constructor chaining.
class Parent {

Parent(int value) {

// Parent class constructor

class Child extends Parent {

Child(int value) {

super(value); // Call Parent's constructor

// Child constructor code

The super keyword is essential for maintaining proper class hierarchy, resolving ambiguity, and
enabling interactions between a subclass and its superclass. It helps in accessing and interacting
with superclass elements while providing the flexibility to customize behavior in the subclass.

Array
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors
so that the normal flow of the application can be maintained.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
Here's an overview of how exception handling works in Java:
Throwing Exceptions: Exceptions are typically thrown when an exceptional condition occurs
within your code. You can throw exceptions explicitly using the throw statement or they can be
thrown automatically by the Java runtime environment when certain errors occur (e.g., dividing
by zero, trying to access an array index that doesn't exist).
java Copy code
throw new SomeException("An error message");

Catching Exceptions: To handle exceptions, you use the try-catch block. Code that might throw
exceptions is placed inside the try block, and you catch and handle these exceptions in the catch
blocks. You can have multiple catch blocks to handle different types of exceptions.
try {
// Code that may throw exceptions
} catch (SomeException e) {
// Handle SomeException
} catch (AnotherException e) {
// Handle AnotherException
} finally {
// Optional: Code that always executes, whether an exception occurs or not
}
The finally Block: The finally block is used to specify code that should always be executed,
regardless of whether an exception is thrown or not. It is optional but commonly used for
cleanup tasks like closing resources (e.g., files, database connections).
Exception Types: Java has a hierarchy of exception classes. The base class for all exceptions is
java.lang.Throwable. It has two main subclasses: java.lang.Exception (for recoverable
exceptions) and java.lang.Error (for unrecoverable errors). You can create your own custom
exception classes by extending java.lang.Exception or its subclasses.
Checked vs. Unchecked Exceptions:
Checked Exceptions: These are exceptions that the compiler forces you to handle explicitly by
either catching them or declaring that your method throws them. Examples include IOException,
SQLException.
Unchecked Exceptions (Runtime Exceptions): These are exceptions that you're not required to
catch or declare explicitly. They usually represent programming errors and extend
java.lang.RuntimeException. Examples include NullPointerException,
ArrayIndexOutOfBoundsException.
Here's an example of catching and handling a checked exception:
javaCopy code
import java.io.IOException;

public class Example {


public static void main(String[] args) {
try {
// Code that may throw an IOException
throw new IOException("An I/O error occurred");
} catch (IOException e) {
// Handle the IOException
System.err.println("IOException: " + e.getMessage());
}
}
}

And here's an example of an unchecked exception:


javaCopy code
public class Example {
public static void main(String[] args) {
String str = null;
try {
// This will throw a NullPointerException
int length = str.length();
} catch (NullPointerException e) {
// Handle the NullPointerException
System.err.println("NullPointerException: " + e.getMessage());
}
}
}

Proper exception handling is crucial for writing robust and reliable Java applications, as it helps
you anticipate and gracefully handle errors that may occur during runtime.

abstract in java
In Java, the abstract keyword is used to define abstract classes and methods. An abstract class is
a class that cannot be instantiated (i.e., you cannot create objects of an abstract class), and it
often serves as a blueprint for other classes. Abstract methods are methods declared in an
abstract class that do not have a body and are meant to be implemented by concrete (non-
abstract) subclasses of the abstract class.
Here are the key points related to abstract in Java:
Abstract Class:
• An abstract class is declared using the abstract keyword.
• An abstract class can contain both abstract methods and concrete methods (methods with
implementations).
• You cannot create an instance of an abstract class using the new keyword. It's meant to be
subclassed.
• Abstract classes can have constructors, and they are typically used to initialize fields or
perform common tasks in subclasses.
• Subclasses of an abstract class must provide implementations for all abstract methods
unless they are also declared as abstract.

abstract class Shape {


abstract void draw(); // Abstract method
void move() {
System.out.println("Moving the shape");
} // Concrete method
}
Abstract Method:
• An abstract method is declared without a method body (no implementation details).
• It is meant to be implemented by concrete subclasses.
• The abstract keyword is used to declare an abstract method.
abstract void draw(); // Abstract method

Interfaces in Java
An interface can contain method signatures (methods without implementations) and constants
(final fields). Classes that implement an interface are required to provide concrete
implementations for all the methods declared in the interface. Interfaces are a key part of
achieving abstraction and enabling multiple inheritance of type in Java. Here are the key points
about interfaces in Java:
Declaring an Interface:
You declare an interface using the interface keyword.
An interface can include method declarations (without implementations) and constants.
interface MyInterface {
void someMethod(); // Method declaration without implementation
int CONSTANT_VALUE = 42; // Constant (implicitly public, static, and final)
}
Implementing an Interface:
• To use an interface, a class must implement it using the implements keyword.
• A class can implement multiple interfaces (Java supports multiple interface inheritance).

class MyClass implements MyInterface {
public void someMethod() {
System.out.println("Implemented someMethod");
}
}

string buffer
In Java, StringBuffer is a class that is part of the java.lang package and is used for creating and
manipulating mutable (modifiable) strings. Unlike the String class, which represents immutable
strings (strings that cannot be changed after they are created), StringBuffer allows you to modify
the content of the string without creating a new object. This can be more efficient when you need
to perform multiple string manipulations.
Here are some key points about the StringBuffer class in Java:
Mutable Strings: A StringBuffer object represents a sequence of characters that can be
modified. You can append, insert, delete, and replace characters within a StringBuffer instance
without creating a new string each time.
Thread-Safe: StringBuffer is designed to be thread-safe, which means it is synchronized to
ensure that multiple threads can safely manipulate the same StringBuffer object without causing
data corruption or race conditions. This makes it suitable for use in multithreaded environments.
Performance: While StringBuffer provides the advantage of mutability, it can be less efficient
than the String class in some cases, especially when used in single-threaded applications. If you
don't need thread safety and are working in a single-threaded environment, you may prefer to use
StringBuilder, which is similar to StringBuffer but is not synchronized and can be faster in some
situations.
Here's an example of how to use StringBuffer in Java:

public class StringBufferExample {


public static void main(String[] args) {
// Create a StringBuffer object
StringBuffer stringBuffer = new StringBuffer("Hello");

// Append text to the StringBuffer


stringBuffer.append(", World!");

// Insert text at a specific position


stringBuffer.insert(6, "Java ");

// Replace a portion of the string


stringBuffer.replace(0, 5, "Hi");

// Delete characters
stringBuffer.delete(3, 5);

// Get the final string


String result = stringBuffer.toString();
System.out.println(result); // Output: Hi, Java World!
}
}

In this example, we create a StringBuffer object and use various methods like append, insert,
replace, and delete to modify the content of the string. Finally, we convert the StringBuffer back
to a regular String using the toString() method.

abstract vs interfaces in java


In Java, both abstract classes and interfaces are used to achieve abstraction and define contracts
that classes must adhere to, but they have different characteristics and use cases. Here are the key
differences between abstract classes and interfaces:
Abstract Class:
Definition:
An abstract class is a class declared with the abstract keyword.
It can have both abstract (unimplemented) and concrete (implemented) methods.
Abstract classes can also have fields (variables), constructors, and instance methods with
implementations.
Constructor:
An abstract class can have constructors.
Constructors are used for initializing fields or performing common tasks in subclasses.
Inheritance:
A class can extend only one abstract class.
Abstract classes are used when you want to provide a common base class with some default
implementation to share among related classes.
Access Modifiers:
Abstract classes can have various access modifiers for their methods and fields (public,
protected, package-private, or private).
Keyword:
The keyword used for defining an abstract class is abstract.
Interface:
Definition:
An interface is a type that defines a contract for classes to implement.
It contains only abstract (unimplemented) methods and constants (public, static, final fields).
Constructor:
Interfaces cannot have constructors because they are not meant to be instantiated.
Inheritance:
A class can implement multiple interfaces.
Interfaces are used to define a common set of methods that unrelated classes can implement,
enabling multiple inheritance of type.
Access Modifiers:
All methods in an interface are implicitly public.
Fields are implicitly public, static, and final.
Keyword:
The keyword used for defining an interface is interface.
Use Cases:
Abstract Class Use Cases:
Use abstract classes when you want to provide a common base class with some shared
implementation details among related classes.
Use them when you have code that is common to all subclasses.
Use abstract classes when you need constructors or instance variables in the base class.
Abstract classes are suitable when you want to enforce the use of certain methods in subclasses
but allow flexibility in other methods.
Interface Use Cases:
Use interfaces when you want to define a contract that unrelated classes can adhere to.
Use them when you want to achieve multiple inheritance of type in Java.
Interfaces are suitable when you don't want to provide any implementation details but only
method signatures.
Use interfaces to create plug-and-play components (e.g., Java's Comparable and Serializable
interfaces) that can be implemented by various classes.

You might also like