Chapter 1 - Introduction Flashcards

1
Q

features of Java

A

Platform Independence - Java code is compiled into an intermediate form called bytecode, which can be executed on any platform with a Java Virtual Machine (JVM). This enables developers to write code once and run it on different platforms without modification.

Object-Oriented Programming (OOP)-
Java is based on the principles of OOP, which promotes the use of objects and classes for modeling and organizing code. This helps in creating modular, maintainable, and reusable code.

Java enforces strong type checking, which means that variable types are explicitly declared and checked at compile time. This helps catch type-related errors early in the development process.

Automatic Memory Management (Garbage Collection):

Java manages memory automatically through a garbage collector, which deallocates memory for objects that are no longer in use. This helps prevent memory leaks and simplifies memory management for developers.

Multi-threading and Concurrency:

Java provides built-in support for creating and managing threads, allowing developers to write concurrent and multithreaded programs. This is important for developing responsive and scalable applications.

Exception Handling:

Java has a robust exception-handling mechanism that allows developers to handle runtime errors gracefully, preventing abrupt program termination. This promotes better program stability.
Standard Library (Java API):

Java comes with a vast standard library (Java API) that includes pre-built classes and packages for various common tasks, such as I/O, networking, data structures, and more. This reduces the need for developers to reinvent the wheel.
Security:

Java has a strong emphasis on security, with features like bytecode verification, runtime security checks, and a security manager. This makes it a preferred choice for building secure applications, especially in web and enterprise environments.
Portability:

Java’s platform independence makes it highly portable. Applications written in Java can run on different operating systems without modification, as long as a compatible JVM is available for that platform.

Performance Optimization:

While Java is often associated with being slower than some low-level languages like C or C++, it offers features like Just-In-Time (JIT) compilation and performance tuning options to optimize the execution speed of Java applications.
Dynamic Loading and Reflection:

Java supports dynamic class loading and reflection, allowing applications to load classes and examine their properties at runtime. This enables advanced features like dynamic configuration and extensibility.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Java code lifecycle

A

Writing the Code:

The first stage involves writing the Java source code. You use a text editor or an Integrated Development Environment (IDE) like Eclipse, IntelliJ IDEA, or NetBeans to write your Java code. This code is typically saved with a .java extension.
Compilation:

After writing the Java code, you need to compile it. The Java source code is compiled into bytecode using the Java Compiler (javac). This bytecode is platform-independent and can be executed on any system with a Java Virtual Machine (JVM).
Bytecode Generation:

During compilation, the Java Compiler generates bytecode files with a .class extension for each class in your program. These bytecode files contain the low-level instructions that the JVM can understand.
Class Loading:

When you run a Java program, the JVM loads the necessary classes into memory. This process is called class loading. The JVM dynamically loads classes as they are needed during the program’s execution.
Initialization:

Once the classes are loaded, the JVM initializes the class variables and runs the static blocks of code, ensuring that classes and their dependencies are properly set up.
Main Method Execution:

Every Java application must have a main method with the following signature:
java
Copy code
public static void main(String[] args)
The JVM starts the program’s execution by invoking the main method, passing it an array of String arguments (args).
Runtime Execution:

During runtime, the program executes the statements within the main method and other methods called from main. It interacts with the JVM, the operating system, and external resources (e.g., files, databases, network services) as needed to perform its tasks.
Garbage Collection:

While the program is running, the JVM’s garbage collector periodically identifies and removes objects that are no longer in use, freeing up memory and preventing memory leaks.
Exception Handling:

During execution, the program may encounter exceptions or errors. Java provides mechanisms for handling these exceptions using try-catch blocks to prevent program crashes.
Termination:

The program’s execution eventually completes, either because it reaches the end of the main method or encounters a return statement. At this point, the program terminates, and any allocated resources are released.
Cleanup:

It’s good practice to include cleanup code, such as closing files or network connections, in a finally block or appropriate destructors to ensure that resources are properly released, even if an exception occurs.
Finalization:

In some cases, objects may need to perform finalization actions before they are reclaimed by the garbage collector. This is achieved by implementing the finalize() method in a class.
Shutdown Hooks:

You can register shutdown hooks using the Runtime.addShutdownHook() method to perform specific actions when the JVM is about to shut down, allowing you to release resources or perform cleanup tasks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Variable in Java

A

variable is a named storage location that holds a value of a particular type. Variables are used to store and manipulate data during the execution of a program. Each variable has a data type, a name, and a value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Variable features

A

Storage Location: A variable represents a storage location in computer memory where data can be stored and retrieved. This storage location has a unique name that allows you to reference it in your code.

Data Types: Variables have data types that define the kind of data they can hold. Common data types include integers (e.g., int), floating-point numbers (e.g., double), characters (e.g., char), and more complex types like strings (e.g., String).

Value Assignment: Variables can be assigned values, which can be literals (e.g., 5, ‘A’, “Hello”), results of calculations, or input from a user or external source.

Changing Values: The value of a variable can change during the execution of a program. This ability to change values is essential for performing calculations and maintaining state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Primitive data types

A

primitive data types are the simplest data types used to represent basic values like numbers, characters, and boolean values. They are called “primitive” because they directly represent values at the lowest level, without being composed of other objects or data types. Java has eight primitive data types. byte,
short,
int
long
float
double
char
boolean

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Byte type

A

it is used to represent 8-bit signed integers. Size and Range:

The byte data type is a 1-byte (8-bit) integer type.
It can represent integer values in the range of -128 to 127.

Default Value:

The default value of a byte variable is 0.
Memory Usage:

byte variables are used when you need to store small integers to conserve memory. They are especially useful when working with large arrays of data where memory efficiency is crucial.

byte is commonly used in situations where memory optimization is essential, such as when reading data from files or network streams, or when dealing with large collections of small integers.

ex
byte steps = 100;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Short data type

A

Size and Range:

The short data type is a 2-byte (16-bit) integer type.
It can represent integer values in the range of -32,768 to 32,767.
Default Value:

The default value of a short variable is 0.
Memory Usage:

short variables are used when you need to store small to moderately-sized integers. They offer a larger range than byte and are suitable for conserving memory while accommodating a broader set of integer values.

Use Cases:

short is used in scenarios where memory optimization is still important but a larger range of integer values is required compared to byte. It is suitable for various numeric applications, including scientific computing and embedded systems.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

int

A

Size and Range:

The int data type is a 4-byte (32-bit) signed integer type.
It can represent integer values in the range of approximately -2 billion to 2 billion.
Default Value:

The default value of an int variable is 0.
Memory Usage:

int variables are used for storing whole numbers in a wide range. They are the most commonly used integer type in Java due to their balance of range and memory efficiency.

int is widely used for general-purpose integer arithmetic in Java. It is suitable for most scenarios where you need to represent and manipulate whole numbers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Difference between primitive types and Wrapper classes

A

Data Representation:

Primitive Types: Primitive data types represent simple values directly and are not objects. They are stored directly in memory, which makes them more memory-efficient and faster to access.
Wrapper Classes: Wrapper classes are objects that encapsulate primitive data types. They provide a way to treat primitive types as objects and offer additional functionality, but they are less memory-efficient due to the overhead of object creation.

Nullability:

Primitive Types: Primitive types cannot have a null value. They always hold a valid value, even if it’s the default value (e.g., 0 for int, false for boolean).
Wrapper Classes: Wrapper classes can be assigned a null value because they are objects. This is useful when you need to represent the absence of a value.

Equality Comparison:

Primitive Types: You compare primitive types using the equality operators (== or !=) to check if their values are the same.
Wrapper Classes: Comparing wrapper class objects using == compares their references, not their values. To compare the values, you should use methods like equals().

Type Conversion:

Primitive Types: Type conversion between primitive types is done implicitly (e.g., widening conversions) or explicitly (e.g., narrowing conversions with casting).
Wrapper Classes: Type conversion between wrapper classes and primitive types requires explicit conversion using methods provided by the wrapper classes, like valueOf() and xxxValue() (e.g., intValue(), doubleValue()).

Methods and Utility:

Primitive Types: Primitive types do not have methods or utility functions. They are limited to basic mathematical and logical operations.
Wrapper Classes: Wrapper classes provide methods for converting, parsing, and manipulating the encapsulated values. For example, Integer has methods like parseInt() and toString().

Collections and Generics:

Primitive Types: You cannot use primitive types in collections (e.g., List<int>) or with Java generics.
Wrapper Classes: You can use wrapper classes with collections and generics, making them essential for working with data structures and algorithms that require objects.</int>

Auto(un)boxing:

Primitive Types: Do not support auto(un)boxing.
Wrapper Classes: Support auto(un)boxing, which allows automatic conversion between primitive types and their corresponding wrapper classes. For example, you can assign an int to an Integer without explicit conversion.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Long tyoe

A

represent integer values with a larger range than the int data type. Size and Range:

The long data type is a 64-bit signed integer type.
It can represent integer values in the range of approximately -9.2 quintillion (-9,223,372,036,854,775,808) to 9.2 quintillion (9,223,372,036,854,775,807).
Default Value:

The default value of a long variable is 0.
Memory Usage:

long variables use more memory than int variables due to their larger size. They are typically used when you need to represent very large integer values or when the range of values exceeds what an int can handle.
Explicit Casting:

When performing arithmetic operations involving long variables, the result is promoted to a long by default. You may need to explicitly cast the result to a narrower data type if you want to store it in a variable of that type.
Suffix:

To explicitly specify a long literal, you can use the suffix L or l. For example, long population = 7_900_000_000L;
Use Cases:

long is used when you need to represent very large integers, such as timestamps, unique identifiers, or quantities that exceed the range of int. It is also commonly used for operations involving large numerical calculations and when working with large datasets.
Wrapper Class:

The long data type has a corresponding wrapper class called Long, which is part of Java’s standard library. This wrapper class allows you to work with long values in an object-oriented manner and provides utility methods for working with long data.

long totalPopulation = 7_900_000_000L;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Float data type

A

Size and Precision:

The float data type is a 32-bit (4-byte) floating-point type.
It provides single-precision, which means it can represent decimal numbers with approximately 6-7 significant decimal digits.
Default Value:

The default value of a float variable is 0.0f.
Memory Usage:

float variables are used to store numbers with fractional parts (floating-point numbers) while conserving memory compared to the double data type. They are suitable for scenarios where precision is not a critical concern, and memory usage is a consideration.
Suffix:

To explicitly specify a float literal, you should use the suffix f or F. For example, float pi = 3.14159f;
Scientific Notation:

You can represent float values using scientific notation, which is often used for very large or very small numbers. For example, float scientificNumber = 1.23e-4f; represents 0.000123.
Approximate Representation:

Due to its limited precision, float values may not always represent decimal numbers exactly. This can lead to rounding errors, especially in complex mathematical operations.
Use Cases:

float is used when memory efficiency is a concern, and the application can tolerate some loss of precision. Common use cases include graphics programming, scientific simulations, and situations where memory is limited.
Wrapper Class:

The float data type has a corresponding wrapper class called Float, which is part of Java’s standard library. This wrapper class allows you to work with float values in an object-oriented manner and provides utility methods for working with float data.

float temperature = 25.5f;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Double

A

Size and Precision:

The double data type is a 64-bit (8-byte) floating-point type.
It provides double-precision, which means it can represent decimal numbers with approximately 15-16 significant decimal digits.
Default Value:

The default value of a double variable is 0.0.
Memory Usage:

double variables are used to store numbers with fractional parts (floating-point numbers) with higher precision compared to the float data type. They consume more memory but offer greater accuracy.
Suffix:

To explicitly specify a double literal, you don’t need a suffix. For example, double pi = 3.141592653589793;
Scientific Notation:

You can represent double values using scientific notation, which is often used for very large or very small numbers. For example, double scientificNumber = 1.23e-10; represents 0.000000000123.
Accuracy and Precision:

double is suitable for scenarios where high precision is required, such as scientific calculations, financial applications, and situations where exact representation of decimal numbers is essential.
Approximate Representation:

Like float, double values may not always represent decimal numbers exactly due to limited precision. Rounding errors can occur in complex mathematical operations.
Use Cases:

double is the default choice for representing floating-point numbers in Java when high precision is needed. It is widely used in scientific and engineering applications, financial calculations, and any situation where accurate representation of real numbers is critical.
Wrapper Class:

The double data type has a corresponding wrapper class called Double, which is part of Java’s standard library. This wrapper class allows you to work with double values in an object-oriented manner and provides utility methods for working with double data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Char

A

primitive data types used to represent single characters from the Unicode character set.

Size:

The char data type is a 16-bit (2-byte) unsigned integer type.
Character Encoding:

It represents characters using the Unicode character encoding standard. Unicode is a universal character set that includes characters from most of the world’s scripts, allowing Java to support a wide range of characters and symbols.
Default Value:

The default value of a char variable is the null character, represented as ‘\u0000’.
Single Characters:

char is specifically used for representing single characters, such as letters, digits, symbols, and special characters.
Character Literals:

You can represent char literals by enclosing a single character in single quotes. For example, char letterA = ‘A’;.
Escape Sequences:

Special characters and escape sequences can be represented using backslashes. For example, char newline = ‘\n’; represents a newline character.
Unicode Escapes:

Unicode characters can be represented using Unicode escape sequences. For example, char euroSymbol = ‘\u20AC’; represents the Euro currency symbol.
Use Cases:

The char data type is used when you need to work with individual characters, such as reading and manipulating text, performing character-level operations, and representing symbols and special characters.
Wrapper Class:

Unlike most other primitive data types, there is no direct wrapper class for char. However, you can use methods from the Character class, which provides utility methods for working with char values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Boolean

A

boolean data type is one of the primitive data types used to represent a binary state with two possible values: true or false. Size and Values:

The boolean data type has a fixed size of 1 bit, but its values are typically represented using a full byte (8 bits) in memory.
It can hold only two values: true and false. These values represent binary logic: true typically means “yes” or “on,” and false means “no” or “off.”
Default Value:

The default value of a boolean variable is false.
Logical Operations:

boolean variables are primarily used for logical and conditional operations. They are commonly used in if statements, loops, and control flow to make decisions based on conditions.
Comparison and Conditions:

boolean values are the result of comparison operations (e.g., a < b, x == y) and conditional expressions (e.g., if (condition)).
Use Cases:

The boolean data type is used to represent the truth value of a condition or the result of a logical operation. It’s essential for writing programs that involve decision-making and branching.
Wrapper Class:

The boolean data type has a corresponding wrapper class called Boolean, which is part of Java’s standard library. The Boolean class provides utility methods for working with boolean values in an object-oriented manner.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Widening (implicit) conversion

A

Widening conversion occurs when a value of a smaller data type is automatically promoted to a larger data type. Java handles this conversion automatically without the need for explicit casting. The widening conversion is considered safe because there is no loss of information.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Narrowing (explicit) conversion

A

process in Java where you manually convert a value from a wider data type to a narrower data type. Unlike widening conversions, which are performed automatically by the Java compiler when moving from a narrower data type to a wider one, narrowing conversions require explicit action from the programmer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Arithmetic operators

A

Addition (+): int sum = num1 + num2

Subtraction (-):

The subtraction operator is used to subtract one numeric value from another.
Example: int difference = num1 - num2;
Multiplication (*):

The multiplication operator is used to multiply two numeric values.
Example: int product = num1 * num2;
Division (/):

