Java Notes
Java Notes
Video Link
KG Coding
Some Other One shot Video Links:
• Complete HTML
• Complete CSS
• Complete JavaScript
• Complete React and Redux
• One shot University Exam Series
• Structure of words in a
sentence.
• Rules of the language.
• For programming exact
syntax must be followed.
1.5 History of Java
.JDK
• It's a software development kit required to develop Java applications.
• Includes the JRE, an interpreter/loader (Java), a compiler (javac), a doc generator
(Javadoc), and other tools needed for Java development.
• Essentially, JDK is a superset of JRE.
2.6 JDK vs JVM vs JRE
.JRE
• It's a part of the JDK but can be downloaded separately.
• Provides the libraries, the JVM, and other components to run applications
• Does not have tools and utilities for developers like compilers or debuggers.
2.6 JDK vs JVM vs JRE
.JVM
• It's a part of JRE and responsible for executing the bytecode.
• Ensures Java’s write-once-run-anywhere capability.
• Not platform-independent: a different JVM is needed for each type of OS.
2.7 Showing Output
2.8 Importance of the main method
• Entry Point: It's the entry point of a Java program, where the execution starts.
Without the main method, the Java Virtual Machine (JVM) does not know where to
begin running the code.
• Public and Static: The main method must be public and static, ensuring it's accessible
to the JVM without needing to instantiate the class.
• Fixed Signature: The main method has a fixed signature: public static void
main(String[] args). Deviating from this signature means the JVM won't recognize it
as the starting point.
FF5F1F
2.9 What is IDE
1. IDE stands for Integrated
Development Environment.
2. Software suite that consolidates basic
tools required for software
development.
3. Central hub for coding, finding
problems, and testing.
4. Designed to improve developer
efficiency.
FF5F1F
2.9 Need of IDE
1. Streamlines development.
2. Increases productivity.
3. Simplifies complex tasks.
4. Offers a unified workspace.
5. IDE Features
1. Code Autocomplete
2. Syntax Highlighting
3. Version Control
4. Error Checking
2.9 Installing IDE(Intellij Idea)
Tasks:
1.Create a class to output “good morning” using a text
editor and check output.
2.Create a new Project in Intelij Idea and output
“subscribe” on the console.
3.Show the following patterns:
FF5F1F
Practice Exercise
Java Basics
Answer in True/False:
1.Computers understand high level languages like Java, C.
2.An Algorithm is a set of instructions to accomplish a task.
3.Computer is smart enough to ignore incorrect syntax.
4.Java was first released in 1992.
5.Java was named over a person who made good coffee.
6.ByteCode is platform independent.
7.JDK is a part of JRE.
8.It’s optional to declare main method as public.
9..class file contains machine code.
10.println adds a new line at the end of the line.
FF5F1F
Practice Exercise
Java Basics
Answer in True/False:
1.Computers understand high level languages like Java, C. False
2.An Algorithm is a set of instructions to accomplish a task. True
3.Computer is smart enough to ignore incorrect syntax. False
4.Java was first released in 1992. False
5.Java was named over a person who made good coffee. False
6.ByteCode is platform independent. True
7.JDK is a part of JRE. False
8.It’s optional to declare main method as public. False
9..class file contains machine code. False
10.println adds a new line at the end of the line. True
KG Coding
Some Other One shot Video Links:
• Complete HTML
• Complete CSS
• Complete JavaScript
• Complete React and Redux
• One shot University Exam Series
1. Variables
2. Data Types
3. Naming Conventions
4. Literals
5. Keywords
6. Escape Sequences
7. User Input
8. Type Conversion and Casting
3.1. What are Variables?
snake_case
• Start with an lowercase letter. Separate words with underscore
• Example: my_variable_name
Kebab-case
• All lowercase letters. Separate words with hyphens. Example:
my-variable-name
Task:
4. Show the following patterns using single print
statement:
3.7 User Input
FF5F1F
Answer in True/False:
1.In Java, a variable's name can start with a number.
2.char in Java can store a single character.
3.Class names in Java typically start with a lowercase letter.
4.100L is a valid long literal in Java.
5.\d is an escape sequence in Java for a digit character.
6.Scanner class is used for reading console input.
7.In Java, an int can be automatically converted to a byte.
8.Java variable names are case-sensitive.
9.Scanner class can be used to read both primitive data types and
strings.
10.Explicit casting is required to convert a double to an int.
FF5F1F
Practice Exercise
Data Types, Variables & Input
Answer in True/False:
1.In Java, a variable's name can start with a number. False
2.char in Java can store a single character. True
3.Class names in Java typically start with a lowercase letter. False
4.100L is a valid long literal in Java. True
5.\d is an escape sequence in Java for a digit character. False
6.Scanner class is used for reading console input. True
7.In Java, an int can be automatically converted to a byte. False
8.Java variable names are case-sensitive. True
9.Scanner class can be used to read both primitive data types True
and strings.
10.Explicit casting is required to convert a double to an int. True
KG Coding
Some Other One shot Video Links:
• Complete HTML
• Complete CSS
• Complete JavaScript
• Complete React and Redux
• One shot University Exam Series
8. Create a program that takes two numbers and shows result of all
arithmetic operators (+,-,*,/,%).
9. Create a program to calculate product of two floating points numbers.
10.Create a program to calculate Perimeter of a rectangle.
Perimeter of rectangle ABCD = A+B+C+D
11.Create a program to calculate the Area of a Triangle.
Area of triangle = ½*B*H
12.Create a program to calculate simple interest.
Simple Interest = (P x T x R)/100
13.Create a program to calculate Compound interest.
Compound Interest = P(1 + R/100)t
14.Create a program to convert Fahrenheit to Celsius
°C = (°F - 32) × 5/9
4.6 if-else
1. Syntax: Uses if () {} to check a condition.
2. What is if: Executes block if condition is true, skips if false.
3. What is else: Executes a block when the if condition is false.
4. Curly Braces can be omitted for single statements, but not
recommended.
5. If-else Ladder: Multiple if and else if blocks; only one executes.
6. Use Variables: Can store conditions in variables for use in if
statements.
4.7 Relational Operators
Equality
• == Checks value equality.
Inequality
• != Checks value inequality.
Relational
• > Greater than.
• < Less than.
• >= Greater than or equal to.
• <= Less than or equal to.
Order of Relational operators is less than arithmetic operators
4.8 Logical Operators
• The decimal number system is said to be of base, or radix, 10 because it uses 10 digits and the
coefficients are multiplied by powers of 10.
• This is the base that we often use in our day to day life.
• Example: (7,392)10 , where 7,392 is a shorthand notation for what should be written as
• Each coefficient aj is multiplied by a power of the radix, e.g., 2j, and the results are added to
obtain the decimal equivalent of the number.
Answer in True/False:
1.In Java, && and || operators perform short-circuit evaluation.
2.In an if-else statement, the else block executes only when the if
condition is false.
3.Java allows an if statement without the else part.
4.The ^ operator in Java is used for exponentiation.
5.Unary minus operator can be used to negate the value of a
variable in Java.
6.a += b is equivalent to a = a + b in Java.
7.In Java, the binary number system uses base 10.
8.The number 1010 in binary is equivalent to 10 in decimal.
9.& and | are logical operators in Java.
10.In Java, a >> 2 shifts the binary bits of a to the left by 2 positions.
FF5F1F
Practice Exercise
Operators, If-else & Number System
Answer in True/False:
1.In Java, && and || operators perform short-circuit evaluation. True
2.In an if-else statement, the else block executes only when the if True
condition is false.
3.Java allows an if statement without the else part. True
4.The ^ operator in Java is used for exponentiation. False
5.Unary minus operator can be used to negate the value of a True
variable in Java.
6.a += b is equivalent to a = a + b in Java. True
7.In Java, the binary number system uses base 10. False
8.The number 1010 in binary is equivalent to 10 in decimal. True
9.& and | are logical operators in Java. False
10.In Java, a >> 2 shifts the binary bits of a to the left by 2 positions.False
KG Coding
Some Other One shot Video Links:
• Complete HTML
• Complete CSS
• Complete JavaScript
• Complete React and Redux
• One shot University Exam Series
1. Comments
2. While Loop
3. Methods
4. Return statement
5. Arguments
6. Arrays
7. 2D Arrays
5.1 Java Comments
1. Used to add notes in Java code
2. Not displayed on the web page
3. Helpful for code organization
4. Syntax:
1. Single Line: //
2. Multi Line: /* */
3. Java Docs: /** */
5.2 What is a Loop?
1. Code that runs multiple times based on a
condition.
2. Repeated execution of code.
3. Loops automate repetitive tasks.
4. Types of Loops: while, for, while, do-while.
5. Iterations: Number of times the loop runs.
5.2 While Loop
28. Develop a program that prints the multiplication table for a given number.
29. Create a program to sum all odd numbers from 1 to a specified number N.
30. Write a function that calculates the factorial of a given number.
31. Create a program that computes the sum of the digits of an integer.
32. Create a program to find the Least Common Multiple (LCM) of two
numbers.
33. Create a program to find the Greatest Common Divisor (GCD) of two
integers.
34. Create a program to check whether a given number is prime.
35. Create a program to reverse the digits of a number.
36. Create a program to print the Fibonacci series up to a certain number.
37. Create a program to check if a number is an Armstrong number.
38. Create a program to verify if a number is a palindrome.
39. Create a program that print patterns:
5.6 What is an Array?
40. Create a program to find the sum and average of all elements in an
array.
41. Create a program to find number of occurrences of an element in an
array.
42. Create a program to find the maximum and minimum element in an
array.
43. Create a program to check if the given array is sorted.
44. Create a program to return a new array deleting a specific element.
45. Create a program to reverse an array.
46. Create a program to check is the array is palindrome or not.
47. Create a program to merge two sorted arrays.
48. Create a program to search an element in a 2-D array.
49. Create a program to do sum and average of all elements in a 2-D array.
50. Create a program to find the sum of two diagonal elements.
Revision
1. Comments
2. While Loop
3. Methods
4. Return statement
5. Arguments
6. Arrays
7. 2D Arrays
FF5F1F
Practice Exercise
While Loop, Methods & Arrays
Answer in True/False:
1. A 'while' loop in Java continues to execute as long as its condition is
true.
2. The body of a 'while' loop will execute at least once, regardless of
the condition.
3. A 'while' loop cannot be used for iterating over an array.
4. Infinite loops are not possible with 'while' loops in Java.
5. A method in Java can return more than one value at a time.
6. It's mandatory for every Java method to have a return type.
7. The size of an array in Java can be modified after it is created.
8. Arrays in Java can contain elements of different data types.
9. An array is a reference type in Java.
10.Java arrays are zero-indexed, meaning the first element has an index
of 0.
FF5F1F
Practice Exercise
While Loop, Methods & Arrays
Answer in True/False:
1. A 'while' loop in Java continues to execute as long as its condition is True
true.
2. The body of a 'while' loop will execute at least once, regardless of False
the condition.
3. A 'while' loop cannot be used for iterating over an array. False
4. Infinite loops are not possible with 'while' loops in Java. False
5. A method in Java can return more than one value at a time. False
6. It's mandatory for every Java method to have a return type. True
7. The size of an array in Java can be modified after it is created. False
8. Arrays in Java can contain elements of different data types. False
9. An array is a reference type in Java. True
10.Java arrays are zero-indexed, meaning the first element has an index True
of 0.
KG Coding
Some Other One shot Video Links:
• Complete HTML
• Complete CSS
• Complete JavaScript
• Complete React and Redux
• One shot University Exam Series
59. Create a program using do-while to find password checker until a valid
password is entered.
60. Create a program using do-while to implement a number guessing game.
61. Create a program using for loop multiplication table for a number.
62. Create a program using for to display if a number is prime or not.
63. Create a program using for-each to find the maximum value in an integer array.
64. Create a program using for-each to the occurrences of a specific element in an
array.
65. Create a program using break to read inputs from the user in a loop and break
the loop if a specific keyword (like "exit") is entered.
66. Create a program using continue to sum all positive numbers entered by the
user; skip any negative numbers.
67. Create a program using continue to print only even numbers using continue for
odd numbers.
68. Create a program using recursion to display the Fibonacci series upto a certain
number.
69. Create a program using recursion to check if a string is a palindrome using
recursion.
7.6 Random Numbers & Math class
Key Methods:
1. abs(): Absolute value.
2. ceil(): Rounds up.
3. floor(): Rounds down.
4. round(): Rounds to nearest integer.
5. max(), min(): Maximum and minimum of two numbers.
6. pow(): Power calculation.
7. sqrt(): Square root.
8. random(): Random number generation.
9. exp(), log(): Exponential and logarithmic functions.
10.Trigonometric functions: sin(), cos(), tan().
70. Define a Student class with fields like name and age, and use
toString to print student details.
71. Concatenate and Convert: Take two strings, concatenate them,
and convert the result to uppercase.
72. Calculate the area and circumference of a circle for a given radius
using Math.PI
73. Simulate a dice roll using Math.random() and display the outcome
(1 to 6).
74. Create a number guessing game where the program selects a
random number, and the user has to guess it.
75. Take an array of words and concatenate them into a single string
using StringBuilder.
76. Create an object with final fields and a constructor to initialize
them.
Revision
1. Ternary operator
2. Switch
3. Loops (Do-while, For, For each)
4. Using break & continue
5. Recursion
6. Random Numbers & Math class
7. Don’t Learn Syntax
8. toString Method
9. String class
10. StringBuffer vs StringBuilder
11. Final keyword
FF5F1F
Practice Exercise
Control Statements, Math & String
Answer in True/False:
1. The ternary operator in Java can replace certain types of if-else
statements.
2. A switch statement in Java can only test for equality with constants.
3. The do-while loop will execute at least once even if the condition is
false.
4. A for-each loop in Java is used to iterate over arrays.
5. The break statement skips the current iteration.
6. The continue statement exits the loop immediately, regardless of the
condition.
7. In Java, recursion is a process where a method can call itself directly.
8. Random numbers generated by Math.random() are inclusive of 0 and 1.
9. The String class is mutable, meaning it can be changed after it's created.
10. StringBuilder is faster than StringBuffer since it is not synchronized.
11. A final variable in Java can be assigned a value once and only once.
FF5F1F
Practice Exercise
Control Statements, Math & String
Answer in True/False:
1. The ternary operator in Java can replace certain types of if-else True
statements.
2. A switch statement in Java can only test for equality with constants. True
3. The do-while loop will execute at least once even if the condition is True
false.
4. A for-each loop in Java is used to iterate over arrays. True
5. The break statement skips the current iteration. False
6. The continue statement exits the loop immediately, regardless of the False
condition.
7. In Java, recursion is a process where a method can call itself directly. True
8. Random numbers generated by Math.random() are inclusive of 0 and 1. False
9. The String class is mutable, meaning it can be changed after it's created. False
10. StringBuilder is faster than StringBuffer since it is not synchronized. True
11. A final variable in Java can be assigned a value once and only once. True
KG Coding
Some Other One shot Video Links:
• Complete HTML
• Complete CSS
• Complete JavaScript
• Complete React and Redux
• One shot University Exam Series
1. Root Class: The Object class is the parent class of all classes in Java, forming
the top of the class hierarchy.
2. Default Methods: It provides fundamental methods like equals(),
hashCode(), toString(), and getClass() that can be overridden by subclasses.
3. String Representation: The toString() method returns a string
representation of the object, often overridden for more informative
output.
8.9 Equals and HashCode
1. equals() Method: Used for logical equality checks between objects. By default, it
compares object references, but it's commonly overridden to compare object states.
2. hashCode() Method: Generates an integer hash code representing an object. It's
crucial for the performance of hash-based collections like HashMap.
3. Equals-Hashcode Contract: If two objects are equal according to equals(), they must
have the same hash code. However, two objects with the same hash code aren't
necessarily equal.
4. Overriding Both: If equals() is overridden, hashCode() should also be overridden to
maintain consistency between these methods.
8.10 Nested and Inner Classes
1. Nested Classes: Classes defined within another class,
divided into static (static nested classes) and non-static
(inner classes).
2. Static Nested Classes: Act as static members of the outer
class; can access outer class's static members but not its
non-static members.
3. Inner Classes: Associated with an instance of the outer
class; can access all members of the outer class, including
private ones.
4. Local and Anonymous Inner Classes: Local inner classes
are defined within a block (like a method) and are not
visible outside it. Anonymous inner classes are nameless
and used for single-use implementations.
5. Use Cases: Useful for logically grouping classes,
improving encapsulation, and enhancing code readability.
FF5F1F
81. Create a class Person with attributes name and age. Override
equals() to compare Person objects based on their attributes.
Override hashCode() consistent with the definition of equals().
1. What is Abstraction
2. Abstract Keyword
3. Interfaces
4. What is Polymorphism
5. References and Objects
6. Method / Constructor Overloading
7. Super Keyword
8. Method / Constructor Overriding
9. Final keyword revisited
10.Pass by Value vs Pass by reference.
9.1 What is Abstraction
1.Core Principle: Abstraction hides complex
implementation details, focusing only on
essential features.
2.Focus on Functionality: Emphasizes what an
object does, not how it does it, through clear
interfaces.
9.1 What is Abstraction
1.Simplifies Complexity: It reduces complexity by
showing only relevant information in class design.
2.Real-World Modelling: Abstraction allows creating
objects that represent real-life entities with key
attributes and behaviours.
9.2 Abstract Keyword
1. What is an Exception
2. Try-Catch
3. Types of Exception
4. Throw and Throws
5. FinallyBlock
6. Custom Exceptions
7. FileWriter class
8. FileReader class
10.1 What is an Exception
throws Keyword:
1. Declares that a method may throw one or more exceptions.
2. Used in the method signature to indicate that the method might throw
exceptions of specified types.
3. A method declared with throws requires the calling method to handle or
further declare the exception.
10.4 Throw and Throws
throw Keyword:
1. Used to explicitly throw an exception from any method or block of code.
2. You can throw either a new instance of an exception or an existing
exception object using throw.
3. Example: throw new ArithmeticException("Division by zero");
10.4 Throw and Throws
10.4 Throw and Throws
10.5 Finally Block
1. Executes code after the try-catch blocks, used mainly for cleanup operations.
2. Always runs regardless of whether an exception is thrown or caught in the try-
catch blocks.
3. Ideal for closing resources like files or database connections to prevent
resource leaks.
10.6 Custom Exceptions
1. Provide a way to use primitive data types (int, char, boolean, etc.) as objects.
2. Automatic conversion between the primitive types and their corresponding
wrapper classes.
3. Once created, the value of a wrapper object cannot be changed.
4. Utility Methods: Each wrapper class provides useful methods, like compareTo,
valueOf, and parseXxx (e.g., parseInt for Integer).
5. Required for storing primitives in collection objects like ArrayList, HashMap, etc.
6. Allows assignment of null to primitive values when needed.
11.2 Autoboxing
1. Collection Interface: The root interface of the collection hierarchy. It declares basic
operations like add, remove, clear, and size.
2. List Interface: An ordered collection. Lists can contain duplicate elements.
3. Set Interface: A collection that cannot contain duplicate elements.
4. Queue Interface: A collection used for holding elements in FIFO prior to processing.
5. Map Interface: Not a true Collection, but part of the Collections Framework. Maps
store key-value pairs. Keys are unique, but different keys can map to the same value.
11.4 List Interface
1. They allow you to write flexible and reusable code by enabling types (classes and
interfaces) to be parameters when defining classes, interfaces, and methods.
2. Generics provide compile-time type safety by allowing you to enforce that certain
objects are of a specific type.
3. With generics, you don’t need to cast objects because the type is known.
4. Generics are denoted by angle brackets <>, e.g., List<String> means a list of strings.
5. Diamond Operator: Introduced in Java 7, the diamond operator <> allows you to infer
the type parameter from the context, simplifying instantiation of generic classes.
FF5F1F
96. Create an enum called Day that represents the days of the
week. Write a program that prints out all the days of the
week from this enum.
97. Enhance the Day enum by adding an attribute that
indicates whether it is a weekday or weekend. Add a
method in the enum that returns whether it's a weekday or
weekend, and write a program to print out each day along
with its type.
98. Create a Map where the keys are country names (as String)
and the values are their capitals (also String). Populate the
map with at least five countries and their capitals. Write a
program that prompts the user to enter a country name
and then displays the corresponding capital, if it exists in
the map.
Revision
1. Variable Arguments
2. Wrapper Classes & Autoboxing
3. Collections Library
4. List Interface
5. Queue Interface
6. Set Interface
7. Collections Class
8. Map Interface
9. Enums
10.Generics & Diamond Operators
FF5F1F
Practice Exercise
Collections & Generics
Answer in True/False
1. Variable arguments can be used to pass an arbitrary number of values to a
method.
2. Autoboxing is the process where primitive types are automatically converted
into their corresponding wrapper class objects by the Java compiler.
3. Every class in the Collections Library implements the Collection interface.
4. Lists guarantee the order of insertion for the elements they contain.
5. Sets in Java inherently maintain the elements in sorted order.
6. In a Map, you can have multiple entries with the same value but not with
the same key.
7. Enums in Java can have constructors, methods, variables, and can
implement interfaces.
8. With the diamond operator, you do not need to specify the type on the
right-hand side of a statement when initializing an object.
9. The List interface provides methods for inserting elements at a specific
position in the list.
10.Wrapper classes in Java, such as Integer and Double, can be extended
like any other class.
FF5F1F
Practice Exercise
Collections & Generics
Answer in True/False
1. Variable arguments can be used to pass an arbitrary number of values to a True
method.
2. Autoboxing is the process where primitive types are automatically converted True
into their corresponding wrapper class objects by the Java compiler.
3. Every class in the Collections Library implements the Collection interface. False
4. Lists guarantee the order of insertion for the elements they contain. True
5. Sets in Java inherently maintain the elements in sorted order. False
6. In a Map, you can have multiple entries with the same value but not with True
the same key.
7. Enums in Java can have constructors, methods, variables, and can True
implement interfaces.
8. With the diamond operator, you do not need to specify the type on the True
right-hand side of a statement when initializing an object.
9. The List interface provides methods for inserting elements at a specific True
position in the list.
10.Wrapper classes in Java, such as Integer and Double, can be extended False
like any other class.
KG Coding
Some Other One shot Video Links:
• Complete HTML
• Complete CSS
• Complete JavaScript
• Complete React and Redux
• One shot University Exam Series
99. Write a program that creates two threads. Each thread should print
"Hello from Thread X", where X is the number of the thread (1 or 2),
ten times, then terminate.
100. Write a program that starts a thread and prints its state after each
significant event (creation, starting, and termination). Use
Thread.sleep() to simulate long-running tasks and Thread.getState() to
print the thread's state.
101. Create three threads. Ensure that the second thread starts only after
the first thread ends and the third thread starts only after the second
thread ends using the join method. Each thread should print its start
and end along with its name.
102. Simulate a traffic signal using threads. Create three threads
representing three signals: RED, YELLOW, and GREEN. Each signal
should be on for a certain time, then switch to the next signal in order.
Use sleep for timing and synchronize to make sure only one signal is
active at a time.
12.8 Intro to Executor Service
Intermediate Operations
1. Laziness: Executed only when a terminal operation is invoked, setting
up a pipeline without processing data.
2. Stream Transformation: Transform one stream into another, e.g.,
filter, map. They're chainable, allowing multiple transformations.
3. State Handling: Can be stateless (like map) or stateful(like sorted),
affecting processing.
13.9 Intermediate vs Terminal Operations
Terminal Operations
1. Computation Trigger: Initiates the stream processing and closes the
stream. After this, the stream can't be reused.
2. Final Outcome: Produces a result (like a sum or list) or a side-effect
(like printing each element). Not chainable.
3. Examples: Operations like collect, forEach, reduce, sum, max, min,
and count are terminal.
13.10 Max, Min, Collect to List
1. max() finds the largest element in
the stream according to a given
comparator or natural ordering.
2. min() identifies the smallest element
in the stream based on a provided
comparator or natural ordering.
3. collect(Collectors.toList()) gathers
all the elements of the stream into a
new List.
13.11 Sort, Distinct, Map
1. sorted() orders the elements of a stream
based on their natural order or a provided
comparator.
2. distinct() filters out duplicate elements,
ensuring that every element in the resulting
stream is unique.
3. map() applies a function to each element of a
stream, transforming them into a new stream
of results based on the function logic.
FF5F1F