[Go to site: main page, start]

0% found this document useful (0 votes)
5 views63 pages

Java Notes

The document provides comprehensive notes on Java programming, covering topics such as high-level and low-level languages, the Java Development Kit (JDK), and the process of running Java code. It includes details on syntax, variables, data types, operators, control flow statements, and the use of the Scanner class for user input. Additionally, it explains concepts like packages, methods, and type casting, making it a useful resource for beginners learning Java.

Uploaded by

website665999
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)
5 views63 pages

Java Notes

The document provides comprehensive notes on Java programming, covering topics such as high-level and low-level languages, the Java Development Kit (JDK), and the process of running Java code. It includes details on syntax, variables, data types, operators, control flow statements, and the use of the Scanner class for user input. Additionally, it explains concepts like packages, methods, and type casting, making it a useful resource for beginners learning Java.

Uploaded by

website665999
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 NOTES

Java is a High-Level Language(easy for humans to read and write).

HLL:High-Level Language , Human understandable code.


LLL:Low-level language(machine language), contains only 1's and 0's
and is directly understood by a computer.
JDK :JAVA DEVELOPMENT KIT

● It is a collection of software tools, libraries, java compiler JRE etc.


● It enables developers to write, compile, and run Java programs.
Compiler
● It translates the entire source code of HLL into LLL or an
intermediate code(closer to machine code) in a single step.
● It scans syntax errors.
Interpreter
● The interpreter translates HLL line by line.

WHOLE PROCESS OF RUNNING A JAVA CODE

Java compiler translates source code into byte [Link] JVM (DTL) loads
and executes the byte code. Optionally, some JVMs may choose to
interpret the byte code directly for certain use [Link] combination
of compilation and interpretation allows Java programs to be both
platform-independent (byte code run on any machine).
|| DAY 1 ||

JDK :[Link]
IDE :[Link]

Boiler-plate || Default Code


public class Demo1 {
public static void main(String[] args) {

}
}

Class- Collection of methods and variables. It is concept of OOPs(DTL).

Method - A method is a block of code which performs certain


operations and returns output(DTL).

Entry Point
The main method is the entry point for executing a Java application.

When you run a Java program, The JVM or java compiler looks for
a public static void main(String args[]) method in that class, and the
signature of the main method must be in a specified format for the JVM
to recognize it as its entry point.

If we update the method's signature, the program will throw the


error NoSuchMethodError:main and terminate.
|| DAY 2 ||

Just like we have some rules that we follow to speak English(the


grammar), we have some rules to follow while writing a Java
program. The set of these rules is called Syntax.
Variables
A variable is a container that holds data. This value can be changed
during the execution of the program.

Before use, you need to declare and define it.

1. Variable Declaration:
int age;
String name; //int and string is data types
2. Variable Initialization:

age = 69;
name = "the boys";
3. Combined Declaration and Initialization:

int age = 69;

String name = "the boys";

4. Final Variables (Constants):

final int a = 7;
|| DAY 3 ||
Identifiers- Identifiers are used to uniquely identify the variables.
Identifier is a name given to a variable, class, method, package, or other
program elements.
Rules for Identifiers in Java:

1. Start: Must start with an alphabet or _ or $ NOT with a digit.

2. End: Can end with an alphabet or _ or $ or numeric digit.

3. No Reserved Words : You cannot use Java's reserved words (also


known as keywords) as identifiers.

4. No Special Symbols: Identifiers cannot contain special symbols like @,


#, %, etc. except for underscores (_) and dollar signs ($).

5. No Space : Spaces are not allowed.

6. Length – No Limit

Java is CASE SENSITIVE : Shery and shery is different for java

Keyword and word :Keywords are reserved(built-in) words which has


specific meanings and cannot be used as [Link], class,
static, if, else, while etc.
|| DAY 4 ||
Literal or Constant:

Any constant value which can be assigned to the variable.

DATA TYPES
Data types are used to classify and define the type of data that a
variable can hold.
There are 2 types of Data Types:

[Link] Data types: pre-defined, fixed size.


[Link]-Primitive Data types: Customize and no fixed size.
Default Values
Default Value (for
Data Type
fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false

the compiler never assigns a default value to an uninitialized local


variable(DTL).

+ operator between two char values


● It perform addition between their Unicode code points.
● For example :

char a = 'a';
char b = 'b';
[Link](a+b);//97+98=195

Output : 195
|| DAY 5 ||
Scanner
To take input from users we use Scanner class.

Scanner class is a built-in class in the [Link] package(DTL). Before


using the Scanner class you have to import the Scanner class using the
import statement as shown below:

To use the Scanner class, you need to create an object of it, and then
you can use that object to interact with the input data.

import [Link];

Scanner sc = new Scanner([Link]);//object


int n = [Link]();

The nextInt() method parses the token from the input and returns the
integer value.

Use methods to read respective data


nextByte(), nextShort(), nextInt(),nextLong(),nextFloat(), nextDouble(),
nextBoolean()

Reading String Data

nextLine() - Reads the whole line

next() - Reads the first word

Reading char data–next().charAt(0)


Problem with nextLine() method:
Ifwe try to read String after reading in an Integer, Double or Float etc.

Java does not give us a chance to input anything for the name variable.

When the method [Link]() is called Scanner object will wait for
us, to hit enter and the enter key is a character(“\n”).
Let’s understand this with the example
Scanner scanner = new Scanner([Link]);

[Link]("Enter an integer: ");


int age = [Link]();

[Link]("Enter a string: ");


String name = [Link]();

[Link](name + " age is = " + age);

Console :
Enter an integer: 69 // 69\n(enter)
Enter a string: age is = 69

In this example:

1. We first prompt the user to enter an integer age using nextInt().


2. After reading the integer, we immediately hit enter and enter is
also a character represented by “\n” – 69\n
3. The int value 69 is assigned in age but not the \n still left in the
memory or buffer.
4. In next line when we Call nextLine() to consume the name it first
check in buffer is there any thing as we have \n in buffer it take \n
(for nextLine() method \n is the stopping point it will consider we
stop giving input and return) and skip the line.

Solution :
Scanner scanner = new Scanner([Link]);

[Link]("Enter an integer: ");


int age = [Link]();

// Consume the newline character left in the input buffer


[Link]();

[Link]("Enter a string: ");


String name = [Link]();

[Link](name + " age is = " + age);

1. After taking an integer input we Call nextLine() to consume the name


character left in the input [Link] next line when we Call nextLine() to
consume the name character left in the input buffer.
2. Then, we prompt the user to enter a string using nextLine().

\ is a special symbol
\n (next Line), \b (backspace), \t (tab), \" (double quote), \' (single
quote), and \\ (backslash).
|| DAY 6 ||

