0% found this document useful (0 votes)
118 views67 pages

JAVA Course Notes

The document contains Java notes and practice problems for learning Java. It covers topics like variables and data types, operators, strings, conditions, loops, arrays, methods, OOP concepts, inheritance, abstract classes, interfaces, packages, and exceptions. The notes provide explanations and examples for each topic. Practice problems are included to help understand concepts and test skills. Contact information is provided for any questions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
118 views67 pages

JAVA Course Notes

The document contains Java notes and practice problems for learning Java. It covers topics like variables and data types, operators, strings, conditions, loops, arrays, methods, OOP concepts, inheritance, abstract classes, interfaces, packages, and exceptions. The notes provide explanations and examples for each topic. Practice problems are included to help understand concepts and test skills. Contact information is provided for any questions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 67

xstechie

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

1. Variable and Datatypes in JAVA

2. Operators and Expressions in JAVA

3. String in JAVA

4. Condition in JAVA
5. Loop Control in JAVA

6. Arrays in JAVA
7. Methods in JAVA

8. Introduction to OOPS ( important )


9. Access Modifier & Constructer
10. Inheritance in JAVA

11. Abstract Classes & Interface

12. Package in JAVA


13. Multithreading in JAVA
14. Error & Exception

15. Advance JAVA – I


16. Advance JAVA – II

1 Instagram - @xstechie
xstechie
JAVA NOTES
0 – Introduction to JAVA
Introduction to JAVA

JAVA is an Object Oriented Programming language Developed by Sum Microsystem of


USA in 1991.

It was originally called “ OAK ” by James Gerlin ( inventor of JAVA )

JAVA = Purely Object Oriented

How JAVA work ?

JAVA is compiled into the bytecode and then it is interpreted to machine code.

Source Code Byte Code Machine Code


Compiled interpreted

JAVA Installation –

Install JDK from https://www.oracle.com/java/technologies/downloads/

Install Intellij Idea ( IDE ) https://www.jetbrains.com/idea/download/

JDK – JAVA Development Kit

Collection of tools used for developing and running JAVA program

JRE – JAVA Runtime Environment

Help in executing program developed in JAVA

JAVA Program Boiler Plate

Package – com.xstechie.java ; A package in JAVA is used to group

relative classes . Think of it’s a folder

in a file directory

