Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
809 views

Java Telusko

The document provides an overview of core Java concepts including data types, variables, methods, classes, and the Java execution process. It discusses primitive data types like byte, short, int, long, float, double, char, and boolean. It also covers declaring and assigning variables, using variables in operations, and outputting values. The document explains that Java code is compiled to bytecode, which runs on the Java Virtual Machine (JVM).

Uploaded by

halconbravo15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
809 views

Java Telusko

The document provides an overview of core Java concepts including data types, variables, methods, classes, and the Java execution process. It discusses primitive data types like byte, short, int, long, float, double, char, and boolean. It also covers declaring and assigning variables, using variables in operations, and outputting values. The document explains that Java code is compiled to bytecode, which runs on the Java Virtual Machine (JVM).

Uploaded by

halconbravo15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Introduction

• In this video, the speaker will cover core Java, from basics to advanced topics.
• Java is a popular language used in enterprise market, mobile development, and web
development.
• JVM technology allows for multiple languages to run on Java.
• Learning core Java makes it easier to learn other languages.

Java Features

• Java has multiple features, such as WORA, multi-threading support, collection API,
and exception handling.
• Java is known for being maintainable and readable.

Java History

• Java was created in 1995 by Sun Microsystems.


• Oracle now owns the trademark for Java.
• Java is updated every six months.

Setting up for Java

• Download JDK (Java Development Kit) and choose the Oracle JDK.
• Download an IDE (Integrated Development Environment) such as VS Code.
• VS Code is lightweight and can do everything needed for the course.
• Set the path for JDK in Windows.

Conclusion

• Java 17 is an LTS (Long Term Support) version.


• Learning Java takes time, but the speaker is excited to teach it.

Installing JDK Click "yes" on the "reinstall" prompt to install JDK

• Click "next" and then "next" again to complete the installation


• Verify that JDK is installed by typing "Java --version" and "JavaC --version" into the
command prompt
• If "JavaC" command not found, check the path variable in environment variables
• To check path variable, search for "environment variables", click on "environment
variables", and make sure "path" is listed under "user variables" or "system variables"
• If "path" is not listed, click "new" and add it with the value being the file path to "bin"
folder in the installed Java directory
• Restart command prompt and check "JavaC --version" again to verify

Setting up VS Code

• Install and launch VS Code


• Open the terminal in VS Code
• Install any recommended Java extensions
• Check that JDK and VS Code are working by typing "JavaC" into the terminal

Writing Java Code

• Open a new file in VS Code and save with a ".java" extension


• Write code to print "Hello world" to the console
• Test Java code using JShell in the terminal by typing "JShell" and experimenting with
code

Introduction Java is a programming language

• To print something, use methods


• Java has an inbuilt method called "print"
• To print text, put it in double quotes
• Java requires a semicolon at the end of each statement

Working with JShell

• JShell is a tool for experimenting with Java code


• JShell is not for building projects
• To print something in JShell, use the "print" method
• If you want to print "hello world", put it in double quotes
• JShell accepts password statements
• JShell does not require a main method

Compiling Java Code

• To build a project in Java, you need to compile your code


• JVM (Java Virtual Machine) is required to execute Java code
• JVM runs on top of an operating system
• JVM only understands byte code
• Java code needs to be compiled into byte code
• Java code is compiled using the Java compiler (Java C)
• The first file in a project needs to have a main method with a specific signature
• The main method signature is "public static void main

Java Syntax for Main Method

• Main method accepts arguments or parameters


• Syntax for main method: public static void main(String[] args)
• public: Java access modifier
• static: keyword used to indicate that the method belongs to the class and not to an
instance of the class
• void: return type of the method which means that it does not return any value
• main: name of the method
• String[] args: argument or parameter of the method. It is an array of strings that
can accept multiple arguments.

Steps for Java Execution


• Create a Java file
• Compile the Java file using compiler
• The compiled Java code becomes a byte code
• Run the byte code on JVM
• JVM looks for the Main method signature in the code
• Output is displayed on screen

Java Class and File Name

• A class is a blueprint or a template for creating objects.


• Java class is created using the keyword class.
• File name and class name should be the same.
• The file extension for Java code is .java.
• The file extension for compiled code is .class.

Java Runtime Environment (JRE) and Java Virtual Machine (JVM)

• JVM stands for Java Virtual Machine.


• JVM is responsible for running the Java code.
• JRE stands for Java Runtime Environment.
• JRE contains the JVM and libraries required to run Java code.
• JDK stands for Java Development Kit.
• JDK contains the JRE, JVM, and development tools required to develop Java
applications.
• Java is write once, run anywhere (WORA) because it can run on any machine with
JRE and JVM installed.

Data Processing in Java

• Java is used to process data.


• Data can be accepted from the user and processed using Java.
• Data can be stored in a database using Java.
• Database is a permanent storage for data.
• Data processing involves accepting data, processing it, and storing it in a database.

Data storage in Java (40:06 - 50:05)

• During processing, data needs to be stored somewhere temporarily


• Data is stored in variables
• Variables are like boxes that hold data
• Variables can hold different types of data such as numbers, text, images, etc.
• Each variable has a name and a type
• Java is strongly typed, meaning each variable has a specific type
• Types include integers, floats, characters, and booleans
• Integers can be further divided into byte, short, int, and long
• Floats can be further divided into float and double
• Variables are created by specifying the type, name, and value
• Values can be assigned using the assignment operator =
• Statements must end with a semicolon
Using variables in Java

• Variables can be used to perform operations


• Operations can be performed with variables or with values directly
• Results can be stored in variables
• Multiple statements can be used for different operations
• The print statement can be used to output variables or values
• The println statement can be used to output variables or values on a new line

Data types in Java

• Java has multiple inbuilt data types


• Data types can be primitive or non-primitive
• Primitive data types include integers, floats, characters, and booleans
• Integers can be further divided into byte, short, int, and long
• Floats can be further divided into float and double
• Non-primitive data types include arrays, strings, and classes

Java Data Types (50:07 - 00:07)

• Java has different types of data types that can be used to store data in variables.
• There are two categories of data types in Java: primitive data types and non-primitive
data types.
• This transcript focuses on primitive data types.
• Primitive data types are inbuilt, meaning they are part of the Java language.
• The different primitive data types in Java are: ** byte ** short ** int ** long ** float
** double ** char ** boolean
• The size and range of each data type varies.
• The range of each data type can be calculated using a formula involving the size of
the data type.

Byte

• Byte is a primitive data type in Java that can store whole numbers.
• The size of byte is 1 byte (8 bits).
• The range of byte is -128 to 127.
• Values outside this range will result in an error.
• To declare a byte variable, use the keyword "byte" followed by the variable name and
value.
• Example: "byte num = 8;"

Short

• Short is a primitive data type in Java that can store whole numbers.
• The size of short is 2 bytes (16 bits).
• The range of short is -32,768 to 32,767.
• Values outside this range will result in an error.
• To declare a short variable, use the keyword "short" followed by the variable name
and value.
• Example: "short num = 558;"

Int

• Int is a primitive data type in Java that can store whole numbers.
• The size of int is 4 bytes (32 bits).
• The range of int is -2,147,483,648 to 2,147,483,647.
• Values outside this range will result in an error.
• Int is the default data type for whole numbers in Java.
• To declare an int variable, use the keyword "int" followed by the variable name and
value.
• Example: "int num = 5;"

Long

• Long is a primitive data type in Java that can store whole numbers.
• The size of long is 8 bytes (64 bits).
• The range of long is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
• Values outside this range will result in an error.
• To declare a long variable, use the keyword "long" followed by the variable name and
value.
• Example: "long num = 5000000000L;"

Float and Double

• Float and double are primitive data types in Java that can store decimal numbers.
• Float takes 4 bytes (32 bits) and double takes 8 bytes (64 bits).
• Float has limited precision compared to double.
• Double is the default data type for decimal numbers in Java.
• To declare a float variable, use the keyword "float" followed by the variable name and
value. ** To assign a float value, add "F" or "f" at the end of the value. ** Example:
"float num = 5.8F;"
• To declare a double variable, use the keyword "double" followed by the variable
name and value. ** Example: "double num = 5.8;"

Char

