0% found this document useful (0 votes)
2 views17 pages

Basic Java

Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems in 1995 and currently owned by Oracle. It is widely used for various applications, including web, enterprise, and mobile development, and is known for its 'Write Once, Run Anywhere' capability due to the Java Virtual Machine (JVM). Key features of Java include its robustness, security, and automatic memory management through garbage collection.

Uploaded by

pkoppula59
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views17 pages

Basic Java

Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems in 1995 and currently owned by Oracle. It is widely used for various applications, including web, enterprise, and mobile development, and is known for its 'Write Once, Run Anywhere' capability due to the Java Virtual Machine (JVM). Key features of Java include its robustness, security, and automatic memory management through garbage collection.

Uploaded by

pkoppula59
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

What is Java?


Java is a high-level, object-oriented, platform-
Bytecode (.class)
independent programming language developed by
Oracle Corporation (originally by Sun Microsystems).

Interview Answer JVM

"Java is a high-level, object-oriented, class-based, ↓


platform-independent, secure, robust programming
language developed by Sun Microsystems in 1995 Windows / Linux / Mac
and currently owned by Oracle. It is widely used for Since every operating system has its own JVM,
developing web applications, enterprise applications, the same Java program runs everywhere.
Android applications, desktop software, and cloud- That's why Java is called
based systems." Write Once, Run Anywhere (WORA).

High-Level Language
Interview Meaning Its slogan is:

"Write Once, Run Anywhere (WORA)"


A high-level language is a programming language that is
easy for humans to read and write.
This means a Java program can run on any operating
system that has a Java Virtual Machine (JVM).
Object-Oriented
Robust
Java follows the Object-Oriented Programming
(OOP) paradigm.
Robust means
Everything is organized using classes and objects.
Strong and reliable.

Class-Based Java is robust because of:

Java is called class-based because almost everything is  Exception Handling


written inside a class.
 Garbage Collection
Platform Independent
 Garbage Collection (GC) in Java is an automatic memory
management process handled by the Java Virtual Machine
This is the most important interview point. (JVM) to identify and delete unused objects from the heap
Normally, memory. Unlike languages like C and C++, where developers
must manually allocate and free memory, Java automates this
C Program
cleanup to prevent OutOfMemoryErrors and memory leaks. [1,

2, 3, 4]
Compiled


 Strong Type Checking

Runs only on Windows executable Featur Easy Meaning


But Java does this: e
Java Program Secure JVM protects the program, no pointers,
automatic memory management.
↓ Robust Exception handling + Garbage Collection +
strong type checking make programs reliable.
Compiler
Java automatically creates:

args[0] = "Rahul";
Features of Java args[1] = "20";
args[2] = "Hyderabad";

 ☕ Simple and easy to learn


 Secure Real Company Example
 Fast (compiled to bytecode)
 Platform independent Suppose you're working at Amazon.
 Object-Oriented Programming (OOP)
 Supports multithreading They have a Java application.
 Rich standard library
Today they want it to run on port 8080.
How Java Works
Java Program (.java) Tomorrow on 9090.

▼ Instead of changing the code
Java Compiler (javac)
int port = 8080;


Bytecode (.class) they start the program like this:

▼ java App 9090
JVM (Java Virtual Machine)
│ Java creates

Runs on Windows / Linux / macOS args[0] = "9090";

Then

Why do we pass [Link] to Scanner? int port = [Link](args[0]);


Imagine Scanner is a person.
That person asks: Now the application runs on port 9090.
"Where should I read data from?"
You answer: The same code can be used in development, testing, and
[Link] production just by changing the startup argument.
meaning
"Read from the keyboard." What is String[] args in Java?
So
Scanner sc = new Scanner([Link]); String[] args is an array of strings that is used to
means receive command-line arguments. These arguments are
"Create a Scanner that reads input from the keyboard." passed to the program by the JVM before the program
What is String[] args? starts executing."
public static void main(String[] args)
args is an array of Strings. What is the use of String[] args?
It allows us to pass input or configuration to the program
Who puts values into args? without changing the source code."
String[] args is used to receive command-line
Not the keyboard. arguments from the JVM. It lets us pass input or
configuration to the program before it starts executing."
The command line.
Java Program Structure
Suppose you run:
public class Main {
java Main Rahul 20 Hyderabad
public static void main(String[] args) {
[Link]("Hello, World!"); JDK, JRE, and JVM
} Think of making a cup of tea.
}
 Kitchen → JDK