Operators
Operator in java is a symbol that is used to perform operation.

Types of Operator & Precedence

Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative */%
additive +-
shift <<>>>>>
relational < > <= >=
equality == !=
bitwise AND &
bitwise
^
exclusive OR
bitwise
|
inclusive OR
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
RULES for Increment and Decrement :

● Can only be applied to variables only


Example : int b = ++a;
Int c = ++10; // compile-time error

● Nesting of both operators is not allowed


Example :int a = 10;
Int b = ++(++a); // compile-time error

● They are not operated over final variables


Example : final int a = 10;
int b = ++a; // compile-time error

● Increment and Decrement Operators can not be applied to booleans.


Example : boolean = false;
a++;

Quiz On Increment And Decrement Operators :


[Link]
|| DAY 7 ||
Package
A Java package is a collection of similar types of sub-packages,
interfaces, and [Link] help you manage and group related classes,
interfaces, and sub-packages to avoid naming conflicts and create a
more organized and maintainable codebase.
Example:

Directories or folders on your computer's file system(manage files).

In Java, there are two types of packages: built-in packages and


user-defined packages.
in-built packages : They are available in Java, including util, lang, awt
etc. We can import all members of a package using package
name.* statement

[Link] package is a special package that is automatically imported by


default in every Java class.
Commonly used classes and types from the [Link] package
include:Primitive Data Types (int, float etc.), String, System, Math etc.
User-defined packages : User-defined packages are those that the users
define. Inside a package, you can have Java files like classes, interfaces,
and a package as well (called a sub-package).
Math Class
[Link] class is a built-in class. It provides mathematical
functions and constants for mathematical operations.

Commonly used methods and constants:

[Link](a) Returns the absolute value of a value.

[Link](a) Returns the sqrt root of a double value.

[Link](a) Returns the closest value that is greater than or equal to the

argument

[Link](a, b) Returns the greater of two values.

[Link](a, b) Returns the smaller of two values.

[Link](a, b) Returns a raised to the power of b.

[Link]() Returns a double value with a positive sign, greater than or equal to 0.0

and less than 1.0.

[Link], [Link](a)(closest value that is greater than or equal to the


argument) etc.
|| DAY 8 ||

CONTROL-FLOW STATEMENTS
Control Flow statements in programming control the order of execution
of statements within a program. They allow you to make decisions,
repeat actions, and control the flow of your code based on conditions.

Types of control flow statements


1. Conditional or Decision Making statements (if-else and switch)
2. Looping statements (for, while, and do-while)
3. Branching statements (break and continue)

[Link] statementsIf-else :
The if-else statement allows you to execute a block of code
conditionally.
If the condition inside the if statement is true, the code inside the if
block is executed;
otherwise, the code inside the else block is executed.
Syntax of if-else :
int age = 30;
if(age >18) {
[Link]("Adult");//executes if condition is true
}else {
[Link]("Abhi chote ho"); //condition false
}
If-Else-If Ladder :

"If-Else-If" ladder consists of an if statement followed by multiple else-if


statements. It is used to evaluate a condition using multiple statements.
The chain of if statements are executed from the top-down.

It checks each if condition, and as soon as one of the if condition


yields true, it executes the statement inside that if block and skip the
rest of the ladder. If none of the conditions evaluates to be true, then
the program executes the statement of the final else block.

For example :
int number = 10;
if (number % 2 == 0) {
[Link]("Number is even.");
}
else if (number % 2 != 0) {
[Link]("Number is odd.");
}
else {
[Link]("Invalid input.");
}

Output : Number is even

If Ladder :

"If" ladder consists of an multiple if statements. It is used to evaluate a


condition using multiple statements. The chain of if statements are
executed from the top-down.

The program checks each if condition, and as soon as one of


the if condition yields true, it executes the statement inside that if block
and still check further conditions. If none of the conditions evaluates to
be true, then the program executes the statement of the
final else block.
int number = 10;
if (number >0) {
[Link]("Number is positive.");
}
if (number <20) {
[Link]("Number is less than 20.");
}
if (number % 2 == 0) {
[Link]("Number is even.");
}