The division operator is used to divide one numeric value by another.
Example: double quotient = (double) num1 / num2; (Note: Casting one operand to double ensures a floating-point result.)
Modulus (%):

The modulus operator returns the remainder of the division of one numeric value by another.
Example: int remainder = num1 % num2;
Increment (++):

The increment operator is used to increase the value of a variable by 1.
Example: num++; (Equivalent to num = num + 1;)
Decrement (–):

The decrement operator is used to decrease the value of a variable by 1.
Example: num–; (Equivalent to num = num - 1;)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Assignement operators

A

Assignment (=):

The assignment operator = is used to assign the value on the right side to the variable on the left side.
Example: int x = 10; assigns the value 10 to the variable x.
Addition Assignment (+=):

The addition assignment operator += adds the value on the right side to the variable on the left side and assigns the result to the variable.
Example: x += 5; is equivalent to x = x + 5; and increments x by 5.
Subtraction Assignment (-=):

The subtraction assignment operator -= subtracts the value on the right side from the variable on the left side and assigns the result to the variable.
Example: x -= 3; is equivalent to x = x - 3; and decrements x by 3.
Multiplication Assignment (*=):

The multiplication assignment operator *= multiplies the variable on the left side by the value on the right side and assigns the result to the variable.
Example: x *= 2; is equivalent to x = x * 2; and doubles the value of x.
Division Assignment (/=):

The division assignment operator /= divides the variable on the left side by the value on the right side and assigns the result to the variable.
Example: x /= 4; is equivalent to x = x / 4; and divides the value of x by 4.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Comparison operators

A

These operators return a boolean result (true or false) based on the comparison. Here are the primary comparison operators in Java:

Equal to (==):

The equal to operator == is used to check if two values or expressions are equal.
Example: if (x == y) checks if x is equal to y.
Not equal to (!=):

The not equal to operator != is used to check if two values or expressions are not equal.
Example: if (x != y) checks if x is not equal to y.
Greater than (>):

The greater than operator > is used to check if the value on the left is greater than the value on the right.
Example: if (x > y) checks if x is greater than y.
Less than (<):

The less than operator < is used to check if the value on the left is less than the value on the right.
Example: if (x < y) checks if x is less than y.
Greater than or equal to (>=):

The greater than or equal to operator >= is used to check if the value on the left is greater than or equal to the value on the right.
Example: if (x >= y) checks if x is greater than or equal to y.
Less than or equal to (<=):

The less than or equal to operator <= is used to check if the value on the left is less than or equal to the value on the right.
Example: if (x <= y) checks if x is less than or equal to y.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Logical operator

A

Java has three primary logical operators: && (logical AND), || (logical OR), and ! (logical NOT).

21
Q

String

A

Strings are classes used to represent sequences of characters, such as words, sentences, or text data.

22
Q

Comparing Strings

A

To compare two strings for equality, you should use the equals() method or equalsIgnoreCase() method if case-insensitive comparison is required. Using == to compare strings checks for reference equality, which may not produce the expected results.

23
Q

Ways to create string

A

using literal,
usings String class
using string builder

24
Q

difference creating string literal and new keyword

A

Both are immutable, but difference is that in heap memory when we have uniqe string literal Java checks if the same string already exists in the pool. If it does, the existing string is reused. This can save memory and allows for efficient comparison using the equals() method.

Unlike string literals, strings created using the new keyword and constructor are not automatically interned in the string pool. Each such instantiation creates a new string object, even if an identical string already exists in the pool.

25
Q

Difference between string literal and string builder

A

the main difference is mutability

26
Q

What are conditional statements in Java, and why are they important?

A

Conditional statements in Java are control structures that allow you to execute specific blocks of code based on certain conditions. They are essential for making decisions and controlling the flow of a program, enabling it to respond dynamically to different inputs and situations.

27
Q

What are the different types of conditional statements in Java?

A