• Char is a primitive data type in Java that can store a single character.
• The size of char is 2 bytes (16 bits).
• Char uses Unicode, which means it can store characters from any language.
• To declare a char variable, use the keyword "char" followed by the variable name and
value. ** The value should be enclosed in single quotes. ** Example: "char c = 'K';"

Boolean

• Boolean is a primitive data type in Java that can store only two values: true and false.
• Boolean takes 1 bit of space.
• Boolean is commonly used for conditions and comparisons in Java.
• To declare a boolean variable, use the keyword "boolean" followed by the variable
name and value. ** Example: "boolean b = true;

Java Literals (00:09 - 10:09)

• Literals are values that are directly written in the code.


• Examples of literals include decimal values, binary values, and hexadecimal values.
• Binary values are written with a prefix of "0b".
• Hexadecimal values are written with a prefix of "0x".
• Underscores can be used to separate digits in a large number for readability.
• Characters can also be treated as integers and can be incremented.
• String literals are also a type of literal.

Type Conversion and Casting

• Variables in Java have a specific type that cannot be changed.


• Different types of variables include byte, int, float, double, char, boolean, and string.
• Assigning a value of one type to a variable of another type may require type
conversion.
• Implicit conversion happens automatically, while explicit conversion is called casting.
• Casting can be used to convert a value of one type to another type.
• Some conversions are not allowed, such as assigning a character value to a boolean
variable.
• When converting to a smaller type, some data may be lost.

Byte Conversion (10:11 - 20:10)

• When assigning an integer value to a byte variable, if the integer value is within the
range of -128 to 127, it can be assigned directly.
• If the integer value is outside of this range, it will use the modulus operator (%) to
find the remainder when divided by 256. This remainder is then assigned to the byte
variable.
• Typecasting can also be used to assign an integer value to a byte variable.

Single-Step Compilation and Execution

• Instead of separately compiling and running a Java program, a shortcut can be used by
running java <filename>.java.
• This shortcut only works for recent versions of Java.

Type Conversion vs. Casting

• Type conversion is an automatic conversion between compatible data types.


• Casting is an explicit conversion where the programmer specifies the desired data
type.

Type Promotion
• When performing an operation on variables of different data types, the lower data
type will be promoted to the higher data type.
• For example, when performing an operation on a byte and an integer, the byte will be
promoted to an integer before the operation is performed.

Operators

• Basic mathematical operators in Java include addition (+), subtraction (-),


multiplication (*), and division (/).
• The modulus operator (%) can be used to find the remainder when dividing two
numbers.
• Examples of using these operators with integer variables were shown in the video.

Arithmetic Operators

Addition, subtraction, multiplication, and division can be performed using arithmetic


operators in Java.

• Incrementing and decrementing can also be done using shorthand operators, such as
num1 += 2 or num1++.
• The difference between num1++ and ++num1 is that the former is post-increment and
the latter is pre-increment.

Relational Operators

• Java provides relational operators for comparing two values.


• These operators include less than <, greater than >, equal to ==, not equal to !=, less
than or equal to <=, and greater than or equal to >=.
• The output of a relational operation is either true or false.

Assignment Operator

• In Java, the equal sign = is used to assign a value to a variable.


• To compare two values, the double equal sign == is used.

Not Equal Operator

• The not equal operator is represented by != in Java.

Precedence of Operators

• Operators in Java have a certain order of precedence, which determines the order in
which they are evaluated in an expression.
• Parentheses can be used to change the order of evaluation.

Introduction (30:13 - 40:13)

• Definition of relational operators and their output


• How to implement relational operators in code
Relational operators in code

• Example of comparing two integer values using relational operators


• Storing and comparing values using less than, greater than, less than or equal to, and
greater than or equal to symbols
• Using double equal to and not equal to symbols to check for equality
• Using relational operators with double and float values
• Combining two operations with logical operators
o Using AND operator to require both operations to be true
o Using OR operator to require at least one operation to be true
o Using NOT operator to reverse the output of an operation
• Introduction to XOR operator
• Short circuit option for combining operations

Java Notes: Conditional Statements and Short Circuiting (40:15 - 50:13)

• Short circuiting allows for efficient evaluation of logical operators


o Using "and" with double ampersand (&&) will only evaluate the second
condition if the first is true
o Using "or" with double pipe (||) will only evaluate the second condition if the
first is false
o "Not" remains as exclamation mark (!)
• Conditional statements allow for code to execute based on certain conditions
o Syntax for if statement: if (condition) { code to execute if
condition is true }
o Syntax for if-else statement:
o if (condition) {
o code to execute if condition is true
o } else {
o code to execute if condition is false
}

o Syntax for if-else if-else statement:


o if (condition1) {
o code to execute if condition1 is true
o } else if (condition2) {
o code to execute if condition1 is false and condition2 is
true
o } else {
o code to execute if both condition1 and condition2 are false
}

• Short circuiting and conditional statements can be used together for efficient and
flexible code

Syntax for if statement

• Use the keyword 'if'


• Mention the condition in round brackets
• If the condition is true, execute the statement(s) inside the block
• Curly brackets are optional if there is only one statement inside the block
• Use double slash to comment in programming
Using if statement with else

• Use 'else' after the 'if' block


• 'else' cannot be used alone, it always works with 'if'
• If the condition in 'if' is false, execute the statement(s) inside the 'else' block

Comparing multiple values

• Use 'if else' statements to compare multiple values


• Curly brackets are necessary when there are multiple statements inside the block
• Use logical operators like 'and' and 'or' to combine conditions

Java Notes (00:19 - 10:16)

• To compare multiple values, use the && operator


• Use if, else if, and else to create conditional statements
• To simplify conditional statements, use the ternary operator ? :
• Switch statements are used to check the value of a variable and execute code based on
its value

Introduction to Java Loops (10:20 - 20:20)

• Loops are used in programming to repeat certain tasks multiple times.


• There are multiple types of loops in Java including while, do while, and for loops.

Using If-Else Statements

• If-else statements can be used to print a specific value based on a condition.


• The switch statement is an alternative to using multiple if-else statements.
• The switch statement matches a value to a specific case and executes the
corresponding code block.

Using Loops to Repeat Code

• Loops can be used to repeat code multiple times.


• The for loop is commonly used in Java to repeat code a specific number of times.
• The while and do-while loops are also available in Java and have their own use
cases.

Example of Using a For Loop

• To use a for loop, you define the starting and ending values and the step size.
• Inside the loop, you can execute code that will be repeated multiple times. **
Example: for(int i = 0; i < 5; i++) { System.out.println("Hello"); }
will print "Hello" five times.

Example of Using a While Loop


• A while loop will repeat code as long as a certain condition is true. ** Example: int
x = 0; while(x < 5) { System.out.println("Hi"); x++; } will print "Hi"
five times.

Example of Using a Do-While Loop

• A do-while loop is similar to a while loop, but it will always execute the code block at
least once. ** Example: int y = 5; do { System.out.println("Hey"); y++; }
while(y < 5); will print "Hey" once, even though the condition is not met.

Conclusion

• Loops are an important part of programming and allow you to repeat code multiple
times.
• The for, while, and do-while loops are available in Java and have their own use
cases.

Introduction to Loops (20:21 - 30:21)

• Loop allows us to do the same thing multiple times.


• Different types of loops available in Java: while loop, do-while loop, for loop.
• In this video, we will understand the while loop.

Syntax of while loop

• To repeat something, we use the keyword while.


• We need to mention a condition in the bracket after while.
• While the condition is true, the statements inside the block will be executed
repeatedly.

Example of while loop

• To print "Hi" multiple times, put the statement inside a block.


• Use while to repeat the statement a finite number of times.
• Increment a variable inside the loop.
• Use a condition to stop the loop.

Syntax to declare a variable

• Declare a variable i and initialize it to 1.


• Most of the time, we use i as a variable name when using loops.

Incrementing a variable

• To increment the value of i, use the syntax i++.

Stopping the loop


• Use an if statement to check if the value of i is less than or equal to 4.
• If the condition is true, the loop will continue to execute.
• If the condition is false, the loop will stop.

Debugging a loop

• Debugging mode allows us to see the loop execution step by step.


• Set a checkpoint to iterate one by one.
• Step into allows us to see each statement execution.
• Step over allows us to go to the next statement.

Nested Loop

• We can put a loop inside another loop.


• To print "Hello" three times after printing "Hi", put the statement inside a block.
• Use while to repeat the statement three times.