Output :Number is positive


Number is less than 20.";
Number is even.
|| DAY 11 ||
Ternary Operator
The ternary operator also known as the conditional operator, is a
shorthand way of writing an if-else statement with a single expression.

The ternary operator has the following syntax:

condition ? expression1 : expression2

Here's how it works:

● If the condition is true, the expression before the : (i.e.,


expression1) is evaluated and returned.
● If the condition is false, the expression after the : (i.e.,
expression2) is evaluated and returned.

int num = ;
String result = (num % 2 == 0) ? "Even" :"Odd";
[Link]("The number is " + result);

Output : Even

Type Conversion
Type casting in Java is the process of converting one data type to
another. It can be done automatically or manually.

Type Casting in Java is mainly of two types.

1. Widening or Implicit Type Casting


2. Narrow or Explicit Type Casting
[Link] or Implicit Conversion:
● Java allows automatic type conversion when a smaller data type is
promoted to a larger data type..
● It is secure since there is no possibility of data loss.
● Both the data types must be compatible with each other :
converting a string to an integer is not possible as the string may
contain alphabets that cannot be converted to digits.

Order :byte->short->int->long->float->double

char->int

Example :
int intValue = 42;
double doubleValue = intValue; // Implicit conversion

[Link] or Narrowing Conversion:


● Sometimes, we need to convert a larger data type to a smaller one
explicitly and it requires a cast operator.
● Narrowing Type Casting in Java is not secure as loss of data can
occur due to shorter range of supported values in lower data type.

Example :
double doubleValue = 42.0;
int intValue = (int) doubleValue; // Explicit
conversion (casting)
|| DAY 12 ||
Looping statements
When we want to perform certain tasks again and again till a given
condition.
For e.g. : Our daily routine, certain song listen again & again
Looping is a feature that facilitates the execution of a set of instructions
repeatedly until a certain condition holds false.
e.g. : print 1 to 10,000 number
Types of Loop
Categorized into two main types
[Link] Controlled
Check the loop condition before entering the loop body. If the condition
is false initially, the loop body will not execute at all.
for and while loops are examples of entry-controlled loops as we check
the condition first and then evaluate the body of the loop..
a. for loop
When we know the exact number of times the loop is going to run, we
use for loop.
Syntax:
for(declaration,Initialization ; Condition ; Change){
// Body of the Loop (Statement(s))
}
Example :
for (int i = 1; i<= 5; i++) {
[Link](i);//run 1 to 5
}

Output : 1 2 3 4 5

FLOW DIAGRAM

Optional Expressions :
In loops, initialization, condition, & update are optional. Any or all of
these are [Link] loop essentially works based on the semicolon ;
// Empty loop
for (;;) {}

// Infinite loop
for (int i = 0;; i++) {}

// initialization needs to be done outside the loop


// i and n needs to be defined before
for (; i< n; i++) {}
Syntax tweaks
● Initialize the variable outside the loop.
● Multiple conditions.
● Increment or Decrement of variable inside loop body
An infinite loop is a loop that continues executing indefinitely, and it
doesn't have a condition that will terminate the loop naturally.
for (;;){
[Link]("This is an infinite loop");
}

In the above code there is no initialization, no condition, and no


iteration expression, meaning it will run indefinitely unless explicitly
terminated.
for(;;);

This is another example of an infinite loop, but this time, there is no


code or statements within the loop. It's just an empty loop that will run
indefinitely.
As the loop has started but it never ends, you terminate it by ; it never
comes out of the loop and if you write any code after this loop, it will be
unreachable because the loop never terminates.
|| DAY 13 ||
while loop
The while loop is used when the number of iterations is not known but
the terminating condition is known.
Loop is executed until the given condition evaluates to false.
Syntax:
// intialization
// while (condition){
// Body of the loop
// Updation
// }

Example :

int i=0;
while (i<5){
[Link](i);
i++;
}

Output :0 1 2 3 4
FLOW DIAGRAM

While always accepts true, if you initially give a false condition (not
Boolean false) it will neither give a syntax error nor enter in the loop.
int i=0;
while (i>9){// false condition but no syntax error
[Link](i);
}

While loop always accepts true ,if you initially give false(Boolean value)
it will give syntax error.
while (false){ //Syntax error (Pura Pura Laal hai)
[Link](“Hello LOLU”);
}
|| DAY 14 ||

do-while Loop
The do-while loop is like the while loop except that the condition is
checked after evaluation of the body of the loop. Thus, the do-while
loop is an example of an exit-controlled loop.

This loop runs at least once irrespective of the test condition, and at
most as many times the test condition evaluates to true.
Syntax :
Initialization;
do {
// Body of the loop (Statement(s))
// Updation;
}
while(Condition);

Example :
int i=1;
do {
[Link]("Hii");
i++;
}while (i<3);

Output :Hii Hii


FLOW DIAGRAM

The code inside the do while loop will be executed in the first step.
Then after updating the loop variable, we will check the necessary
condition; if the condition satisfies, the code inside the do while loop
will be executed again. This will continue until the provided condition is
not true.

Infinitive do-while Loop


int i = 0;
do{
i++;
}while(i> -1);