Public class main {

Public stativ void main (String [ ] args ){ function

System.out.println( “Hello World” );

2 Instagram - @xstechie
xstechie
JAVA NOTES
}

Basic Structure of a JAVA program

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

For Classes we use Pascal Convention

Normal – Add two number

Pascal – AddTwoNumber

For Function we use camel Case Convention

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 .

Vocabulary & Grammar of JAVA

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 ;

Datatype var name value it store

Rules for declaring a variable name

we can choose a name while declaring a JAVA variable if the following rules are followed:

1. Must not begin with a digit int 1arr is invalid!


2. Name is case sensitive xstechie and Xstechie are different
3. Should not be a keyword like ( void , static )
4. White space not allowed int xs techie ; invalid
5. Can contain alphabet ,$character , _character, digit, if the other condition are met

Data Types

Data Type in JAVA fall under the following categories

1. Primitive Data Type ( Interis )


2. Non - primitive Data Type ( Derived)

Primitivie Data Type

There are 8 primitive data type supported by JAVA

1. byte - Value ranges from -128 to 127


Takes 1 byte
Default value is 0.

4 Instagram - @xstechie
xstechie
JAVA NOTES

2. Short - Value ranges from – ( 216 )/2 to ( 2 )16/2 -1


Takes 1 byte
Default value is 0.

3. Int - Value ranges from – ( 232 )/2 to ( 2 )32/2 -1


Takes 4 byte
Default value is 0.

4. Float - Value ranges from – ( see JAVA docs )


Takes 4 byte
Default value is 0.0F

5. Long - Value ranges from – ( 264 )/2 to ( 264 )/2 -1


Takes 8 byte
Default value is 0.0l

6. Double - Value ranges from – ( see Docs )


Takes 8 byte
Default value is 0.0d

7. Char - Value ranges from – 0 to 65535( 210 -1 )


Takes 2 byte
Default value is 0.

8. Boolean - Value can be true or false


Size depend on JUM
Default value is False.

Quick Quiz :- Write a JAVA program to add three numbers

Datatype Code

byte age = 34;

int age2 = 56;

short age3 = 87;

long ageDino = 56666666666L;

char character = ‘ A ’;

5 Instagram - @xstechie
xstechie
JAVA NOTES
Float F1 = 5.6f;

Double d1 = 4.66D;

Boolean a = true;

How to choose Datatypes for our variables

Primitive Data Types

Integral( int ) Float( Decimal ) char ( ‘ ’) Boolean (true or


false)

Bytes ,short ,int,long(L) ( float , Double )

( 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

A constant value which can be assigned to the variables is called as a literal

101 integer literal

10.1f float literal

10.1 double literal ( default type for decimal )

‘A’ character literal

True Boolean literal

“xstechie” String literal

Keyword

Words which are reserved and used by the JAVA compiler .They cannot be used as an
Identifier.

See docs for more

Reading data from the keyboard

In order to read data from keyboard . JAVA has a Scanner Class

6 Instagram - @xstechie
xstechie
JAVA NOTES
Scanner class has a lot of method to read the data from the keyboard

Scanner s – new Scanner ( System.in );

Int a = s.nextInt( ); Read from the Keyboard

Method to read from the keyboard

( integer in this case )

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

1. Write a program to sum three number in JAVA

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

“Hello <name > have a good day ”

4. Write a JAVA program to detect whether a number entered by the user is integer or not.

5. Write a JAVA program to convert Kilometer into miles.

8 Instagram - @xstechie
xstechie
JAVA NOTES

2 – Operator and Expression

Operator are used to perform operation on variables and value .

7 + 11 = 18
Operand Operator Operand Result

Types of Operator

1. Arithmetics Operator  + , - , * , / , % , ++ , --

2. Assigment Operator  = , +=

3. Comparison Operator  ==, >= , <=

4. Logical Operator  && , ||, !

5. Bitwise Operator  &,| ( Operator Outwise )

a. Arithmetics Operator cannot work with Boolean


b. % operator can work on float & doubles

Presedence of Operator

The Operator are applied and evaluated based on precedence. For example ( +, - )
has less

Precedence compared to ( * , / ) hence * and / are evaluated first .

In case we like to change this order , we use parenthesis

Presedence & Associativity

Int a = 6 * 5 – 34/2;

Highest presendece goes to * and / . They are then evaluated on the basis of left to
right associativity

Int b = 60/5 – 34*2;

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

Resulting Datatypes after Arithmetic Operation

Following table summarizes the resulting datatype after arithmetic operation on them

1. Return = byte + short  int


2. Return = short + int  int
3. Return = long + float float
4. Return = int + float float
5. Return = char + int  int
6. Return = char + short  int
7. Return = long + double  double
8. Return = float + double  double

Increment and Decrement Operator

a++ , ++a  Increment Operator

a-- , --a  Decrement Operator

These will operate on all datatypes except Booleans

a++  First use the value and then incremented.

++a  First incremented the value then use it.

Int i = 56;

Int b = i++;

First b is assigned I ( 56 ) then I is incremented

10 Instagram - @xstechie
xstechie
JAVA NOTES
Int j = 67;

Int c = ++j;

First j is incremented then c is assigned j ( 68 )

Quick Quiz – Try increment and decrement operator on a JAVA variables.

11 Instagram - @xstechie
xstechie
JAVA NOTES
2 – Practice Set

1. What will be the result of the following expression


Float a = 7/4 * 9/2;

2. Write a JAVA program to encrypt a grade by adding 8 to it .Decrypt it to show the


correct grade

3. Write comparison operator to find out whether a given number is greater than the
user entered number or not

4. Write the following expression in JAVA


v2 – u2 /2as

5. Find the value of the following expression .


Int x = 7;
Int a = 7 * 49/7 + 35/7;
Value of a ?

12 Instagram - @xstechie
xstechie
JAVA NOTES
3 – String in JAVA

A String is a sequence of character

What is 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.

A string is instantiated as follows:

String name;

Name = new String ( “xstechie” );

String is a class but can be used like a datatype:

String name = “xstechie”;


Reference object

Different ways to print in JAVA:

We can use the following ways to print in JAVA:

1. System.out.print( ); no new line at the end


2. System.out.println( ); New line at the end
3. System.out.printf( );
4. System.out.format( );

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 );

Output  The value of a is 7 and the value of b is 4.32

13 Instagram - @xstechie
xstechie
JAVA NOTES
String Methods

String method operate on JAVA String. They can be used to find length of the String,

Connect to lowercase , etc

Some of the commonly used String methods are:

String name = “xstechie”;

No. Method Description

1 char charAt(int index) It returns char value for the particular index

2 int length() It returns string length

3 static String format(String format, It returns a formatted string.


Object... args)

4 static String format(Locale l, String It returns formatted string with given locale.
format, Object... args)

5 String substring(int beginIndex) It returns substring for given begin index.

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.

8 static String join(CharSequence It returns a joined string.


delimiter, CharSequence... elements)

9 static String join(CharSequence It returns a joined string.


delimiter, Iterable<? extends
CharSequence> elements)

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.

12 String concat(String str) It concatenates the specified string.

13 String replace(char old, char new) It replaces all occurrences of the specified char value.

14 String replace(CharSequence old, It replaces all occurrences of the specified CharSequence.


CharSequence new)

15 static String equalsIgnoreCase(String It compares another string. It doesn't check case.


another)

16 String[] split(String regex) It returns a split string matching regex.

17 String[] split(String regex, int limit) It returns a split string matching regex and limit.

18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char value index.

20 int indexOf(int ch, int fromIndex) It returns the specified char value index starting with given index.

21 int indexOf(String substring) It returns the specified substring index.

22 int indexOf(String substring, int It returns the specified substring index starting with given index.
fromIndex)

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase using specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase using specified locale.

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

Sequence of character after backslash ‘ \ ’ are Escape sequence character

Escape sequence character consist of more than one character but represent one
character when used within the strings

Example 1. \n  new line

2. \t  tab

3. \’  single quote

4. more on JAVA docs

16 Instagram - @xstechie
xstechie
JAVA NOTES
3 – Practice Set

1. Write a JAVA program to convert a String to lower case.

2. Write a JAVA program to replace space with undercore.

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 )