Explanation  Gas Stove → JRE
public class Main  Burner (that actually heats the pot) → JVM

 public → Accessible from anywhere. You need the whole kitchen to make tea, but only the
 class → Blueprint for creating objects. stove and burner to heat it.
 Main → Class name (must match the file name
[Link]). Similarly, to develop Java programs, you need the
JDK. To run Java programs, you only need the JRE
(which contains the JVM).
public static void main(String[] args)

This is the main method, where program execution


starts. 1. JVM (Java Virtual Machine)

 public → Accessible by the JVM.


 static → Can run without creating an object.
 void → Returns nothing.
 main → Entry point of the program.
 String[] args → Stores command-line
arguments.

[Link]("Hello, World!");

Prints text to the console.

Output:

Hello, World!

Java Syntax Rules


 Every statement ends with a semicolon (;).
 Java is case-sensitive.
 Code blocks are enclosed in { }.
 Class names usually start with a capital letter.
 Variable and method names usually start with a The JVM is the program that runs Java bytecode.
lowercase letter.
 Java developers follow naming conventions to When you write Java code:
make code easier to read.
[Link]("Hello");
Element Convention
Class the computer cannot understand it directly.
PascalCase (first letter uppercase, each word capitalized)
Method camelCase
First, the Java compiler converts it into bytecode
Variable camelCase
(.class file).
Constant UPPER_SNAKE_CASE
Then the JVM reads that bytecode and converts it into You only want to play it, not modify it.
machine instructions that your operating system can
execute. You need:

Responsibilities of JVM  JVM ✔


 Java libraries ✔
 Executes Java bytecode
 Converts bytecode to machine code You do not need the compiler.
 Manages memory
 Performs garbage collection That's exactly what the JRE provides.
 Handles runtime errors

Why do we need the JVM?


3. JDK (Java Development Kit)
Different operating systems understand different
machine code. The JDK is used to develop Java applications.
 Windows machine code ≠ Linux machine code ≠
It contains:
macOS machine code
 JRE
Instead of compiling Java separately for every operating  JVM
system, Java compiles once to bytecode. Each operating  Java compiler (javac)
system has its own JVM that understands the same  Debugging tools
bytecode.  Documentation tools
 Other development utilities
Java Code

▼ With the JDK, you can:
Bytecode (.class)
│  Write Java code

 Compile it
Windows JVM → Windows Machine Code
 Run it
Linux JVM → Linux Machine Code  Debug it

macOS JVM → macOS Machine Code

This is why Java is called platform independent.


Relationship
JDK

2. JRE (Java Runtime Environment) ├──

JRE

│ ├── JVM
The JRE provides everything needed to run a Java │ └── Java Libraries
program. │
├── javac (Compiler)
├── Debugger
It contains: ├── Documentation Tool
└── Other Development Tools
 JVM
 Java libraries So:
 Runtime files
JDK ⊃ JRE ⊃ JVM
What it does
(JDK contains JRE, and JRE contains JVM.)
Suppose you download a Java game.
How a Java Program Runs │ └── boolean

Write Code (.java) └── Non-Primitive Data Types
│ ├── String
▼ ├── Arrays
JDK ├── Classes
(javac compiler)
├── Interfaces

▼ └── Objects
Bytecode (.class)


JRE

1. byte

JVM What is it?
│ byte stores small integer values.
▼ Memory
Machine Code 1 byte = 8 bits

Range

-128 to 127
Output
Syntax
byte age = 100;