There will be no output for the above code also, the code will never
end. Value of initialize to 0 then increment by 1 so it can never be -1
hence the loop will never end.
|| DAY 15 ||
Switch Statements
The switch statement is a control flow statement that allows you to
select one of many code blocks to be executed based on the value of an
[Link] simple words, the Java switch statement executes one
statement from multiple conditions.

Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default: // optional
// code block to be executed if no cases match
}
Example
char ch = 'a';
switch (ch) {
case 'a':
[Link]("Vowel");
break;
case 'e':
[Link]("Vowel");
break;
case 'i':
[Link]("Vowel");
break;
case 'o':
[Link]("Vowel");
break;
case 'u':
[Link]("Vowel");
break;
default:
[Link]("Consonant");
}
Output : Vowel
● The value of the ch variable is compared with each of the case
values. Since ch = a, it matches the first case value and ch – ‘a’:
Vowel is printed.
● The break statement in the first case breaks out of the switch
statement.

Important Points about Java's switch statement:

● No variables: The case value must be a literal or constant.


● No duplicates: No two cases should be of same value. Otherwise,
a compilation error is thrown.
● Allowed Types: int, long, byte, shortand String type. Primitives are
allowed with their wrapper types.
● Optional Break Statement: Break statement is optional. If a case is
matched and there is no break statement mentioned, subsequent
cases are executed until a break statement or end of the switch
statement is encountered (fall through statement).
● Optional default case: default case value is optional.
The default statement is meant to execute when there is no match
between the values of the variable and the cases. It can be placed
anywhere in the switch block .

Multiple cases can be combined together with commas


char ch = 'a';
switch (ch) {
case 'a','e','i','o','u' :
[Link]("Vowel");
break;
default:
[Link]("Consonant");
}
Fall through statement

A fall-through statement occurs when there is no break statement at


the end of a case block. When a case block does not have a break
statement, the code execution continues to the next case block, even if
the condition for that case is not met. This behavior is known as
fall-through.

Example :
int number = 2;

switch (number) {
case 1:
[Link]("One");
case 2:
[Link]("Two");
case 3:
[Link]("Three");
default:
[Link]("Default");
}

Output : Two Three Default

It executed the code for case 2, then continued to case 3, and finally to
the default block.

Arrow Switch
int number = 2;
switch (number) {
case 1 -> [Link]("One");
case 2 -> [Link]("Two");
case 3 -> [Link]("Three");
default -> [Link]("Default");
}
It simplifies code and eliminates the need for explicit break statements.

yield keyword
yield keyword is used in combination with the new switch expression
introduced in Java 12 to return a value from a switch expression.

It allows you to specify the value to be returned from a particular case


block in the switch expression.
int dayOfWeek = 3;
String dayName = switch (dayOfWeek) {
case 1 :yield "Monday";
case 2 : yield "Tuesday";
case 3 : yield "Wednesday";
case 4 : yield "Thursday";
case 5 : yield "Friday";
default : yield "Unknown";
};
[Link]("Day of the week is: " + dayName);

Output :Day of the week is: Wednesday


|| DAY 16 ||
Nested Loops
Nested loop means a loop statement inside another loop statement.
That is why nested loops are also called as “loop inside loop“.

for loops, while loops, and do-while loops, and you can nest any of
these loop types inside one another.
for ( initialization; condition; increment ) {
for ( initialization; condition; increment ) {
// statement of inside loop
}
// statement of outer loop
}

Note: There is no rule that a loop must be nested inside its own type. In
fact, there can be any type of loop nested inside any type and to any

level.
|| DAY 17 ||
Array
An array is a linear data structure used to store a collection of elements
of the same data type in contiguous memory locations.
Arrays in Java are non-primitive data types and it can store
both primitive and non-primitive types of data in [Link] are fixed in
size, meaning that when you create an array you need to give specific
size and you cannot change the size later.
Declaring an Array
DataType[] arrayName;

Creating an Array

After declaring an array, you need to create an actual instance of the


array with a specific size using the new keyword. For example, to create
an array of integers with a size of 5:
int[] numbers = new int[5];

size and initialization can't be done together

int[] arr = new int[3]{1, 2, 3}; // compilation err


// You can to this
int[] arr = new int[]{1, 2, 3};
int[] arr = {1, 2, 3};

Stack memory holds the references while Heap memory holds the
actual object:
Stack: It is memory in which the size of the stack is limited and
predefined during program execution. Exceeding this limit can result in
a StackOverflowError(DTL)

Heap: The heap memory in Java can grow and shrink dynamically(DTL).

● Reference of the array is stored on the stack(int[] arr).


● Reference is essentially a memory address that points to the
location in the heap where the actual array object is stored.

Address

Contiguous Elements: The elements of the array are stored in


contiguous memory locations. This means that the memory addresses
for each element are sequential. The memory address of the first
element in the array is the base address of the array.

Internally the address is in hexadecimal number (combination of


alphabets & numeric characters) this is just for your understanding (we
take 100,104,108 etc).

In Java you cannot access the memory directly, you generally work with
higher-level abstractions, and the specifics of memory addresses are
hidden from you & handled by the Java Virtual Machine (JVM).
Elements in the array are accessed by their index. When you use an
index to access an element, Java calculates the memory address of that
element using the base address of the array and the size of the
elements.

Address = Base address + (index * 4)

Address of 1st index = 100 + (1*4) = 104

Enhanced for loop || for-each loop


The for-each also called as enhanced for loop, was introduced in Java 5.
It is one of the alternative approaches that is used for traversing arrays.
Traverse the array without using the index & makes the code simple as
it reduces the code length.
Syntax:
for(datatype element : arrayName) {
// Code
}