4. Write a JAVA program to detect double and triple spaces in a string.

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

What are conditions in Java?

Conditions (also known as condition queues or condition variables) provide a means


for one thread to suspend execution (to "wait") until notified by another thread
that some state condition may now be true.

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.

In Java, there are two forms of conditional statements:


1. the if-else statement, to choose between two alternatives;
2. the switch statement, to choose between multiple alternatives;

The if-else statement

The if-else statement allows us to select between two alternatives.


Syntax:
if (condition to be check){
then-statement if condition is true}
else{
else-statement if condition Is false}

Rational Operator in JAVA


It used to calculate condition (true or false) inside the if statement
Example of Rational Operator are :
==, >=, >, <, <=, !=
Note  = is used for assignment where as ‘ ==’ is used for equality check

18 Instagram - @xstechie
xstechie
JAVA NOTES

Logical Operator in JAVA

&& , || , and ! are most commonly used logical operator in JAVA

These are read as:

&&  AND

| |  OR

!  NOT

Note  used to provide logic to our program

AND Operator

Evaluate to true if both condition are true


True && True = True
True && False = False
False && True = False
False && False = False

OR Operator

Evaluate to true when at least one of the condition is true

True || True = True


True || False = True
False || True = True
False || False = False

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 Case Control Instruction

