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

Java Notes

The document provides an overview of Java programming, emphasizing its object-oriented principles, syntax, and data types. It explains key concepts such as access modifiers, strongly typed language rules, control structures (if-else, switch), loops (for, while, do-while), and array handling. Additionally, it covers exceptions in type casting and the importance of proper data initialization in Java.

Uploaded by

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

Java Notes

The document provides an overview of Java programming, emphasizing its object-oriented principles, syntax, and data types. It explains key concepts such as access modifiers, strongly typed language rules, control structures (if-else, switch), loops (for, while, do-while), and array handling. Additionally, it covers exceptions in type casting and the importance of proper data initialization in Java.

Uploaded by

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

JAVA

i) Object-oriented programming (OOP) is at the core of Java.


ii) All object-oriented programming languages provide
mechanisms that help you implement the object-oriented
model. They are encapsulation, inheritance, and
polymorphism. These are the 3 oops principle

• A First Simple Program:


public class Main {
public static void main(String[] args) {
[Link]("Hello World");
}
}

Structure of the java code:


What is the use of public keyword which was used before the class Main:
public class Main{}:
• In Java, public is an Access Modifier. It is a security setting. It tells the
Java compiler: "This code is open to the world. Any other file or
program can see it and use it."
• If you don't make a class public, it becomes restricted, meaning only
files sitting in the exact same folder can look inside it.
• The Public-Import Relationship Definition: In Java, declaring a class
or method as public grants it global visibility, making it accessible
outside of its own folder (package). The import keyword is then used
by other Java files to locate and bring that public code into their own
workspace so they can use it.

public static void main(String[] args)


• In short: static allows the Java Virtual Machine (JVM) to run your
main method instantly without having to create an object of your
class first.
• What does String[] mean?
• In Java, brackets [] mean an Array. An array is simply a list of
items grouped together.
• So, String[] tells Java: "Expect a list of text words coming in
from the outside world." Even if you pass a number (like 50000
or 10), Java will initially read it as a text word string.
• In Java, String is a built-in class that represents text, and the square
brackets [] represent an array (a list). Therefore, String[] args
means args is a variable that holds a String Array object, which
acts as a collection container holding multiple individual String
objects inside it.
• args is NOT a single String: It is the name of the entire list
container.
• args is an Array Object: Java treats lists as objects themselves.
• The contents inside are Strings: Every single slot inside that
array container holds an individual String object (like a word or
input text from the terminal).
Java Is a Strongly Typed Language:
In programming, when we say a language is strongly typed, it means the
language is an absolute stickler for rules regarding data types (like
numbers, decimals, and text). It forces you to be completely explicit about
what kind of data you are working with, and it will refuse to run your code
if you try to mix incompatible types by mistake.
1. Every Container Must Have a Declared Label
In Java, you cannot just create a variable out of thin air and throw a value
into it. You must explicitly tell the computer ahead of time exactly what
type of data that variable is allowed to hold.

int marks = 98; // Perfectly fine: 98 is a whole number (integer)


String name = "Alex"; // Perfectly fine: "Alex" is a text string

2. No Mixing Incompatible Types (Type Safety)


Once you define a variable's data type, that variable is locked into that
type for the rest of its life. You cannot accidentally stuff a text word into a
number box.
int accountBalance = 5000;
accountBalance = "Five Thousand"; // ERROR! Java will block this immediately.
3. Strict Rules for Conversions (Data Constraints)
If you want to move data from one type to another, a strongly typed
language makes you do it intentionally.
Imagine you have a precise decimal number (a double) representing a
student's GPA, and you want to convert it into a simple whole number

double preciseGpa = 9.84;


int roundedGpa = preciseGpa; // ERROR! Java will say "Possible loss of precision"

The Primitive Types:


Java defines eight primitive types of data: byte, short, int, long, char, float,
double, and Boolean

Integers:
Java defines four integer types: byte, short, int, and long. All of these are
signed, positive and negative values. Java does not support unsigned,
positiveonly integers. Many other computer languages support both
signed and unsigned integers.
CHARACTER:
:

Core Definition
• The char Data Type: In Java, the char data type is used strictly to
store individual characters (like 'A', '7', or '$').

Unicode & Global Portability


• International Design: Java uses Unicode to represent characters so
that programs can be written for worldwide use.
• All Human Languages: Unicode is a massive, unified system that can
represent characters from almost all human languages (including
Latin, Greek, Arabic, Hebrew, Katakana, and more).
• The Trade-off: Using Unicode is slightly inefficient for languages like
English, German, or French (which only need 8 bits), but it is a
necessary price to pay for global portability.

Technical Specs & Memory Layout


• 16-Bit Size: Because Unicode required 16 bits of data when Java was
created, a char in Java takes up exactly 16 bits (2 bytes) of memory.
• Positive Range Only: The numerical range of a char is 0 to 65,536.
There are no negative values for characters in Java.

Connection to Older Standards