Java has several conditional statements, including:
if: Used for simple conditional branching.
else if: Used for multiple condition checks.
else: Provides a default branch if none of the previous conditions are met.
switch: Used for multiple-choice conditions.
Ternary conditional operator (? :): A concise way to express a conditional operation in a single line.

28
Q

Explain the difference between if and else if statements in Java. When would you use each?

A

if statements are used for simple, independent conditions. They are evaluated sequentially, and multiple if blocks can be used independently.
else if statements are used when you have multiple related conditions, and you want to choose one branch among several. Only one else if branch is executed.

29
Q

What is the purpose of the switch statement in Java, and how does it differ from if statements?

A

The switch statement is used to select one of many code blocks to be executed. It differs from if statements by providing a way to test multiple conditions against a single value.

30
Q

How do you handle multiple conditions in an if statement?

A

Multiple conditions in an if statement can be handled by nesting if statements, using logical operators (&& for “and,” || for “or”), or employing else if and else blocks to create complex conditional logic.

31
Q

What is a ternary conditional operator, and how is it used in Java?

A

The ternary conditional operator (? :) is a shorthand way of expressing conditional operations in a single line. It evaluates a boolean expression and returns one of two values based on the result of the evaluation.

32
Q

How do you prevent NullPointerException when working with conditional statements involving objects?

A

To avoid NullPointerExceptions, you should perform null checks on object references using if statements or use the null-safe Objects.requireNonNull() method to ensure an object reference is not null before using it in a conditional statement.

33
Q

What is short-circuiting in conditional expressions, and why is it important?

A

Short-circuiting is the behavior in which a logical operator (&& or ||) stops evaluating expressions as soon as the result can be determined. It is important for optimizing code and avoiding unnecessary evaluations that might lead to errors.

34
Q

What is the default case in a switch statement, and when should you use it?

A

The default case in a switch statement is executed when none of the other case values match the tested expression. It serves as a catch-all branch for unmatched cases and should be used when you want to handle unspecified cases gracefully.

35
Q

Explain the “fall-through” behavior in a switch statement. How can you control it?

A

“Fall-through” in a switch statement occurs when control passes from one case block to the next without a break statement. To control it, you can use break statements to exit the switch block when a condition is met, or explicitly use break or return to prevent further execution.

36
Q

What is the significance of the break statement in a switch statement?

A

The break statement in a switch statement is used to exit the switch block and prevent further execution of subsequent case statements. It is crucial for controlling the flow of the switch statement.

37
Q

How do you handle exceptions in conditional statements?

A

To handle exceptions in conditional statements, you can use try-catch blocks to catch and handle exceptions that may occur within the conditional code. This allows you to gracefully handle errors without terminating the program.

38
Q

What is the difference between a nested if statement and a compound if statement?

A

A nested if statement is an if statement contained within another if statement. It allows for more complex conditional logic. A compound if statement uses logical operators (&&, ||) to create compound conditions in a single if statement.

39
Q

Difference between static and instance variables

A

Scope:

Static Variable: Static variables are associated with the class itself rather than with instances (objects) of the class. They have class-level scope, which means they are shared among all instances of the class.
Instance Variable: Instance variables are specific to individual instances (objects) of the class. Each object has its own copy of instance variables.
Declaration:

Static Variable: Static variables are declared using the static keyword within the class, typically at the class level (outside of any method). They are often used to store data that is shared among all instances of the class.
Instance Variable: Instance variables are declared within the class but outside of any method or constructor. They are used to store data that is specific to each object created from the class.
Initialization:

Static Variable: Static variables can have an initial value, and they are initialized once when the class is loaded into memory. If not explicitly initialized, they are assigned default values (e.g., 0 for integers, null for objects).
Instance Variable: Instance variables are initialized when an object is created. If not explicitly initialized, they are assigned default values.
Access:

Static Variable: Static variables can be accessed using the class name followed by the variable name (ClassName.staticVariable). They can also be accessed using an instance of the class, but it is not recommended.
Instance Variable: Instance variables are accessed using an instance (object) of the class (objectName.instanceVariable).
Lifetime:

Static Variable: Static variables exist for the entire lifetime of the program or until the class is unloaded from memory.
Instance Variable: Instance variables exist as long as the object to which they belong is alive. They are eligible for garbage collection when the object is no longer referenced.
Common Use Cases:

Static Variable: Static variables are often used for constants, counters, shared data, and configurations that are common to all instances of a class.
Instance Variable: Instance variables are used to store data that varies from object to object, representing the object’s state.

40
Q

Object methods in java

A

In Java, all classes inherit certain methods from the Object class, which is the root of the class hierarchy. These methods are inherited by all Java classes unless explicitly overridden. Here are some commonly used methods from the Object class:

toString():

Returns a string representation of the object.
By default, it returns the class name followed by the memory address of the object in hexadecimal format. It is often overridden in subclasses to provide a meaningful string representation of the object’s state.
equals(Object obj):

Compares the current object with the specified object for equality.
By default, it compares object references (memory addresses). It is often overridden in subclasses to provide custom equality comparison based on the object’s sta.

hashCode()
This method returns a hash code value for the object. It’s used for hash-based collections such as HashMap. If two objects are equal according to the equals() method, their hash codes must be equal as well.

getClass()
This method returns the runtime class of the object. It returns an instance of Class, which provides information about the class’s name, fields, methods, and more.

clone()
This method creates and returns a copy of the object. It’s used for making a shallow copy of the object. To make a deep copy, you need to override this method appropriately.

finalize()
This method is called by the garbage collector before the object is reclaimed. It’s intended to perform any necessary cleanup operations.

41
Q

Why the main() method is public static?

A

First, let’s see why the main() method is static in Java?
The main() method is static in Java, so the JVM can directly invoke it without instantiating the class’s object.

If the main() method is non-static, then JVM needs to create an instance of the class, and there would be ambiguity if the constructor of that class takes an argument – which constructor should be called by JVM and what parameters should be passed? We know that JVM can’t instantiate a Java class without calling a constructor method.

The below example demonstrates why the main() method is static in Java?
package net.javaguides.corejava;

public class MainMethodDemo {

public MainMethodDemo(int arg0) {
    //One argument constructor
}

public MainMethodDemo(int arg0, int arg1) {
    //Two arguments constructor
}

public MainMethodDemo(String arg[]) {

}

public void main(String...args) {
    //Non Static main method
} } Now, let's see why the main() method is public?

We know that anyone can access/invoke a method having public access specifier. The main() method is public in Java because it has to be invoked by the JVM. So, if main() is not public in Java, the JVM won’t call it.

42
Q

Can we overload the main() method in Java?

A

Yes, We can overload the main() method. A Java class can have any number of main() methods. But to run the java class, the class should have a main() method with signature as public static void main(String[] args).

43
Q

Can we declare the main() method as private or protected or with no access modifier?

A

No, the main() method must be public. You can’t define the main() method as private or protected or with no access modifier. This is because to make the main() method accessible to JVM.
The below diagram shows runtime error, if you define the main() method other than public.

44
Q

Can we declare the main() method as a non-static?

A

No, the main() method must be declared as static so that JVM can call the main() method without instantiating its class. If you remove ‘static’ from the main() method signature, the compilation will be successful but the program fails at runtime.

45
Q

Can we change the return type of the main() method?

A

No, the return type of the main() method must be void only. Any other type is not acceptable.

46
Q

Can the main() method take an argument other than String array?

A

No, an argument of the main() method must be a String array. But, from the introduction of var args, you can pass var args of string type as an argument to the main() method. Again, var args are nothing but the arrays.

47
Q

Can we make the main final in Java?

A

Yes, you can make the main() method final.

48
Q

What does the String intern() method do?

A

The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool.
We can call the intern() method to tell the JVM to add it to the string pool if it doesn’t already exist there, and return a reference of that interned string:

49
Q

Why String is a popular HashMap key in Java?

A

Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for keys in a Map and its processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.