Example:
int arr[] = {1, 2, 3};
for (int elem : arr) {
[Link](elem + ", ");
}
Output: 1, 2, 3
|| DAY 18 ||

Complexity
Complexity in algorithms refers to the amount of resources (such as
time or memory) required to solve a problem or perform a task.
Algorithm: An algorithm is a well-defined sequential computational
technique that accepts a value or a collection of values as input and
produces the output(s) needed to solve a problem.
Example: Seen someone cooking your favorite food for you? Is the
recipe necessary for it? Yes, it is necessary as a recipe is a sequential
procedure that turns a raw potato into a chilly potato. This is what an
algorithm is: following a procedure to get the desired output. Is the
sequence necessary to be followed? Yes, the sequence is the most
important thing that has to be followed to get what we want.

TIME COMPLEXITY
The Time Complexity of an algorithm/code is not equal to the actual
time required to execute a particular code. You will get different timings
on different machines.
Instead of measuring actual time required in executing each statement
in the code, Time Complexity considers how many times each
statement executes.
It is defined as the number of times a particular instruction set is
executed rather than the total time taken.
Example 1 :
public class Demo {
public static void main(String[] args) {
[Link]("Hello Duniya!!");
}
}

Hello World” is printed only once on the screen.


So, the time complexity is constant: O(1)

Example 2:
int n = 5;
for (int i = 1; i <= n; i++) {
[Link]("Hello Duniya!!");
}

Hello World” is printed n times on the screen.


So, the time complexity is constant: O(n)

Complexity Representation
There are major 3 notations –
Big Oh - O(N) - Upper bound : The maximum amount of time required
by an algorithm considering all input values. This is how we define the
worst case of an algorithm's time complexity.
Big Omega - Ω(N) - Lower bound: The minimum amount of time
required by an algorithm considering all input values also the best case
of an algorithm's time complexity.
Theta - θ(N) - Lower & Upper Bound: average bound of an algorithm. In
this we know algorithm will take exactly N steps
Time complexity graph

We always check the worst time complexity or maximum amount of


time required by an algorithm considering all input values.

There are different types of time complexities used


1. Constant time – O (1)
2. Linear time – O (n)
3. Logarithmic time – O (log n)
4. Quadratic time – O (n^2)
5. Cubic time – O (n^3)

Time Limit Exceed(TLE)


Machine can perform 10^8 op / second
MAX value of N Time complexity
10^9 O(logN) or Sqrt(N)
10^8 O(N) Border case
10^7 O(N) Might be accepted
10^6 O(N) Perfect
10^5 O(N * logN)
10^4 O(N ^ 2)
10^2 O(N ^ 3)
<= 160 O(N ^ 4)
<= 18 O(2 *N )
N 2

<= 10 O(N!), O(2 )


N

--make your code within the upper bound limit or constraints (limit).
Space Complexity
The space Complexity of an algorithm is the total space taken by the
algorithm with respect to the input size. Space complexity includes both
Auxiliary space and space used by input.
Auxiliary Space is the extra space or temporary space used by an
algorithm.
Space complexity is a parallel concept to time complexity. If we need to
create an array of size n, this will require O(n) space. If we create a
two-dimensional array of size n*n, this will require O(n2) space.

