Java Notes-2.
Java Notes-2.
Java compiler translates source code into byte code.The JVM (DTL) loads
and executes the byte code. Optionally, some JVMs may choose to
interpret the byte code directly for certain use cases.This combination
of compilation and interpretation allows Java programs to be both
platform-independent (byte code run on any machine).
|| DAY 1 ||
JDK :https://www.oracle.com/java/technologies/downloads/#jdk21-windows
IDE :https://www.jetbrains.com/idea/download/?section=windows
}
}
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';
System.out.println(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 java.util.Scanner;
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 input.nextLine() 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(System.in);
Console :
Enter an integer: 69 // 69\n(enter)
Enter a string: age is = 69
In this example:
Solution :
Scanner scanner = new Scanner(System.in);
\ 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 :
Math.ceil(a) Returns the closest value that is greater than or equal to the
argument
Math.random() 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.
1.Conditional 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) {
System.out.println("Adult");//executes if condition is true
}else {
System.out.println("Abhi chote ho"); //condition false
}
If-Else-If Ladder :
For example :
int number = 10;
if (number % 2 == 0) {
System.out.println("Number is even.");
}
else if (number % 2 != 0) {
System.out.println("Number is odd.");
}
else {
System.out.println("Invalid input.");
}
If Ladder :
int num = ;
String result = (num % 2 == 0) ? "Even" :"Odd";
System.out.println("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
1.Entry 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++) {
System.out.println(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 skippable.The loop essentially works based on the semicolon ;
// Empty loop
for (;;) {}
// Infinite loop
for (int i = 0;; i++) {}
Example :
int i=0;
while (i<5){
System.out.println(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
System.out.println(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)
System.out.println(“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 {
System.out.println("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
expression.In 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':
System.out.println("Vowel");
break;
case 'e':
System.out.println("Vowel");
break;
case 'i':
System.out.println("Vowel");
break;
case 'o':
System.out.println("Vowel");
break;
case 'u':
System.out.println("Vowel");
break;
default:
System.out.println("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:
System.out.println("One");
case 2:
System.out.println("Two");
case 3:
System.out.println("Three");
default:
System.out.println("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 -> System.out.println("One");
case 2 -> System.out.println("Two");
case 3 -> System.out.println("Three");
default -> System.out.println("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 it.They 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
Heap: The heap memory in Java can grow and shrink dynamically(DTL).
Address
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) {
System.out.print(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) {
System.out.print("Hello Duniya!!");
}
}
Example 2:
int n = 5;
for (int i = 1; i <= n; i++) {
System.out.println("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[]){
Demo.sum(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.
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.
class PassByValue {
public static void main(String[] args) {
int[] array = new int[2];
array[0] = 2;
array[1] = 3;
add(array);
System.out.println("Result from main: " + (array[0] + array[1]));
}
private static void add(int[] array) {
array[0] = 10;
System.out.println("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);
System.out.println("Result from main: " + (array[0] + array[1]));
}
public static void add(Integer[] array) {
array = new Integer[2];
array[0] = 10;
array[1] = 3;
System.out.println("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.
● 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 –
1.Default|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) {
this.name = name;
}
Student(String name, String age) {
this.name = name;
this.age = 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 - StringBuilder.Capacity()
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=a.intValue();
double first=a.doubleValue();
Useful Method & Parsing Strings
parseInt() - Returns an Integer type value of a specified String representation
int a = Integer.parseInt("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(System.in);
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)
}
|| DAY 27 ||
Collection Framework
Collection
● A collection refers to a group or assembly of things.
● In the context of programming, a group of objects or a single unit
used to store multiple data is known as a collection.
Framework
● A framework is a set of classes and interfaces which provide a
ready-made architecture.
Collection Framework
● It is an API which contains predefined classes and interfaces(DTL)
which is used to store multiple data.
● It contains two main parts(packages)
1. java.util.Collection - store data directly
2. java.util.Map - store data in key-value pair e.g: rollNo - name
Collection VS Collections
Collection(Interface)
Collections(Utility class)
Syntax :
ArrayList<String> list = Arrays.asList(new
String[]{“lab”,”labi”});
ArrayList<String> list1 = new ArrayList<>(list);
Methods in ArrayList
Method Description
add(int index, Object o) Inserts a specific element into the list at the specified index
addAll(Collection c) add all the elements present in collection at the end of list.
addAll(int index, Collection c) add all the elements present in collection at the index.
remove(Object o) Removes the first occurrence of the specified element from list
remove(int index) Removes the element present at specified index from list.
removeAll(Collection c) Removes all the elements present in collection from the list.
indexOf(Object o) Returns the index of the first occurrence of the specified element
lastIndexOf(Object o) Returns the index of the last occurrence of the specified element
set(int index, Object o) Replace the element at the specified position in the list
toArray() Returns an array containing all the elements present in the list
Example :
Why Hashing ?
The time complexity for searching in an ArrayList is O(n) in the worst
case because it involves iterating through the list and the average time
complexity for basic operations (insertion, deletion, and retrieval) is
O(1) in Hashing.
HashMap
● HashMap is a data structure that implements the Map interface.
● It stores data in the form of key-value pairs.
● It uses hashing to efficiently store and retrieve key-value pairs.
● HashMap allows only one null key and multiple null values, but
keys are unique (no duplicate keys are allowed).
● It does not maintain the insertion order.
● It provides constant-time average complexity for basic operations
such as get, put, and remove.
Syntax :
HashMap<KeyDataType,ValueDataType> map = new HashMap<>();
Example :
HashMap<Integer,Integer> map = new HashMap<>();
Operations on HashMap
● Adding an element : put(key, value)
● Retrieve an element : get(key)
● Replace or Update : replace(key, newValue)
● Remove : remove(key)
● DeleteAll : clear()
● Check if map contain particular key: containsKey(key)
● Check if map contain particular value : containsValue(key)
● Check if map is empty : isEmpty()
● Size : size()
Example :
import java.util.HashMap;
public class Demo {
public static void main(String[] args) {
// Initialization of a HashMap
HashMap<Integer, String> map = new HashMap<>();
//Adding an element
map.put(1,"Polu");
map.put(2,"Laby");
map.put(3,"Lab");
HashSet
● HashSet is a data structure that implements the Set interface.
● It does not allow duplicate elements.
● It uses hashing to efficiently store and retrieve key-value pairs.
● It can contain at most one null element.
● It does not maintain the insertion order.
● It provides constant-time average complexity for basic operations.
Syntax :
HashSet<dataType> set = new HashSet<>();
Example :
HashSet<Integer> set = new HashSet<>();
Operations on HashMap
● Adding an element : add(data)
● Remove : remove(value)
● DeleteAll : clear()
● Check if set contain particular key: contains(value)
● iterator over all the values : iterator()
● Size : size()
Example :
import java.util.HashSet;
public class Demo {
public static void main(String[] args) {
// Initialization of a HashMap
HashSet<Integer> set = new HashSet<>();
//Adding an element
set.add(1);
set.add(3);
set.add(5);
set.add(1);//duplicate set - [1,3,5]
//Search
set.contains(1); //true
set.contains(2); //false
//Remove
set.remove(1);// [3,5]
//Iterate on set
Iterator itr = set.iterator();
while (itr.hasNext()){
System.out.println(itr.next());//print- 3,5
}
//remove all
set.clear();//delete all elements
}
}
|| DAY 28 ||
Getter and Setter
Methods are used to retrieve the value of a data member and update or
set the value of a data member respectively.
Getters are also called accessors and Setters are also called mutators.
By using getter & setter we’re indirectly accessing the private variables.
Example :
class Student {
// private variables
private String name;
private int rollno;
● In the above program, inside the "Student" class there are two
private variables that are 'name' and 'rollno'.
● Directly we cannot access those variables outside the class which
is an implementation of encapsulation or data hiding(DTL).
● So we are using getters as getName() and getRollno() methods to
retrieve the values and setters.
● Inside setters, we used "this pointer" to access the data members
of the current object it is pointing to.
● Here without directly accessing the variables, we are easily
changing their values by just calling the setter functions and
printing it by calling the getter functions.
toString() - method of the Object class returns the string representation of
an object.
Array of Objects
● An array is a collection of similar types of elements.
● It consists of both primitive (int, char, etc.) data-type elements
and non - primitive (Object) references of a class.
Example :
import java.util.Scanner;
class Students {
//can make multiple variable
String name;
public Students(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" + "name='" + name + '\'' + ", age=" + age
+ '}';
}
public static void main(String[] args) {
Students student[] = new Students[5];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < student.length; i++) {
System.out.println("Enter name = ");
String name = sc.nextLine();
Students obj = new Students(name);
student[i] = obj;
}
for (Students obj : student){
System.out.println(obj);
}
}
}
Static Variable
● Static variables are associated with the class rather than with the
objects.
● Only a single copy of the static variable is created and shared
among all the instances of the class.
● If an object modifies the value of a static variable, the change is
reflected across all objects.
● Memory-efficient as they are not duplicated for each instance.
● We can only create static member variables at the class level, and
cannot make static local variables.
Example
Consider a machine that produces different varieties of pens like blue, black, green,
etc. for a company ‘X’.
All pens are different in their properties, but one attribute is common among all the
pens is its company name i.e ‘X’.
class Pen {
String penType; // Type of pen whether gel or another
String color; // Color of the pen
int length; // Length of the pen
static String companyName; // static variable
}
The companyName variable is of static type which implies it is shared among
all instances of the Pen class.
Example 2
class Country {
// Static variable
static int countryCounter;
String name;
int dummyCounter;
public static void main(String[] args) {
// Creating first instance
Country ob1 = new Country();
// Assigning values to object's data variables.
ob1.name = "India";
ob1.dummyCounter = 1;
++ob1.countryCounter;
// Creating second instance of the class
Country ob2 = new Country();
ob2.name = "france";
ob2.dummyCounter = 1;
++ob2.countryCounter;
System.out.println("ob1.countryCounter = " +
ob1.countryCounter);
System.out.println("ob2.countryCounter = " +
ob2.countryCounter);
System.out.println("Country.countryCounter = " +
Country.countryCounter);
}
}
Output : ob1.countryCounter = 2
ob2.countryCounter = 2
Country.countryCounter = 2
This shows the variable is shared across all instances and it can be accessed using the
class identifier as well.
Static Method
The static methods are the class methods and they don't belong to
instances of the class. So , they are accessed by the class name of the
particular class.
class StaticMethod{
static void print(){
System.out.println("This is the static method");
}
}
Static blocks
● A static block is a block that is associated with the static keyword.
● It is stored in the memory during the time of class loading and
before the main method is executed, so the static block is
executed before the main method. It runs once when the class is
loaded into the memory.
● Static blocks executed before constructors.
● (JDK) version 1.5 or previous the static block can be executed
successfully without the main() method inside the class. JDK
version 1.5 or later will throw an error.
● Static block in java is used for changing the default value of static
variables, initializing static variables of the class, writing a set of
codes that you want to execute during the class loading in
memory.
Example
public class Main {
static {
//static block
System.out.println("Hi, I'm a Static Block!");
}
Main(){
System.out.println("Hi, I'm a Constructor!");
}
public static void main(String[] args){
//main method
Maint1 = new Main();
System.out.println("Hi, I'm a Main Method!");
}
}
OUTPUT - Hi, I'm a Static Block!
// Instance block
{
System.out.println("Instance Block!");
}
// Static block
static {
System.out.println("Static Block!");
}
public static void main(String args[]) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
System.out.println("Main Block!");
}
}
Output : Static Block!
Instance Block!
Instance Block!
Main Block!
|| DAY 30 ||
Inheritance
● Inheritance is an object-oriented programming concept in which
one class acquires the properties and behavior of another class.
● It represents a parent-child relationship between two classes.
● This parent-child relationship is also known as an IS-A relationship.
Would you write the code for all standard operations, like addition,
subtraction, etc., again? No, you have already written that code. Using
inheritance in this case, you can achieve this objective.
Inheritance concept
Subclass : A subclass, also known as child class or derived class, is the
class that inherits the properties and behaviors of another class.
Superclass : A superclass, also known as parent class or base class, is
the class whose properties and behaviors are inherited by the subclass.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
This is the simplest form of inheritance, where one class inherits
another class.
Ex: Below is a simple program that illustrates the Single Inheritance
class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
// Inheriting SuperClass to SubClass
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
class Main {
public static void main(String args[]) {
Parrot obj = new Parrot();
obj.whatColourAmI();
obj.fly();
}
}
Output : I am green!
I am a Bird
2. Multilevel Inheritance
This is an extension to single inheritance, where another class again
inherits the subclass, which inherits the superclass.
Ex: Below is a simple program that illustrates the Multilevel Inheritance
class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
// Inheriting class Bird
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
// Inheriting class Parrot
class SingingParrot extends Parrot {
void whatCanISing() {
System.out.println("I can sing Opera!");
}
}
class Main {
public static void main(String args[]) {
SingingParrot obj = new SingingParrot();
obj.whatCanISing();
obj.whatColourAmI();
obj.fly();
}
}
Output : I can sing Opera! || I am green! || I am a Bird
3. Hierarchical Inheritance
In Hierarchical inheritance, a single superclass is inherited separately by
two or more subclasses.
Ex: Below is a simple program that illustrates the Hierarchical Inheritance
class Bird {
void fly() {
System.out.println("I am a Bird");
}
}
class Parrot extends Bird {
void whatColourAmI() {
System.out.println("I am green!");
}
}
class Crow extends Bird {
void whatColourAmI() {
System.out.println("I am black!");
}
}
class Main {
public static void main(String args[]) {
Parrot par = new Parrot();
Crow cro = new Crow();
//Call methods of Parrot Class
par.whatColourAmI();
par.fly();
class A {
void testMethod() {
System.out.println("I am from class A");
}
}
class B {
void testMethod() {
System.out.println("I am from class B");
}
}
// Not possible to inherit classes this way, But for understanding, let us
suppose
class C extends A, B {
void newMethod() {
System.out.println("I am from subclass");
}
}
class Main {
public static void main(String args[]) {
C obj = new C();
obj.testMethod();
// Ambiguity here as it's present in both A and B class
}
}
Note: The above program is just for understanding that multiple inheritance of
classes is invalid in Java.
5. Hybrid Inheritance
Hybrid Inheritance is a combination of hierarchical inheritance and
multiple inheritance. This is also not possible and Invalid in Java.
void printSchoolName() {
//access the name variable of the parent class
System.out.println("Name: " + super.name);
}
public static void main(String[] args) {
Child ob = new Child();
ob.printSchoolName();
}
}
class Parent {
String name = "Pappu";
void printParent() {
System.out.println("name = " + name);
}
}
class Child extends Parent {
String name="Pappi";
void printChild() {
super.printParent();
System.out.println("name = " + this.name);
}
public static void main(String[] args) {
Child ob = new Child();
ob.printChild();
}
}
class Parent {
Parent() {
System.out.println("Parent constructor");
}
}
class Child extends Parent {
Child() {
System.out.println("Child constructor");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
class Base {
String name;
Base(){
this("");
System.out.println("Default constructor base
class");
}
Base(String name){
this.name = name;
System.out.println("parameterized constructor base
class");
}
}
class Derived extends Base {
Derived() {
System.out.println("Default constructor derived");
}
Derived(String name) {
super(name);
System.out.println("parameterized constructor of
derived");
}
public static void main(String args[]) {
Derived obj = new Derived("test");
}
}
NOTE :
Example :
class PitaJi{
//virtual method
void display() {
System.out.println("Pita Ji");
}
}
class Putra1 extends PitaJi{
//overriding display method
void display() {
System.out.println("Putra1");
}
}
class Putra2 extends PitaJi{
//overriding display method
void display() {
System.out.println("Putra2");
}
}
class Main {
public static void main (String[] args) {
//Create an object of parent class
PitaJi ob = new PitaJi();
ob.display();
Advantages
● The subclasses have the privilege to use the same method as their
parent or define their specific implementation for the same
method wherever necessary.
● Therefore, in one way, it supports code reusability when using the
same method and implementation.
car=new CarA();
System.out.println("Car A: " + car.speed + "
mph");
car=new CarB();
System.out.println("Car B: " + car.speed + "
mph");
}
}
OUTPUT : Regular car: 60 mph
Car A: 60 mph
Car B: 60 mph
On accessing the value of the variable, it's clear that it doesn't change
because overriding doesn't work on variables and it still refers to the
variable of the parent class. So, the output remains 60.
|| DAY 32 ||
Access Modifiers
● Access modifiers provide a restriction on the scope of the class,
instance variables, methods, and constructors.
● Used to control the visibility/access of instance variables,
constructors, and class methods.
For example: In your Facebook account when you set the privacy of
status to the public everyone on Facebook can access your status
whether it is your friend, friend of your connection, or not a friend.
Let's understand the private modifier
class Scaler {
private int roll;
private String name;
Scaler(int a) {
System.out.print(a);
}
private Scaler() {}
private void print() {
System.out.println("This is the Scaler class");
}
}
class Main {
public static void main(String args[]) {
//Creating the instance of the Scaler class
//This will successful run
Scaler ob1 = new Scaler(1);
For example: In your Facebook account when you change the privacy of
your status to only for me, only you will be able to access the status,
and no one, even your friends, will not be able to see your status..
Let's understand the public modifier:
First package:
package First;
package Second;
import First.Hello;
public class Main {
public static void main(String[] args) {
Hello ob = new Hello();
System.out.print(ob.id + “ ”); //print 1
ob.print();
}
}
We got the correct output, because we can access the public modifier's
methods or instance variables in any class of the same or different
package.
For example: In the Facebook account, when you set your privacy status
to "visible to your friends only".You and your known friends can access
your status.Any other person will not be able to access your status info.
Let's understand the default modifier:
First Package
package First;
public class Hello {
int id = 1;
void print() {
System.out.println("Hello class");
}
}
class Main {
public static void main(String[] args) {
Hello ob = new Hello();
ob.print();
}}
Output : Hello class
The program will run successfully because default members and methods can be accessed in the same
package.
Second Package
package Second;
import First.Hello;
class Second{
public static void main(String[] args) {
Hello ob = new Hello();
ob.print();
}}
Output: print() is not public in First.Scaler; cannot be accessed
from outside package
The line ob.print() will cause an error because we cannot access the
protected method outside its own package, but we can access it by
inheriting it in some other class of different packages, that's why
ob1.print() will not cause any error.
Final keyword
The final keyword is a non-access modifier that is used to define entities
that cannot be changed or modified.
Consider the below table to understand where we can use the final
keyword:
Type Description
Example
public class Main{
public static void main(String[] args) {
final StringBuffer strBuffer = new
StringBuffer("Hellow");
System.out.println(strBuffer);
● while declaration
● Inside the instance initializer block
● Inside the constructor
Final Method
Final keyword can be used with methods to prevent them from being
overridden by subclasses.
Example
class Parent {
// declaring method as final
public final void display() {
System.out.println("Parent");
}
}
class Child extends Parent {
// try to override final method
public void display(){
System.out.println("Child");
}
}
Output : cannot override display() method is final
Final Class
● Likewise with the final variables and final methods, we can also
use the final keyword with classes. These classes are called the
final classes.
● Final classes can not be inherited by any other classes.
● If we try to inherit a class which is declared as a final, the system
will throw a compile time error.
Example
// Final Class
public final class X {
public void displayX() {
System.out.println("Hellow World!");
}
}
public class Y extends X {
public void displayY() {
System.out.println("Welcome!");
}
}
Output : cannot inherit from final X
Note:
● Abstract classes
● Interfaces
Abstract Class
● An abstract class can be created without having any abstract
methods.
● It can have final methods, which means methods that cannot be
overridden by subclasses.
● Abstract classes are uninstantiable, implying that objects cannot
be directly created from them.
● Abstract classes can have constructors, including parameterized
constructors.
When Constructors are Called ?
Simba is eating.
Abstract Method
● An abstract method is a method declared without an
implementation(semi-implemented) in an abstract class.
● Abstract methods do not have a method body. They end with a
semicolon (;) instead of curly braces.
● The presence of an abstract method in a class forces that class to
be declared as abstract.
● A derived class of an abstract class must either override all its
abstract methods or be declared abstract itself.
● Abstract methods cannot be declared as private because they
need to be accessible to subclasses for overriding(private is class
level access modifier).
● Static methods, being part of the class and not the object's state,
cannot be overridden in the traditional sense.
Example
abstract class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
abstract void makeSound();
Woof! Woof!
Name: Whiskers
Meow!
Example
interface Car {
public void start();
}
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal implements Walkable, Swimmable {
public void walk() {
System.out.println("Dog is walking");
}
public void swim() {
System.out.println("Dog is swimming");
}
// This class can also have its own methods
void bark() {
System.out.println("Woof! Woof!");
}
}
public class Demo {
public static void main(String[] args) {
// Create an instance of the derived class
Dog myDog = new Dog();
myDog.eat();
myDog.walk();
myDog.swim();
myDog.bark();
}
}
"In the above example, the class Dog inherits from two parent
interfaces, indicating that multiple inheritance can be achieved
using interfaces.”
Error
Exception Handling
Exception handling is a mechanism to handle unwanted interruptions
like exceptions and continue with the normal flow of the program.
We use try-catch blocks and other keywords like finally, throw, and
throws to handle exceptions.
1. Checked Exceptions
2. Unchecked Exceptions
1. try block -
Syntax :
try{
//doubtful statement
}
2. catch block
Syntax :
try {
// Code that can raise exception
int div = 509 / 0;
} catch (ArithmeticException e) {
System.out.println(e);
}
● Java can have a single try block and multiple catch blocks and a
relevant catch block gets executed.
● we can have deep (two-level) nesting which means we have a
try-catch block inside a nested try block
Example
try {
int a[] = new int[5];
System.out.println(a[10]);
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBounds Exception
occurs");
} catch (Exception e) {
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
4. finally block
Example :
try {
int data = 100/0;
System.out.println(data);
} catch (Exception e) {
System.out.println("Can't divide integer by 0!");
} finally {
System.out.println("finally block");
}
5. throw keyword
6. throws keyword
Example :
public class Main {
static void checkAge(int age) throws ArithmeticException
{
if (age < 18) {
throw new ArithmeticException("Access denied");
} else {
System.out.println("Access granted");
}
}
public static void main(String[] args) {
checkAge(15);
}
}
|| DAY 36 ||
File API
● File handling refers to the process of manipulating files and
directories, meaning reading and writing data to a file.
● With the help of File Class, we can work with files. This File Class is
inside the java.io package.
Example
String path = "C:\\Users\\pc\\Desktop\\";
File folder = new File(path + "temp");//temp is directory name
folder.mkdir();//make directory or folder
Create a new file : We use the createNewFile() method to attempt to
create a new file in combination with exception handling.
Example:
import java.io.File;
import java.io.IOException;
a. void write(int c)
d. void flush()
e. void close()
mkdir() : Creates a new directory using the pathname. If a directory is created, the
method returns true; otherwise, false.
createnewfile() : Generates a new file with no content. Method returns true, and a new
file is created. If the filename already exists, it returns false.
delete() : Deletes the file or directory. The method returns true if the file or directory
deleted, otherwise returns false. Syntax : boolean var = file.delete();
list() : Returns lists the names of files and folders in a given directory.
Syntax : String[] paths= file.list();
exists() : If the abstract file path exists, the method returns true; otherwise, it returns
false. Syntax : boolean var = file.exists();
|| DAY 37 ||
Importance
Step 2 :Open the command prompt (cmd) and navigate to the directory
where your Java code file is located. Use javac file_name.java to
compile the code.
Step 3 : After compilation, a new file with the same name as your class
but with a ".class" extension will be created in the same folder.
Step 4 : type java file_name execute the compiled Java program.
Step 5 : Press Enter, and you will see the output displayed in the
command prompt window.
■ Step 1: Writing the code in IDE, we have our code file as abc.java
■ Step 2: Once you have written the code. The compiler checks the
code for syntax errors and any other compile time errors and if no
error is found the compiler converts the java code into an
intermediate code(abc.class file) known as bytecode. This
intermediate code is platform independent (you can take this
bytecode from a machine running windows and use it in any other
machine running Linux or MacOS etc). Also this bytecode is an
intermediate code, hence it is only understandable by the JVM
and not the user or even the hardware /OS layer.
■ Step 3: This is the start of the Run Time phase, where the
bytecode is loaded into the JVM by the class loader(another
inbuilt program inside the JVM).
■ Step 4: Now the bytecode verifier(an inbuilt program inside the
JVM) checks the bytecode for its integrity and if no issues are
found passes it to the interpreter.
■ Step 5: Since java is both compiled and interpreted language, now
the interpreter inside the JVM converts each line of the bytecode
into executable machine code and passed it to the OS/Hardware
i.e. the CPU to execute.
|| DAY 38 ||
Bitwise Operators
Bitwise operators work on a binary equivalent of decimal numbers
● 1 | 0 => gives 1
● 0 | 1 => gives 1
● 0 | 0 => gives 0
● 1 | 1 => gives 1
● 1 ^ 0 => gives 1
● 0 ^ 1 => gives 1
● 0 ^ 0 => gives 0
● 1 ^ 1 => gives 0
|| DAY 39 ||
Stack Memory
Stack Data Structure
● A stack is a linear data structure. It provides a container to store
data items which can be accessed from one side of the container
only.
● Here the element that is inserted at last is deleted first.
● This is called the Last-In-First-Out (LIFO) principle.
Stack Memory
● The Stack Memory utilizes Static Memory Allocation, storing
function calls, method-specific data, and object references.
● It has a fixed size that doesn't change during execution.
● Access is in the Last-In-First-Out (LIFO) order.
Example:
Consider the following program with methods main, addOne, and
addTwo. The stack usage is explained step by step.
Stack OverflowError
In cases where there's insufficient space to create new objects, the
system may raise a java.lang.StackOverFlowError.
Recursion
● Process by which a problem depends on solutions to smaller
instances of the same problem.
● Breaks down a complex problem into simpler, similar
subproblems.
● The base case is the simplest form of the problem that doesn't
need further breakdown.
● Base case(s) are essential to prevent infinite recursion.
Uses extra space in the stack for recursive calls.
● Each recursive call adds a new frame to the call stack.
● The stack keeps track of the function calls and their local variables.
Considerations:
Iterative vs Recursion
● Iterative:
● Uses loops for repetitive execution.
● Generally more memory-efficient.
● Recursion:
● Uses function calls to solve problems.
● May be more intuitive for problems with inherent recursive
structure.
● Can lead to stack overflow for deep recursion or without
proper base cases.