Feature JVM JRE JDK Using int also works, but byte uses less memory.
Full form Java Java Runtime Java
Virtual Environment Development In real projects, byte is used less often.
Machine Kit
Purpose Runs Java
bytecode
Provides the
runtime
Develops and
runs Java
2. short
environment programs
What is it?
Contains ❌ No ❌ No ✅ Yes
short stores medium-sized integer values.
compiler
Memory
(javac)? 2 bytes = 16 bits
Contains — ✅ Yes ✅ Yes Range
JVM? -32,768 to 32,767
Contains ❌ No ✅ Yes ✅ Yes
libraries?
Used by End users End users and Developers What developers actually use
and developers Data Used in Real When
developers Type Projects?
byte ❌ Rarely Binary data, files, networking
short ❌ Very rarely Special cases, memory-
Types of Data Types constrained systems
int ✅ Very Most whole numbers
Java data types are divided into two categories: frequently
long ✅ Frequently Very large numbers (IDs,
Data Types timestamps, large counts)

├── Primitive Data Types (8)
│ ├── byte Java Data Types
│ ├── short
│ ├── int There are 8 primitive data types and many non-
│ ├── long primitive (reference) types.
│ ├── float
│ ├── double 1. byte
│ ├── char Stores small integers.
byte age = 100; Memory: 8 bytes
Memory: 1 byte Real-time usage: ✅ Very common
Range: -128 to 127 Examples:
Real-time usage: ❌ Very rare double price = 99.99;
double percentage = 87.5;

2. short
Stores medium-sized integers. 7. char
short marks = 30000; Stores a single character.
Memory: 2 bytes char grade = 'A';
Range: -32,768 to 32,767 char gender = 'M';
Real-time usage: ❌ Rare Memory: 2 bytes
Real-time usage: ⚠️Occasional
Usually used when only one character is needed.
3. int ⭐ (Most Used)
Stores whole numbers.
int age = 25; 8. boolean
int salary = 50000; Stores only two values.
int quantity = 10; boolean isLoggedIn = true;
Memory: 4 bytes boolean isAdmin = false;
Range: -2,147,483,648 to 2,147,483,647 Possible values:
Real-time usage: ✅ Very common true
Examples: false
int age = 22; Real-time usage: ✅ Very common
int marks = 95; Examples:
int quantity = 5; boolean isActive = true;
boolean isDeleted = false;

4. long
Stores very large whole numbers. float vs double
long mobileNumber = 9876543210L;
long population = 8000000000L; Float double
Memory: 8 bytes 4 bytes 8 bytes
Range: Less precision More precision
-9,223,372,036,854,775,808 About 6–7 decimal digits About 15–16 decimal digits
to Needs f suffix No suffix needed
9,223,372,036,854,775,807
Used less often Used most often
Real-time usage: ✅ Common for large values
For small values also mostly we use double..
Examples:
long userId = 1234567890123L; Why?
long timestamp = [Link]();
Because:
5. float
1. double is the default decimal type
Stores decimal numbers.
When you write:
float price = 99.99f;
double value = 10.5;
Memory: 4 bytes
it works directly.
Real-time usage: ❌ Rare
With float, you must write:
Most developers prefer double.
float value = 10.5f;
Without the f:
float value = 10.5;
6. double ⭐ (Most Used for Decimals)
❌ Compilation error.
Stores decimal numbers with higher precision.
double salary = 55000.75; 2. Better precision
double pi = 3.14159; Even if the number is small:
double percentage = 87.5; <= Less than or equal a <= b true
double stores it more accurately.

Java libraries use double 4. Logical Operators


Methods like:
[Link]() Assume:
[Link]()
[Link]() boolean x = true;
[Link]() boolean y = false;
Operator Meaning Example Output
&& Logical AND x && y false
Java Operators Cheat Sheet in table format. || Logical OR X || y Logical OR
! Logical NOT !x false

