Java Programming Basics and Syntax Guide
Java Programming Basics and Syntax Guide
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.
If we update the method's signature, the program will throw the
error NoSuchMethodError:main and terminate.
|| DAY 2 ||
Comments
Single-line comment: Use // to add a single-line comment.
Example : // This is single line comment
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:
|| DAY 3 ||
6. Length – No Limit
|| 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:
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
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];
Scanner sc = new Scanner([Link]);//object
int n = [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”).
Example
Scanner scanner = new Scanner([Link]);
Console :
Enter an integer: 69
Enter a string: age is = 69
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]);
\ is a special symbol
\n (next Line), \b (backspace), \t (tab), \" (double quote), \' (single
quote), and \\ (backslash).
|| DAY 6 ||
Operators
Operators can be easily defined as characters that represent an
operation. These symbols perform different operations on several
variables and values.
Types of Operator
1. Arithmetic Operator :
Arithmetic operator can be divided into two categories -
● Unary Operators :
Increment Operator (++) : Increase the value by 1.
Decrement Operator( - -) : Decrease the value by 1.
4. ShortHand operators
The assignment operator can be combined with other operators to
build a shorter version of the statement. +=, -=, *=, /=, %=
|| DAY 7 ||
Package
A Java package is a collection of similar types of sub-packages,
interfaces, and classes. They help you manage and group related
classes, interfaces, and sub-packages to avoid naming conflicts and
create a more organized and maintainable codebase.
Example:
Math Class
[Link] class is a built-in class. It provides mathematical
functions and constants for mathematical operations.
[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.
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 :
|| 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.
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
[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 a shorter range of supported values in lower data
type.
Example :
double doubleValue = 42.0;
int intValue = (int) doubleValue; // Explicit
conversion (casting)
|| DAY 12 ||
Loops
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++) {}
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(;;);
|| 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:
initialization
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
[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);
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
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.
|| DAY 16 ||
Nested Loops
Nested loop means a loop statement inside another loop statement.
That is why nested loops are also called “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 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
Stack memory holds the references while Heap memory holds the actual
object:
Heap: The heap memory in Java can grow and shrink dynamically(DTL).
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.
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.
TIME COMPLEXITY
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 Within Class Within Subclass Outside
Modifier package 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;
}
}
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.
Example:
class PassByValue {
public static void main(String[] args) {
int[] array = new int[2];
array[0] = 2;
array[1] = 3;
add(array);
[Link]("Result from main: " + (array[0] + array[1]));
}
private static void add(int[] 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]));
}
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.
Jagged Arrays
A jagged array is an array of arrays where the inner arrays can have
different lengths. Each row of a jagged array can store arrays of
varying sizes, making it a "non-rectangular" array.
Example
int[][] jaggedArray = new int[3][]; // Declaring a jagged array
with 3 rows
jaggedArray[0] = new int[4]; // First row has 3 elements
jaggedArray[1] = new int[5]; // Second row has 5 elements
jaggedArray[2] = new int[1]; // Third row has 1 elements
|| 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
For example – Animal, car, Birds etc. all are categories not a real
world entity.
Syntax:
accessModifier class ClassName{
//attributes
//methods
}
Rules –
● Same name as the class
● Never have any return type not even void.
● Cannot make static.
● Can have access modifiers, which control the visibility of the
constructor.
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;
}
}
|| DAY 23 ||
Overloading - Method, Constructor
Method Overloading
Create method 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);
}
● 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"
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";
|| || ||
For example :
String name = "apkasubhnaam";
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");
Example:
|| 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() - Generates Empty String Builder with 16-character capacity.
StringBuilder(int capacity) - Empty String Builder with the provided length capacity.
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
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 conversion of
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]();
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)
|| 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
[Link]: A root interface representing a group of objects. It
provides methods for adding, removing, and checking elements. It is
implemented by several classes such as ArrayList, LinkedList,
HashSet, TreeSet, etc.
Collection VS Collections
Collection(Interface)
Collections(Utility class)
ArrayList
● ArrayList is an implemented class of List interface which is present
in the [Link] package.
● It is a growable and resizable array, used for creating dynamic
arrays.
What is Generics
Generics are mainly used to impose type safety in programs. Type safety
is when the compiler validates the datatype of constants, variables, and
methods whether it is rightly assigned or not.
Syntax :
ArrayList<String> list = [Link](new
String[]{“lab”,”labi”});
ArrayList<String> list1 = new ArrayList<>(list);
Methods in ArrayList
Method Description
add(Object o) Adds a specific element at the end of ArrayList.
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 :
|| DAY 28 ||
Hashing
Hashing is a technique or process that allows for efficient operations,
such as insertion, deletion, and searching, with an average constant
time complexity of O(1).
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.
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 [Link];
public class Demo {
public static void main(String[] args) {
// Initialization of a HashMap
HashMap<Integer, String> map = new HashMap<>();
//Adding an element
[Link](1,"Polu");
[Link](2,"Laby");
[Link](3,"Lab");
//Update
[Link](1,"Lolu");
//Remove
[Link](1);
}
}
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 [Link];
public class Demo {
public static void main(String[] args) {
// Initialization of a HashMap
HashSet<Integer> set = new HashSet<>();
//Adding an element
[Link](1);
[Link](3);
[Link](5);
[Link](1);//duplicate set - [1,3,5]
//Search
[Link](1); //true
[Link](2); //false
//Remove
[Link](1);// [3,5]
//Iterate on set
Iterator itr = [Link]();
while ([Link]()){
[Link]([Link]());//print- 3,5
}
//remove all
[Link]();//delete all elements
}
}
|| DAY 28 ||
Getter and Setter
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;
class Main {
public static void main(String[] args) {
// object of the class is created
Student s1 = new Student();
[Link]("Labra");
[Link](69);
// printing the value returned by getName()
[Link]([Link]());
// printing the value returned by getRollno()
[Link]([Link]());
}
}
● 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.
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
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.
[Link] = "India";
[Link] = 1;
++[Link];
// Creating second instance of the class
Country ob2 = new Country();
[Link] = "france";
[Link] = 1;
++[Link];
[Link]("[Link] = " +
[Link]);
[Link]("[Link] = " +
[Link]);
[Link]("[Link] = " +
[Link]);
}
}
Output : [Link] = 2
[Link] = 2
[Link] = 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(){
[Link]("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
[Link]("Hi, I'm a Static Block!");
}
Main(){
[Link]("Hi, I'm a Constructor!");
}
public static void main(String[] args){
//main method
Maint1 = new Main();
[Link]("Hi, I'm a Main Method!");
}
}
OUTPUT - Hi, I'm a Static Block!
Example
class MyClass {
// Instance block
{
[Link]("Instance Block!");
}
// Static block
static {
[Link]("Static Block!");
}
public static void main(String args[]) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
[Link]("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
This is the simplest form of inheritance, where one class inherits
another class.
class Bird {
void fly() {
[Link]("I am a Bird");
}
}
// Inheriting SuperClass to SubClass
class Parrot extends Bird {
void whatColourAmI() {
[Link]("I am green!");
}
}
class Main {
public static void main(String args[]) {
Parrot obj = new Parrot();
[Link]();
[Link]();
}
}
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() {
[Link]("I am a Bird");
}
}
// Inheriting class Bird
class Parrot extends Bird {
void whatColourAmI() {
[Link]("I am green!");
}
}
// Inheriting class Parrot
class SingingParrot extends Parrot {
void whatCanISing() {
[Link]("I can sing Opera!");
}
}
class Main {
public static void main(String args[]) {
SingingParrot obj = new SingingParrot();
[Link]();
[Link]();
[Link]();
}
}
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() {
[Link]("I am a Bird");
}
}
class Parrot extends Bird {
void whatColourAmI() {
[Link]("I am green!");
}
}
class Crow extends Bird {
void whatColourAmI() {
[Link]("I am black!");
}
}
class Main {
public static void main(String args[]) {
Parrot par = new Parrot();
Crow cro = new Crow();
//Call methods of Parrot Class
[Link]();
[Link]();
4. Multiple Inheritance
In Multiple Inheritance , a single class inherits from two different
superclasses. Multiple Inheritance for classes is Invalid in Java.
class A {
void testMethod() {
[Link]("I am from class A");
}
}
class B {
void testMethod() {
[Link]("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() {
[Link]("I am from subclass");
}
}
class Main {
public static void main(String args[]) {
C obj = new C();
[Link]();
// 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.
Hybrid Inheritance of classes is invalid in Java.
|| DAY 31 ||
Super and Constructor chaining
The super keyword is used to access the members of the immediate
parent class from child class.
1. Refer immediate parent class instance variable
class Parent {
String name = "Pappu";
}
void printSchoolName() {
//access the name variable of the parent class
[Link]("Name: " + [Link]);
}
public static void main(String[] args) {
Child ob = new Child();
[Link]();
}
}
class Parent {
String name = "Pappu";
void printParent() {
[Link]("name = " + name);
}
}
class Child extends Parent {
String name="Pappi";
void printChild() {
[Link]();
[Link]("name = " + [Link]);
}
public static void main(String[] args) {
Child ob = new Child();
[Link]();
}
}
class Parent {
Parent() {
[Link]("Parent constructor");
}
}
class Child extends Parent {
Child() {
[Link]("Child constructor");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
}
}
class Base {
String name;
Base(){
this("");
[Link]("Default constructor base
class");
}
Base(String name){
[Link] = name;
[Link]("parameterized constructor base
class");
}
}
class Derived extends Base {
Derived() {
[Link]("Default constructor derived");
}
Derived(String name) {
super(name);
[Link]("parameterized constructor of
derived");
}
public static void main(String args[]) {
Derived obj = new Derived("test");
}
}
NOTE :
class Parent {
Parent() {
[Link]("Parent constructor");
}
}
class Child extends Parent {
Child() {
[Link]("Child constructor");
}
}
public class Main {
public static void main(String[] args) {
//Object of Child class assign to Parent class
Parent parent = new Child();
Example :
class PitaJi{
//virtual method
void display() {
[Link]("Pita Ji");
}
}
class Putra1 extends PitaJi{
//overriding display method
void display() {
[Link]("Putra1");
}
}
class Putra2 extends PitaJi{
//overriding display method
void display() {
[Link]("Putra2");
}
}
class Main {
public static void main (String[] args) {
//Create an object of parent class
PitaJi ob = new PitaJi();
[Link]();
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();
[Link]("Car A: " + [Link] + "
mph");
car=new CarB();
[Link]("Car B: " + [Link] + "
mph");
}
}
|| 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 Fb{
private int roll;
private String name;
Fb(int a) {
[Link](a);
}
private Fb() {}
private void print() {
[Link]("This is the Scaler class");
}
}
class Main {
public static void main(String args[]) {
//Creating the instance of the Fb class
//This will successful run
Fbob1 = new Fb(1);
Second package:
package Second;
import [Link];
public class Main {
public static void main(String[] args) {
Hello ob = new Hello();
[Link]([Link] + “ ”); //print 1
[Link]();
}
}
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() {
[Link]("Hello class");
}
}
class Main {
public static void main(String[] args) {
Hello ob = new Hello();
[Link]();
}}
Output : Hello class
Second Package
package Second;
import [Link];
class Second extends First {
public static void main(String[] args) {
First ob = new First();
//This line will cause an error
[Link]();
Second ob1 = new Second();
//This line will not cause an error
[Link]();
}
}
The line [Link]() 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
[Link]() will not cause any error.
Private Yes No No No No
Protected Yes Yes Yes Yes No
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
1. Final Variable
public class Main{
public static void main(String[] args) {
final int count = 10;
// Again initializing final variable
count = 15;//error
final int myNumber = 10;
int result = myNumber * 5;//you can do this
[Link](result);
}
}
count=15 compilation error final variable cannot be re-assigned.
Example
public class Main{
public static void main(String[] args) {
final StringBuffer strBuffer = new
StringBuffer("Hellow");
[Link](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() {
[Link]("Parent");
}
}
class Child extends Parent {
// try to override final method
public void display(){
[Link]("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() {
[Link]("Hellow World!");
}
}
public class Y extends X {
public void displayY() {
[Link]("Welcome!");
}
}
Output : cannot inherit from final X
Note:
|| DAY 33 ||
Abstraction
Abstraction in daily life, such as using a car, means benefiting from
functionalities like brakes and engines without understanding their
intricate workings. We enjoy the benefits without needing to
understand all the complicated details, keeping things simple for us
users.
● 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.
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) {
[Link] = name;
}
abstract void makeSound();
Woof! Woof!
Name: Whiskers
Meow!
|| DAY 34 ||
Interface
● An interface is a blueprint of a class and contains abstract
methods.
● Methods are public and abstract by default(you don’t have to
explicitly use the “abstract” keyword).
● Any class implementing your interface will need to provide
implementations of those methods.
Example
interface Car {
public void start();
}
Example
class DieselCar implements Car{
public void start(){
[Link]("Diesel Car
starting...Vrooooom!");
}
}
public class Demo {
public static void main(String[] args) {
Car mercedes = new DieselCar();
}
}
class Animal {
void eat() {
[Link]("Animal is eating");
}
}
class Dog extends Animal implements Walkable, Swimmable {
public void walk() {
[Link]("Dog is walking");
}
public void swim() {
[Link]("Dog is swimming");
}
// This class can also have its own methods
void bark() {
[Link]("Woof! Woof!");
}
}
public class Demo {
public static void main(String[] args) {
// Create an instance of the derived class
Dog myDog = new Dog();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
"In the above example, the class Dog inherits from two parent
interfaces, indicating that multiple inheritance can be achieved
using interfaces.”
Important Points
● An interface can be used when we want to achieve 100%
abstraction. On the other hand, abstract classes can be used to
achieve anything between 0–100% abstraction.
● An interface cannot have constructors because we cannot create
objects of an interface.
● If you want a class to achieve multiple inheritances, there is only
one way: interfaces.
● If an interface is made private, or if the methods in it are made
private or protected, then a compilation error will be thrown.
|| DAY 35 ||
Exception Handling
Exception
Exceptions are unwanted conditions that disrupt the flow of the
program. For example, if a user is trying to divide an integer by 0 then it
is an exception, as it is not possible mathematically.
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) {
[Link](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];
[Link](a[10]);
} catch (ArithmeticException e) {
[Link]("Arithmetic Exception occurs");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBounds Exception
occurs");
} catch (Exception e) {
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
4. finally block
Example :
try {
int data = 100/0;
[Link](data);
} catch (Exception e) {
[Link]("Can't divide integer by 0!");
} finally {
[Link]("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 {
[Link]("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 [Link] package.
Example
String path = "C:\\Users\\pc\\Desktop\\";
File folder = new File(path + "temp");//temp is directory name
[Link]();//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 [Link];
import [Link];
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 = [Link]();
list() : Returns lists the names of files and folders in a given directory.
Syntax : String[] paths= [Link]();
exists() : If the abstract file path exists, the method returns true; otherwise, it returns
false. Syntax : boolean var = [Link]();
|| DAY 37 ||
Java RunTime(JRE)
● Java Runtime Environment is provided by Java to run the
applications.
● It is an implementation of JVM. It consists of run-time libraries.
● The components of JRE include - JVM(the most important
component of JRE), Deployment technologies, Class Loader
Subsystem, Bytecode verifier, Interpreter, Libraries, User Interface
Toolkits.
● It consists of various integration libraries like- Java Database
Connectivity(JDBC), JNDI(Java Naming and Directory Interface),
RMI (Remote Method Invocation) etc.
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 [Link]
■ 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([Link] 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
2. Bitwise XOR(^)
If the bits are opposite, the solution has a 1 in that bit position and if
they are matched, a 0 is returned.
● 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 [Link].
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.