|| DAY 19 ||
Methods
● It is a block of code that performs a specific task.
● A method runs or executes only when it is called.
● Methods provide for easy modification and code reusability. It will
get executed only when invoked/called.
Method Signature / Method Prototype / Method Definition
A method in Java has various attributes like access modifier, return
type, name, parameters etc.
Methods can be declared using the following syntax:
accessModifier returnType methodName(parameters..){
//logic of the function}
Example :
public static int sum(int a, int b) {
int sum = a+b;
return sum;
}

Here, public - access modifier || static - special specifier


int - return type
sum - method name || int a and int b - parameter
Access Modifiers
Access Modifier Within Class Within package Subclass outside Outside
package package

Private ✅ ❌ ❌ ❌

Protected ✅ ✅ ✅ ❌

Default ✅ ✅ ❌ ❌

Public ✅ ✅ ✅ ✅
Methods mainly are of two type -
● Static
● Non-static
Static Method
● A method declared as static does not need an object of the class to
invoke it.
● All the built-in methods are static - min, max, sqrt etc. called using
Math class name
Example :
public class Demo {
public static void main(String args[]){
[Link](1,2);//call by classname
}
// static method
public static int sum(int a, int b){
int sum = a+b;
return sum;
}
}

Non-Static Method or Instance Method


● Non-Static Method or Instance methods are attached to the
objects of a class, rather than the class itself.
● In simple words, you need to create an object to invoke them.
Example :
public class Demo {
public void main(String args[]){
Demo obj = new Demo();
[Link](1,2);//call by object reference
}
// static method
public static int sum(int a, int b){
int sum = a+b;
return sum;
}
}

|| DAY 20 ||

Arguments
An argument is a value passed to a function when the function is called.
A parameter is a variable used to define a particular value during a
method definition.
In common we call both parameter and argument as either
parameter/argument.
Classification of Arguments
Formal argument : The identifier used in a method at the time of
method definition.
Example:
returnType methodName(dataType parameterName1, dataType p2) {
// body
}

Actual argument : The actual value that is passed into the method at
the time of method calling.
Example:
methodName(argumentValue1, argumentValue2);

Arguments Passing
1. Pass By Value:
When we pass only the value part of a variable to a function as an
argument, it is referred to as pass by value.

Any change to the value of a parameter in the called method does not
affect its value in the calling method.

As can be seen in the figure below, only the value part of the variable is
passed i.e. a copy of the existing variable is passed instead of passing
the origin variable. Hence, any changes done to the value of the copy
will not have any impact on the value of the original variable. Java
supports pass-by-value.
Example:

public class Main{


public static void solve(int a){
a = a+10; // changes inside called method
}
public static void main(String[] args) {
int a = 10;
[Link]("Value of a "+ a);
solve(a);
[Link]("Value of a "+ a);
}
}

Output : Value of a 10
Value of a 10
2. Pass by reference: Not supported by Java
In pass-by-reference, changes made to the parameters inside the
method are also reflected outside. Though Java does not support
pass-by-reference.
In Java, when we create a variable of class type or non primitive , the
variable holds the reference to the object in the heap memory. This
reference is stored in the stack memory. The method parameter that
receives the object refers to the same object as that referred to by the
argument.
Thus, changes to the properties of the object inside the method are
reflected outside as well. This effectively means that objects are passed
to methods by use of call-by-reference.

Changes to the properties of an object inside a method affect the


original argument as well. However, if we change the object altogether,
then the original object is not changed. Instead a new object is created
in the heap memory and that object is assigned to the copied reference
variable passed as argument.

Pass by Value for non-primitives


Example:

class PassByValue {
public static void main(String[] args) {
Integer[] array = new Integer[2];
array[0] = 2;
array[1] = 3;
add(array);
[Link]("Result from main: " + (array[0] + array[1]));
}
private static void add(Integer[] array) {
array[0] = 10;
[Link]("Result from method: " + (array[0] + array[1]));
}
}

Output : Result from method: 13


Result from main: 13
The called method is able to modify the original object but not replace
it with another object.

Example:

class PassByValue {
public static void main(String[] args) {
Integer[] array = new Integer[2];
array[0] = 2;
array[1] = 3;
add(array);
[Link]("Result from main: " + (array[0] + array[1]));
}

public static void add(Integer[] array) {


array = new Integer[2];
array[0] = 10;
array[1] = 3;
[Link]("Result from method: " + (array[0] + array[1]));
}
}
}

Output : Result from method: 13


Result from main: 5
Here, we can see that if we reinitialize the array object, which is passed
in arguments, the original reference breaks(i.e., we have replaced the
original object reference with some other object reference), and the
array no longer is referenced to the original array. Hence the value in
the main() method didn’t change.
Points to Remember
● Java supports pass-by-value only.
● Java doesn’t support pass-by-reference.
● Primitive data types and Immutable class objects strictly follow
pass-by-value; hence can be safely passed to functions without
any risk of modification.
● For non-primitive data types, Java sends a copy of the reference to
the objects created in the heap memory.
● Any modification made to the referenced object inside a method
will reflect changes in the original object.
● If the referenced object is replaced by any other object, any
modification made further will not impact the original object.

Varargs (...)
Varargs also known as variable arguments is a method that takes input
as a variable number of arguments.
The varargs method is implemented using a single dimension array
internally. Hence, arguments can be differentiated using an index. A
variable-length argument can be specified by using three-dot (...) or
periods.

Syntax
public static void solve(int ... a){
// method body
}

Rules
● There can be only one varargs in a method
● If there are other parameters then varargs must be declared in the
last.
|| DAY 21 ||
Multi D Arrays
Multidimensional Arrays can be thought of as an array inside the array
i.e. elements inside a multidimensional array are arrays themselves.

Multidimensional arrays, like a 2D array, are a bunch of 1D arrays put


together in an array. A 3D array is like a bunch of 2D arrays put together
in a 1D array, and so on.

To access array elements in multidimensional arrays,more than one


index is used.

General syntax to initialize the array:

arrayName = new DataTye[length 1][length 2]....[length N];

int[ ][ ] twodArray= new int[3][3];


|| DAY 22 ||
OOPS Introduction
OOPs is a programming paradigm (procedure or method )to solve real
world problems.
It is a way of organizing and designing code to model real-world entities
and their interactions. The main purpose of OOPs programming is to
implement ideas and solve real-world problems.
OOPs (Object Oriented Programming System) refer to languages that
use objects in programming.
Main pillars of OOPs:

● Object
● Class
● Inheritance
● Polymorphism
● Abstraction
● Encapsulation

Classes and objects are the building blocks of an object-oriented


programming language.
Class:
● If we want to store different types of data we use class.
● Class is a user-defined or customized data type.
● Class is not a real world entity. It is just a template or blueprint or
prototype of an object.
● Also, it doesn't occupy any memory.
● Class is a collection of objects.
For example – Animal, car, Birds etc. all are categories not a real world
entity.
Syntax:
accessModifier class ClassName{
//attributes
//methods
}

Object:
● Object is an instance(part) of a class.
● Object is a real world entity.
● Object occupies memory.
For example – Dog, cat (type of animal).
Verna, MG hector, Jeep (type of car).
Object consists of –
● Identity - Unique Name
● State | Attribute - color, breed, age [DOG] (represent by variable)
● Behavior – run, eat, bark etc [DOG] (represent by methods)
Syntax : –
className obj = new className();
The new keyword is responsible for allocating memory for objects.
Example :
Animal obj = new Animal();
Here, Animal () is a constructor.
Lets, understand this through the example