1. Arithmetic Operators
5. Unary Operators
Operator Name Example
+ Addition 10 + 5 Assume:
- Subtraction 10 - 5
* Multiplication 10 * 5 int a = 10;
/ Division 10 / 5 Operator Meaning Example Output
% Modulus (Remainder) 10 % 3 + Unary Plus +a 10
- Unary Minus -a -10
++ ++a 11
2. Assignment Operators --
Increment
Decrement --a 9
! Logical !true false
Assume: NOT
int a = 10;
Operator Meaning Equivalent Result
=
+=
Assign a
a
=
=
10
a + 5
10
15
6. Increment & Decrement
Add and assign
-= Subtract and assign a = a - 5 5
Assume:
*= Multiply and assign a = a * 5 50
/= Divide and assign a = a / 5 2 int a = 10;
%= Modulus and a = a % 3 1 Operator Meaning Example Output
assign ++a Pre ++a 11
Increment
a++ Post a++ Uses 10, then
Increment becomes 11
3. Relational --a Pre --a 9

(Comparison) Operators a--


Decrement
Post a-- Uses 10, then
Decrement becomes 9
Assume:

int a = 10;
int b = 20;
7. Ternary Operator
Operator Meaning Example Outpu
Syntax
t condition ? value1 : value2;
== Equal to a == b false
!= Not equal a != b true
Example:
> Greater than a > b false
< Less than a < b true int age = 20;
>= Greater than or equal a >= b false
String result = age >= 18 ? "Adult" : ├── Uses one operand
"Minor"; │ ↓
│ Unary Operator

. Bitwise Operators └── Performs logical NOT

(Advanced) Logical Operator

Why are ++ and -- in Unary Operators?


Assume: Same reason.
Example:
int a = 5; int a = 10;
int b = 3;
Operato Meaning Example Output a++;
r Here:
& Bitwise AND a & b 1 ++ works on only one variable (a).
| Bitwise OR a | b 7 So mathematically, it is a Unary Operator.
^ Bitwise XOR a ^ b 6
~ Bitwise NOT ~a -6
What is a Unary
Operator?
9. Shift Operators
A Unary Operator is an operator that works on only
(Advanced) ONE operand (one variable or one value).

Assume: Unary = One Operand

int a = 8;
Operator Meaning Example Output
<< Left Shift a << 1 16
>> Right Shift a >> 1 4
>>> Unsigned a >>> Depends on the binary
Right Shift 1 representation (mainly
useful with negative Different Data Types with
numbers)
Scanner (for Learning)

Why is ! in both Logical and Unary?


Data Type Scanner Method Example
Because: Input
Logical operators describe what operation they perform Byte nextByte() 100
(working with boolean values). Short nextShort() 30000
Unary operators describe how many operands they use Int nextInt() 25
Long nextLong() 9876543210
(one operand). Float nextFloat() 12.5
! satisfies both conditions. Double nextDouble() 99.99
Example: Boolean nextBoolean() true
boolean isStudent = true; Char next().charAt(0) A
String (one next() Rahul
[Link](!isStudent);
word)
Here: nextLine() Rahul Kumar
String (full
! works on one operand (isStudent) → Unary
line)
Operator
It performs logical NOT → Logical Operator
So it belongs to both categories.
Think of it like this:
! Operator

Suppose you're calculating the average marks.
int totalMarks = 95;
int subjects = 2;

What is Type Casting? double average = (double) totalMarks / subjects;

[Link](average);
Type Casting means:
Output
47.5
Converting a value from one data type to another. Without casting:
double average = totalMarks / subjects;
Example: Output
47.0
int → double
double → int
char → int
long → int

Think of it like pouring water into different-sized 1. Implicit Type Casting (Automatic)
containers. Also called Widening.
Java automatically converts a smaller data type into a larger
Small Glass (int) → Large Bottle (double) ✅ data type.
Easy byte
Large Bottle (double) → Small Glass (int) ❗ ↓
Some water may be lost short

int
Types of Type Casting long


There are 2 types: float