• ASCII Range: The standard, traditional ASCII character set is still
preserved and ranges from 0 to 127.
• ISO-Latin-1 Range: The extended 8-bit character set ranges from 0 to
255.
 && (AND): Strict. Requires all conditions to be true.
 || (OR): Generous. Requires at least one condition to be true.
 ! (NOT): Rebellious. Flips true to false and vice versa.
1. The if-else-if Ladder
Simple Definition
"An if-else-if ladder is a top-down chain of conditions. Java checks each
condition one by one from top to bottom. The moment it finds a
condition that is true, it executes that specific block of code and skips the
entire remaining rest of the ladder."
Think of it like walking down a flight of stairs where each step has a gate.
You stop and open the very first gate that is unlocked, and you don't look
at any of the stairs below it.

Simple Example:
Java
int marks = 85;

if (marks >= 90) {


[Link]("Grade A");
} else if (marks >= 80) {
[Link]("Grade B"); // Java stops here, prints this, and exits
the ladder!
} else if (marks >= 70) {
[Link]("Grade C");
} else {
[Link]("Fail"); // The safety net if everything else is false
}

2. The switch Statement


Simple Definition
"Instead of testing conditions step-by-step, a switch statement acts like a
multi-way router or an elevator. It takes a single target value and jumps
directly to the matching case label instantly."
Think of it like an elevator in a mall: if you press the button for Floor 3
(case 3:), the elevator goes straight to Floor 3 without stopping at Floors 1
or 2.

Simple Example:
Java
int dayNumber = 2;

switch (dayNumber) {
case 1:
[Link]("Monday");
break;
case 2:

[Link]("Tuesday"); // Java jumps straight here!

break; // The emergency brake that stops the execution


case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid Day"); // Runs if no match is found
}

Two Critical "Exceptional Rules" for Your Exams


Exception A: The "Fall-Through" Trap in Switch
If you forget to put the break; statement at the end of a case, Java will not
stop running. It will bleed down into the next case and execute its code
too, even if that case doesn't match your value!
Java
int option = 1;
switch(option) {
case 1:
[Link]("One"); // Prints "One"
case 2:

[Link]("Two"); // ALSO PRINTS "Two" because there


was no break above!
}
Exception B: Data Type Restrictions for Switch
An if ladder can check any condition using ranges and complex math (like
marks >= 80 && marks < 90).
A switch statement can only test for exact matching values, and it only
accepts specific data types:
• Allowed: Whole numbers (int, byte, short, char), String objects, and
Enums.

• Banned/Error: Decimals (float, double) and boolean values are


completely illegal inside a switch statement expression.

Comparison Cheat Sheet

Feature if-else-if Ladder switch Statement

How it Jumps directly to the


Top-to-bottom sequentially.
searches match (Faster).

Condition Can check ranges (e.g., < or Can only check for exact
Types >) and relational tests. values (e.g., ==).

Execution Moves out automatically Requires break; to prevent


Control once a block finishes. falling through.

Menu selections,
Complex ranges (like
Best Used For weekdays, or fixed choice
calculating GPA thresholds).
settings.

public class ForLoopDemo {


public static void main(String[] args) {
// Loop runs from 1 up to 5
for (int i = 1; i <= 5; i++) {
[Link]("Iteration number: " + i);
}
}
}
while loop:::
public class WhileLoopDemo {
public static void main(String[] args) {
int i = 1; // 1. Initialization

// 2. Condition checked BEFORE running


while (i <= 5) {
[Link]("While loop count: " + i);

i++; // 3. Increment (If you forget this, the loop runs forever!)
}
}
}
public class DoWhileLoopDemo {
public static void main(String[] args) {
int i = 1; // 1. Initialization

do {
[Link]("Do-While loop count: " + i);
i++; // 3. Increment

} while (i <= 5); // 2. Condition checked AT THE END


}
}
 Whitespace: Spaces, tabs, and blank lines.
 Identifiers: Names you give to your classes, variables, and methods
(e.g., Main, roundedGpa).
 Literals: Constant, raw values typed directly into the code (e.g., 9.84,
"Hello").
 Comments: Notes for humans that the computer ignores (e.g., // This is
a comment).
 Separators: Symbols that structure the code layout (e.g., semicolons ;,
curly braces {}, parentheses ()).
 Operators: Symbols used for math or logic tests (e.g., +, ==, &&).
 Keywords: Built-in words reserved for Java's internal rules (e.g., public,
class, int).
Dynamic Initialization:

Case 1: The "Squeeze" Exception (int to byte)


This happens when you take a large whole number and force it into a tiny
8-bit box (byte).
As we discussed earlier, a byte can only hold 256 values (from -128 to
127). If your integer is bigger than 127, Java uses the Modulo 256 rule to
spin a number wheel and find a remainder.