While Loop Notes (30:24 - 40:23)

• Use different variables for nested loops to avoid conflicts


• Nested while loops can be used to print a value a certain number of times
• Use an analogy of days in a week and hours in a day to understand nested while loops
• While loops execute a block of code while a condition is true
• Do-while loops execute a block of code at least once, even if the condition is false
• Do-while loops are useful for situations where a block of code needs to be executed at
least once
• For loops can combine the initialization, condition, and increment statements into one
line
• For loops start counting from 0, unlike while and do-while loops which start from 1

For Loop Notes

• For loops combine the initialization, condition, and increment statements into one line
• For loops start counting from 0 by default, unlike while and do-while loops which
start from 1

Java Loops Overview (40:25 - 50:23)

• There are three types of loops in Java: while loop, do-while loop, and for loop
• Loops allow us to repeat certain actions until a certain condition is met
• We need to be careful to avoid infinite loops

For Loop

• The for loop is used when we know how many times we want to repeat a certain
action
• Syntax: for (initialization; condition; update) { // code to be
executed }
• The initialization statement is executed only once when the loop starts
• The condition is tested at the beginning of each iteration. If it is true, the loop
continues. If it is false, the loop ends
• The update statement is executed at the end of each iteration
• Example: for (int i = 0; i < 5; i++) { // code to be executed }** The
loop will start with i = 0, continue as long as i is less than 5, and increment i by 1 after
each iteration ** To print 0 to 4, we can use for (int i = 0; i < 4; i++) {
System.out.println(i); }

Nested For Loops

• We can use nested for loops to perform more complex tasks


• Syntax:

for (int i = 0; i < outerLimit; i++) {


for (int j = 0; j < innerLimit; j++) {
// code to be executed
}
}

• The outer loop will run outerLimit times, and the inner loop will run innerLimit
times for each iteration of the outer loop
• Example: printing a calendar for a week with work hours from 9am to 5pm ** Outer
loop will have values from 1 to 7 for each day of the week ** Inner loop will have
values from 9 to 17 for each hour of work ** We can use for (int i = 1; i <= 7;
i++) for the outer loop and for (int j = 0; j < 9; j++) for the inner loop **
Inside the inner loop, we can print the hour using System.out.print(j + 9) and
add the next hour with System.out.print(" - " + (j + 10))** We can use
System.out.println() to move to the next line after printing the hours for a day

Loops in Java (50:26 - 00:25)

• For Loop is used when we know the number of iterations we want to perform.
• While Loop is used when we don't need a counter, for example, when reading a file.
• Do-While Loop is used when we want to execute something at least once, even if the
condition is false.
• For Loop is the most frequently used loop in Java for database files and network
operations.

Object Oriented Programming in Java

• Everything is an object in the real world and in the programming world.


• Every object in Java has properties and behaviors.
• Objects are created using classes in Java.
• JVM creates objects using the blueprint provided by the class.
• A class can be created in the same file as the main class.
• Variables should be on separate lines for better readability and maintainability.
• Code can be organized into separate classes for better abstraction and reusability.

Introduction (00:27 - 10:26)


• Designing is more important than assembling in Java programming.
• Manufacturing will be done by JVM.

Designing a Class

• Put properties and methods in a class.


• Use "class" and "curly brackets" to define a class.
• A class has two things: properties and methods.
• A class can have variables and methods.
• Define a method with "public" access and a return value.
• Java is statically typed, so specify the data type for variables and return values.

Adding Behavior to a Method

• Use a method to perform an action.


• A method has a name, access, and return type.
• Define a method with a name, access, and return type.
• Use a method to perform an operation.
• Use "return" to return a value from a method.

Creating an Object

• To call a method, you need an object.


• Create an object with the "new" keyword.
• Use the class name and the reference variable name to access the methods of an
object.
• A class can have a special method called a constructor to initialize variables.

Calling a Method with an Object

• To call a method, you need an object.


• Use the object name and the method name to call a method.
• The method should return a value if specified.
• Accept the returned value in a variable.
• Use the returned value in the program.

Java Programming: Understanding Classes, Variables, Methods, Objects,


JVM, JRE, and JDK (10:28 - 20:26)

• To create a class in Java, use the keyword 'class' followed by the class name.
• Variables can be created in a class using the data type and variable name.
• Methods can be created in a class using the access modifier, return type, method
name, and parameters.
• Objects can be created in Java by calling the 'new' keyword followed by the class
name. ** The object reference is then assigned to a variable of the same type as the
class.
• To execute Java code, the code needs to be compiled into bytecode using the Java
Development Kit (JDK).
• The bytecode is then executed by the Java Virtual Machine (JVM).
• The Java Runtime Environment (JRE) provides the necessary libraries and other files
needed to run the Java code.
• JDK contains JRE and JVM along with other development tools.
• Understanding the concepts of classes, variables, methods, objects, JVM, JRE, and
JDK is essential for Java programming.

Java Basics: Methods and Classes (20:28 - 30:27)

• A behavior is defined in Java with the help of methods, which can be linked to a class.
** A class is a blueprint or idea. ** A method defines what a class can do.
• Every method has to specify what type of access it is giving (public, private, etc.).
• A method can do something and/or return something. ** For example, a method can
return an integer value or a string.
• To call a method in Java, an object of the class must be created. ** An object is an
instance of a class. ** A reference variable is used to access the object.
• A class can also have variables. ** Variables can be defined with different types (int,
double, string, etc.).
• The static keyword is used to define a method or variable as belonging to the class,
rather than an individual object. ** Static methods and variables can be accessed
without creating an object of the class.
• If-else statements can be used in a method to define conditions for execution.

Introduction (30:29 - 40:29)

• The speaker discusses Java programming and taking notes on a Java video transcript.
• The task is to take bullet notes on Java.

Adding Two Numbers

• To add two numbers in Java, use the int data type to accept two values, N1 and N2.
• Create a variable to store the result of the addition, or simply return N1 + N2.
• This is an example of method overloading.

Adding Three Numbers

• To add three numbers, create a new method that accepts three values.
• Remember to pass in three values, not two. Otherwise, the compiler will return an
error.
• Alternatively, use the same method name with different parameters to solve this
problem.

Local Variables

• Variables can be local or instance variables.


• Local variables are declared within a method.
• Instance variables are declared outside of a method, but within a class.

Method Overloading
• Method overloading is when multiple methods have the same name, but different
parameters.
• Parameters can be of different types or different numbers.

Stack and Heap Memory

• Java has two types of memory: stack and heap memory.


• Stack memory stores data in a last in, first out order.
• Heap memory has more open space and can store data in any order.

Running Code in the JVM

• The JVM executes Java code.


• Every method has its own stack.
• Variables are stored in the stack with a key-value pair.

Java Notes (40:32 - 50:31)

• Variables N1 and N2 are defined and assigned values of 3 and 4 respectively.


• The add method adds N1 and N2, returning the result as R1.
• The add method belongs to the object created in the Heap memory, which is linked to
the stack through an address.
• The object in Heap memory contains instance variables and method declarations.
• Multiple objects can be created and used, each having its own instance variables and
methods.
• Arrays allow for multiple values to be stored in a single variable, reducing the need
for multiple variables.
• Arrays are declared using square brackets.
• A single array variable can hold multiple values, separated by commas and enclosed
in curly brackets.

What is an array? (50:32 - 00:30)

• An array can hold multiple values.


• Imagine an array as a tray of cups that can hold multiple cups.
• Arrays are used to store multiple values in one variable.
• The size of an array is fixed once it is defined.
• Arrays can hold any number of values.

Creating an array

• Basic syntax: int[] nums = {3, 7, 2, 4};


• To create an array without initial values: int[] nums = new int[4];
• The index values for the array start at 0.
• To fetch a value from an array: nums[index]
• To assign a value to an array: nums[index] = value

Printing and updating array values


• To print a value from an array: System.out.println(nums[index]);
• To update a value in an array: nums[index] = new_value;

Using loops with arrays

• A loop can be used to print all the values in an array.


• Use a for loop: for (int i = 0; i < nums.length; i++)
• The length method is used to get the size of the array.

Multi-Dimensional Arrays in Java (00:33 - 10:33)

• Multi-dimensional arrays are a way to have multiple arrays combined to form one big
array.
• This is called a multi-dimensional array.
• To represent this, we can use a nums array which will have an array of arrays.
• To create a multi-dimensional array, use two square brackets to indicate that it is an
array of arrays.
• The nums array will be of type integer and have two square brackets.
• To define the size of the multi-dimensional array, specify the number of rows and
columns.
• To assign values to the multi-dimensional array, use nested loops to iterate through
each element.
• Use the nums array with two indices to represent a specific element.
• The Math class in Java can be used to generate random values for the multi-
dimensional array.

Array Basics (10:36 - 20:35)

• Multi-dimensional arrays can be created in Java. ** Enhanced for loop can be used to
iterate over multi-dimensional arrays. ** Jagged arrays have varying column sizes. **
Three-dimensional arrays can also be created, with additional square brackets and
loops.
• Array drawbacks include: ** Once size is specified, it cannot be changed. **
Traversing arrays for searching or inserting values is time-consuming. ** Arrays
cannot hold different types of values.

Collections

• Collections in Java offer more flexibility than arrays.


• Collections can hold different types of values.
• Collections can be resized dynamically.
• Collections offer more efficient searching and insertion of values.

Arrays in Java (20:37 - 30:36)

• Collections are used to store multiple values of different types


• Arrays are useful when you have a fixed size
• To create an array in Java, you need to specify the data type and size
• Arrays start at index 0 and end at size-1
• Accessing an index outside the bounds of an array will result in a runtime error
(exception)
• Arrays have a property called "length" that returns the number of elements in the
array

Creating an Array of Objects

• You can create an array of objects in Java


• You need to create the objects first and then assign them to the array
• Arrays in Java can only hold references to objects, not the objects themselves

Printing Array Values

• You can print array values using a for loop that iterates over the indexes of the array
• You can use the "length" property of an array to specify the end condition of the for
loop
• To print the values of an array of objects, you need to access the individual properties
of each object using dot notation
• Printing an object directly will result in the memory address of the object being
printed

For Each Loop

• The for each loop is another way to iterate over an array in Java
• It is more concise than a traditional for loop
• It does not require a counter variable or accessing array indexes
• It is useful when you only need to access the values of an array, not the indexes

For Each Loop (Enhanced For Loop) (30:39 - 40:38)

• Works with array and array type of data


• Syntax: for (type var : array) {...}
• Iterates through all values in the array and gives one value at a time
• No counter or increment needed
• Example:
• int[] nums = {1, 2, 3};
• for (int n : nums) {
• System.out.println(n);
}

String

• Used to store a character stream


• Represented with double quotes
• String is a class, not a primitive type
• Creating a String variable: String name = "Naveen";
• String can be concatenated with plus operator
• Example: String greeting = "Hello " + name;
Methods in Java Class (40:40 - 50:39)

• Class has methods to perform actions


• Useful methods include:
o charAt(int index): returns the character at specified index
o concat(String str): concatenates two strings

String Objects in Java

• Strings in Java are important for programmers


• In Java, new String can be omitted when creating a string
• Behind the scenes, Java creates an object for the string
• Strings are immutable, meaning they cannot be changed
• When a string is changed, a new object is created and the old one becomes eligible for
garbage collection

String Buffer and String Builder

• String Buffer and String Builder classes can be used to create mutable strings
• String Buffer provides a buffer size of 16 bytes, which can be increased
• Appending data to mutable strings is done using the append() method

String Buffer (50:41 - 00:40)

• Offers many methods, including append to add data


• Can use toString to convert to a String
• Other methods include delete, insert, substring, and ensureCapacity
• Similar to String Builder, but String Buffer is thread safe

Static Variables

• Shared by all objects of a class


• Can be accessed using class name or object, but should be accessed using class name
• Can be used to have a common value across all objects of a class

Static keyword (00:42 - 10:40)

• Static keyword makes something a class member, not an object member.


• Static variables can be used in non-static methods.
• Saves memory as not every object will have its own copy of the variable.

Static block

• Used to initialize static variables.


• Static block is called only once, irrespective of how many objects are created.
• Static block is called before the Constructor.
• Class loader loads the class first, then creates the object.
• Java class can be used to load the class.
Static method

• Can be used directly with a class name.


• Non-static variables cannot be used directly inside a static method.
• Static variables can be used inside a static method.

Static Method (10:43 - 20:40)

• Cannot use a non-static variable inside a static method.


• Solution: pass the object reference as a parameter and use it to access the non-static
variable.
• Main method is static because it is the starting point of execution and needs to be
accessible without creating an object of the class.

Encapsulation

• Encapsulation is a concept of object-oriented programming.


• Private variables can only be accessed within the same class.
• Access to private variables should be through public methods.
• Example: create a class called Human with private variables age and name. Use
public methods to set and get the variables.

Encapsulation of Data and Methods in Java (20:43 - 30:41)

• Private variables in a class can only be accessed by its own methods, not from outside
the class.
• To access private variables, create public methods (Getters and Setters) in the class
that can be called from outside the class.
• Getters are methods that return the value of a private variable.
• Setters are methods that assign a value to a private variable.
• Getters and Setters should have a clear and descriptive name that defines their
purpose.
• It is not compulsory to use the names "get" and "set", but it is a standard convention
followed in Java.
• Every variable should have a Getter and a Setter method.
• Local variables are created inside a method and have a limited scope.
• Instance variables are created inside a class and have a wider scope than local
variables.
• The 'new' keyword is used to create a new instance of a class and allocate memory for
it in the heap.

Java Notes (30:44 - 40:44)

• Instance variable and local variable with the same name can cause confusion.
• To differentiate between instance and local variable, pass the object itself as a
parameter.
• The keyword "this" represents the current object and can be used to refer to instance
variables.
• Constructors are methods without a return type that are used to assign default values
to instance variables when an object is created.

Constructor basics in Java (40:46 - 50:44)

• Constructor has the same name as the class name.


• Constructor never returns anything.
• Constructor is a special method.
• Constructor must be public.
• When creating an object, the constructor is always called.
• Default constructor is created automatically by Java if not explicitly defined.
• Parameterized constructor is defined with parameters.

Default Constructor vs Parameterized Constructor

• Default Constructor is blank.


• Parameterized Constructor is defined with parameters.
• Both can be used to assign values to object properties.

Using Constructors and Parameters in Java

• Constructors can be used to assign values to object properties.


• A Constructor can be used to connect with a database or network.
• Standard practice is to perform operations in a method, not directly in the Constructor.
• Parameters can be added to Constructors to allow for customization of object property
values.
• Parameterized Constructor is defined with parameters.
• Default Constructor is automatically created if not explicitly defined.

Super in Java

• Super is used to access a parent class's properties and methods.


• When a child class extends a parent class, the child class can access its parent class's
properties and methods using "super".
• Super is used to call the parent class's Constructor.

Introduction (50:47 - 00:45)

• Keep it simple - Class A and B with a simple statement


• Compiling the code and expecting an output
• Object creation calls the constructor of a class

Calling Constructor of Superclass

• Expecting constructor of B to be called when B object is created


• However, constructor of A is also called, which is unexpected
• When creating an object of a class, constructor of both superclass and subclass are
called
• Adding a parameterized constructor in B, which takes an integer value, results in
printing "in B int"
• Adding a parameterized constructor in A as well and passing a value to B's
constructor results in printing "in A int" and "in B int"
• Every constructor in Java has a method called super, which calls the constructor of the
superclass even if not mentioned
• Super method means call the constructor of the superclass
• Default constructor of A is called when super is used with no parameter
• Passing a parameter to super calls the parameterized constructor of A

Playing with Super

• Calling the default constructor of B and passing a value to super results in calling the
parameterized constructor of A and B
• Questioning what the superclass of A is, and introducing the concept of object class,
which every class in Java extends, even if not mentioned
• Multi-level inheritance, where B extends A and A extends object
• Super represents the constructor of the object class
• Using super to execute both constructors of B using one object, by passing a value to
B's constructor and calling super and this to call the constructor of A and B
respectively.

Constructor Execution (00:47 - 10:45)

• The this keyword executes the constructor of the same class.


• The default constructor executes the super method which calls the constructor of the
superclass.
• Naming conventions dictate that class names should start with a capital letter, variable
and method names should start with a small letter, and constants should be all capital.
• Camel casing is used for naming conventions in Java, where the first letter of the
second word is capitalized to make it more readable.
• The first letter of the second word should be capitalized even if the word only has two
letters.
• Snake casing with underscores is used in some languages, but Java follows camel
casing.
• Classes and interfaces should always start with a capital letter, whereas variables and
methods should start with a small letter.
• Constants should be all capital.
• Using good names for variables, classes, and methods help make code more readable.

Object Creation

• To call a method, an object must first be created.


• An object is created using the new keyword followed by the constructor.
• The object is assigned to a reference variable.
• Anonymous objects are objects created without a reference variable.
• Anonymous objects can only be used once and cannot be reused.
• Anonymous objects are created using the new keyword followed by the constructor,
without assigning it to a reference variable.
OOPS concept (10:48 - 20:47)

• OOPS stands for Object Oriented Programming.


• In OOPS, we have object class encapsulation.
• Inheritance is one of the most important concepts in OOPS.
• Inheritance allows copying the features from the upper class to the child class.
• In real-world examples, inheritance can be seen in the human world where children
inherit the properties of their parents.

Inheritance in Java

• In Java, we have different classes.


• We can create a subclass to inherit properties and features from the parent class.
• Inheritance helps to avoid defining basic features again and again.
• The subclass is a child class and the superclass is a parent class.
• The subclass can also be referred to as a derived class and the superclass as a base
class.

Example of Inheritance in Java

• Example of a simple class called Calculator.


• Calculator has methods for addition, subtraction, multiplication, and division.
• If we want to create an advanced calculator, we can create a new class called
AdvancedCalculator which is a subclass of the Calculator class.
• The AdvancedCalculator class will have all the features of Calculator class along
with its own advanced features.
• We can create an object of the AdvancedCalculator class and access all the basic
and advanced features.

Inheritance and Subclasses in Java (20:49 - 30:48)

• Inheritance is useful when adding extra features to a class.


• Redundancy is avoided by not repeating method definitions and classes.
• A subclass extends a superclass.
• Inheritance allows for creating new classes with existing features.
• Multiple classes can inherit from the same superclass.
• Multi-level inheritance involves a hierarchy of parent-child relationships.
• Single-level inheritance involves only two classes.

Example: Calculator Classes

• An advanced calculator can extend the basic calculator class.


• The advanced calculator can add more features, such as multiplication and division.
• If a further calculator is needed, like a scientific calculator, it can be created by
extending the advanced calculator.
• Multiple-level inheritance is possible with a hierarchy of parent-child relationships
between classes.

Java does not support multiple inheritance (30:52 - 40:51)


• In Java, multiple inheritance does not work.
• Syntax for extending from multiple classes gives an error.
• Multiple inheritance is not supported in Java because of the Ambiguity problem.
• Ambiguity problem: when there is a method with the same name in both parent
classes, and the child class cannot decide which parent class method to inherit.

Method Overriding

• In Java, method overriding allows a subclass to provide a specific implementation of a


method that is already provided by its parent class.
• Method overriding is used to provide a specific implementation of a method that is
already provided by its parent class.
• To override a method, the method name, return type, and parameters must be the
same as the parent class method.

Example of Method Overriding

• In class A, a method called show is defined to print "in show".


• Class B extends A and inherits the show method.
• In class B, show is overridden to print "in B show" instead of "in show".
• The overridden method in the subclass is called instead of the original method in the
parent class when the method is invoked on an object of the subclass.

Syntax for Method Overriding

• To override a method, the method in the subclass must have the same name, return
type, and parameters as the method in the parent class.
• Use the @Override annotation to indicate that a method is intended to override a
method in the parent class.
• The @Override annotation is optional, but it helps to ensure that the method in the
subclass is actually overriding a method in the parent class.

Example of syntax for Method Overriding


class A {
public void show() {
System.out.println("in show");
}
}

class B extends A {
@Override
public void show() {
System.out.println("in B show");
}
}

Benefits of Method Overriding

• Method overriding allows for polymorphism, which is the ability of an object to take
on many forms.
• It allows us to write more flexible and reusable code.
• It helps us to avoid code duplication and increase code readability.

Method Overriding (40:53 - 50:52)

• Method overriding is when a subclass has a method with the same name and
parameters as its superclass.
• The subclass's method will override the superclass's method.
• The subclass's method can have a different implementation than the superclass's
method.
• The @Override annotation can be used to indicate that a method is overriding a
superclass's method.

Packages

• Packages are used to organize Java code into groups of related classes.
• A package is like a folder that contains Java classes.
• Packages can be nested within other packages to create a hierarchical structure.
• The package keyword is used to declare a package.
• The import keyword is used to import classes from other packages.
• The fully qualified name of a class includes both the package name and the class
name.
• The javac compiler automatically looks for classes in the correct package directories.

Packages in Java (50:56 - 00:56)

• Every class in a build class used in Java belongs to a package.


• String and System are also classes but are part of the java.lang package which is
imported by default.
• To create a package in Java, create a folder inside a folder.
• Package names should be unique when sharing with others.
• To make a package name unique, reverse the domain name of the company or
individual.
• To import all files in a folder, use the "*" wildcard.
• When using the "*" wildcard, it only imports all files, not all folders.
• Access modifiers control the visibility of classes, methods, and variables.
• Access modifiers include public, private, protected, and default.

Access Modifiers

• Public: Can be accessed from anywhere.


• Private: Can only be accessed within the same class.
• Default: Can only be accessed within the same package.
• Protected: Can be accessed within the same package and by subclasses in other
packages.

Modifiers in Java (00:58 - 10:58)

• Private can only be accessed within the same class


• Public can be accessed from anywhere
• Protected can be accessed within the same class, within the same package, and in a
subclass in a different package
• Default can be accessed within the same package

Polymorphism in Java

• Polymorphism means many behaviors


• Compile-time polymorphism: behavior is defined at compile time, e.g. method
overloading
• Runtime polymorphism: behavior is defined at runtime, e.g. method overriding
• Dynamic method dispatch is a way to implement runtime polymorphism

Example of Dynamic Method Dispatch

• Class B extends Class A


• Object of B can be referred to as type A
• Type of variable is A, but implementation is B
• Example of inheritance: laptop is a computer, so laptop extends computer

Creating Objects in Java (11:00 - 20:59)

• To create an object of a class, use the syntax: <class name> obj = new <class
name>();
• An object can be referred to by its class name or a superclass name.
• Polymorphism allows objects of different classes to be treated as if they are objects of
the same superclass.
• An object's behavior is determined by its class, not its reference type.

Final Keyword in Java

• final can be used with variables, methods, and classes.


• A final variable cannot be reassigned.
• A final class cannot be inherited.
• A final method cannot be overridden.

Dynamic Method Dispatch

• When a method is called on a superclass reference variable that refers to a subclass


object, the subclass version of the method is called.
• The method to be called is resolved at runtime, not at compile time.
• This is known as dynamic method dispatch and is an example of polymorphism.
• Dynamic method dispatch only works with inheritance.

Final Keyword (21:01 - 30:58)

• Use final keyword with a variable to make it constant.


• Use final keyword with a class to stop inheritance.
• Use final keyword with a method to stop method overriding.
Object Class

• Every class in Java extends the Object class.


• Object class contains many methods such as equals, notify, hashCode, toString, etc.
• When an object is printed, it calls the toString() method of the Object class.
• We can override the toString() method to print desired output when an object is
printed.
• The equals() method of the Object class compares objects based on their hash code,
but we can override it to compare objects based on their values.

Java object class (31:01 - 40:59)

• Use the equals method to compare objects in Java.


• Use hashCode to generate a hash code for an object.
• Use toString to get a string representation of an object.
• Use your own IDE to generate equals, hashCode, and toString methods.
• equals and hashCode should have the same variables.
• Implement multiple checks in equals method.
• toString can also be generated with IDE.

Typecasting in Java

• Typecasting is converting the type of a value.


• Java will not allow typecasting that may result in data loss.
• Typecasting can be done with a parent class and a child class object.
• Upcasting is referring to a child class object with a parent class reference.
• Downcasting is referring to a parent class object with a child class reference.

Upcasting and Downcasting (41:01 - 51:01)

• Can implicitly use upcasting and downcasting in Java


• Upcasting: creating a parent reference and child object
• Downcasting: going back to the child reference

Abstract Classes and Methods

• Abstract keyword used to declare a method in a class without implementation


• Abstract method can only belong to an abstract class
• Abstract classes can also have normal methods
• Abstract classes can have both abstract and normal methods
• Compulsory to define all abstract methods when extending an abstract class
• Abstract classes cannot be instantiated, but can be referenced by an abstract class
reference
• Can restrict object creation with abstract classes

Example: Car Class

• Car class with two methods: drive() and playMusic()


• Cannot implement drive() method yet, but want to declare it in the class
• Use abstract keyword to declare drive() as an abstract method
• Abstract class cannot be instantiated, so must be extended by a child class (e.g.
WagonR)
• Child class must implement all abstract methods from the parent abstract class
• Abstract class can have multiple abstract methods and normal methods
• Compulsory to define all abstract methods when extending an abstract class
• Can restrict object creation with abstract classes

Abstract Keyword (51:03 - 01:02)

• Used with methods to declare them as abstract


• If a class has any abstract methods, it must be declared as abstract
• An abstract class can have normal methods as well
• An abstract class cannot be instantiated
• To create an object, a subclass that implements all the abstract methods must be
created
• The subclass is called a concrete class
• An abstract class can also be called a concrete class

Inner Class

• A class inside another class


• Can be used when a class is only required for a specific purpose
• Inner class variables and methods only work for the outer class
• To access the inner class, an object of the outer class must be created first
• Inner classes can be made static and accessed without an object of the outer class
• Making an outer class static is not allowed

Anonymous Inner Class

• A class without a name


• Can be used to change the behavior of a method
• A new class is created that extends the original class and overrides the desired method
• The object of the new class has a reference to the original class

Example Code
class A {
void show() {
System.out.println("In A Show");
}
}

class B extends A {
void show() {
System.out.println("In B Show");
}
}

public class Main {


public static void main(String[] args) {
A obj;
obj = new B();
obj.show();
}
}

• This code creates two classes, A and B, where B extends A


• The method show in class B overrides the show method in class A
• The object is created as A but references the show method in B, so "In B Show" is
printed

Anonymous Inner Class (01:05 - 11:03)

• Used when a class will be used only once for a particular use.
• No need to create a new class in this scenario.
• Implement a new implementation for a method by defining it just before the
semicolon.
• Anonymous Inner Class is created inside the demo class with no name.
• Anonymous Inner Class is called anonymous because it has no name.
• Used frequently when working with interfaces and functional interfaces.

Interfaces

• An interface is not a class but a type.


• Every method in an interface is public abstract by default, so no need to include those
keywords.
• An interface is used to design something, to show the methods that need to be
implemented.
• Cannot be instantiated.
• To implement an interface, create a class that implements the interface and provide
implementation for its methods.
• The class must use the implements keyword to implement an interface.
• A class can implement multiple interfaces.

Interface in Java (11:05 - 21:03)

• To implement an interface, use the "implements" keyword.


• It becomes compulsory to define all methods in the interface when implementing it.
• All variables in an interface are by default final and static.
• Interface inheritance is done using the "extends" keyword.
• A class can implement multiple interfaces.
• When using a reference of interface type, only methods defined in that interface can
be called.

Need for Interface

• Example: A developer needs a laptop to write code.


• A laptop class is created with a method "code".
• A developer class is created with a method "DevApp" that accepts a laptop object.
• The developer can call the "code" method of the laptop object.
Laptop Class and Object (21:06 - 31:03)

• A method called code() is defined inside the Laptop class.


• An object of Laptop is created using new Laptop().
• Each developer needs a different laptop object.
• The laptop object is passed to the DevApp method which calls the code() method.
• The code() method is executed and the output is displayed.

Dependency on Laptop

• Developers usually ask for a laptop to write code.


• Some companies provide desktops instead of laptops.
• The current design is tightly coupled with a laptop object.
• A computer can be a laptop or a desktop, and the developer is dependent on a
computer.
• The Computer class is created with the code() method, kept empty.
• Laptop is declared as a subclass of Computer.
• Desktop is declared as a subclass of Computer.
• A reference to the parent class can be used to create an object of the subclass.
• The Lab object is created as new Laptop() and the Desk object is created as new
Desktop().
• A reference to the parent class is used in the DevApp method, and an object of the
subclass is passed as an argument.
• The code() method is executed based on the object passed.

Abstract Class and Interface

• The Computer class can be made abstract and the code() method can be made
abstract too.
• This creates an abstraction layer between Laptop and Desktop.
• Developers are dependent on a computer rather than a specialized device.
• An interface can be used instead of an abstract class.
• The implements keyword is used instead of the extends keyword.
• An interface reference is used instead of a class reference.

Enums

• Enums are named constants.


• They are useful for creating constants where a few specific values are required.
• An enum class named Status is created.
• Different constants are defined inside the Status class.
• An object of the Status class is created using one of the constants.
• The name() method is used to get the name of the constant.
• Enums can be used instead of string or number constants.

Introduction to Enums in Java (31:06 - 41:05)

• Error message when using an undeclared status


• Enums have numbered statuses
• The ordinal() method retrieves the status number
• The values() method retrieves all statuses in an array
• Enhanced for loop can print all statuses

Working with Enums in Java

• Enums can be compared using if-else statements


• Enums can also be used with switch statements
• enum extends EnumClass
• Custom class can be treated as an enum
• A Constructor can be used with a custom class- laptop is used as an example
• Instance variable price can be added to the laptop class
• Enum Constructor is similar to a class Constructor

Example: Defining Laptop Models with Prices

• MacBook costs $2000


• Dell XPS costs $2200
• Surface costs $1500
• ThinkPad costs $1800

Java Constructors and Objects (41:06 - 51:06)

• Constructor takes a value and assigns it to an object's variable


• Objects have different values for the same variable
• Private variables can be accessed with getters and setters
• Default constructor is needed when parameterized constructor is used
• Private constructor can be used to create objects within the same class

Java Annotations

• Annotations provide extra information to the compiler or runtime


• Overriding methods can cause logical problems or bugs
• "@Override" annotation shows the intention to override a method
• Inbuilt annotations are available in Java
• Solving problems at compile time is better than at runtime or deployment

Annotations in Java (51:08 - 01:08)

• Java annotations can be used on class, method, and variable levels.


• Examples of class-level annotations are "@Deprecated" and "@Transient".
• Method-level annotations include "@Override" and "@SafeVarargs".
• Annotations can also be created with custom retention levels, such as "SOURCE" for
only during compilation or "RUNTIME" for during runtime as well.

Functional Interface in Java

• Functional interface is an interface with only one abstract method.


• A functional interface can be annotated with "@FunctionalInterface" to ensure it has
only one abstract method.
• Lambda expressions can only be used with functional interfaces.
• Lambda expressions are a syntactical sugar that simplifies anonymous inner classes
by allowing the code to be written more concisely.

Lambda Expressions in Java

• Lambda expressions are a way to simplify anonymous inner classes for functional
interfaces.
• Lambda expressions use a syntax of "(argument) -> (body)" to represent a single
abstract method.
• Lambda expressions can take in multiple arguments and have multiple statements, but
for a single-line statement, the curly braces and semicolon can be omitted.

Types of Interfaces (01:10 - 11:08)

• Normal Interface: Interface with 2 or more methods.


• Functional Interface (SAM): Interface with only one method. Can also be called SAM
(Single Abstract Method) interface.
• Marker Interface: Interface with no methods. Used to give permission to the compiler
for certain actions.

Lambda Expressions

• Only works with functional interfaces.


• Can reduce code by removing unnecessary curly brackets, parentheses, and type
declarations.
• Can be used to pass a method as an argument to another method.

Exceptions and Errors

• Three types of errors: compile time, runtime, and logical.


• Exceptions are unexpected events that occur during the execution of a program.
• In Java, exceptions are represented by objects.
• Exceptions can be handled using try-catch blocks.
• Checked exceptions must be handled or declared in the method signature, while
unchecked exceptions do not need to be handled or declared.

Types of Errors in Java (11:11 - 21:11)

• Syntactical errors are easy to solve and occur at compile time.


• Logical errors are harder to solve and occur at runtime.
• Runtime errors occur when the code stops working suddenly at runtime.

Handling Exceptions in Java

• Exceptions are a type of runtime error that can be handled.


• It is important to handle exceptions to prevent critical errors.
• To handle exceptions, critical statements should be put in a separate block using a
try-catch statement.
• If an exception occurs, the catch block will execute and the error can be handled.
• The handling code should be written in the catch block.

Handling Exceptions in Java (21:14 - 31:14)

• Use try-catch blocks to handle exceptions in Java code.


• Only critical statements should be placed inside the try block.
• If an exception occurs in the try block, the catch block will be executed.
• The catch block will only execute if an exception occurs in the try block.
• Multiple try-catch blocks can be used in a single code block.
• Print the exception message to understand what went wrong.

Types of Exceptions

• ArithmeticException occurs when an arithmetic operation cannot be performed in


Java.
• ArrayIndexOutOfBoundsException occurs when an array is accessed with an invalid
index.
• Handle exceptions with specific catch blocks.
• Use the parent class Exception to handle any other types of exceptions.

Best Practices

• Provide specific error messages to help users understand what went wrong.
• Handle all possible exceptions to avoid unexpected code behavior.
• Follow the sequence of parent and child classes when using try-catch blocks.
• Keep non-critical statements outside of the try block.

Class Hierarchy in Java Exceptions (31:15 - 41:15)

• Object class is at the top of the hierarchy because every class in Java extends Object.
• Throwable class is below Object. It is the parent class of Exception and Error.
• Exception and Error are subclasses of Throwable.
• Exception has many subclasses, including:
o RuntimeException, which includes subclasses such as
ArithmeticException, IndexOutOfBoundsException, and
NullPointerException.
o Other checked exceptions, such as SQLException and IOException.
• Error has subclasses such as OutOfMemoryError and StackOverflowError.
• All runtime exceptions are unchecked exceptions, while other exceptions are checked
exceptions.
• Checked exceptions must be handled by the programmer, while handling unchecked
exceptions is optional.

Using the throw Keyword

• The throw keyword is used to manually throw an exception.


• To use throw, create an object of the desired exception class (e.g.
ArithmeticException) and pass it as a parameter to throw.
• This will cause the exception to be thrown and can be caught using a catch block.

Creating Custom Exceptions (41:17 - 51:13)

• To create a custom exception, create a class that extends Exception or


RuntimeException.
• The custom exception class should have a constructor that accepts a String
parameter for the exception message.
• To throw the custom exception, create an instance of the custom exception class and
throw it using the throw keyword.

The throws Keyword

• The throws keyword is used to declare that a method may throw an exception.
• If a method throws an exception that is not caught within that method, the exception is
propagated up to the calling method.
• Checked exceptions, such as IOException, must be handled by the calling method or
declared in the method signature using throws.
• Unchecked exceptions, such as RuntimeException, do not need to be handled or
declared using throws.

Java Class and Exception Handling (51:17 - 01:15)

• To create a class in Java, use the keyword "class" followed by the class name.
• To load a class in Java, use the "Class.forName()" method.
• If the class is not found, a ClassNotFoundException is thrown.
• To handle exceptions in Java, use the "try-catch" block.
• If a method throws an exception, you can either handle it with "try-catch" or declare it
with the "throws" keyword.
• The "throws" keyword is used to declare the exceptions that a method might throw.
• You can also use the "printStackTrace()" method to print the entire stack of methods
called.

Taking Input from User in Java

• To print something on the console in Java, use "System.out.println()".


• To take input from the user, use the "System.in.read()" method.
• The "System.in.read()" method returns the ASCII value of the entered character.
• To get the actual value, subtract the entered value by 48.
• For bigger numbers, use the Scanner class to take input from the user.

Taking Input in Java (01:17 - 11:17)

• In Java, to take input from the user, we can use the System.in.read() method.
• However, this method reads only one character at a time, so to read multiple
characters, we need to use a loop or a specialized class.
• The specialized class for taking input is called BufferedReader, which belongs to the
java.io package.
• To use BufferedReader, we need to import the java.io package and create an
object of BufferedReader.
• We also need an object of InputStreamReader to pass to the BufferedReader
constructor, which in turn needs an object of InputStream.
• We can pass System.in as the input stream object.
• Once we have the BufferedReader object, we can use the readLine() method to
read a line of input as a string.
• To convert the string input to an integer, we can use the Integer.parseInt()
method.
• We can also use the Scanner class for taking input, which was introduced in Java 1.5.
• To create an object of Scanner, we need to pass System.in as the argument to the
constructor.
• We can then use the nextInt() method of Scanner to directly read an integer from
the input.
• Both BufferedReader and Scanner are resource-intensive classes, so it is important
to close them after use to free up resources.

Using Try with Finally for Resource Management

• In Java, the try-catch-finally block is used for exception handling.


• The finally block is used to execute statements that should be executed regardless
of whether an exception occurs or not.
• If we only want to execute statements in the finally block, we can skip the catch
block and use try-finally instead.
• The finally block is often used for resource management, such as closing file
streams or database connections.
• We can also use the try-finally block to ensure that certain statements are always
executed, even if an exception occurs.

Java Input using BufferedReader (11:19 - 21:17)

• To get input from the user, we can use BufferedReader.


• To work with BufferedReader, we need to first get an object of InputStreamReader.
• We can then pass the InputStreamReader object to the BufferedReader constructor.
• We can read the input by calling the readLine method of the BufferedReader object.
• We need to parse the input to the desired data type using methods such as parseInt.
• We should handle any exceptions that may occur while reading input, such as
NumberFormatException and IOException.

Closing Resources with finally block

• Whenever we open a resource, it's important to close it properly.


• We can close the resource in the finally block.
• If we declare the resource inside the try block, we should declare it outside as well so
that the finally block can access it.
• The finally block is used to close resources such as files, input/output streams, and
database connections.
Threads in Java

• Threads are used to break down a task into smaller units that can run in parallel.
• In Java, we can have multiple threads running at the same time in a single program.
• Threads are lightweight and share resources, allowing for efficient multitasking.
• Many frameworks create threads for us, so we often do not need to create threads
manually.

Creating Threads in Java

• We can create threads by creating a class that extends the Thread class and overriding
the run method.
• We can also create threads by implementing the Runnable interface and passing an
instance of the class to a Thread constructor.
• We should be careful when working with threads, as issues such as race conditions
and deadlocks can occur if not handled properly.

Introduction (21:19 - 31:19)

• To execute two methods in parallel, we need to use threads in Java.

Creating Classes and Methods

• To create a class that prints "Hi" multiple times, we create a function called show and
use a loop to print "Hi" 10 times.
• To create another class that prints "Hello", we create a similar function called show
with the only difference being it prints "Hello" instead of "Hi".
• We create objects for both classes and call their respective show methods.

Converting Classes to Threads

• To execute the show methods in parallel, we need to convert the classes into threads.
• To do this, we extend the Thread class and use the start method instead of the show
method to execute them.
• We need to create a run method for each thread to specify what it should execute
when started.

Execution and Scheduling

• When threads are executed, a scheduler in the operating system decides which thread
should execute at a given time.
• The scheduler time-shares between the available threads and executes them in parallel
on multi-core CPUs.
• The number of threads that can be executed at a given time is limited by the number
of cores on the CPU.

Creating and Running Multiple Threads (31:21 - 41:19)

• Use the Thread class to create multiple threads


• Call the start() method to execute the thread
• Threads execute simultaneously but scheduling is controlled by the OS
• Use the Runnable interface to create threads instead of extending the Thread class

Thread Priority

• Use the setPriority() method to set the priority of a thread


• Priority ranges from 1 to 10, with 1 being the least priority and 10 being the highest
• Default priority is 5 (normal)
• Priority only suggests to the scheduler what should be done, but the scheduler may
have different algorithms to work with
• Use the getPriority() method to get the current priority of a thread

Delaying Execution

• Use the sleep() method to pause the execution of a thread for a specified amount of
time
• The sleep() method can throw an InterruptedException, so it should be
surrounded by a try-catch block
• sleep() puts the thread into a waiting stage

Optimizing Thread Execution

• Thread execution is controlled by the scheduler, so there is no guarantee of order


• Use delays and thread priority to suggest to the scheduler how threads should be
executed
• Different schedulers have different algorithms for scheduling threads

Java Thread Basics (41:21 - 51:20)

• Threads are important to execute multiple tasks simultaneously.


• Two ways to create threads in Java: extending the Thread class or implementing the
Runnable interface.
• To start a thread, call the start() method.
• If implementing the Runnable interface, pass the object to the Thread constructor.
• Lambda expressions can be used to reduce the number of lines of code.

Race Conditions and Thread Safety

• Mutation refers to the ability to change a variable's value.


• Threads and mutation together can create instability in code.
• Thread safety ensures that only one thread can access a variable at a time.
• To make a method thread safe, use synchronization or the volatile keyword.

Java Multithreading: Synchronization and Thread States (51:23 - 01:23)

• Thread synchronization is important when multiple threads share a variable.


• The synchronized keyword ensures that only one thread can access a synchronized
method or block at a time.
• Thread states: ** New state: when a thread is created but not yet started. ** Runnable
state: when a thread is ready to run but not running yet. ** Running state: when a
thread is currently executing its task. ** Waiting/Block state: when a thread is waiting
for another thread to release a lock or waiting for input/output operations. ** Dead
state: when a thread has completed its task or is terminated.
• Use the join() method to ensure that the main thread waits for other threads to
complete.
• Thread behavior can be unpredictable, especially when multiple threads are working
with shared variables.
• Use synchronization to make sure that only one thread works with a variable at a time.

Java Thread States (01:26 - 11:24)

• When a thread is started, it goes into an enabled state.


• When the thread is executing and waiting for the scheduler, it is in an enabled state.
• Running state refers to when the thread is actually running on the CPU.
• Waiting state can be achieved with the help of sleep or wait methods.
• notify method is used to come back from the waiting state to the enabled state. The
scheduler assigns the task, and the thread goes into the running state.
• stop method is deprecated and should not be used to stop threads.
• Threads can also be sent from the runnable to the dead state.

Java Collection API

• Collection API is a concept for working with data structures in Java.


• Collection, an interface, is a part of the Collection API.
• Collections, a class, has multiple methods for working with collections.
• Collection API provides inbuilt classes for working with data structures like Queue
and Stack.
• Collection API is useful when working with expandable arrays and different
algorithms and structures.
• Collection interface can be implemented using various classes like ArrayList and
LinkedList.

Interfaces and Classes in Java Collection API

• Collection interface is extended by List, Queue, and Set interfaces.


• List interface has implementations like ArrayList and LinkedList.
• Queue interface has implementations like PriorityQueue and Deque.
• Set interface has implementations like HashSet and TreeSet.

Collection API and List (11:26 - 21:26)

• The Collection API includes a concept called a map and multiple implementations of
the map.
• We can use either a list or a set, but let's start with a list.
• To create a list, we use the code List nums = new ArrayList();.
• We can add values to the list using the add() method.
• The list supports index values and has methods such as get(), set(), and
indexOf().
• To print the entire list, we can simply use System.out.println(nums).
• To print each value in the list, we can use an enhanced for loop.
• When using a list, we need to specify the type of element we want to work with, such
as List<Integer> nums = new ArrayList<Integer>();.
• Specifying the type of element with generics helps prevent runtime errors and allows
for easier bug detection.
• Lists can have repeated values, but sometimes we want a collection with only unique
values.

Collection Interface and Set Interface (21:28 - 31:27)

• Collection is an interface which is extended by a Set interface.


• Set supports unique values.
• Set implements the HashSet class and doesn't maintain a sequence.
• To use Set, import the package and specify the generic type, for example,
HashSet<Integer> nums = new HashSet<>().
• Set doesn't have index values and doesn't support the get() method.

Iterator Interface

• The Iterator interface is used to iterate through the elements of a Set.


• The iterator() method returns an iterator object.
• Use the hasNext() method to check if there is a next element, and the next()
method to get the next element.

TreeSet

• TreeSet is a class that implements SortedSet and maintains elements in sorted order.

Map Interface

• Map is not an implementation or an extension of the Collection interface.


• Map is a collection of key-value pairs.
• The key and the value can be of any data type.
• The TreeMap class implements the Map interface and maintains the elements in
sorted order.

Introduction to Java Map (31:31 - 41:29)

• Printing a map in Java using System.out.println()


• Observing that the map is not following a sequence, but rather looks like a set
• Fetching a particular student's marks by specifying the key using get()
• Adding a new value to an existing key using put()
• Keys are unique in a map, values can be repeated
• Exploring methods like keySet(), values(), remove(), and replace()
• The Map interface has two implementations: HashMap and HashTable
• HashTable is synchronized while HashMap is not
• Using Collections.sort() to sort a Java list

Sorting a List with Comparator

• Using Comparator to sort a list with a custom logic


• Creating an anonymous class to implement the Comparator interface
• Defining the compare() method to specify the custom sorting logic

Sorting Elements in Java (41:32 - 51:30)

• To sort elements in Java, one of the algorithms used is the comparison-based sorting
algorithm.
• The basic rule for sorting is to compare two values and swap them if needed.
• To specify when to swap and when not to swap, you need to pass an object of a
comparator interface.
• The comparator interface allows you to specify your own logic for sorting.
• You can use the sort method to sort a list of integers or strings based on the
comparator object.
• If you want to sort an object of a custom class, you can either make the class
implement the comparable interface or pass a comparator object to the sort method.
• The comparable interface has a method called compareTo() that you can implement to
specify the natural ordering of the elements in the class.
• The comparator interface has a method called compare() that you can implement to
specify the logic for sorting the elements in the class.

Example: Sorting elements in Java

• To sort a list of integers in ascending order, you can use the sort method of the
Collections class and pass a comparator object that compares two integers and swaps
them if needed.
• To sort a list of strings based on their length, you can use the sort method and pass a
comparator object that compares the length of two strings and swaps them if needed.
• To sort a list of custom objects, you can either make the class implement the
comparable interface and implement the compareTo() method or pass a comparator
object that compares two objects based on a specific property and swaps them if
needed.

Comparable and Comparator in Java (51:33 - 01:32)

• Can use Comparator instead of Comparable to override logic


• Functional interfaces like Comparator can use Lambda expressions
• Ternary operator can replace if-else statements in Comparator

Introduction to Stream API

• New concept introduced in Java 1.8


• Provides methods like filter, map, and reduce for working with collections
• Stream is an interface in the java.util.stream package
• For each method introduced in Java 1.8 for iterating through collections
• Consumer is a functional interface used with for each method

Introduction to Stream API and forEach (01:34 - 11:32)

• Stream is an interface introduced in Java 8.


• The stream() method returns an object of type Stream.
• The forEach() method is used to iterate over the elements of a collection.

Using forEach with Consumer Interface

• forEach() method takes an object of type Consumer.


• Consumer is a functional interface with a single method accept.
• A lambda expression can be used in place of an object of type Consumer.
• The lambda expression can be written in one line if it has only one statement.

Using Filter and Map with Stream API

• The filter() method is used to filter elements based on a condition.


• The map() method is used to perform an operation on each element of a stream.
• Both filter() and map() methods return a new stream.

Understanding Reduce Method

• The reduce() method is used to perform a reduction operation on the elements of a


stream.
• It takes two parameters, an initial value and a BinaryOperator.
• BinaryOperator is a functional interface with a single method apply.
• The reduce() method returns a single value.

Introduction to Java functions (11:36 - 21:35)

• Use of functions like filter, map, and reduce in Java


• Example of Big Data and filtering unwanted data

Java Stream API

• Applying filter, map, and reduce functions using Stream API


• Benefits of using Stream API over traditional for loop
• Writing functions in one line using Lambda expressions

Filter function

• Filter function requires an object of Predicate interface


• Predicate interface has "test" method that returns a Boolean value based on a
condition
• Applying filter on a stream using Predicate interface or Lambda expression

Map function
• Map function requires an object of Function interface
• Function interface has "apply" method that applies a specified logic on a value and
returns the result
• Applying map on a stream using Function interface or Lambda expression

Reduce function

• Reduce function requires an object of BinaryOperator interface


• BinaryOperator interface extends Function interface and has "apply" method that
applies a specified operation on two values and returns the result
• Applying reduce on a stream using BinaryOperator interface or Lambda expression
• Adding two values at a time using reduce function

Stream API for Java (21:38 - 23:21)

• Stream allows for applying multiple functions


• Can retrieve a sorted stream using the .sorted() function ** .sorted() returns a
sorted stream ** Does not use reduce() function ** Can be printed directly using
.forEach()
• Can use parallel stream for filtering with multiple threads ** Does not work with
sorted() function ** Only use parallel stream for filtering

You might also like