double
1. Implicit Type Casting (Widening / Automatic)
No data is lost.
2. Explicit Type Casting (Narrowing / Manual)
Example 1
public class Main {
Term Meaning public static void main(String[] args) {
Type Any conversion from one type to
Conversion another int a = 100;
Type A conversion where you explicitly
Casting specify the target type using (type) double b = a;
Are type casting and type conversion the same?
Type conversion is the general process of changing one data [Link](a);
type to another. It includes both automatic (implicit) [Link](b);
conversion and manual (explicit) conversion. Type casting }
usually refers specifically to the manual conversion where }
we use (type). Output
Why do we use Type Casting in real-time applications? 100
Answer: 100.0
We use type casting when different data types need to work
together. It helps convert data from one type to another Example 2
safely, especially while performing calculations, processing char ch = 'A';
user input, handling database values, reading files, or
working with APIs. Java performs automatic conversion int value = ch;
when it's safe (widening), and requires explicit casting when
there is a possibility of data loss (narrowing). [Link](value);
Output
65
Real-Time Use Cases
Because the ASCII/Unicode value of 'A' is 65.
1. Calculations (⭐⭐⭐⭐⭐ Most Common)
Example 3 [Link](value);
int num = 25; Output
-1294967296
long value = num; Why?
Because 3000000000 is larger than the maximum int
[Link](value); value (2147483647).
Output The value overflows, resulting in an incorrect number.
25
Integer Division Example
Why does Java allow this automatically? int a = 10;
Because there is no risk of losing data. int b = 3;
int
100
double result = a / b;

double
100.0 [Link](result);
Nothing is lost. Output
3.0
Why?
2. Explicit Type Casting (Manual)
Because a / b is evaluated first as integer division, giving 3,
Also called Narrowing.
and then 3 is assigned to a double as 3.0.
Java converts a larger type into a smaller type.
Since data may be lost, you must tell Java explicitly.
Correct Way
Syntax:
int a = 10;
(smallerDataType) value
int b = 3;
Example 1
double result = (double) a / b;
double price = 99.99;
[Link](result);
int value = (int) price;
Output
3.3333333333333335
[Link](value);
Output
99
The decimal part is removed (truncated).

Example 2 What is an Array?


double marks = 89.75;
An array is a collection of same type of elements stored
int result = (int) marks; in contiguous memory locations.
[Link](result);
What does contiguous memory locations mean?
Output
89
“Contiguous memory locations” means the array
Example 3 elements are stored next to each other in memory, with
long salary = 50000; no gaps between them.

int value = (int) salary; Why is contiguous memory useful?

[Link](value);  Fast access: Java can directly calculate the


Output address of any element.
50000
 Efficient looping: CPU can read nearby memory
This works because 50000 fits within the int range.
quickly.
Data Loss Example
 Simple indexing: arr[i] is easy to find using the
long number = 3000000000L; formula above.

int value = (int) number; Array Syntax


Method 1 (Declaration + Memory Allocation) It contains many useful methods for arrays.
Arrays
int[] numbers = new int[5];
|
or |-- sort()
int numbers[] = new int[5]; |-- toString()
Both are valid. |-- binarySearch()
Developers mostly use: |-- equals()
int[] numbers;
Step 3: What is sort()?
Inside the Arrays class, there is a method:
Default Values public static void sort(int[] arr)
Notice this:
Data Type Default Value int[] arr
byte 0
This is NOT your array.
short 0
int 0 It is just the method's parameter.
long 0L Think of it like this.
float 0.0f Your code:
double 0.0 int[] arr = {5,3,1};
char '\u0000' (null character)
boolean false [Link](arr);
Object/ null Java secretly does this:
Your variable
String
Step 1: What is an array? arr
When you write: │
int[] arr = {10, 20, 30}; ▼
Java creates an array object in memory. +---+---+---+
|5 |3 |1 |
Think of memory like this: +---+---+---+
Memory
+----+----+----+ Now the sort() method starts.
|10 |20 |30 | It receives the same reference.
+----+----+----+ sort()
Now the variable arr doesn't contain the numbers.
parameter arr
It only remembers where the array is. │
arr


+---+---+---+

