Java Basics – Long Answers
1. Define Array and OOPs Concepts
Definition of Array:
An array is a collection of elements stored in contiguous memory locations. All the elements
in an array are of the same data type, and they are accessed using a common name with an
index.
Features:
- Fixed size
- Same data type
- Indexed access (starting from 0)
- Efficient memory management
Types:
- Single Dimensional Array: int[] arr = {1, 2, 3};
- Multi-Dimensional Array: int[][] matrix = {{1,2},{3,4}};
Advantages:
- Easy access
- Memory efficient
Disadvantages:
- Fixed size
- Costly insert/delete
Definition of OOPs:
Object-Oriented Programming (OOP) is a paradigm based on the concept of "objects", which
can contain data and methods.
Major Concepts:
- Class: Blueprint of objects.
- Object: Instance of a class.
- Inheritance: Reuse properties.
- Polymorphism: One interface, many forms.
- Encapsulation: Binding data and code.
- Abstraction: Hiding complexity.
2. Different Types of Constructors
Definition:
Constructor is a special method used to initialize objects in Java. It has the same name as the
class and no return type.
Types:
1. Default Constructor:
- No parameters.
- Java provides it automatically.
2. Parameterized Constructor:
- Takes parameters to assign values.
3. Copy Constructor:
- Takes another object of same class as argument.
- Java doesn’t provide it by default.
Constructors can be overloaded and can call each other using this().
3. What is an Operator? Types of Operators in Java
Definition:
Operators are symbols used to perform operations on variables and values.
Types of Operators in Java:
1. Arithmetic Operators: +, -, *, /, %
2. Relational Operators: ==, !=, >, <, >=, <=
3. Logical Operators: &&, ||, !
4. Assignment Operators: =, +=, -=, *=, /=, %=
5. Unary Operators: +, -, ++, --, !
6. Bitwise Operators: &, |, ^, ~, <<, >>
7. Ternary Operator: condition ? value1 : value2
These operators allow arithmetic, logical, comparison, and assignment operations.
4. Describe Different Data Types Used in Java
Data types define the size and type of variable values.
Types:
1. Primitive Data Types (8 types):
- byte, short, int, long: integer values
- float, double: decimal values
- char: single character
- boolean: true/false
2. Non-Primitive Data Types:
- String, Array, Class, Interface, Object
Primitive types store values; non-primitive store references to objects.
5. Write About Garbage Collection
Garbage Collection (GC) in Java is the process of automatically deallocating memory by
destroying unused objects.
How it Works:
- JVM monitors objects.
- If no references, object is marked for GC.
- Memory is reclaimed for reuse.
Phases:
- Marking
- Deletion
- Compaction
Types of GC:
- Serial, Parallel, CMS, G1
Advantages:
- Automatic memory management
- Avoids memory leaks
Limitations:
- No control over GC timing
- May cause pause in execution