Code Example:
Java
public class SqueezeDemo {
public static void main(String[] args) {
int bigValue = 130;
// 130 is bigger than a byte's max limit of 127!

byte tinyBox = (byte) bigValue;

// Math: 130 wrapped around the 256-wheel lands on a negative


space
[Link]("Squeezed Byte Value: " + tinyBox); // Output: -126
}
}
Case 2: The "Chop" Exception (double to int)
This happens when you try to force a decimal number into a whole
number box. Java doesn't care about rounding math rules (like .8 rounding
up). It simply slices off the decimal point entirely (truncation).

Code Example:
Java
public class ChopDemo {
public static void main(String[] args) {
double exactPrice = 99.99;

int wholePrice = (int) exactPrice;

// The '.99' is completely thrown away!


[Link]("Chopped Integer Value: " + wholePrice); //
Output: 99
}
}
Case 3: The "Over-Limit Cap" Exception (Massive double to int)
What if your decimal number is so massive that it goes way past the
maximum capacity of an integer (2.14 Billion)? Java cannot wrap it using
modulo because decimals don't use wheels. Instead, it caps it out at the
absolute maximum integer limit.

Code Example:
Java
public class CapDemo {
public static void main(String[] args) {
double superMassive = 3500000000.75; // 3.5 Billion (Integer max is
2.14 Billion)

int cappedInt = (int) superMassive;

// It stays locked at the absolute max wall of an int


[Link]("Capped Integer Value: " + cappedInt); // Output:
2147483647
}
}
Case 4: The "Secret Text Mapping" Exception (int to char)
As you learned from your notes, a char is a 16-bit positive number under
the hood that maps to a Unicode symbol. If you take a standard integer
and force it into a char, Java doesn't print the number; it looks up that
number in its global alphabet dictionary and prints the corresponding
character symbol.

Code Example:
Java
public class CharMappingDemo {
public static void main(String[] args) {
int codeNumber = 65; // 65 is the traditional ASCII/Unicode code for
'A'
char characterSymbol = (char) codeNumber;

// Java converts the number directly into its matching symbol


[Link]("Mapped Character: " + characterSymbol); //
Output: A
}
}

The Ultimate Exception: Total Rejection (String to int)


There is one massive trap to watch out for. You cannot use casting symbols
like (int) to convert text words (String) into numbers. They are completely
different species in memory.
If you try to write int number = (int) "10";, Java will throw a severe
compilation error and refuse to build your program.

The Fix (Parsing):


To turn text numbers into real numbers, you must use a special built-in
command tool called [Link]():
Java
public class StringParsingDemo {
public static void main(String[] args) {
String textNumber = "500";
// int brokenAttempt = (int) textNumber; ERROR! This will not
compile.

// Correct Way: Use the Parse tool


int realNumber = [Link](textNumber);

[Link]("Successfully Parsed Number: " + (realNumber +


5)); // Output: 505
}
}
ARRAY:
1. What is a 1-D Array?
• A one-dimensional array is essentially a list of variables that all have the same
data type (like a list of all integers or all decimals).

2. Declaring an Array (The Blueprint)

• To create an array, you first declare its variable type using this general form:
type var-name[];
• Example: int month_days[];
• Crucial Rule: This line only creates a blueprint variable named month_days. At
this point, no physical array actually exists in memory yet.

3. Allocating Memory using new (The Physical Creation)

