JAVA Course Notes
JAVA Course Notes
JAVA NOTES
Hello Guyz. I made these Java notes for you. It also includes practice sets
for you: which will make your java even better and if you have any problem
or don’t understand the topic, then message me on Instagram @xstechie
All Concepts
0. Introduction to JAVA
3. String in JAVA
4. Condition in JAVA
5. Loop Control in JAVA
6. Arrays in JAVA
7. Methods in JAVA
1 Instagram - @xstechie
xstechie
JAVA NOTES
0 – Introduction to JAVA
Introduction to JAVA
JAVA is compiled into the bytecode and then it is interpreted to machine code.
JAVA Installation –
in a file directory
2 Instagram - @xstechie
xstechie
JAVA NOTES
}
1. Method A method is a block of code which only runs when it is called. You
can pass data, known as parameters, into a method. Methods are used to perform
certain actions, and they are also known as functions.
2. Classes Everything in Java is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and brake.
Naming Convention
Pascal – AddTwoNumber
Camel – addTwoNumber
3 Instagram - @xstechie
xstechie
JAVA NOTES
1 – Variable and Datatypes
Just like we have some rule that we follow to speak English ( the grammar ) , we have some
rule to follow while running a JAVA program the set of these rules is called syntax .
Variables
A variable is a container that store a value. This value can be changed during the
execution of the program.
Ex - int number = 8 ;
we can choose a name while declaring a JAVA variable if the following rules are followed:
Data Types
4 Instagram - @xstechie
xstechie
JAVA NOTES
Datatype Code
char character = ‘ A ’;
5 Instagram - @xstechie
xstechie
JAVA NOTES
Float F1 = 5.6f;
Double d1 = 4.66D;
Boolean a = true;
( F,f ) ( D,d )
In order to choose the datatype we first need to find the type of data we want to store . After
that we need to analyse the min & max value we might use .
Literals
Keyword
Words which are reserved and used by the JAVA compiler .They cannot be used as an
Identifier.
6 Instagram - @xstechie
xstechie
JAVA NOTES
Scanner class has a lot of method to read the data from the keyboard
Quick Quiz
Write a program to calculate percentage of a given student in CBSE board exam . His
marks from 5 subject must be taken as input from the keyboard ( Marks are out of 100 ).
7 Instagram - @xstechie
xstechie
JAVA NOTES
1 – Practice Set
2. Write a program to calculate CGPA using marks of three subjects ( out of 100 )
3. Write a JAVA program which asks the user to enter his/her name and greet them with
4. Write a JAVA program to detect whether a number entered by the user is integer or not.
8 Instagram - @xstechie
xstechie
JAVA NOTES
7 + 11 = 18
Operand Operator Operand Result
Types of Operator
1. Arithmetics Operator + , - , * , / , % , ++ , --
2. Assigment Operator = , +=
Presedence of Operator
The Operator are applied and evaluated based on precedence. For example ( +, - )
has less
Int a = 6 * 5 – 34/2;
Highest presendece goes to * and / . They are then evaluated on the basis of left to
right associativity
9 Instagram - @xstechie
xstechie
JAVA NOTES
Associativity
Associativity tells the direction of execution on of operation .It can either be left to
right.
* / Left to Right
+ - Left to Right
++ , = Right to Left
Quick Quiz – How will you write the following expression in JAVA ?
1. x – y/2
2. b2 – 4ac/2a
3. v2 – v2
4. a*b–d
Following table summarizes the resulting datatype after arithmetic operation on them
Int i = 56;
Int b = i++;
10 Instagram - @xstechie
xstechie
JAVA NOTES
Int j = 67;
Int c = ++j;
11 Instagram - @xstechie
xstechie
JAVA NOTES
2 – Practice Set
3. Write comparison operator to find out whether a given number is greater than the
user entered number or not
12 Instagram - @xstechie
xstechie
JAVA NOTES
3 – String in JAVA
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
String name;
System.out.printf( “%c” ch );
%d for double, int
%f for float
%s for string
Example
int a = 7;
Float b = 4.32f;
System.out.printf( the value of a is %d and value of b is %f, a ,b );
13 Instagram - @xstechie
xstechie
JAVA NOTES
String Methods
String method operate on JAVA String. They can be used to find length of the String,
1 char charAt(int index) It returns char value for the particular index
4 static String format(Locale l, String It returns formatted string with given locale.
format, Object... args)
6 String substring(int beginIndex, int It returns substring for given begin index and end index.
endIndex)
7 boolean contains(CharSequence s) It returns true or false after matching the sequence of char value.
10 boolean equals(Object another) It checks the equality of string with the given object.
14 Instagram - @xstechie
xstechie
JAVA NOTES
11 boolean isEmpty() It checks if string is empty.
13 String replace(char old, char new) It replaces all occurrences of the specified char value.
17 String[] split(String regex, int limit) It returns a split string matching regex and limit.
20 int indexOf(int ch, int fromIndex) It returns the specified char value index starting with given index.
22 int indexOf(String substring, int It returns the specified substring index starting with given index.
fromIndex)
15 Instagram - @xstechie
xstechie
JAVA NOTES
27 String trim() It removes beginning and ending spaces of this string.
28 static String valueOf(int value) It converts given type into string. It is an overloaded method.
Escape sequence character consist of more than one character but represent one
character when used within the strings
2. \t tab
3. \’ single quote
16 Instagram - @xstechie
xstechie
JAVA NOTES
3 – Practice Set
3. Write a JAVA program to to fill in a letter template which looks like below
Letter = “Dear <|name|> , thnx a lot”
Replace <|name|> with a string ( xstechie )
5. Write a JAVA program to format “Dear xstechie , This JAVA program is nice” using
escape sequence character.
17 Instagram - @xstechie
xstechie
JAVA NOTES
4 – Condition in JAVA
Statements in Java
Till now we have seen two types of executable statements (without counting
declarations):
1. Method invocation
2. Assignment
Conditional statements
Java, like all other programming languages, is equipped with specific statements that
allow us to check a condition and execute certain parts of code depending on
whether the condition is true or false. Such statements are called conditional, and are
a form of composite statement.
18 Instagram - @xstechie
xstechie
JAVA NOTES
&& AND
| | OR
! NOT
AND Operator
OR Operator
NOT Operator
Negative the givel logic (True become false and false become true)
!True = False
!False = True
19 Instagram - @xstechie
xstechie
JAVA NOTES
Else – if clause
Instead of using multiple if statement. We can also use else if along with if thus
forming an if-else – if-else ladder
Using such kind of logic reduce indents last else is executed only if all the conditions
fail
If( condition ){
//statement;
}
Else if ( condition ){
//statement;
}
Else if ( condition ){
//statement;
}
Else {
}
Switch( variable ){
Case c1:
//code
Break;
Case c2:
//code
Break;
Case c3:
//code
Break;
default :
//code
}
Variable can be an integer , character or string in JAVA. A Switch can occur within
another but in practice this is rarely done
20 Instagram - @xstechie
xstechie
JAVA NOTES
4 – Practice Set
2. Write a program to find out whether a student is pass or fail if it require total 40% and
at least 33% in each subject to pass .Assume 3 subject and take marks as an input user
21 Instagram - @xstechie
xstechie
JAVA NOTES
5 – Loops Control Instruction
Sometime we want or program to execute a few set of instructiom over and over again
for example – print 1 to 1000’
Print multiplication table of 7 ,etc
Loops make it easy for us to fill the computer that a given set of instruction need to be
executed repeatedly.
Types of Loops
1. While loop
2. Do – while loop
3. For loop
While loops
If the condition never be false while loop keep getting executed such a loop Is knows
as a infinite loop.
Ex – int I = 1;
While( i<=3){
System.out.println( i );
i++; }
Output 1 , 2, 3
While( true ){
System.out.println( “I am infinite loop” );
}
Output infinite
Quick Quiz
Write a program to print natural number from 100 to 200.
22 Instagram - @xstechie
xstechie
JAVA NOTES
Do-While loops
This is similar to a while loop except the fact that it is guaranteed to execute at least
once.
do{
//statement
}while( condition );
Example – int b = 0;
do{
System.out.println(b);
b++;
}while( b<5 );
Output 1, 2, 3, 4,
Quick Quiz
Write a program to print first n natural number using do while loop.
For loops
The Syntax of a for loop look like this:
For( initialize; check Boolean expression; update ){
//code;
}
A for loop is usually used to execute a piece od code for specific number of time
Quick Quiz
Write a program to print first n Odd number using for loop.
Quick Quiz
Write a program to print first n natural number using for loop in reverse order
23 Instagram - @xstechie
xstechie
JAVA NOTES
Break and Continue
Break Statement
The break statement is used exit the loop irrespective of whether the
condition is true or false
Whenever a “break” is encountered inside the loop, the control is sent outside
the loop
Example –
For ( int i = 1; i>0 ; i++){
If( i ==2){
System.out.println(“This is break”);
Break;
Continue Statement
The continue statement is used to immediately move to the next iteration of
the loop. The control is taken to the next iteration thus skipping everything
below “continue” inside the loop for that iteration.
Example –
For ( int i = 1; i>0 ; i++){
If( i ==2){
System.out.println(“This is break”);
Continue;
}
System.out.println( i );
System.out.println( “best” );
}
In While
Int i =0;
While( i<10 ){
i++;
if( i== 2 ){
System.out.println(“This is break/continue”);
Break/continue;
}
System.out.println( i );
}
24 Instagram - @xstechie
xstechie
JAVA NOTES
5 – Practice Set
5. Write a program to calculate the sum of the number occurring in the multiplication
table of 8
25 Instagram - @xstechie
xstechie
JAVA NOTES
6 – Arrays in JAVA
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class,
and implements the Serializable as well as Cloneable interfaces. We can store primitive values
or objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
26 Instagram - @xstechie
xstechie
JAVA NOTES
Types of Array in java
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
We can declare, instantiate and initialize the java array together by:
27 Instagram - @xstechie
xstechie
JAVA NOTES
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the
loop.
for(data_type variable:array){
//body of the loop
}
Let us see the example of print the elements of Java array using the for-each loop.
In such case, data is stored in row and column based index (also known as matrix
form).
28 Instagram - @xstechie
xstechie
JAVA NOTES
Syntax to Declare Multidimensional Array in Java
29 Instagram - @xstechie
xstechie
JAVA NOTES
6 – Practice Set
2. Write a program to find out whether a given integer is present is an array or not
3. Calculate the average marks from an array containing mark of all student in physics
using for each loop.
30 Instagram - @xstechie
xstechie
JAVA NOTES
7 – Methods in JAVA
In general, a method is a way to perform some task. Similarly, the method in Java is a
collection of instructions that performs a specific task. It provides the reusability of code. We
can also easily modify code using methods. In this section, we will learn what is a method
in Java, types of methods, method declaration, and how to call a method in Java.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
as we have shown in the following figure.
31 Instagram - @xstechie
xstechie
JAVA NOTES
Following method return sum of two numbers
Int mySum( int a , int b ){
Int c = a + b;
Return c; return value
}
Calling a Method
A method can be called by creating an object of the classs in which the method exist
followed by the method call.
Static Keyword
It is used to associate a method of a given class with the class rather the object. Static
method in a class is shared by all the objects.
The value 2 and 4 are copied to a and b and then a+b = 2+4 = 6 is returned in c
which is an integer.
32 Instagram - @xstechie
xstechie
JAVA NOTES
Method Overloading
Two or more methods can have same name but different parameter such methods
are called Overloaded methods
Void xstechie( )
Void xstechie( int a) overloaded method xstechie
Void xstechie( int a , int b ) overloaded method xstechie
A function with var args can be created in JAVA using following Syntax;
Recursion
A function in JAVA can call itself such calling of function by itself is called recursion
Quick Quiz Write a program to calculate ( recursion must be used )factorial of a number
in JAVA
Quick Quiz Print Fibonacci number in JAVA like ->( 0, 1 , 1, 2, 3, 5, 8, 13, 21, 34).
33 Instagram - @xstechie
xstechie
JAVA NOTES
7 – Practice Set
34 Instagram - @xstechie
xstechie
JAVA NOTES
8 – Introduction to OOPS
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Class
A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Object
35 Instagram - @xstechie
xstechie
JAVA NOTES
details of each other's data or code. The only necessary thing is the type of message
accepted and the type of response returned by the objects.
Oops terminology
2. Encapsulation Binding (or wrapping) code and data together into a single unit
are known as encapsulation. For example, a capsule, it is
wrapped with different medicines.
3. Inheritence When one object acquires all the properties and behaviors of a
parent object, it is known as inheritance. It provides code
reusability. It is used to achieve runtime polymorphism.
36 Instagram - @xstechie
xstechie
JAVA NOTES
A class with methods
37 Instagram - @xstechie
xstechie
JAVA NOTES
8 – Practice Set
3. Create a Class square with method to inialize its side , calculating area parameter ,
etc.
38 Instagram - @xstechie
xstechie
JAVA NOTES
9 – Access Modifiers & Constructors
Access Modifiers
1. Private
2. Default
3. Protected
4. Public
Example :
Return name;
this.name = “xstechie”
this.name = n
39 Instagram - @xstechie
xstechie
JAVA NOTES
Constructer in JAVA
In order to write our own contructor, we define a method with same as class name
Public Employees ( ){
Name = “xstechie”;
Id = 46;
Name = n;
}
Note 1. Constructor can take parameter without being overload.
2. There can be more than two overloaded contructors.
Quick Quiz Object the employees constructor to initialize the salary to Rs 10,000.
40 Instagram - @xstechie
xstechie
JAVA NOTES
9 – Practice Set
2. Use Constructor and calculate surface area and volume of the cylinder
41 Instagram - @xstechie
xstechie
JAVA NOTES
10 – Inheritance in JAVA
inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes
that are built upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you can add new methods and fields in
your current class also.
42 Instagram - @xstechie
xstechie
JAVA NOTES
Constructor in Inheritance
When a Derived class is extended from the base class , the constructor of the Base class
is executed first followed up by the constructor of the derived class
For the inheritance hierarchy , the constructor
C1 Parent
C2 Child
C3 Grand Child
Constructor executed in top to bottom order
This Keyword
This is a way for us to reference an object of the class which is being created/reformed.
this.area = 2 this a reference to current object
Super Keyword
A reference variable used to refer immediate parent class object
o Can be used to refer immediate parent class object
o Can be used to invoke parent class methods
o Can be used to invoke
Method Overriding
If the child class implement the same method present in the parent class again it is
known as method overriding.
( Redifining method of superclass (in Sub class))
When an object of subclass is created and the override method is called , the method
which has been implemented in the subclass is called & its code is executed.
43 Instagram - @xstechie
xstechie
JAVA NOTES
Dynamic Method Dispatch
Dynamic method dispatch is the mechanism by which a call to an overridden method
is resolved at run time, rather than compile time.
44 Instagram - @xstechie
xstechie
JAVA NOTES
class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
45 Instagram - @xstechie
xstechie
JAVA NOTES
10 – Practice Set
1. Create a class circle and use inheritance to create cylinder from it.
2. Create a class rectangle and use inheritance to create another class cuboid. Try to
keep it as close to real world scenario as possible.
4. Create methods for area & volume in Question 2 Also create getter and setter.
46 Instagram - @xstechie
xstechie
JAVA NOTES
11 – Abstract classes & Interfaces
Abstract class and interface both are used to achieve abstraction where we can
declare the abstract methods. Abstract class and interface both can't be instantiated.
Abstract Method
A method that is declared without an implementation.
Abstract class
IF a class includes abstract methods, then the class itself must be declared as
Public abstract class Xstechie{
Abstract void xs( );
//more code
}
When an abstract class is subclasses , the subclass usually provides implementation for
all of the methods inparent class, If it doesn’t , it must be declared abstract
Note
It is possible to create reference of an abstract class
It is not possible to create an object of an abstract class.
Interfaces in JAVA
Interface in English is a point where two system meet and interact . In JAVA interface
is a group of related methods with empty bodies.
Example
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");}
47 Instagram - @xstechie
xstechie
JAVA NOTES
1) Abstract class can have abstract and non- Interface can have only abstract methods. Since Java 8,
abstract methods. it can have default and static methods also.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.
4) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.
5) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.
6) An abstract class can extend another Java class and An interface can extend another Java interface only.
implement multiple Java interfaces.
7) An abstract class can be extended using keyword An interface can be implemented using keyword
"extends". "implements".
8) A Java abstract class can have class members like Members of a Java interface are public by default.
private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface
public abstract void draw(); void
} }
48 Instagram - @xstechie
xstechie
JAVA NOTES
Is multiple inheritance possible in java?
When one class extends more than one classes then this is called multiple inheritance.
For example: Class C extends class A and B then this type of inheritance is known as
multiple inheritance. Java doesn’t allow multiple inheritance.
Default methods
An interface can have static and default methods. Default methods enable us to add
new functionality to existing interfaces . This feature was introduced in JAVA 8 to ensure
backward compatibility while updating an interface. Interface can also include private
methods for default method to use.
Inheritance in Interfaces
A class can extends another class and/ can implement one and more than one
interface.
Remember that interface cannot implement another interface , only class can do that!
Example:
49 Instagram - @xstechie
xstechie
JAVA NOTES
public final void doIt ( ) {
// not allowed
// customer.increaseLimit( 1000 );
// customer = new Customer();
}
}
When applied to a class, no derived class can be created by inheriting from this class.
When applied to a method, this method can not be overrided.
When applied to an argument of method, inside the method, you cannot change
what the argument (handle) is pointing to.
When applied to a data member, the data member can not be changed.
50 Instagram - @xstechie
xstechie
JAVA NOTES
11 – Practice Set
1. Create an abstract class Pen with methods write( ) and refill( ) as abstract method.
2. Use the Pen class from Question no.1 to create a Concrete class Fountain Pen with
additional method changeNib( )
3. Create a class Monkey with jump( ) and bite( ) methods. Create a class human which
inherit thismonkey class and implement BasicAnimal interface with eat( ) and sleep( )
methods.
4. Create a class Telephone with ring( ) , lift( ) and disconnect( ) methods as abstract
methods . Create another class smartphone and demonstrate polymorphism.
51 Instagram - @xstechie
xstechie
JAVA NOTES
12 –Package in JAVA
Package in Java is a mechanism to encapsulate a group of classes, sub packages
and interfaces.
Types of packages:
Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of
the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user. First we create a
52 Instagram - @xstechie
xstechie
JAVA NOTES
directory myPackage (name should be same as the name of the package). Then create
the MyClass inside the directory with the first statement being the package names.
There are many packages to choose from. In the previous example, we used
the Scanner class from the java.util package. This package also contains date and
time facilities, random-number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the java.util package:
Creating a Package
Access modifier determine whether other classes can we a particular field or invoke a
particular method can be public , private, protected or default (no modifier)
Access Modifier within class within package outside package outside package
by subclass only
Private Yes No No No
53 Instagram - @xstechie
xstechie
JAVA NOTES
Protected Yes Yes Yes No
12 – Practice Set
2. Use a built-in package in JAVA to write a class which display message (by using print)
after taking input from user.
3. Create a package in class with three package levels folder , folderL1, folderL2.
54 Instagram - @xstechie
xstechie
JAVA NOTES
13 –Multithreading in JAVA
Multiprocessing and multithreading both are used to achieve multitasking.
In a nutshell….
Without threading :
With thread:
Main
Func( )
Func( ) End
Creating a Thread
55 Instagram - @xstechie
xstechie
JAVA NOTES
New Instance of thread created which is not yet started by invoking start( ).
Thread( )
Thread ( String name )
Thread ( Runnable r)
Thread ( Runnable r, String name )
Thread methods
Sleep ( )
Join ( )
More on docs.oracle methods of threads
13 – Practice Set
1. Write a program to print “Good Morning” and “Welcome” continuously on the screen
in JAVA using threads.
2. Add a sleep method in welcome thread of question no.1 to delay its execution for
200ms.
56 Instagram - @xstechie
xstechie
JAVA NOTES
14 –Error & Exception in JAVA
No matter how smart we are, error are our constant companions with practice we
keep better at finding & correcting them
Syntax error
Logical error
Runtime error also called exception
Syntax Error
When compiler finds something wrong with our program it throw a syntax error.
A = a + 3;
Logical Error
A logical error or bug occur when a program compiled and run but does the wrong
thing.
Runtime errors
JAVA may sometime encounter an error while the program is running . These are
also called exception
These are encounter due to circumstance like bad inout and ( or ) resources
constraints. Ex user supplier ‘s’ + 8 to a program which add 2 numbers
Syntax errors and logical errors are encountered by the programmers whereas as
Runtime errors are encountered by the users.
57 Instagram - @xstechie
xstechie
JAVA NOTES
Exception in JAVA
An exception is an event that occur when program is executed disrupting the normal
flow of instructions.
Syntax: try{
//code to try}
Catch( exception e) {
//code if exception
}
58 Instagram - @xstechie
xstechie
JAVA NOTES
Nested try – catch
Similarly we can further nest try catch blocks inside the nested try catch blocks
Quick Quiz Write a program that allow you tu keep accessing an array until a valid index
is given by the user.
If ( b ==0 ) {
Throw new Arithmetic Exception (“ div by 0” );
}
Else{
Return a/b
}
In a similar manner we can throw user defined exception:
Throw new MyException ( “Exception thrown” )
59 Instagram - @xstechie
xstechie
JAVA NOTES
The Throw Exception
The JAVA throw keyword is used to declare ab exception This gives ab information to
the programmer that there might be an exception so its better to prepared with a try
– catch block:
Finally block contain the code which is always executes whether the exception is
handled or not. It is used to execute code containing instruction to release the
system resources , class a connection etc.
14 – Practice Set
2. Write a JAVA program that print “XS” during Arithmetics exception and “xstechie”
during an Illegal argument exception.
3. Write a program that allow you to keep accessing an array until a valid index is given.
If retries exceed 5 print “error”.
60 Instagram - @xstechie
xstechie
JAVA NOTES
15 – Advance JAVA
Collection Framework
A collection represent a group of object JAVA collection provide classes and interface
for us to be able to write code quickly and efficiently.
We need collection for efficient storage and better manipulation of data in JAVA.
Collection class is available in JAVA.util package. Collection class also provide static
methods for sorting , searching etc.
JAVA.time package for Date & time in JAVA from JAVA 8 onward
Before JAVA 8 JAVA.util package used to hold the date & time classes NOPw these
classes are depreciated.
61 Instagram - @xstechie
xstechie
JAVA NOTES
How JAVA stored a Date ?
Date in JAVA is stored in the form of a long number. This long number holds the
number of millisecond passed since 1 jan 1970.
JAVA assume that 1900 is the start year which means it calculate years passed since
1900 whenever we ask it for year passed.
System.out.println( d );
JAVA Date class has few methods which can be used for ex : getDate( ), getDay( ) etc.
Calendar a = Calendar.getInstance( );
62 Instagram - @xstechie
xstechie
JAVA NOTES
getTime methods return a Date Object
other methods can be looked up from the JAVA docs
This class is used an instance of Gregorian Calendar. We change the year month &
date using set methods!
Time zone class is used to create Time zone in JAVA some of the important methods
of Time Zone class are:
JAVA.time Package
ArrayList in JAVA
63 Instagram - @xstechie
xstechie
JAVA NOTES
LinkedList in JAVA
Linked List is a part of the Collection framework present in java.util package. This
class is an implementation of the LinkedList data structure which is a linear data
structure where the elements are not stored in contiguous locations and every
element is a separate object with a data part and address part. The elements are
linked using pointers and addresses. Each element is known as a node.
ArrayDeque in JAVA
Hashing Technique
The hash function is a key-value mapping function. When two or more keys are
mapped to the same value using these hashing methods, there exists duplicate
values. The use of chain hashing prevents collisions. Each hash table cell should lead
to a linked list of entries that have the same hash function value.
classes Hashset
Hashmap
LinkedHashMap collection
HashTable
64 Instagram - @xstechie
xstechie
JAVA NOTES
15 – Practice Set
1. Create an ArrayList and store names of 10 student inside it. Print it using a for – each
loop.
2. Use the Date class in JAVA to print time in the following format
21 : 47 : 02
4. Create a set in JAVA. Try to store duplicate element inside this et and verify that only
one instance is stored
65 Instagram - @xstechie
xstechie
JAVA NOTES
16 – Advance JAVA
Annotation in JAVA
Lamba Expression
JAVA Generics
Introduced from JDK 5.0 onward. Very similar to C++ Templates (but not the same)
If we write
a.get(75);
66 Instagram - @xstechie
xstechie
JAVA NOTES
File handling in JAVA
67 Instagram - @xstechie