public class Student {


String name;
int age;
String year;

public void printInfo() {


[Link]("Student{ name='" + name + '\''
+ ", age=" + age + ", year='" + year + '\'' + '}');
}
public static void main(String[] args) {
Student s1 = new Student();
[Link] = "Golu";
[Link] = 69;
[Link] = "I";
[Link]();//call method
}
}

Here, we initialize object by reference


If we want to initialize multiple variables then initializing by reference is
not an efficient way.
Then we use a constructor.
Constructor:
● It is a special type of method.
● Called at the time of object creation.
● Responsible for initializing the object.

Rules –
● Same name as the class
● Never have any return type not even void.
● Cannot make static.
Types –
[Link]|No-Arg Constructors|No Parameterized Constructor
● Do not have any arguments.
● Created by default in Java when no constructors are written
by the programmer.
2. Parameterized Constructor
● Constructors with one or more arguments..
● It is possible to write multiple constructors for a single class.
For example
public Student() {
String name;
int age;

Student(String stuName) {
name = stuName;
}
Student(String stuName, String stuAge) {
name = stuName;
age = stuAge;
}
}

When you use the same name for data members (instance variables)
and constructor parameters in a class, it can lead to ambiguity for the
compiler.
In such cases, you can use the "this" keyword to clarify which variable
you are referring to.
public Student() {
String name;
int age;

Student(String name) {
[Link] = name;
}
Student(String name, String age) {
[Link] = name;
[Link] = age;
}
}

this keyword helps the compiler understand whether you are working
with the local parameter or the instance variable that shares the same
name.
● Represent the current calling object.

|| DAY 23 ||
Overloading - Method, Constructor
Create methods having the same name but differ in the -
● type(data type) of parameters
● number of parameters.
● Sequence or order of parameters.
Rules :
● Must change number, type, or order of parameters.
● Can change the return type.
● Can change the access modifier
Example :
public class Sum{
public int sum(int a, int b) {
return (a + b);
}
public int sum(int a, int b, int c) {
return (a + b + c);
}
public double sum(double a, double b) {
return (a + b);
}

public static void main(String[] args) {


Sum s = new Sum();
[Link]([Link](3, 2));
[Link]([Link](2, 2, 4));
[Link]([Link](10.5, 20.5));
}
}

This is how we achieve method overloading.

Polymorphism
● Polymorphism is one of the main aspects of Object-Oriented
Programming(OOP).
● “Poly” means many and “Morphs” means forms.
● The ability of a message to be represented in many forms.
Polymorphism is mainly divided into two types.

● Compile-time polymorphism
● Runtime polymorphism(DTL)
Compile-time polymorphism can be achieved by method overloading.
The decision of which method to call is made by the compiler at
compile time based on the method's name and the number and types
of its parameters.
It's also referred to as "early binding" or "static polymorphism" because
the determination of which method to call is static and known at
compile time.
Static in detail(DTL).
|| DAY 24 ||
String API
● If we need to store any name or a sequence of characters then we
use String.
● String is an array of characters or sequence of characters.
● Java platform provides the String class to create strings.
Syntax
String stdName = "Pappu";

|| || ||

DataType variableName Array of Characters


String str = "abc"; is equivalent to: char data[] = {'a', 'b', 'c'};

String is an array of characters. Let us see how to create string objects.


String object can be created using two ways:

1. Using String Literal.


2. Using new keywords.

Using String Literal and String Constant Pool


A literal, in computer science, is a notation used for representing a
value.

String literal can be created and represented using the double-quotes.


All of the content/characters can be added in between the double
quotes.
For example :
String name = "apkasubhnaam";

Strings are stored in a special place in the heap called "String Constant
Pool" or "String Pool".

String Constant Pool


● The string constant pool is a storage area in the heap memory that
stores string literals.
● When a string is created, the JVM checks if the same value exists
in the string pool.
● If it does, the reference to that existing object is returned.
Otherwise, a new string object is created and added to the string
pool, and its reference is returned.

String str1 = "Pappu";


// New String is not created.
// str2 is pointing to the old string value only.
String str2 = "Pappu";

Using New Keyword


Strings can be created using the new keyword. When a string is created
with new, a new object of the String class is created in the heap
memory, outside the string constant pool.

Unlike string literals, these objects are allocated separate memory


space in the heap, regardless of whether the same value already exists
in the heap or not.
Syntax : String str = new String("string_value");

Example:
String str1 = new String("Pappu");
// New String is created.
// str2 is pointing to the new string value.
String str2 = new String("Pappu");

Let’s understand through example


String str1 = "Program";
String str2 = "Program";
String s = new String("Program");

In memory it stored like this -


Methods of Java Strings
length(), charAt(int index),substring(int beginIndex, int endIndex[optional])
, contains(), toUpperCase(), toLowerCase(), equals(), join() etc.
For more methods : [Link]

Comparing Strings

● Avoid using == (compare value and address both)


● Use equals()(it compares only value)
● compareTo() :[[Link](string2)] It returns a +ve integer if
string1 is greater than string2, -ve if string2 is greater than string1, and zero if
both are equal.

Java Strings: Mutable or Immutable


● Strings are immutable.
● Means their values cannot be changed once initialized.

Example:

String str = "Chacha";


[Link](str1);// Output: Chacha
str = str + “ and Chachi”;
[Link](str1);// Output: Chacha and Chachi

