variable declaration in java:
Arrays in Java:
An array is an important linear data structure that allows us to
store multiple values of the same type.
To declare an array, define the variable type with square brackets:
Declaring an Array:
int[] arr;
Or
int arr[];
Initialization an Array:
int arr[] = new int[size];
When an array is declared, only a reference of an array is created. We use
new to allocate an array of given size.
Arrays as Objects:
In Java, arrays are objects themselves, inheriting
from java.lang.Object. This means they have methods like toString(), equals(),
and hashCode(), and they also have a built-in length property to get the number of
elements.
Features of Arrays:
Store Primitives and Objects:
Java arrays can hold both primitive types (like int,
char, boolean, etc.) and objects (like String, Integer, etc.)
Contiguous Memory Allocation:
When we use arrays of primitive types, the
elements are stored in contiguous locations. For non-primitive types,
references of items are stored at contiguous locations.
Note: "contiguous locations" means how data is stored in memory,
Zero-based Indexing:
The first element of the array is at index 0.
Fixed Length:
After creating an array, its size is fixed; we cannot change it.
Change an Array Element:
To change an element, assign a new value to a specific index. The index
begins with 0 and ends at (total array size)-1.
// Changing the first element to 20
arr[0] = 90;
Array Length:
We can get the length of an array using the length property:
// Getting the length of the array
int n = arr.length;
Advantages of Java Arrays:
Efficient Access: Accessing an element by its index is fast and has constant
time complexity, O(1).
Memory Management: Arrays have fixed size, which makes memory
management straightforward and predictable.
Data Organization: Arrays help organize data in a structured manner,
making it easier to manage related elements.
Disadvantages of Java Arrays:
Fixed Size: Once an array is created, its size cannot be changed, which can
lead to memory waste if the size is overestimated or insufficient storage if
underestimated.
Type Homogeneity: Arrays can only store elements of the same data type,
which may require additional handling for mixed types of data.
Insertion and Deletion: Inserting or deleting elements, especially in the
middle of an array, can be costly as it may require shifting elements.
Two-Dimensional Array (2D-Array)
Two-dimensional array is the simplest form of a multidimensional array. A
2-D array can be seen as an array storing multiple 1-D array for easier
understanding.
Syntax (Declare, Initialize and Assigning)
// Declaring and Intializing
data_type[][] array_name = new data_type[x][y];
// Assigning Value
array_name[row_index][column_index] = value;
Three - Dimensional Array (3D-Array)
3D-Array is a complex form of a multidimensional array. A 3D-array can be
seen as an array of 2D array for easier understanding.
Command Line Arguments in Java:
Java command-line argument is an argument, i.e., passed at the
time of running the Java program. Command-line arguments passed from the
console can be received by the Java program and used as input.
Example:
java Geeks Hello World
Note: Here, the words Hello and World are the command-line
arguments. JVM will collect these words and will pass these
arguments to the main method as an array of strings called args. The
JVM passes these arguments to the program inside args[0] and
args[1].
Why Use Command Line Arguments?
It is used because it allows us to provide input at runtime without modifying
the whole program.
It helps to run programs automatically by giving them the needed information
from outside.
String Class in Java:
The String class in Java is used to create and
manipulate sequences of characters. It is one of the most commonly used classes in
Java. Objects of the String class are immutable, which means they cannot be
changed once created.
Features of the String Class:
1. Immutable:
Immutable means that once a String object is created, its value cannot be changed.
2. Thread-Safe:
String in Java is thread-safe because it is immutable, allowing safe access by
multiple threads without synchronization.
3. Supports Various Utility Methods:
String is a predefined final class in Java present in java.lang
package. It provides various methods to create, manipulate, and compare strings,
like length(), charAt(), concat(), equals(), etc.
4. Implements Interfaces:
The String class in Java implements three important interfaces.
CharSequence: Allows access to characters in the string using
charAt(), length(), etc.
Comparable<String>: Enables comparing two strings
lexicographically using compareTo()
Serializable: Allows string objects to be converted into a byte
stream.
Java String Methods:
String plays a very important role. It represents a sequence of characters and
is widely used for storing and manipulating text.
A string is like an array of characters, but unlike arrays, it
is immutable and comes with many built-in methods in Java. With the help
of these methods, we can perform various operations such as
concatenation, comparison, and manipulation.
1. int length() Method
This method provides the total count of characters in the string.
2. charAt(int i) Method
This method returns the character at ith index.
3. String substring(int i) Method
This method return the substring from the ith index character to end.
4.String concat( String str) Method
This method appends the given string to the end of the current string.
Inheritance in Java:
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.
Explanation:
Animal is the base class.
Dog, Cat and Cow are derived classes that extend Animal class and provide
specific implementations of the sound() method.
The Geeks class is the driver class that creates objects and demonstrates
runtime polymorphism using method overriding.
Note: In practice, inheritance and polymorphism are used together in
Java to achieve fast performance and readability of code.
Syntax:
class ChildClass extends ParentClass {
// Additional fields and methods
}
Super Class/Parent Class:
The class whose features are inherited is known as a
superclass(or a base class or a parent class).
Sub Class/Child Class:
The class that inherits the other class is known as a
subclass(or a derived class, extended class or child class). The subclass
can add its own fields and methods in addition to the superclass fields and
methods.
Extends Keyword:
This keyword is used to inherit properties from a superclass.
Why Use Inheritance in Java?
Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
Abstraction: The concept of abstraction where we do not have to provide all
details, is achieved through inheritance. Abstraction only shows the
functionality to the user.
How Inheritance Works in Java?
The extends keyword is used for inheritance in Java. It enables the subclass to
inherit the fields and methods of the superclass. When a class extends
another class, it means it inherits all the non-primitive members (fields
and methods) of the parent class and the subclass can also override or
add new functionality to them.
Note: The extends keyword establishes an "is-a" relationship between the child
class and the parent class. This allows a child class to have all the
behavior of the parent class.
Types of Inheritance in Java:
1. Single Inheritance:
A subclass inherits from a single superclass. This is the
most basic form of inheritance.
2. Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a
base class and as well as the derived class also acts as the base
class for other classes.
3. Hierarchical Inheritance:
In hierarchical inheritance, more than one subclass is
inherited from a single base class. i.e. more than one derived
class is created from a single base class. For example, cars and
buses both are vehicle.
4. Multiple Inheritance (Through Interfaces):
In Multiple inheritances, one class
can have more than one superclass and inherit features
from all parent classes.
Note: that Java does not support multiple inheritances with classes. In Java,
we can achieve multiple inheritances only through Interfaces.
5. Hybrid Inheritance:
It is a mix of two or more of the above types of
inheritance. In Java, we can achieve hybrid inheritance only
through Interfaces if we want to involve multiple inheritance to
implement Hybrid inheritance.
Java IS-A type of Relationship:
IS-A represents an inheritance relationship in
Java, meaning this object is a type of that object.
Differences between Methods and Constructors:
n Java, both methods and constructors are blocks of code associated with a
class, but they serve distinct purposes and have key differences:
Constructor:
Purpose: A constructor's primary purpose is to initialize a newly
created object. It sets the initial state (values of instance variables) of
an object when it is instantiated.
Naming: A constructor must have the same name as the class it
belongs to.
Return Type: Constructors do not have a return type, not even void.
Invocation: Constructors are invoked implicitly when an object is
created using the new keyword.
Inheritance: Constructors are not inherited by subclasses.
Method:
Purpose:
A method defines the behaviour or actions that an object can
perform. It encapsulates a specific task or operation.
Naming:
A method can have any valid Java identifier as its name, and it does
not need to match the class name.
Return Type:
Methods must have a return type (which can be void if no value is returned).
Invocation: Methods are invoked explicitly by calling them on an object
or class reference.
Inheritance: Methods can be inherited by subclasses.