Switch-case is used when we have to make a choce between number of alternative


for a given variable

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

1. What will be the output of this program


Int a = 10;
If( a == 11 ){
System.out.println(“I am 11”); }
Else{
System.out.println(“I am not 11”);
}

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

Primarily , these are three type of loops in JAVA

1. While loop
2. Do – while loop
3. For loop

We will look into these one by one;

While loops

While( Boolean condition ){


//statement
}

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 );

While  check the condition & execute the code


Do – while  execute the code & check the 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.

Decrementing For loop


For ( i = 7; , i!=0 , i-- ){
System.out.println( i );
}
Output  7, 6, 5, 4, 3, 2, 1

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

1. Write a program to print the following pattern


****
***
**
*

2. Write a program to sum first n even number using while loop.

3. Write a JAVA program to print multiplication table of a given number n.

4. Write a JAVA program to print multiplication table of 10 in reverse order.

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

Normally, an array is a collection of similar type of elements which has contiguous


memory location.

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

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];

Example of Java Array

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]);
}}

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

//Java Program to illustrate the use of declaration, instantiation


//and initialization of Java array in a single line

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]);
}}

For-each Loop for Java Array

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.

The syntax of the for-each loop is given below:

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.

//Java Program to print the array elements using for-each loop


class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}

Multidimensional Array in Java

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

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java


int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example of Multidimensional Java Array


Lets see the simple example to declare, instantiate, initialize and print the
2Dimensional array.
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
} }}
Output 1 2 3
245
445

29 Instagram - @xstechie
xstechie
JAVA NOTES
6 – Practice Set

1. Create an Array of 5 floats and calculate their sum

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.

4. Write a JAVA program to reverse an array.

5. Write a program to find the maximum number of an array.

6. Write a program to find whether an array is sorted or not.

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.

What is a method in Java?


A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve
the reusability of code. We write a method once and use it many times. We do not
require to write code again and again. It also provides the easy
modification and readability of code, just by adding or removing a chunk of code.
The method is executed only when we call or invoke it.

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.

Calc obj = new Calc( );  Object Creation


Obj.mySum(a , b); method call upon an object
The value from the method call ( a and b ) are copied to the a and b of the function
mySum Thus even if we multiply the values a and b inside the method , the values in
the main method will not be change.

Void Return Type


When we don’t want our method to return anything we use void as the return type.

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.

Process of method invocation in JAVA

Consider the method Sum

Int Sum( int a , int b ){


Return a + b; }

The method is called like this


Calc obj = new Calc( );
C = obj.sum( 2,4 );

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

Methods overloading cannot be performed by changing the return type of


methods.

Variables Argument ( var args )

A function with var args can be created in JAVA using following Syntax;