Above, when we concatenate a string " and Chachi" with str, a new
string value is created. str then points to this newly created value, while
the original value remains unchanged or the actual string value remains
unchanged. This behavior demonstrates the immutability of strings.
|| DAY 25 ||
StringBuilder
StringBuilder in Java is an alternative to the String class.

It is used for storing the mutable (changeable) sequence which means


we can update the elements of the StringBuilder class without creating
a new StringBuilder sequence in memory.

Syntax
StringBuilder ob = new StringBuilder();

Default Capacity
Method - [Link]()

● 16 bytes is the default capacity of the StringBuilder when


StringBuilder contains no elements.
● When the StringBuilder capacity gets full. Internally StringBuilder
updates the capacity by (previous Capacity+1)*2.
● [Link]() and [Link]() are the two
different methods.

Constructors of StringBuilder

StringBuilder() - Generates Empty String Builder with 16-character capacity.

StringBuilder(int capacity) - Empty String Builder with the provided length capacity.

StringBuilder(String) - The provided string is used to generate a String Builder.

Length of string + 16 characters capacity.

StringBuilder(char) - Generates Empty String Builder with capacity char ASCII


Methods of StringBuilder
append(String s) - append the specified string to the provided string.

insert(int offset, String s) - insert the provided string at the designated place.

replace(int startIndex,int endIndex,String str) - string from the startIndex and endIndex values are replaced

using this method.

delete(int startIndex, int endIndex) - delete the string from startIndex and endIndex that are provided.

reverse() - It is used to reverse the string.

capacity() - return the current capacity.

ensureCapacity(int cap ) - make sure that the capacity is at least equal to the cap(input).

substring(int beginIndex) - substring starting at the beginIndex till end is returned using it.

substring(int beginIndex, int endIndex) - retrieve the substring starting at the beginIndex and endIndex values.

|| DAY 26 ||

Wrapper Classes
Wrapper classes in Java provide a way to represent the value of
primitive data types as an object.
● In the Collection framework, Data Structures such as ArrayList
store data only as objects and not the primitive types.
● As a result, Wrapper classes are needed as they wrap or
represent the values of primitive data types as an object and
its vice versa is also possible.
Below are the Primitive Data Types and their corresponding Wrapper
classes:

Primitive Data Type Wrapper Class

char Character

boolean Boolean

byte Byte

short Short

int Integer

long Long

float Float

double Double

Creating Wrapper Objects


Using the wrapper class and its constructor by passing a value to it
Integer number = new Integer(77);//int
Integer number2 = new Integer("77");//String
Float number3 = new Float(77.0);//double argument
Float number4 = new Float(77.0f);//float argument
Float number5 = new Float("77.0f");//String
Character c1 = new Character('S');//Only char
Character c2 = new Character(1234);//COMPILER ERROR
Boolean b = new Boolean(true);//value stored - true
This way of creating an instance of wrapper classes using constructor is
deprecated as of the latest version of JDK.

Creating the object using the wrapper class.


Integer intValue = 10;
Double doubleValue = 8.89;
Character charValue = 'S';

Autoboxing
Autoboxing is when the compiler performs the automatic convert the
primitive data types to the object of their corresponding wrapper
classes.

For example, converting an int to Integer, a double to Double, etc.


int a = 10;
Integer intValue = a;

Unboxing
● It is just the opposite process of autoboxing.
● Unboxing is automatically converting an object of a wrapper type
(Integer, for example) to its corresponding primitive (int) value.
Integer a=new Integer(5);
//Converting Integer to int explicitly
int first=[Link]();
double first=[Link]();
Useful Method & Parsing Strings
parseInt() - Returns an Integer type value of a specified String representation
int a = [Link]("69");//String to int

you can also parseDouble, parseLong, parseFloat etc.

valueOf() - Returns an Integer object holding the value of the specified


primitive data type value.
String a = [Link](7);//a = 7(String)
Integer a = [Link](“7”);a = 7(Integer)
Double a = [Link](“21”);//a = 21.0

BufferedReader API
● BufferedReader & Scanner class both are sources that serve as
ways of reading inputs.
● Scanner class is a simple text scanner that can parse primitive
types and strings.
● BuffereReader reads text from a character-input stream, buffering
characters so as to provide for the efficient reading of the
sequence of characters.

Syntax :
InputStreamReader inpSReader = new InputStreamReader([Link]);

BufferedReader reader = new BufferedReader(inpSReader);

We create a BufferedReader object through the newly created object of


InputStreamReader(It reads bytes and decodes them into characters).
Difference Between Scanner And BufferedReader
BufferedReader :
● BufferedReader uses buffering to read a sequence of characters
from a character-input stream.
● BufferedReader allows changing the size of the buffer.
● BufferedReader has a larger default buffer size (8 KB).

Scanner :
● Scanner can parse primitive types and strings using regular
expressions.
● Scanner has a fixed buffer size
● Scanner has a smaller buffer size (1 KB)

Methods of Java BufferedReader


read() : Reads a single character.

readLine() : Reads a line of text.

To read input using BufferReader


public class ReadInput{

public static void main(String[] args) throws IOException {

BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));

String s = [Link](); // read String

int i = [Link]();//read Int

char i = (char)[Link]();//read char

//read boolean value we use makeSupported method which returns the boolean value true if the stream supports mark()

boolean i = [Link]();

} }
|| DAY 27 ||

You might also like