Java Notes
Java Notes
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]
}
}
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.
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:
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:
6. Length – No Limit
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:
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.
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];
The nextInt() method parses the token from the input and returns the
integer value.
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]);
Console :
Enter an integer: 69 // 69\n(enter)
Enter a string: age is = 69
In this example:
Solution :
Scanner scanner = new Scanner([Link]);
\ 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.
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 :
[Link](a) Returns the closest value that is greater than or equal to the
argument
[Link]() Returns a double value with a positive sign, greater than or equal to 0.0
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.
[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 :
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.");
}
If Ladder :
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.
Order :byte->short->int->long->float->double
char->int
Example :
int intValue = 42;
double doubleValue = intValue; // Implicit conversion
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++) {}
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);
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.
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.
Example :
int number = 2;
switch (number) {
case 1:
[Link]("One");
case 2:
[Link]("Two");
case 3:
[Link]("Three");
default:
[Link]("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.
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
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).
Address
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.
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!!");
}
}
Example 2:
int n = 5;
for (int i = 1; i <= n; i++) {
[Link]("Hello Duniya!!");
}
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
--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;
}
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;
}
}
|| 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:
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.
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]));
}
}
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]));
}
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.
● Object
● Class
● Inheritance
● Polymorphism
● Abstraction
● Encapsulation
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
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);
}
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";
|| || ||
Strings are stored in a special place in the heap called "String Constant
Pool" or "String Pool".
Example:
String str1 = new String("Pappu");
// New String is created.
// str2 is pointing to the new string value.
String str2 = new String("Pappu");
Comparing Strings
Example:
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.
Syntax
StringBuilder ob = new StringBuilder();
Default Capacity
Method - [Link]()
Constructors of StringBuilder
StringBuilder(int capacity) - Empty String Builder with the provided length capacity.
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
delete(int startIndex, int endIndex) - delete the string from startIndex and endIndex that are provided.
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:
char Character
boolean Boolean
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing
Autoboxing is when the compiler performs the automatic convert the
primitive data types to the object of their corresponding wrapper
classes.
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
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]);
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)
//read boolean value we use makeSupported method which returns the boolean value true if the stream supports mark()
boolean i = [Link]();
} }
|| DAY 27 ||