• To create the actual, physical array in your computer's memory, you must
allocate space using a special operator called new.
• The general form is:
array-var = new type[size];
• Example: month_days = new int[12]; (This allocates a 12-element array of
integers in the computer's memory).

4. When are Array Elements Automatically Stored as Zero?


The absolute moment you use the new operator to allocate the physical memory,
Java automatically fills every single slot in that array with a default placeholder value
based on its type.
Elements are automatically stored as 0 under these exact conditions:
• For Numeric Types: If you create an array of whole numbers or decimals (like
int, byte, short, long, float, or double), Java automatically initializes every slot
to 0 (or 0.0).
• For Booleans: If it's a boolean[] array, every slot automatically starts as false.
• For Object References: If it's an array meant to hold complex data objects,
every slot starts as null.
So, the second month_days = new int[12]; runs, you instantly have 12 slots in
memory, and all 12 slots are automatically filled with 0 before you even type
anything else!

1. When Memory is NOT Created (Declaration Only)


Memory is not created when you only tell Java that an array variable exists, without
giving it a size.

Code Example:
Java
int[] marks; // Or: int marks[];
What happens in memory?
• Zero memory is allocated for data slots. * Java only creates a tiny pointer
variable named marks, but it points to nothing (null).
• No boxes are carved out in your RAM, and no zeros are stored because there is
nowhere to put them. If you try to use marks[0] right now, your program will
crash.
2. When Memory IS Created and Initialized to 0 (Allocation using new)
Memory is physically created and filled with 0 the exact microsecond you use the
new keyword followed by a specific size.

Code Example:

Java
marks = new int[4];
What happens in memory?
• Java immediately goes to your computer's RAM and carves out a block big
enough to hold exactly 4 integers.
• Because you used new and left the boxes empty, Java automatically runs a
safety routine and initializes every single box to 0.

Index marks[0] marks[1] marks[2] marks[3]

What's inside? 0 0 0 0

3. The Exception: When Memory is Created but NOT Initialized to 0


There is a third scenario where memory is created, but it skips the 0 step entirely
because you supply your own numbers right away using curly braces {}.

Code Example:

Java
int[] marks = {95, 88, 70, 99};
What happens in memory?
• Java creates the 4 physical boxes in RAM.
• It bypasses the zero step and directly drops your values (95, 88, etc.) straight
into those slots.
OPERATOR:

1. The Increment Operators (Adds 1)

Pre-Increment (++x)
"Increases the variable by 1 FIRST, then uses the new value in the calculation."
Java
int x = 5;
int y = ++x; // x becomes 6 first, then y becomes 6
// Final: x = 6, y = 6
Post-Increment (x++)
"Uses the current value in the calculation FIRST, then increases the variable by 1
afterwards."
Java
int x = 5;
int y = x++; // y gets the original 5 first, then x becomes 6
// Final: x = 6, y = 5

2. The Decrement Operators (Subtracts 1)


Pre-Decrement (--x)
"Decreases the variable by 1 FIRST, then uses the new value in the calculation."
Java
int x = 5;
int y = --x; // x drops to 4 first, then y becomes 4
// Final: x = 4, y = 4
Post-Decrement (x--)
"Uses the current value in the calculation FIRST, then decreases the variable by 1
afterwards."
Java
int x = 5;
int y = x--; // y gets the original 5 first, then x drops to 4
// Final: x = 4, y = 5

Summary Cheat Sheet for Your Exams

Simple English Value used in What happens


Operator Syntax
Meaning Equation to x?

Pre-Increment ++x Increase then Use Uses New Value Adds 1

Post-Increment x++ Use then Increase Uses Old Value Adds 1

Decrease then
Pre-Decrement --x Uses New Value Subtracts 1
Use

Use then
Post-Decrement x-- Uses Old Value Subtracts 1
Decrease
RIGHT AND LEFT SHIFT:
1. Left Shift Operator (<<)

Simple Definition
"The Left Shift operator moves all the binary bits of a number to the left by a
specified number of positions. As the bits move left, empty slots open up on the
right side, which are automatically filled with zeros."

The Fast Math Shortcut


Every single time you shift a number to the left by 1 position, you are essentially
multiplying that number by 2.
• Formula: $\text{Result} = x \times 2^n$ (where $x$ is the number and $n$ is
the number of positions shifted).

Simple Example:

If you take the number 5 and left shift it by 2 positions (5 << 2):
• Math: $5 \times 2^2 \rightarrow 5 \times 4 = \mathbf{20}$
• What happens to the bits: 00000101 (5) shifts left twice $\rightarrow$
00010100 (which is 20).

2. Right Shift Operator (>>)

Simple Definition
"The Right Shift operator moves all the binary bits of a number to the right by a
specified number of positions. The bits on the far right end fall off and are lost
forever, while the sign bit (positive or negative status) is preserved on the left."

The Fast Math Shortcut

Every single time you shift a number to the right by 1 position, you are essentially
dividing that number by 2 (and chopping off any decimals).
• Formula: $\text{Result} = \frac{x}{2^n}$
Simple Example:
If you take the number 20 and right shift it by 2 positions (20 >> 2):
• Math: $\frac{20}{2^2} \rightarrow \frac{20}{4} = \mathbf{5}$
• What happens to the bits: 00010100 (20) shifts right twice $\rightarrow$
00000101 (which is 5).

Summary Cheat Sheet for Your Labs

Operator Symbol Action Simple Math Effect

Moves bits left, fills Multiplies the number by $2$


Left Shift <<
right with 0. for each shift.

Moves bits right, Divides the number by $2$


Right Shift >>
discards far-right bits. (drops decimals) for each shift.

CODITIONAL OPERATOR OR TERNARY OPERATOR:


The Simple Structure

Instead of writing multiple lines of if and else, you layout the code like this:
$$\text{Condition} \ \mathbf{?} \ \text{Value if True} \ \mathbf{:} \ \text{Value if
False};$$
1. The Condition: The question you are asking (must result in a true or false).
2. The ? (Question Mark): Means "Let's check the condition!"
3. The First Value: The reward you get if the question is true.
4. The : (Colon): Means "Otherwise..."
5. The Second Value: The reward you get if the question is false.

A Simple Example (Before vs. After)


Imagine you want to check a student's marks. If they score 50 or above, they "Pass".
Otherwise, they "Fail".
The Long Way (if-else)
Java
String result;
if (marks >= 50) {
result = "Pass";
} else {
result = "Fail";
}
The Quick Way (Ternary Shortcut)
Java
String result = (marks >= 50) ? "Pass" : "Fail";

Breaking Down Your Syllabus Example


Let's look at the exact line from your textbook notes:
Java
ratio = denom == 0 ? 0 : num / denom;
This line is an excellent safety guard to prevent a fatal math crash (dividing a number
by zero is impossible). Here is exactly how Java reads it in plain English:
• The Question: Is the denominator equal to 0? (denom == 0)
• If True: Set the ratio to 0. (Bypasses the division so the program doesn't crash).
• If False: Go ahead and divide safely! (num / denom).
The One Strict Exception Rule
For your lab viva questions, remember this rule: Both options (before and after the
colon) must return the same type of data. * Correct: int outcome = (age > 18) ? 100 :
200; (Both are integers).

• Lexical/Syntax Error: int outcome = (age > 18) ? 100 : "Too Young";
(This breaks because you cannot mix an integer 100 with a text string "Too Young"
inside the same variable!)

The Core Precedence Table (Highest to Lowest)


For your upcoming lab quizzes and code tracing questions, here is a simplified
hierarchy chart showing how Java decides what to execute first:

Rank Operator Category Symbols Simple English Example Rule

Parentheses & Brackets and post-changes are


1 (), x++, x--
Postfix evaluated at the absolute start.

Pre-changes and the NOT operator


2 Prefix & Unary ++x, --x, !
come next.

Standard math core (Multiplication,


3 Multiplicative *, /, %
Division, Modulo).

Standard math addition and


4 Additive +, -
subtraction.
Rank Operator Category Symbols Simple English Example Rule

Bitwise shifting happens after


5 Shift Operators <<, >>
standard math.

Greater than / Less than comparison


6 Relational <, >, <=, >=
checks.

Equality testing happens after


7 Equality ==, !=
magnitude checks.

Strict rule: && is always evaluated


8 Logical AND &&
before `

9 Logical OR `

10 Ternary ?: The short inline if-else decision.

The anchor: Storing the final value


11 Assignment =, +=, -=
into a variable always happens last!

A Famous Trick Exam Question: && vs ||


Professors love to blend logical operators on tests to see if you catch the ranking
rules. Look at this expression:
Java
boolean check = true || false && false;
• Incorrect Left-to-Right Guess: true || false becomes true. Then true && false
becomes false.
• The Correct Java Reality: Because && has a higher precedence than ||, Java
processes the right side first!
1. false && false evaluates to false.
2. The expression simplifies to: true || false.
3. The final answer stored in check is true.

Simple Definition
"The break statement instantly terminates the loop or switch statement it is
currently inside. The program completely stops running that block and jumps
straight to the very next line of code outside it."
Think of it like a smoke alarm in a building. The moment it goes off, you don't finish
your current task—you drop everything and exit the building immediately.

Code Example:

Java
for (int i = 1; i <= 5; i++) {
if (i == 3) {

break; // Instantly exits the entire loop right here!

}
[Link]("Counting: " + i);
}
[Link]("Loop is dead.");
• Output: ```text Counting: 1 Counting: 2 Loop is dead.
• *(Notice that 3, 4, and 5 never get printed because the loop was permanently
terminated).*

2. continue (The Skip Button)

Simple Definition
"The continue statement does not kill the loop. Instead, it instantly stops the
current round (iteration), skips any remaining code below it for that specific round,
and jumps straight to the loop's next update cycle."
Think of it like skipping a bad track on a music playlist. You don't throw away your
headphones or stop listening to music entirely; you just skip the current song to start
playing the next one.

Code Example:
Java
for (int i = 1; i <= 4; i++) {
if (i == 3) {

continue; // Skips the rest of this round's code!

}
[Link]("Processing item: " + i);
}
• Output: ```text Processing item: 1 Processing item: 2 Processing item: 4
*(Notice that 3 is completely skipped, but the loop safely recovered and kept running
for 4).*
Visible inside Visible inside Visible to
Access Visible to the
the Same the Same Subclasses
Modifier Key Entire World?
Class? Package? outside package?

private Yes No No No

default (Blank) Yes Yes No No

protected Yes Yes Yes No

public Yes Yes Yes Yes

TO GET THE INPUT FROM USER:


In Java, there are three main ways to get input from a user. To keep things easy to
understand, we can think of them like different ways of ordering food:
1. The Scanner Class (Like a casual dine-in restaurant – most common and
beginner-friendly).
2. The Command Line Arguments (Like a drive-thru – you give your order before
you even enter the program).
3. The BufferedReader Class (Like a high-speed commercial kitchen – fast and
efficient, but requires extra setup).
Here is the simple, step-by-step breakdown of how each one works.

1. The Scanner Class (The Easiest & Most Common Way)

The Scanner class is the absolute best way for beginners to capture input. It reads
words, numbers, or full sentences directly from the console while the program is
running.

Simple Example:

Java
import [Link]; // Step 1: Import the tool

public class InputDemo {


public static void main(String[] args) {
// Step 2: Create a Scanner object named 'input'
Scanner input = new Scanner([Link]);

[Link]("Enter your name: ");


String name = [Link](); // Reads a string (text)

[Link]("Enter your age: ");


int age = [Link](); // Reads an integer (whole number)

[Link]("Hello " + name + ", you are " + age + " years old!");
[Link](); // Step 3: Close the scanner when done
}
}

Key Scanner Methods to Remember:


• [Link]() → Reads just one single word.
• [Link]() → Reads an entire line of text (including spaces).
• [Link]() → Reads a whole number (int).
• [Link]() → Reads a decimal number (double).

2. Command-Line Arguments (The Fastest Way)


Instead of waiting for the program to run and prompt you with a question, you can
pass your inputs at the exact same time you start the program.
Those values are automatically captured by the String args[] array sitting inside your
main method header!

Simple Example:

Java
public class CommandLineDemo {
public static void main(String args[]) {
// Check if the user actually provided inputs
if ([Link] >= 2) {
String name = args[0]; // First word passed
String age = args[1]; // Second word passed

[Link]("Hello " + name + "! You are " + age + " years old.");
} else {
[Link]("Please provide your Name and Age when running the
program!");
}
}
}

How you run this in your terminal:

Bash
java CommandLineDemo Keshav 18
• Output: Hello Keshav! You are 18 years old.

3. BufferedReader (The High-Speed Factory Way)


BufferedReader is an older, classic Java method. It reads input in large blocks (buffers)
rather than character-by-character, making it incredibly fast.
It is a bit tougher for beginners because it forces you to handle potential errors
(IOException) and treats everything as a String, meaning you have to manually
convert text into numbers.

Simple Example:

Java
import [Link];
import [Link];
import [Link]; // Must import this to handle system errors

public class MultiInputDemo {


// Notice the 'throws IOException' at the end of the line below!
public static void main(String[] args) throws IOException {
// Setting up the stream pipeline
BufferedReader reader = new BufferedReader(new
InputStreamReader([Link]));

[Link]("Enter your favorite number: ");


String textInput = [Link](); // Reads input strictly as text

// Conversion Step: Changing the String "10" into the actual integer 10
int number = [Link](textInput);

[Link]("Your double score is: " + (number * 2));


}
}

Quick Summary Cheat Sheet

Feature Scanner Command Line (args[])BufferedReader

Ease of Use (Easiest) (Medium) (Harder setup)

When do you Before the program


While the program runs. While the program runs.
input? starts.

Speed Moderate Instant Extremely Fast

Handles int, double, Everything comes in asEverything


a comes in as a
Data Types
String automatically. String. String.
Feature Scanner Command Line (args[])BufferedReader

Lab assignments, mini- Quick configuration Competitive programming


Best Used
projects, interactive inputs or automation or reading huge files
For
menus. scripts. quickly.

Explanation for scanner:


Scanner:
Think of a class as a blueprint or a tool schema. The Scanner blueprint outlines a tool whose sole
purpose is to take raw data text from a source, break it down into separate pieces using spaces as
markers, and translate those pieces into clean programming variables (like numbers or text strings).

[Link]:
[Link] is an InputStream that acts as a physical data pipeline connected directly to your
computer's standard input source—which, by default, is your keyboard.

However, [Link] is incredibly primitive. It reads data as a raw, continuous stream of binary bytes
(numbers representing characters), one byte at a time.

• If you type the word "Hi", [Link] doesn't see a word; it just sees the raw byte values 72
and 105.

• It has no built-in logic to group those bytes into a readable sentence, a whole integer, or a
decimal number.

Scanner contruct:
The method Scanner() (specifically known as a Constructor) is the initialization factory method of
the Scanner class. Its job is to allocate memory and physically construct a living "Scanner worker
object" in your system's RAM.
The constructor acts as the configuration step. It sets up the internal character buffers, loads up the
rules for parsing text, and prepares the tools (like nextInt() and nextLine()) so you can use them on
your next lines of code.

The 4 Categories of next Functions

1. The Standard Text Grabbers (2 Methods)

These are used to grab words or full lines of text exactly as they are typed.

• next(): Grabs the next single word (stops at a space).

• nextLine(): Grabs the entire remaining line of text (stops at the Enter key).

2. The Whole Number (Integer) Grabbers (4 Methods)

These grab whole numbers and automatically convert them to the correct size in memory.

• nextInt(): Converts the word to a standard 4-byte integer (int). This is the one you will use
99% of the time in your labs.

• nextLong(): Converts the word to a massive 8-byte integer (long) for incredibly large
numbers.

• nextShort(): Converts the word to a small 2-byte integer (short).

• nextByte(): Converts the word to a tiny 1-byte integer (byte).

3. The Decimal (Floating-Point) Grabbers (2 Methods)

These grab fractional numbers with decimal points.

• nextDouble(): Converts the word to a highly accurate 8-byte decimal (double). Most
common for decimals.

• nextFloat(): Converts the word to a standard 4-byte decimal (float).

4. The Specialized Data Grabbers (5 Methods)

These are used for advanced pattern matching, true/false logic, or handling data from different
countries.

• nextBoolean(): Looks strictly for the words "true" or "false" and converts them into a
boolean flag.
• nextBigInteger() & nextBigDecimal(): Used in math or banking applications where numbers
are too massive to fit into standard primitive memory variables.

• next(Pattern pattern) & next(String pattern): Advanced functions where you pass a custom
rule (a Regular Expression) to make the Scanner search for very specific structures—like a
phone number format (XXX) XXX-XXXX or a VIT registration number format 26BCEXXXX.

Command-Line Arguments: The Drive-Thru Method

Instead of waiting for the program to start and ask you questions mid-run, Command-Line
Arguments allow you to feed your data directly into the program at the exact moment you
launch it in the terminal.

The Core Mechanism

Every time you write a standard Java program, you include this master line:

Java

public static void main(String[] args) { ... }

• String[]: An array (a container list) of words.

• args: Short for "arguments" (your inputs).

When you pass data from the terminal, Java automatically packages those words and drops
them into the args[] array before executing a single line of your code.

Simple Code Example

Java

public class ArgsDemo {

public static void main(String[] args) {

// Check if the user actually passed inputs to avoid crashes

if ([Link] >= 2) {

String name = args[0]; // First word

String age = args[1]; // Second word

[Link]("Hello " + name + ", age " + age);

} else {
[Link]("Please provide Name and Age in the terminal!");

How to Run it in the Terminal

You pass your data values directly after the class name, separated by single spaces:

Bash

java ArgsDemo Keshav 18

What happens behind the scenes:

• The word java wakes up the JVM engine.

• The word ArgsDemo tells the JVM which file blueprint to run.

• java and ArgsDemo are execution keywords—they are completely skipped by the array.

• args[0] cleanly becomes "Keshav".

• args[1] cleanly becomes "18".

Output: Hello Keshav, age 18

The 2 Major Viva / Exam Traps

1. The ArrayIndexOutOfBoundsException Crash

If your code tries to read args[1], but you only type one word in the terminal (java
ArgsDemo Keshav), the program will instantly crash.

• The Rule: Always wrap your logic inside an if ([Link] >= X) check to ensure the user
gave you enough data slots before reading them.

2. Passing Phrases with Spaces

Because Java treats spaces as boundaries, if you type java ArgsDemo Tamil Nadu, then
args[0] becomes "Tamil" and args[1] becomes "Nadu".

• The Fix: If you want a multi-word input to stay inside a single slot, wrap it in double
quotation marks in your terminal:

Bash
java ArgsDemo "Tamil Nadu" 18

(Now args[0] = "Tamil Nadu" and args[1] = "18")

EQUALS() Method:
1. The Core Purpose of .equals()

The .equals() method is a built-in tool used to check if the actual text content inside two
objects is exactly identical (letter-by-letter, case-sensitive).

2. The Big Difference: == vs .equals()

(Note: In your question, you wrote a single =, which is used to assign a value to a variable,
like int x = 5;. In Java, we use a double equals == to compare two things).

Here is how they differ when comparing objects like Strings:

== (Compares the Memory Address)

• It looks at the outside container.

• It checks if both variables point to the exact same physical spot in your RAM.

.equals() (Compares the Internal Content)

• It looks at the inside cargo.

• It ignores where the objects are stored in memory and checks if the characters match
exactly.

Clean Code Example & Output

Java

public class ComparisonDemo {

public static void main(String[] args) {

String s1 = "apple";

String s2 = new String("apple"); // Forces Java to create a separate memory slot

// 1. Using ==
[Link]("Using == pointer check: " + (s1 == s2));

// 2. Using .equals()

[Link]("Using .equals() content check: " + [Link](s2));

Terminal Output:

Plaintext

Using == pointer check: false

Using .equals() content check: true

Why did this happen?

Even though both variables hold the word "apple", the new keyword forced s2 to sit in a
completely different neighborhood inside your computer's memory.

• == saw two different addresses and said false.

• .equals() looked inside both addresses, saw a-p-p-l-e in both, and said true.

If you do not use the new keyword and instead create your Strings using plain double
quotes (called String Literals), Java activates its efficiency mode to save your RAM.

Here is exactly what happens behind the scenes, short and sweet.

The Rule of the String Constant Pool (SCP)

When you write:

Java

String s1 = "apple";

String s2 = "apple";

1. Line 1 (s1): Java goes to a special neighborhood in your RAM called the String Constant Pool
(SCP). It looks around and asks, "Does the word 'apple' exist here?" It doesn't, so Java
creates one "apple" object in the pool and points s1 to it.
2. Line 2 (s2): Java looks into the pool again and asks, "Does 'apple' exist here?" This time, yes
it does! Instead of wasting memory creating a duplicate copy, Java simply points s2 to the
exact same physical address as s1.

The Result: == and .equals() Both Become TRUE

Because both variables are forced to share the exact same physical spot in memory, both
checks will return true:

Java

public class LiteralDemo {

public static void main(String[] args) {

String s1 = "apple";

String s2 = "apple"; // Shares memory with s1

// 1. == checks if they share the exact same memory address

[Link]("Using == address check: " + (s1 == s2));

// 2. .equals() checks if the internal letters match

[Link]("Using .equals() text check: " + [Link](s2));

Terminal Output:

Plaintext

Using == address check: true

Using .equals() text check: true

Summary Cheat Sheet:

• Without new (String Literal): Identical text values share the same home in RAM. Both ==
and .equals() are true.
• With new keyword: Java is forced to build a brand-new house in RAM every single time. ==
becomes false, and only .equals() stays true.

1. The Core Memory Rules

• Strings are Immutable: Once a String is created in memory, its text can never be changed. If
you alter it, Java just creates a brand-new string object elsewhere.

• String Constant Pool (SCP): A special, cost-saving storage room inside your computer's RAM
(Heap memory) used to store text literals.

2. The Two Ways to Create a String

Way A: Without new (String Literals)

Java

String s1 = "apple";

String s2 = "apple";

• What happens: Java checks the SCP room. It creates "apple" once at an address (e.g., 1000).
When s2 is created, Java reuse the shortcut and points s2 to the exact same address 1000.

• Result: s1 == s2 is true because they share the exact same memory address.

Way B: With the new Keyword

Java

String s1 = "apple";

String s2 = new String("apple");

• What happens: s1 goes to the shortcut pool at address 1000. But the new keyword forces
Java to bypass the pool for s2. It carves out a completely fresh, isolated house in the main
Heap Memory at a brand-new address (e.g., 5000).

• Result: s1 == s2 is false because address 1000 does not match address 5000.

3. == vs .equals() Cheat Sheet

• == (Address Checker): Compares the outside container. It checks if both variables point to
the exact same memory address number (1000 == 5000 is false).

• .equals() (Cargo Checker): Looks inside the containers. It ignores the memory address
numbers and checks if the internal letters match exactly, one-by-one ("apple" matches
"apple" so it is true).
.length() — The Character Counter
• What it does: Counts the total number of characters inside the String, including empty
spaces and symbols.

• Example:

Java

String s = "Hello Roll";

[Link]([Link]()); // Output: 10

.charAt(index) — The Letter Grabber


• What it does: Grabs the single character sitting at a specific index position. Remember, Java
indexing always starts counting from 0.

• Example:

Java

String s = "Apple";

[Link]([Link](0)); // Output: 'A'

[Link]([Link](3)); // Output: 'l'

.toLowerCase() & .toUpperCase() — The Casing


Changers
• What they do: Convert your entire string text into all-lowercase or all-uppercase letters.
Very useful for cleaning up user logins.

• Example:

Java

String s = "ViT";

[Link]([Link]()); // Output: vit

[Link]([Link]()); // Output: VIT


.trim() — The Space Eraser
• What it does: Strips away any accidental empty spaces from the very front and the very
back of a string. It completely leaves the spaces inside the middle of the words alone.

• Example:

Java

String s = " Kattegat Viking ";

[Link]("'" + [Link]() + "'"); // Output: 'Kattegat Viking'

.contains("word") — The Search Scanner


• What it does: Scans the string to check if a specific word or phrase exists inside it. It returns
a simple true or false (case-sensitive).

• Example:

Java

String s = "Cybersecurity Core";

[Link]([Link]("Sec")); // Output: false (It uses a lowercase 's' in the string)

[Link]([Link]("Core")); // Output: true


Jagged array:
Taking input for a jagged array requires a nested loop (a loop inside a loop) because you are dealing
with rows and columns.

• The Outer Loop (i): This acts as a vertical elevator. It starts at Row 0 and moves down to the
last row, controlled by [Link].

• The Inner Loop (j): This acts as a horizontal scanner. It moves across the columns of the
current row.

• The Golden Rule: Because a jagged array has unequal columns, you can never hardcode the
column limit (like j < 3). You must use matrix[i].length so the inner loop dynamically shrinks
or grows to fit that exact row's size.

Code for Your Notes

Java

import [Link]; // Required to capture keyboard input[cite: 1]

public class JaggedArrayInputDemo {

public static void main(String[] args) {

Scanner input = new Scanner([Link]); // Create the input pipeline[cite: 1]

// 1. Declare and allocate rows for a jagged array[cite: 1]

int[][] matrix = new int[3][];

matrix[0] = new int[2]; // Row 0 has 2 columns[cite: 1]

matrix[1] = new int[3]; // Row 1 has 3 columns[cite: 1]

matrix[2] = new int[1]; // Row 2 has 1 column[cite: 1]

[Link]("Enter data for the jagged array:");

// 2. Nested loops for user input[cite: 1]


// Outer loop controls the current row index (i)[cite: 1]

for (int i = 0; i < [Link]; i++) {

// Inner loop adapts to the length of the current row (matrix[i].length)[cite: 1]

for (int j = 0; j < matrix[i].length; j++) {

[Link]("Slot [" + i + "][" + j + "]: ");

matrix[i][j] = [Link](); // Store primitive integer into RAM[cite: 1]

[Link](); // Clean up system resources[cite: 1]

You might also like