|5 |3 |1 |
+----+----+----+
+---+---+---+
|10 |20 |30 |
+----+----+----+ Notice both arrows point to the same array.
So arr is a reference variable. Not two arrays.
Think of it like a house address. Only one.
House = Array
Address = arr Now imagine sort() changes
arr[0] = 1;
Step 2: What is Arrays? What happens?
Before
Now look at this:
[Link](arr); 5 3 1
Here, After
Arrays 1 3 5
is just a class. The original array changed because both references
Just like point to the same object.
[Link](25);
Here, Step 4: Why doesn't sort return anything?
Math
Look carefully.
is a class.
Suppose I give you my notebook.
Similarly,
Arrays You rearrange the pages.
is another class. After you're done...
Do you need to give me another notebook? Imagine its code looked like this:
No. public static String toString(int[] arr){
You already changed mine.
Exactly the same with String result = "[";
[Link](arr);
It changes the existing array. for(int i=0;i<[Link];i++){
So Java says
void result += arr[i];
meaning
"I already changed your array. I don't need to return a if(i != [Link]-1)
new one." result += ", ";

Step 5: Then what is toString()? }


Now suppose the array is
1 3 5 result += "]";
You want to print it.
return result;
You write
[Link](arr);
}
You expect
[1, 3, 5] If the array is
But Java prints 135
[I@36baf30c it returns
Why? "[1, 3, 5]"
Because arr is an object. Notice...
Whenever you print an object, It returns a String.
Java automatically calls It doesn't print.
[Link](); Then
It's exactly the same as if you had written: [Link]([Link](arr));
[Link]([Link]()); prints that returned String.
Step 6: So what is toString()? Final Picture
toString() is a method whose job is: int[] arr = {5,3,1};
Convert an object into text (a String). arr
For example, │
Imagine a Car class: ▼
class Car { +---+---+---+
|5 |3 |1 |
String brand = "BMW"; +---+---+---+
} ↓
Now [Link](arr);
Car c = new Car(); Changes the same array.
arr
[Link](c); │
Java actually does ▼
[Link]([Link]()); +---+---+---+
If you never write your own toString(), Java uses the |1 |3 |5 |
default one from Object, which prints something like: +---+---+---+
Car@7adf9f5f ↓
That's why arrays also print something like [Link](arr);
[I@36baf30c
Returns
because arrays don't provide a nicer toString(). "[1, 3, 5]"

Step 7: Then why [Link](arr)? [Link](...)
The creators of Java knew arrays don't print nicely. Prints
So they wrote another method inside the Arrays class. [1, 3, 5]
[Link](arr)
the given value
parallelSort(a void ✅ Yes Sorts using
Java Arrays Methods
rr)
multiple
threads (large
Cheat Sheet toString(arr) String ❌ No
arrays)
Returns a
readable string
Method Retu Mod Returns Purpose representation
rn ifies New equals(arr1, boolea ❌ No Checks if two
Typ Orig Array/O arr2) n
arrays have the
e inal bject? same elements
Arra copyOf(arr, int[] ❌ No Creates and
y? newLength)
returns a new
[Link](ar void ✅ ❌ No Sorts the
r) copied array
Yes array copyOfRange(ar int[] ❌ No Copies a range
[Link] Stri ❌ ✅ String Converts r, from, to)
g(arr) ng into a new
No array to array
readable binarySearch(a int ❌ No Searches in a
text rr, key)
sorted array
[Link]( bool ❌ ❌ No Compares compare(arr1, int
a, b) ean ❌ No Lexicographica
No two arrays arr2)
lly compares
[Link](ar void ✅ ❌ No Fills array
r, value) two arrays
Yes with one mismatch(arr1, int ❌ No Returns the
value arr2)
first different
[Link]( int[ ❌ ✅ New Copies the
arr, n) ] index
No Array array 1. [Link]()
[Link] int[ ❌ ✅ New Copies
ange(arr, ]
What is it?
No Array part of the sort() arranges the array elements in ascending order.
from, to)
array int[] arr = {5,2,4,1};
[Link] int ❌ ❌ No Searches a
earch(arr,
No sorted [Link](arr);
key)
array Output:
[Link] int ❌ ❌ No Lexicogra [1,2,4,5]
(a, b)
No phically Return Type
compares void
arrays It returns nothing.
[Link] int ❌ ❌ No Finds first Does it modify the original array?
h(a, b)
No different ✅ Yes
The original array becomes sorted.
index
[Link] Stri ❌ Internally
✅ String Prints
tring(arr) ng For primitive arrays (int[], char[], etc.), Java uses a highly
No 2D/3D
optimized sorting algorithm (Dual-Pivot Quicksort in current
arrays
[Link] bool ❌
JDKs). You don't need to mention the algorithm in a fresher
❌ No Compares interview unless asked.
als(a, b) ean
No multi- Interview Answer
dimension [Link]() sorts the elements of an array in
al arrays ascending order. It modifies the original array and returns
[Link](array1, array2);
void.
Method Retur Modifie Purpose
n Type s 2. [Link]()
Origina What is it?
l? Returns a readable String representation of an array.
sort(arr) void ✅ Yes Sorts the array Without it:
fill(arr, void ✅ Yes Fills all
value)
[Link](arr);
elements with Output
[I@36baf30c Interview Answer
With it: [Link]() creates and returns a new array
[Link]([Link](arr)); containing a copy of the original elements.
Output
[1, 2, 3] 5. [Link]()
Return Type What is it?
String Copies only a selected range.
Does it modify the original array? int[] arr = {10,20,30,40,50};
❌ No.
Internally int[] copy = [Link](arr,1,4);
It reads every element and builds a new String like: Output
"[1, 2, 3]" [20,30,40]
Interview Answer Return Type
[Link]() returns a String containing all array int[]
elements in a readable format. It does not modify the Modifies Original?
original array. ❌ No.
Interview Answer
3. [Link]() [Link]() returns a new array containing
What is it? elements from the specified start index (inclusive) to end
Checks whether two arrays have the same length and the index (exclusive).
same elements in the same order.
int[] a = {1,2,3}; 6. [Link]()
int[] b = {1,2,3}; What is it?
Searches for an element using Binary Search.
[Link](a,b); [Link](arr,30);
Output Output
true 2
Return Type Return Type
boolean int
Modifies Original? Returns the index.
❌ No. Modifies Original?
Internally ❌ No.
It compares: Important
Length The array must already be sorted.
Element 0 Interview Answer
Element 1 [Link]() searches a sorted array and
Element 2 returns the index of the searched element.
...
If everything matches → true 7. [Link]()
Otherwise → false What is it?
Interview Answer Fills every element with the same value.
[Link]() compares two arrays element by [Link](arr,100);
element and returns true if both arrays are equal. Output
[100,100,100]
4. [Link]() Return Type
What is it? void
Creates a new copy of an array. Modifies Original?
int[] copy = [Link](arr, [Link]); ✅ Yes.
Return Type Interview Answer
int[] [Link]() replaces every element of an array with
(or char[], String[], etc., depending on the array type) the specified value.
Modifies Original?
❌ No. 8. [Link]()
Internally What is it?
Creates a new array. Compares two arrays lexicographically (element by
Copies elements one by one. element).
Returns the new array. int[] a = {1,2,3};
int[] b = {1,2,4};
[Link](a,b); Rule 1: Returns 0
Output If both arrays are exactly the same.
-1 int[] a = {1,2,3};
Return Type int[] b = {1,2,3};
int
Meaning [Link]([Link](a,b));
Negative → first array is smaller Output:
Zero → arrays are equal 0
Positive → first array is greater Reason:
Modifies Original? 1 == 1
2 == 2
❌ No.
3 == 3
Interview Answer
[Link]() compares two arrays element by
Rule 2: Returns a Negative Value
element and returns a negative, zero, or positive value
If the first different element in the first array is smaller.
depending on their lexicographical order.
int[] a = {1,2,3};
int[] b = {1,2,4};
9. [Link]()
What is it? [Link]([Link](a,b));
Finds the first index where two arrays differ. Output:
int[] a = {1,2,3,4}; -1
int[] b = {1,2,5,4}; Comparison:
1 == 1 ✔
[Link](a,b);
Output 2 == 2 ✔
2
Return Type 3 < 4 ❌
int So it returns negative.
Modifies Original?
❌ No. Another example:
Interview Answer int[] a = {5,8,1};
[Link]() returns the index of the first int[] b = {5,9,1};
different element between two arrays. If they are equal, it
returns -1. [Link]([Link](a,b));
Output:
-1
10. [Link]()
Because
What is it? 8 < 9
Sorts the array like sort(), but for large arrays it can use
multiple threads to improve performance. Rule 3: Returns a Positive Value
Return Type If the first different element in the first array is greater.
void int[] a = {1,2,8};
Modifies Original? int[] b = {1,2,4};
✅ Yes.
Interview Answer [Link]([Link](a,b));
[Link]() sorts the array in ascending Output:
order and may use multiple threads for better performance 1
on large arrays. Because
8 > 4

Return Values
Another example
Return Value Meaning int[] a = {5,10,2};
0 Both arrays are equal int[] b = {5,9,100};
Negative (< 0) First array is smaller
Positive (> 0) First array is larger [Link]([Link](a,b));
[Link](a, b); Output
It compares element by element from left to right. 1
It stops at the first difference. Because
10 > 9 Instead of writing
Java doesn't even compare 2 and 100. String name = "Rahul";
It already found the first difference. every time,
we can simply run
Different Length Arrays java Main Rahul
Example 1 Tomorrow
int[] a = {1,2}; java Main Ravi
int[] b = {1,2,3}; The same program works for different inputs.

[Link]([Link](a,b)); Real-Life Uses


Output ✅ Passing a filename
-1 ✅ Passing a port number
✅ Passing database details
✅ Passing environment (dev, test, prod)
What are Command Line Arguments ✅ Passing configuration values when starting an application
(CLA)?
Command Line Arguments are values passed to a Interview Answer (Simple)
Java program when it starts executing.
"Command Line Arguments (CLA) are the values
These values are received by the String[] args passed to a Java program when it starts executing.
parameter in the main() method. They are stored in the String[] args parameter of
the main() method and are used to provide input or
configuration before the program begins execution."

Syntax
public static void main(String[] args)
Interview Point
Here,
String[] args toString() does not mean:
stores the command-line arguments.
"Convert an object into a nice String."
Example
Suppose you run your program from the terminal: It simply means:
java Main Rahul 21 Hyderabad
The JVM automatically creates: "Return some String representation of this object."
args[0] = "Rahul";
args[1] = "21"; The quality of that representation depends on the class:
args[2] = "Hyderabad";
Now your program can use these values.  [Link]() → Default representation
public class Main { ([I@36baf30c)
public static void main(String[] args) {  [Link]() → Human-readable
representation ([10, 20, 30])
[Link](args[0]);
[Link](args[1]); Arrays are also objects in Java. When we
[Link](args[2]); print an array reference,
[Link]() calls the array's
}
} toString() method. Since arrays do not
Output provide a human-readable implementation of
Rahul toString(), the default representation (like
21 [I@36baf30c) is printed. To display the array
Hyderabad
elements, Java provides the utility method
[Link](), which returns a readable
Why do we use Command Line Arguments?
string containing all the elements.
They allow us to pass input to the program before it starts,
without changing the source code.
🔥 One line to remember
Example:
Every array is an object, but not every object is an array. volatile
int[] arr = {10,20,30}; transient
native
[Link](arr);
strictfp

Internally:

String temp = [Link](); // default


[Link]()
[Link](temp);

Output:

[I@36baf30c

Then where does [Link]() come


from?

This is a different method.

[Link]([Link](arr));

Execution:

String temp = [Link](arr); //


Reads elements and creates "[10, 20, 30]"
[Link](temp);

Why does [Link]() print a String object


normally, but an array prints something like
[I@36baf30c?"

println() always calls toString(). String


overrides toString(), so it prints the actual
text. Arrays don't override toString(), so
they use [Link](), which prints
ClassName@hashcode (for arrays, something
like [I@36baf30c). Therefore, we use
[Link]() to print array elements

ACCESS SPECIFIERS(ACCESS
MODIFIERS)

In Java, access specifiers and access modifiers refer


to the same thing. They control the visibility of
classes, methods, variables, and constructors."

If the interviewer asks about modifiers, you can also


mention:

Access Non-Access Modifiers


Modifiers
public static
private final
protected abstract
default synchronized

You might also like