public static void xstechie( int…. arr ){

//arr is available here as int[] arr

Xstechie can be called with zero or more argument like this:


xstechie( 7 ), xstechie( 7, 5 ), xstechie( 7, 5, 6 ), xstechie( 7, 5, 6, 8 )

Recursion

A function in JAVA can call itself such calling of function by itself is called recursion

Example  factorial of a number

Factorial ( n ) = n * factorial ( n-1)

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

1. Write a JAVA method to print multiplication table of a number n.

2. Write a program using function to print the following pattern.


*
**
***
****

3. Write a recursion function to calculate sum of first n numbers

4. Write a function to print the following pattern.


****
***
**
*
5. Write a function to convert celcius temperature into Fahrenheit.

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

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.

Object

An Object can be defined as an instance of a class. An object contains an address


and takes up some space in memory. Objects can communicate without knowing the

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.

How to model a problem in Oops

We identify the following:

Noun  class  employees

Adjective  Attribute  name , age, salary

Verb  Methods  getSalary( ) . increment( )

Oops terminology

1. Abstraction  Hiding internal details and showing functionality is known as


abstraction.

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.

4. Polymorphism  If one task is performed in different ways, it is known as


polymorphism.

Writing a Custom Class

We can write a custom class as follows:

Public class employees{

Int id;  Attribute 1


String name;  Attribute 2

36 Instagram - @xstechie
xstechie
JAVA NOTES
A class with methods

We can add methods to our class employees as follows:

Public class employees{


Public int id;
Public String name;

Public int getSalary( ){


//code
}
Public int getDetails( ){
//code
}
}

37 Instagram - @xstechie
xstechie
JAVA NOTES
8 – Practice Set

1. Create a class and method

2. Create a Class cellphone with methods to print “ringing…” , “Vibrating…”etc.

3. Create a Class square with method to inialize its side , calculating area parameter ,
etc.

4. Create a Class rectangle and repeat 3.

38 Instagram - @xstechie
xstechie
JAVA NOTES
9 – Access Modifiers & Constructors

Access Modifiers

Specific where a property/method is a accessible

There are four types of Access Modifier in JAVA

1. Private
2. Default
3. Protected
4. Public

Getter and Setter

Getter  Return the value

Setter  Set/Update the value

Example :

Public class Employees{

Private int id;

Private String name;

Private String getName( ){

Return name;

Private void setName( ){

this.name = “xstechie”

Private void setName( String n ){

this.name = n

39 Instagram - @xstechie
xstechie
JAVA NOTES
Constructer in JAVA

A member function used to initialize an object while creating

Employees xstechie = new Employees( );


xstechie.setName( “xs bhai” );

In order to write our own contructor, we define a method with same as class name

Public Employees ( ){

Name = “xstechie”;

Id = 46;

Constructor Overloading in JAVA

Constructor can be overloaded just like others method in JAVA


We can overload the employee constructor like:

Public Employees (String n ){

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

1. Calculate surface area and volume of the cylinder

2. Use Constructor and calculate surface area and volume of the cylinder

3. Overload a constructor used to initialize a rectangle of length 5 and breath 5 for


using custom parameter

4. Calculate surface area and volume of the Sphere

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.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality. In the terminology of Java, a
class which is inherited is called a parent or superclass, and the new class is called child or
subclass.

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

Constructor during Constructor Overloading


When there are multiple constructor in the parent class the constructor without any
parameter is called from the child class
If we want to call the constructor with parameter from the parent class , we can use
super keyword.
Super(a , b);  calls the constructor from the parent which takes 2 variables

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.

 When an overridden method is called through a superclass reference, Java determines


which version(superclass/subclasses) of that method is to be executed based upon the
type of the object being referred to at the time the call occurs. Thus, this determination
is made at run time.
 At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
 A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.

Therefore, if a superclass contains a method that is overridden by a subclass, then when


different types of objects are referred to through a superclass reference variable, different
versions of the method are executed. Here is an example that illustrates dynamic method
dispatch:
// A Java program to illustrate Dynamic Method

// Dispatch using hierarchical inheritance


class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

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();

// obtain a reference of type A


A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;

// calling B's version of m1()


ref.m1();

// now ref refers to a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}

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.

3. Create method for area and volume in Question no.1

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.

What does Abstract ( class ) mean ?

Abstract in English mean existing in thought or as an idea without concrete


existence.

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

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}

Difference between abstract class and interface

Abstract class Interface

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!

Polymorphism using Interfaces

Example:

final class MyClass {

public final float pi = 3.1415926 f;

49 Instagram - @xstechie
xstechie
JAVA NOTES
public final void doIt ( ) {

System.out.println ( "Done !" );


}

public void process ( final Customer customer ) {

// 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.

5. Create a class TVRemote and use it to inherit another interface SmartTvRemote.

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.

Using a JAVA package

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

 First create a directory within name of package.


 Create a java file in newly created directory.
 In this java file you must specify the package name with the help of package
keyword.
 Save this file with same name of public class.
 Now you can use this package in your program.

Access Modifier in JAVA

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)

Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access Modifier within class within package outside package outside package
by subclass only

Private Yes No No No

Default Yes Yes No No

53 Instagram - @xstechie
xstechie
JAVA NOTES
Protected Yes Yes Yes No

Public Yes Yes Yes Yes

12 – Practice Set

1. Create a class calculator , ScCalculator and HybridCalculator and group into a


package.

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….

 Thread use shared memory area


 Thread  faster content switching
 A thread is light – weight whereas a process is heavyweight.
Example  A word process can have one thread running in foreground as an
editor and another in the background auto saving the document.

Flow of Control in JAVA

Without threading :

Main  func( )  fun3( )  END

With thread:

Main
Func( )

Func( ) End
Creating a Thread

There are two ways to create a thread in JAVA


 Bt extending Thread class
 By implementing Runnable interface

Life cycle of a Thread

55 Instagram - @xstechie
xstechie
JAVA NOTES
New  Instance of thread created which is not yet started by invoking start( ).

Runnable  After invocation of Start( ) & before it is selected to be run by the


scheduler.

Running  After thread scheduler has selected it.

Non Runnable  Thread Alive , not eligible to run.

Terminated  run( ) method has exited.

The Thread Class

Below are the commonly used Constructer of thread class.

 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.

3. Demonstrate getPriority( ) and setPriority( ) methods in JAVA threads

4. How do you get state of a given thread in JAVA

5. How do you get reference to the current thread in JAVA.

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

There are three types of error in JAVA

 Syntax error
 Logical error
 Runtime error  also called exception

Syntax Error

When compiler finds something wrong with our program it throw a syntax error.

Int a = 9  no semicolon, Syntax error

A = a + 3;

D = 4;  variable not declared , syntax error

Logical Error

A logical error or bug occur when a program compiled and run but does the wrong
thing.

 Message delivered wrongly


 Wrong time of chats being displayed
 Incorrect redirect

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.

There are mainly two types of exception in JAVA

 Checked exception  Compile time exception


 Unchecked exception  Runtime Exception

Commonly occurring Exceptions

Following are few commonly occurring exception

 Null pointer Exception


 ArrayIndexOutofBound Exception
 Number Format Exception
 Arithmetic Exception
 Illegal Argument Exception

Try – Catch block in JAVA

In JAVA exceptions are managed using try – catch blocks

Syntax: try{
//code to try}
Catch( exception e) {
//code if exception
}

Handling specific Exception

In JAVA, we can handle specific exceptions by typing multiple catch blocks


: try{
//code to try}
Catch( ArithmeticException e) {  Handle all exception of type
//code if exception Arithmetic
}
Catch( exception e) { 
//code if exception
}

58 Instagram - @xstechie
xstechie
JAVA NOTES
Nested try – catch

We can nest multiple try – catch blocks as follows:


Try{
Try{
}
Catch( exception e) {
}
}
Catch ( exception e ) {
}

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.

Exception Class in JAVA

We can write our custom exception using exception class in JAVA


Public class xstechie extends Exception {
// overridden methods
}

The Exception class has following important methods:


 String toString( )  executed when print is can
 Void printStachTrace  print stack trace
 String getMessage  print the exception message

The Throw Keyword


The throw keyword is used to throw an exception expilicity by the programmer.

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:

Public void calculate ( int a , int b) throw IO exception{


//code
}

JAVA Finally 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

1. Write a program to demonstrate syntax , logical & runtime errors.

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”.

4. Modify program in Q3 to throw a custom exception if more retries are reached

5. Wrap the program in Q3 inside a method which throws your exception.

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.

Why do we need Collection?

We need collection for efficient storage and better manipulation of data in JAVA.

For ex -: we use array to store integer but what if we want to

 Resize this array?


 Insert an element in between?
 Delete an element in Array?
 Apply certain operation to change this Array?

How are collection available

Collection in JAVA are available as classes and Interfaces

Following are few commonly used collection in JAVA:

 ArrayList  for variables size collection


 Set  for distinct collection
 Stack  A LIFO data structure ( LIFO = last in first out )
 Hashmap  for storing key-value pains

Collection class is available in JAVA.util package. Collection class also provide static
methods for sorting , searching etc.

Date & Time in JAVA

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.currentTimeMillis( ) return no of millisecond passed. one no of ms are


calculated , we can calculate minute , seconds & year passed.

Quick Quiz  Is It safe to store the no of ms in a variables of type long ?

The Date Class in JAVA

Date d = new Date( );

System.out.println( d );

We can also use constructor provided by the Date class.

JAVA Date class has few methods which can be used for ex : getDate( ), getDay( ) etc.

All these methods are depretiated.

Calender class in JAVA

Calendar is an abstract class that provide calendar related methods in JAVA :

Calendar.getInstance  return a Calendar instance based on Current time

Calendar a = Calendar.getInstance( );

a.getTime( )  print time

Calendar class methods

 Get methods is used to get years, date , minutes, seconds


 a.get ( Calendar.SECOND)
 a.get ( Calendar.MINUTES)
 a.get ( Calendar.DATE)
 a.get ( Calendar.YEAR)

62 Instagram - @xstechie
xstechie
JAVA NOTES
 getTime methods return a Date Object
 other methods can be looked up from the JAVA docs

Gregorian Calendar Class

This class is used an instance of Gregorian Calendar. We change the year month &
date using set methods!

Time Zone in JAVA

Time zone class is used to create Time zone in JAVA some of the important methods
of Time Zone class are:

 getAvailableIOS ( )  get All the available IOS supported


 getDefault( )  get the default Timezone
 getId( )  get the ID of a minutes.

JAVA.time Package

 Available from JAVA 8 onward


 Capable of storing even neon second

Following as some of the most commonly used classes

LocalDate  Represent a Date

LocalTime  Represent a Time

LocalDateTime  Represent a Date + Time

DateTimeFormatte  Formatted for displaying & parsing date-time object

ArrayList in JAVA

ArrayList is a part of collection framework and is present in java.util package. It


provides us with dynamic arrays in Java. Though, it may be slower than standard
arrays but can be helpful in programs where lots of manipulation in the array is
needed. This class is found in java.util package.

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

he ArrayDeque in Java provides a way to apply resizable-array in addition to the


implementation of the Deque interface. It is also known as Array Double Ended
Queue or Array Deck. This is a special kind of array that grows and allows users to
add or remove an element from both sides of the queue.

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.

hashIndex = key % noOfBuckets

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

3. Repeat Ques 2 using Calendar class.

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

It used to provide extra information about a program. Annotation provide metadata


to class/methods.

Following are some common annotation built into JAVA.

@override  used to mark override element in the child class.

@suppressWaring  used to suppress the generated warning by the


compiler.

@depreciated  used to mark depreciated methods.

@functionalInterface  used to ensure an interface is a functional interface.

Lamba Expression

Added in JAVA 8. Lamba expression let us express instances at single methods


classes more compactly. Anonymous classes are used to implement a base class
without giving it a name. for classes with a single method even anonymous classes
slightly excessive & cumbersome.

JAVA Generics

Introduced from JDK 5.0 onward. Very similar to C++ Templates (but not the same)

If we write

ArrayList a = new ArrayList( ) ;

a.get(75);

int a num = a.get(0);  we can’t do this

int a num = (int) a.get(0)  we will have to do this

hence generics aim to reduce bugs & enhance type safety

Note:Type parameter in JAVA generics cannot be a primitive data type.

66 Instagram - @xstechie
xstechie
JAVA NOTES
File handling in JAVA

Reading from & writing to files is an important aspect of any programming


languages.

We can use the file class in JAVA to create a file Object

 Create newfile( ) method  create a file object


 For reading files we can use the same scanner class and supply it a file object.
 To delete a file in JAVA we can use file object delete( ) method.

67 Instagram - @xstechie

You might also like