Core Java Notes
Core Java Notes
History of Java
Java was developed by James Gosling at Sun Microsystems, Inc. (Started in 1988).
Java Originated at Sun Microsystems, Inc. 1991.
On January 27, 2010, Sun Microsystems was acquired by Oracle corporation for 7.4
billion US Dollars.
Java is Everywhere
Java resides in Mobile, Client Machines, Server Machines, Embedded Devices, Smart
Phones, etc.
It shared the same basic features of the language and libraries.
Principle of Java: “Write Once, Run Anywhere” (WORA) or sometimes “Write Once,
Run Everywhere” (WORE).
Java Flavors
J2SE (Java Standard Edition)
JEE (Java Enterprise Edition)
JME (Java Micro Edition for Mobiles) and so on…
Why Java?
Java is platforms independent (Windows, Mac, Linux, Raspberry Pi, etc).
It is high level programming language.
It is one of the most popular programming language in the world.
It is easy to learn and simple to use.
It is open-source and free.
It is secure, fast and powerful.
It has huge community support (Millions of Developers).
Java is an Object Oriented Programming Language which gives a clear structure to
programs and allows code to be reused, lowering development costs.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 1/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Features of Java
Simple
Object Oriented
Distributed
Interpreted
Robust
Secure
Portable
Multi-Threaded
Garbage Collector
Points to Remember
Java is a case sensitive language like C and C++.
Java is nearly 100% object oriented language (means not totally object oriented). In
Java, it is not possible to make a function which is not a member of any class (as we
can do in C++).
Java language is totally made without Pointers (In C and C++ we are worked on
pointer).
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 2/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Java Program
OUTPUT:
Hello World!
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 3/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 4/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
character char 2 16
byte byte 1 8
short short 2 16
integer int 4 32
float float 4 32
long long 8 64
double double 8 64
boolean boolean NA NA
2. User-Defined or Reference Data Types : Data types which are created by the users.
Note:
Primitive types has always a value but reerence types has no value i.e. null.
Primitive data types always starts with a Lowercase while Reference data types
starts with Uppercase.
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 5/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
/*
this is multi line comments.
it will comment a group of lines.
*/
Example
127
0x7f
0177
0101101100
byte -> short -> char -> int -> long -> float -> double
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 6/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
9
9.0
double -> float -> long -> int -> char -> short -> byte
Example
OUTPUT:
9.78
9
Addition
Subtraction
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 7/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Multiplication
Division
Modulus
Increment
1. pre-increment
2. post-increment
Decrement
1. pre-decrement
2. post-decrement
Example
OUTPUT:
a+b = 30
a-b = -10
a*b = 200
a/b = 2
a%b = 0
2. Comparison Operators:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 8/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Operators Use
== Equal To
!= Not Equal To
3. Logical Operators:
Operators Use
&& (Logical AND) Returns true if both the conditions are true
! (Logical NOT) Reverse the result, returns false if the result is true
4. Assignment Operators:
= x=5 x=5
+= x+=3 x=x+3
-= x-=3 x=x+3
*= x*=3 x=x+3
/= x/=3 x=x+3
%= x%=3 x=x+3
|= x|=3 x=x+3
^= x^=3 x=x+3
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 9/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
5. Bitwise Operators:
Operators Use
<< (Zero-fill left Shift left by pushing zeroes in from the right side and letting
shift) the almost bits fall off
>>> (Zero-fill Shift right by pushing zeroes in from the left and letting the
right shift) rightmost bits dall off
>> (Signed right Shift right by pushing copies of the leftmost bit in from the
shift) left and letting the rightmost bit fall off
1 int i = 10;
2
3 if(i>5){
4 System.out.println("Greater than 5");
5 }
6 else{
7 System.out.println("Smaller than 5");
8 }
OUTPUT:
Greater than 5
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 10/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 int i = 10;
2
3 if(i>5){
4 System.out.println("Greater than 5");
5 }
6 else if(i==0){
7 System.out.println("Zero Value");
8 }
9 else{
10 System.out.println("Smaller than 5");
11 }
OUTPUT:
Greater than 5
Note
Ternary Operator:
Example
OUTPUT:
1
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 11/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Example
OUTPUT:
0
1
2
3
2. continue : continue statements skip a specific value and continue the loop.
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 12/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
0
1
2
3
5
6
7
8
9
Example
OUTPUT:
0
1
2
3
4
2. do/while loop:
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 13/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
0
1
2
3
4
3. for loop:
Example
OUTPUT:
0
1
2
3
4
Note
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 14/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 for(item:array_list){
2 //some statements
3 }
Example
OUTPUT:
Thursday
If we have to add any default case then we can add default case at the bottom of
the switch cases. make sure there is no need of break in default case.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 15/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Example
OUTPUT:
Hey Programmers
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 16/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
Rajat
Immutable Mutable
StringBuffer s = new
String s = new String("Rajat");
StringBuffer("Rajat");
s.concat("Kotangale");
s.append("Kotangale");
System.out.println(s);
System.out.println(s);
OUTPUT: Rajat
OUTPUT: RajatKotangale
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 17/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
String StringBuffer
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 18/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
s2 ––-> Rajat
RajatKotangale Kotangale
RajatSolution Solution
String
A string is an object representing a sequence of characters.
It's a fundamental data type and is part of the java.lang package, which means it's
readily available in all Java programs without needing to import any additional
packages.
Strings in Java are immutable, meaning their values cannot be changed after they
are created.
This immutability ensures that once a string object is created, its contents remain
constant throughout its lifetime.
Strings in Java are typically enclosed in double quotes ("").
Methods:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 19/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
sequence of characters.
4. endsWith(String suffix) - Tests if this string ends with the specified suffix.
5. equals(Object anObject) - Compares this string to the specified object.
6. equalsIgnoreCase(String anotherString) - Compares this string to another string,
ignoring case considerations.
7. indexOf(int ch) - Returns the index of the first occurrence of the specified character.
8. indexOf(String str) - Returns the index of the first occurrence of the specified
substring.
9. isEmpty() - Returns true if, and only if, length() is 0.
10. length() - Returns the length of this string.
11. replace(char oldChar, char newChar) - Returns a new string resulting from
replacing all occurrences of oldChar in this string with newChar.
12. replace(CharSequence target, CharSequence replacement) - Replaces each
substring of this string that matches the literal target sequence with the specified literal
replacement sequence.
13. split(String regex) - Splits this string around matches of the given regular
expression.
14. startsWith(String prefix) - Tests if this string starts with the specified prefix.
15. substring(int beginIndex) - Returns a new string that is a substring of this string.
16. substring(int beginIndex, int endIndex) - Returns a new string that is a substring
of this string.
17. toLowerCase() - Converts all of the characters in this String to lower case using the
rules of the default locale.
18. toUpperCase() - Converts all of the characters in this String to upper case using the
rules of the default locale.
19. trim() - Returns a copy of the string, with leading and trailing whitespace omitted.
20. valueOf(int i) - Returns the string representation of the int argument.
StringBuffer
A StringBuffer is a class in Java that provides a mutable sequence of characters.
It is similar to the String class, but unlike strings, StringBuffers can be modified once
they are created.
This makes StringBuffer useful for situations where you need to manipulate strings
frequently without creating new objects each time.
StringBuffer provides methods for appending, inserting, deleting, and modifying
characters in the sequence.
It is often used in situations where efficient string manipulation is required, such as
when building long strings dynamically.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 20/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Methods:
1. append() - Appends the specified string representation to the end of the StringBuffer.
2. capacity() - Returns the current capacity of the StringBuffer.
3. charAt(int index) - Returns the character at the specified index in the StringBuffer.
4. delete(int start, int end) - Removes the characters from the specified start index to
the end index - 1.
5. deleteCharAt(int index) - Removes the character at the specified index.
6. ensureCapacity(int minCapacity) - Ensures that the capacity of the StringBuffer is at
least equal to the specified minimum capacity.
7. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) - Copies characters from
this StringBuffer into the destination character array.
8. indexOf(String str) - Returns the index within this StringBuffer of the first occurrence
of the specified substring.
9. insert(int offset, String str) - Inserts the specified string into the StringBuffer at the
specified position.
10. insert(int offset, char c) - Inserts the specified character into the StringBuffer at the
specified position.
11. length() - Returns the length (number of characters) of the StringBuffer.
12. replace(int start, int end, String str) - Replaces the characters from the start index
to the end index - 1 with the specified string.
13. reverse() - Reverses the characters in the StringBuffer.
14. setCharAt(int index, char ch) - Sets the character at the specified index to the
specified character.
15. setLength(int newLength) - Sets the length of the StringBuffer to the specified
length.
16. substring(int start) - Returns a new String that contains a subsequence of
characters currently contained in the StringBuffer, starting from the specified index.
17. substring(int start, int end) - Returns a new String that contains a subsequence of
characters currently contained in the StringBuffer, starting from the specified start index
and ending at the specified end index - 1.
18. toString() - Returns a string representing the data in the StringBuffer.
StringBuilder
StringBuilder is a class that provides a mutable sequence of characters, similar to
StringBuffer but with some differences in synchronization.
It is part of the java.lang package and is commonly used for efficient string
manipulation when thread safety is not a concern.
Methods
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 21/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1. append(String str): Appends the specified string to the end of the StringBuilder.
2. append(Object obj): Appends the string representation of the specified object to the
end.
3. append(char c): Appends the specified character to the end.
4. append(CharSequence s): Appends the specified character sequence to the end.
5. insert(int offset, String str): Inserts the specified string at the specified position.
6. insert(int offset, Object obj): Inserts the string representation of the specified object
at the specified position.
7. insert(int offset, char c): Inserts the specified character at the specified position.
8. insert(int offset, CharSequence s): Inserts the specified character sequence at the
specified position.
9. delete(int start, int end): Deletes the characters from the start index to the end
index - 1.
10. deleteCharAt(int index): Deletes the character at the specified index.
11. replace(int start, int end, String str): Replaces the characters from the start index
to the end index - 1 with the specified string.
12. substring(int start): Returns a new StringBuilder that contains a subsequence of
characters currently contained in the StringBuilder, starting from the specified index.
13. substring(int start, int end): Returns a new StringBuilder that contains a
subsequence of characters currently contained in the StringBuilder, starting from the
specified start index and ending at the specified end index - 1.
14. reverse(): Reverses the order of characters in the StringBuilder.
15. length(): Returns the length (number of characters) of the StringBuilder.
16. setCharAt(int index, char ch): Sets the character at the specified index to the
specified character.
17. charAt(int index): Returns the character at the specified index.
18. indexOf(String str): Returns the index within the StringBuilder of the first
occurrence of the specified substring.
19. lastIndexOf(String str): Returns the index within the StringBuilder of the last
occurrence of the specified substring.
20. toString(): Returns a string representing the data in the StringBuilder.
Examples
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 22/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Example 1
Example 2
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 23/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Class
Using class keyword we implement the encapsulation.
Encapsulation is a process of binding data and code into a single unit. This is called
Encapsulation.
Class is a description of an object's property and behavior.
Creating a class is as good as creating data type
Class is defining a category of data.
It is a logical entity.
It is declared using class keyword
Class can be public, default, abstract and final only. We cannot use static, private
keywords in outer class.
Class cannot be declared public more than 1 times in a single file.
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 24/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Example
1 package java_tutorials_by_rajat;
2
3 class Box{
4 private int length, breadth, height;
5
6 public void setDimension(int l, int b, int h){
7 this.length = l;
8 this.breadth = b;
9 this.height = h;
10 }
11
12 public void getDimention(){
13 System.out.println("Length : "+ length);
14 System.out.println("Breadth : "+ breadth);
15 System.out.println("Height : "+ height);
16 }
17 }
18
19 public class ObjectExample {
20 public static void main(String[] args) {
21 Box b1 = new Box();
22 b1.setDimension(10, 20, 30);
23 b1.getDimention();
24 }
25 }
OUTPUT:
Length : 10
Breadth : 20
Height : 30
If we assign b1 new instance of box then create a new object to the same reference
therefore, the object we have created is destroyed and the values that we have assigned
before are destroyed and new values are assigned to it as 0, 0, 0.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 25/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Example
1 package java_tutorials_by_rajat;
2
3 class Box{
4 private int length, breadth, height;
5
6 public void setDimension(int l, int b, int h){
7 this.length = l;
8 this.breadth = b;
9 this.height = h;
10 }
11
12 public void getDimention(){
13 System.out.println("Length : "+ length);
14 System.out.println("Breadth : "+ breadth);
15 System.out.println("Height : "+ height);
16 }
17 }
18
19 public class ObjectExample {
20 public static void main(String[] args) {
21 Box b1 = new Box();
22 b1.setDimension(10, 20, 30);
23 b1.getDimention();
24 b1 = new Box();
25 b1.getDimention();
26 }
27 }
OUTPUT:
Length : 10
Breadth : 20
Height : 30
Length : 0
Breadth : 0
Height : 0
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 26/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Primitive or Reference data types are sort left out in the world of objects that is,
they cannot participate in the object activities.
Therefore, we use wrapper class to fulfill this fault to make java as fully object-
oriented.
So basically, we are going to create objects of different data types using wrapper
class.
We can also convert them from primitive to object and object to primitive.
There are wrapper class for every primitive data type in java:
boolean Boolean
byte Byte
char Char
short Short
int Integer
long Long
float Float
double Double
Unboxing Boxing
xxxValue() valueOf()
Example of Boxing
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 27/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 package java_tutorials_by_rajat;
2
3 public class WrapperClassExample {
4 public static void main(String[] args) {
5 int i = 12;
6 float j = 3.14f;
7 Integer i1 = Integer.valueOf(i);
8 Float f1 = Float.valueOf(j);
9 System.out.println(i1);
10 System.out.println(f1);
11 }
12 }
OUTPUT:
12
3.14
Example of Unboxing
1 package java_tutorials_by_rajat;
2
3 public class WrapperClassExample {
4 public static void main(String[] args) {
5 Integer i1 = new Integer(12);
6 Float f1 = new Float(3.14f);
7 int i = i1.intValue();
8 float j = f1.floatValue();
9 System.out.println(i);
10 System.out.println(j);
11 }
12 }
OUTPUT:
12
3.14
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 28/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Auto-Unboxing Auto-Boxing
In this scenario we can pass directly primitives into objects and objects into primitives.
Everything is managed by java automatically.
1 package java_tutorials_by_rajat;
2
3 public class WrapperClassExample {
4 public static void main(String[] args) {
5 int i = 12;
6 float j = 3.14f;
7 Integer i1 = i;
8 Float f1 = j;
9 System.out.println(i1);
10 System.out.println(f1);
11 }
12 }
OUTPUT:
12
3.14
1 package java_tutorials_by_rajat;
2
3 public class WrapperClassExample {
4 public static void main(String[] args) {
5 Integer i1 = 12;
6 Float f1 = 3.14f;
7 int i = i1;
8 float j = f1;
9 System.out.println(i);
10 System.out.println(j);
11 }
12 }
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 29/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
12
3.14
Methods:
1. valueOf():
Static method (if method is static then there is no need to create an object).
Return object reference of relative wrapper class.
2. parseXXX():
Static method
XXX can be replaced by any primitive data type
It returns XXX types values.
3. xxxValue():
1. Non Static
We can not make static function in non static inner class. But we can make static
final function.
In Non Static we have three types:
A)Instance Inner Class:
B)Local Inner Class
C)Anonymous Inner Class
2. Static
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 30/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Example
1 package com.rajatkotangale;
2
3 public class InstanceInnerClassExample {
4 class Demo{
5 private int i;
6
7 public void setInteger(int num){
8 this.i=num;
9 }
10
11 public int getInteger(){
12 return i;
13 }
14 }
15
16 public static void main(String[] args) {
17 InstanceInnerClassExample i1 = new InstanceInnerClassExample();
18 InstanceInnerClassExample.Demo d1= i1.new Demo();
19 d1.setInteger(10);
20 System.out.println(d1.getInteger());
21 }
22 }
OUTPUT:
10
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 31/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 package com.rajatkotangale;
2
3 public class LocalInnerExample {
4 public void printSomething(){
5 class Demo{
6 //created constructor, we can also make methods.
7 public Demo(){
8 System.out.println("Working...");
9 }
10 }
11 /*make sure to create object below the inner class
12 at the time of local inner class*/
13 Demo d1 = new Demo();
14 }
15 public static void main(String[] args) {
16 LocalInnerExample li = new LocalInnerExample();
17 li.printSomething();
18 }
19 }
OUTPUT:
Working…
Example
File 1:
1 package com.rajatkotangale;
2
3 public class Demo {
4 abstract class A{
5 protected int i;
6 abstract void setInteger();
7 public int getInteger(){
8 return i;
9 }
10 }
11 }
File 2:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 32/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 package com.rajatkotangale;
2
3 public class AnonymousClassExample {
4 public static void main(String[] args) {
5 Demo d1 = new Demo();
6 Demo.A a= d1.new A(){
7 public void setInteger(){
8 this.i=10;
9 }
10 };
11 a.setInteger();
12 System.out.println(a.getInteger());
13 }
14 }
OUTPUT:
10
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 33/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Advantages of package
packaging also help us to avoid class name collision when we use the same class
name as that of other.
The benefits of using package reflet the ease of maintenance, organization, and
increase collaboration among developers.
Note: We can create same class name file in different package but we can not create
same name class file in same package.
package world;
javac -d . filename.java
java package_name.filename
OUTPUT:
cd Documents
cd Java Programs
javac -d . Example.java
java.world.Example
Hello World
Points to Remember
1. private : When members of the class are private, they can not accessed from outside
of the class body. They are meant to be accessed from the same class in which they are
declared.
2. protected : When members are protected, they can be accessed from any class of
the same package and if we want to use in diffrent package, we have to extends the
class that we want to use.
3. public : When members are public, they are accessible from any class of any
package.
4. default : When members are default, they are accessible only from the any class of
same package.
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 35/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 //public class
2 public class Example{
3 //private variable
4 private int x;
5
6 //public function
7 public void setValue(int num){
8 x = num;
9 }
10
11 //public function
12 public int getValue(){
13 return x;
14 }
15
16 public static void main(String args[]){
17 Example example = new Example();
18 example.setValue(10);
19 System.out.println(example.getValue());
20 }
21 }
OUTPUT:
10
Note:
Modifiers can be used for class, member variables and member functions.
Outer class can be public or default only.
But in inner class we can use all four access modifiers.
Syntax:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 36/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
extends is a keyword.
Base class means superclass(parent).
Derived class means subclass(child).
1. Single Inheritance:
2. Multi-Level Inheritance:
One superclass and it's one subclass, and that subclass have another subclass and
same repeat again and again…
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 37/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
3. Heirarchical Inheritance:
4. Multiple Inheritance:
Example 1
File 1
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 38/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
File 2
File 3
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 39/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
Roll No: 100
Name: Rajat
Age: 24
Example 2
File 1
File 2
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 40/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
File 3
OUTPUT:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method setRollNo(int) is undefined for the type Person
The method getRollNo() is undefined for the type Person
This error is occurs due to the reference of the class is Person at the time of object
creation. So therefore we can't access setRollNo() and getRollNo() method.
So the point is that if we are creating the object of subclass but the reference is of
parent class then we can not access methods of child class.
Points to Remember
In the java programming language, each class is allowed to have one direct
superclass, and each superclass has the potential for an unlimited number of
subclass.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 41/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Private members of the superclass are not accessible by the subclass and can only
be indirectly accessed.
Members that have default accessibility in the superclass are also not accessible by
subclass in the other package.
Example
1 class Box{
2 private int l,b,h;
3
4 public void setDimension(int l, int b, int h){
5 this.l=l;
6 this.b=b;
7 this.h=h;
8 }
9 }
10 public class Example{
11 public static void mai (String args[]){
12 Box box = new Box();
13 box.setDimension(12,10,5);
14 }
15 }
if a method needs to pass the current object to another method, it can do so using
the this reference.
Note that the this reference can not be used in a static context, as static code is not
executed in the context of any object.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 42/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
If your method overrides one of it's superclass methods, you can invoke the
overridden method through the use of the keyword super.
It avoids name conflit between member variables of superclass and subclass.
1 class A{
2 //superclass z
3 int z;
4
5 public void f1(){}
6 }
7 class B extends A{
8 // subclass z
9 int z;
10
11 public void f1(){}
12
13 public void f2(){
14 //local variable z
15 int z;
16 z=2;
17 this.z=3;
18 super.z=4;
19 System.out.println("Super Class Z = "+super.z);
20 System.out.println("Sub Class Z = "+this.z);
21 System.out.println("Local Variable Z = "+z);
22 }
23 }
24 public class Example{
25 public static void main (String args[]){
26 B obj = new B();
27 obj.f2();
28 }
29 }
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 43/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
Super Class Z = 4
Sub Class Z = 3
Local Variable Z = 2
1. Overloading
If two methods of a class (whether both declared in the same class or both inherited
by a class or one declared and one inherited) have same name but different
signitures(parameters), then the method is said to be overloaded.
It is said to be static.
It occurs at compile time.
Example
1 class A{
2 public void f1(int x){
3 System.out.println("Class A");
4 }
5 }
6 class B extends A{
7 public void f1(int x, int y){
8 System.out.println("Class B");
9 }
10 }
11 public class Example{
12 public static void main (String args[]){
13 B obj = new B();
14 obj.f1(5);
15 obj.f1(5,6);
16 }
17 }
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 44/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
Class A
Class B
2. Overriding
Method overriding is defining a method in sub-class with the same signiture with
specific implementation in respect to subclass.
It is said to be dynamic.
It occurs at runtime.
Example
1 class A{
2 public void f1(int x){
3 System.out.println("Class A");
4 }
5 }
6 class B extends A{
7 public void f1(int x){
8 System.out.println("Class B");
9 }
10 }
11 public class Example{
12 public static void main(String args[]){
13 B obj = new B();
14 obj.f1(5);
15 }
16 }
OUTPUT:
Class B
Points to Remember
In overriding we have to make sure the name and signitures of methods are same.
And one method is in super class and another in subclass.
In overloading we can place methods in different class or within same class.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 45/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Abstract Clases
Abstract classes are declared with the abstract keyword.
An abstract class cannot be instantiated(means we can not create object of abstract
class).
There are so many common things are between different object so we can use abstract
class means that no implementation is there so whether it is Student or Faculty, it works
for both by extending it.
Abstract Methods
An abstract class can include methods that contains no implementation. These are
called abstract methods.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 46/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
The abstract method declaration must have end with semicolon rather than a block.
If a class has any abstract methods, whether declared or inherited the entire class
must be declared as abstract.
If a class is abstract then we can also use non-abstract methods.
Static methods can't be abstract.
Here we achieve only 50% of abstraction therefore, we introduced interface to
achieve 100% abstraction.
Example
OUTPUT:
Working…
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 47/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Interface just specify the method declaration (implicitly public abstract) and can
only contains fields (implicitly public static final).
Using interface we can also achieve multiple inheritance which is not possible in java
inheritance.
We can not create an object of interface also as like abstract.
Interface do not have constructor (we can not use super keyword).
Example
1 interface SomeName{
2 int x;
3 void someFunction();
4 }
Example
1 interface I1{
2 void someFunction();
3 }
4 class A implements I1{
5 public void someFunction(){
6 System.out.println("Working...");
7 }
8 }
9 public class InterfaceExample{
10 A myObj = new A();
11 myObj.someFunction();
12 }
OUTPUT:
Working…
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 48/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 interface A{
2 public void show();
3 }
4 interface B{
5 public void print();
6 }
7 class C implements A,B{
8 public void show(){
9 System.out.println("Display...");
10 }
11 public void print(){
12 SYstem.out.println("Print...");
13 }
14 }
15 public class MultipleIheritanceExample{
16 public static void main (String args[]){
17 C myObj = new myObj();
18 myObj.show();
19 myObj.print();
20 }
21 }
OUTPUT:
Display…
Print…
Note: Functions in abstract class are by default abstract. we don't need to use abstract
keyword.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 49/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Note: In interface, all the variables which we are using are by default static and functions
are non static. So there is no need to use static keyword.
Abstract class can have final or non final variables. Interface can have only final
variables.
Interface do not have constructor unlike abstract class.(Compiler also can't make
constructor be default).
Example
Note: Constructor is a special member function which has no need to call, just we need
to create a object then it will called automatically.
Because, only memory allocation to the objects doesn't make them object but they are
properly initialized then they are called to be objects. So this is the work of constructor.
Example
In below example we have created a instance of Example, but as you can see there is
only memory allocation is done but is obejct is properly initialized?
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 50/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1. Parameterized
2. Default
Points to Remember
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 51/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 class A{
2 int a;
3 public A(){
4 System.out.println("A");
5 }
6 }
7 class B extends A{
8 int b;
9 public B(){
10 System.out.println("B");
11 }
12 }
13 public class Example{
14 public static void main(String args[]){
15 B obj = new B();
16 }
17 }
OUTPUT:
A
B
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 52/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 class A{
2 public A(){
3 System.out.println("A 1");
4 }
5 }
6 class B extends A{
7 public B(){
8 this(4);
9 System.out.println("B 1");
10 }
11
12 public b(int k){
13 System.out.println("B 2");
14 }
15 }
16 public class Example{
17 public static void main(String args[]){
18 B obj = new B();
19 }
20 }
OUTPUT:
A1
B2
B1
Explaination:
As we know we didn't use super keyword because compiler automatically add super
keyword in default constructor of subclass. But in this above example we used this
keyword in constructor of subclass which calls the constructor of subclass. But we had
passed one argument in this kewyword, so it will called the paramterized constructor
first i.e. B 2. then in B 2 function compiler will add super keyword, therefore, it will call A
1. and the output like A 1, B 2 followd by B 1.
First line of constructor is either super() or this() (by default super() hota hai).
Constructor never contains super() and this() both at a time.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 53/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Note:
Example
OUTPUT:
INDIA
2. Static Function:
(See above example for reference)
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 54/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
3. Static Class:
Example
1 class Parent{
2 public static void f1(){
3 System.out.println("Hello");
4 }
5 }
6 class Child extends Parent{
7
8 }
9 public class Example{
10 public static void main(String args[]){
11 Child.f1();
12 }
13 }
OUTPUT:
Hello
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 55/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 class Parent{
2 public static void f1(){
3 System.out.println("Hello");
4 }
5 }
6 class Child extends Parent{
7 public static void f1(){
8 System.out.println("Yo! Man");
9 }
10 }
11 public class Example{
12 public static void main(String args[]){
13 Child.f1();
14 }
15 }
OUTPUT:
Yo! Man
If subclass has a method M with the same signiture as of the method present in the
super class, then method M hides the method of superclass. (Called it as function hiding
when we use static keyword, but if we remove the static keyword then is behave like
overriding).
In above example child's function hides the function of it's parent due to static keyword.
Note: In such case, if we declared a static method in parent class then we have to use
static method in child class also. We can not do one static and another one is non static.
Points to Remember
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 56/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Example
File 1
1 package pack2;
2 public class Student{
3 private int rollNo;
4 private String name;
5
6 public void setRollNo(int r){
7 rollNo=r;
8 }
9
10 public void setName(String n){
11 name=n;
12 }
13
14 public int getRollno(){
15 return rollNo;
16 }
17
18 public String getName(){
19 return name;
20 }
21 }
File 2
1 package pack1;
2 import pack2.Student;
3
4 public class Example{
5 public static void main(String args[]){
6 Student s1 = new Student();
7 s1.setRollNo(100);
8 s1.setName("Rajat");
9 System.out.println("Roll No : "+s1.getRollNo());
10 System.out.println("Name : "+s1.getName());
11 }
12 }
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 57/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
Initialization Block: X = 0
Initialization Block: X = 0
Note: Instance initialization block runs automatically when we created a object but it
have more preference than the constructor. thats why we get the value 0 both the times.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 58/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Instance initializers are permitted to refer to the current object via the keyword this
and to use the keyword super.
OUTPUT:
Static Initialization Block: K = 0
Note: Static block runs before the object creation. And static block runs once for all the
objects that we are creating but instance inistialization block ruhns freshly for every new
object.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 59/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
A java variable can be declared using the keyword final, then the final variable can
be assigned only once.
A varibale that is declared as final and not initialized is called a blank final variable.
A blank final varibale forces either the constructor to initialize it or initialization
block to do this job.
Static member variable when qualified with a final keyword, it becomes blank until
initialized.
Final static variable can be initialized during declartion or within the static block.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 60/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Local variables that are final must be initialized before it's use, but you should
remember this rule is applicable to non final local variables too.
once they are initialized, can not altered.
4. final class:
1 //final class
2 final class Dummy{}
3 public class Example{
4 public static void main(String args[]){
5
6 }
7 }
Once we created a final class so we cannot create subclass of it. means that there is
inheritance is not possible (No inheritance).
5. final methods:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 61/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 class Dummy{
2 //final method
3 public final void someFunction(){
4
5 }
6 }
7 class MoreDummy extends Dummy{
8 // show error
9 public void someFunction(){
10
11 }
12 }
13 public class Example{
14 public static void main(String agrs[]){
15
16 }
17 }
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 62/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
The following are various ways to make object eligible for GC:
1. Nullifying the reference variables:
if an object is no longer required then assign them null to all it's references then it
automatically eligible for GC.
Runtime r = Runtime.getRuntime();
r.freeMemory(); // free memory in the heap
r.totalMemory(); //total memory of the heap
r.gc(); //Requesting JVM to run GC
4. Island of Isolation:
The "Island of Isolation" happens when a group of objects only reference each other, but
nothing else in the program refers to them. This means they're isolated from the rest of
the program, but they still take up memory because they're not being removed by the
garbage collector. It's like a little island of useless objects floating around in your
program's memory, taking up space.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 63/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Example
Consider the example of ATM Machine, we can set some exceptions like if there is no
money in the ATM Machine or if user reached to it's daily limit then, if user want to
withdraw some money from his/her account so then we have to show some arror
messages to them.
Exception Handeling
Java exception handeling is used to handle error conditions in a program systematically
by taking the necessary action.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 64/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Throwable
The Throwable class provides a string variable that can be set by the subclass to
provide a detailed message that provides more information of the exception
occurred.
All classes of Throwables define a one parameter constructor that takes a string as
the detailed message.
Methods:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 65/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
The class Exception represents exceptions that a program faces due to abnormal or
special conditions during execution.
1. Unchecked Exceptions
2. Checked Exceptions
Syntax
try{
//exception which we have to handle
}
catch(<Exception type> <parameter>){
//statement
}
finally{
//finally block statement
}
Example
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 66/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
Exception: / by zero
Hello
Note:
For each try block there can be zero or more catch blocks, but only one finally.
The catch blocks and finally block must along appear in conjugation with a try block.
A try block must be followed by either least one catch or one finally block.
The order exceptions handlers in the catch block must be from the most specific
exceptions.
In try block, if there is any exception found after that line no code will be executed
after that line. i.e. System.out.println("In Try");
If exception is type of Arithmetic then we have to use ArithmeticException only. But
if we use any other class then JVM runs the default catch mechanism.
If we create our catch block then code will be not stop but if default catch
mechanism is executed then code will be stop.
If we created multiple catch blocks then it will verified every catch method which is
suitable for the try block.
A program can explicitly throw an exception using the throw statement besides the
implicit exception thrown.
Syntax:
throw<ThrowableInstance>
The execution reference must be of type Throwable class or one of its subclass.
A detailed message can be passed to the constructor when the exception object is
created.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 67/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
Exception in thread "main" java.lang.ArithmeticException: Insufficient Balance
atExample.main(Example.java.7)
OUTPUT:
Exception: Insufficient Balance
Program Continue…
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 68/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Note:
To handle checked exceptions we have to use throws keyword or we have to handle
them with try catch blocks.
Example
1 import java.io.*;
2
3 public class Example{
4 public static void main(String args[]) throws IOException{
5 throw new IOException();
6 System.out.println("After Exception");
7 }
8 }
OUTPUT:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
uneacheble code at example.main(Example.java:5)
But if we write ArithmeticException instead of IOException then also it will not show
error because ArithmeticException is unchecked exception.
Throws
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 69/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
The trhwos keyword in java programming langauge takes arguments as a list of the
object of type java,lang.Throwable class.
Example
1 package com.rajatkotangale;
2
3 public class CustomizedException {
4 public static void main(String[] args) {
5 int age = 17;
6 try {
7 if(age<=18){
8 throw new AgeException("Underage....");
9 }
10 }
11 catch(AgeException e) {
12 System.out.println(e.toString());
13 }
14 catch(Exception e){
15 System.out.println(e.toString());
16 }
17 }
18 }
19
20 class AgeException extends Exception{
21 public AgeException(String str) {
22 super(str);
23 }
24 }
OUTPUT:
com.rajatkotangale.AgeException: Underage…
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 70/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Methods:
1. next()
2. nextLine()
3. nextBoolean()
4. nextByte()
5. nextDouble()
6. nextFloat()
7. nextInt()
8. nextLong()
9. nextShort()
A scanner breaks its input into tokens using a delimiter (ending mark of data)
pattern, which by default matches whitespaces.
The resulting tokens may then be converted into values of different types using the
various next methods.
Example
1 import java.util.Scanner;
2
3 public class Example{
4 public static void main(String args[]){
5 Scanner sc = new Scanner(System.in);
6 System.out.println("Enter Your Name :");
7 String name = sc.nextLine();
8 System.out.println("Enter Your Age :");
9 int age = sc.nextInt();
10 System.out.println("Name: "+name);
11 System.out.println("Age: "+age);
12 }
13 }
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 71/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
Enter Your Name :
Rajat
Enter Your Age :
24
Name: Rajat
Age: 24
1 enum Level {
2 LOW,
3 MEDIUM,
4 HIGH
5 }
6
7 public class Main {
8 public static void main(String[] args) {
9 Level myVar = Level.MEDIUM;
10 System.out.println(myVar);
11 }
12 }
OUTPUT:
MEDIUM
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 72/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
MEDIUM
An enum can, just like a class, have attributes and methods. The only difference is
that enum constants are public, static and final (unchangeable - cannot be
overridden).
An enum cannot be used to create objects, and it cannot extend other classes (but it
can implement interfaces).
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 73/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Example
1 import java.util.regex.Matcher;
2 import java.util.regex.Pattern;
3
4 public class Main {
5 public static void main(String[] args) {
6 Pattern pattern = Pattern.compile("w3schools", Pattern.CASE_INSENSITIVE)
7 Matcher matcher = pattern.matcher("Visit W3Schools!");
8 boolean matchFound = matcher.find();
9 if(matchFound) {
10 System.out.println("Match found");
11 } else {
12 System.out.println("Match not found");
13 }
14 }
15 }
OUTPUT:
Match Found
Flags
Flags in the compile() method change how the search is performed. Here are a few of
them:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 74/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Expression Description
[abc] Find one character from the options between the brackets
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
\d Find a digit
Quantifiers
Quantifiers define quantities:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 75/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Quantifier Description
Syntax:
1 import java.util.ArrayList;
2 import java.util.function.Consumer;
3
4 public class Main {
5 public static void main(String[] args) {
6 ArrayList<Integer> numbers = new ArrayList<Integer>();
7 numbers.add(5);
8 numbers.add(9);
9 numbers.add(8);
10 numbers.add(1);
11 Consumer<Integer> method = (n) -> { System.out.println(n); };
12 numbers.forEach( method );
13 }
14 }
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 76/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
5
9
8
1
Example Exaplaination
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 77/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Array Class
1. Sorting Methods:
sort(T[] a): Sorts the specified array of objects into ascending order.
sort(T[] a, Comparator<? super T> c): Sorts the specified array of objects
according to the order induced by the specified comparator.
sort(int[] a): Sorts the specified array of ints into ascending numerical order.
sort(int[] a, int fromIndex, int toIndex): Sorts the specified range of the array of
ints into ascending numerical order.
Similar methods exist for other primitive types (byte, short, long, float, double, char) and
for arrays of those types.
2. Searching Methods:
binarySearch(T[] a, T key): Searches the specified array of objects for the specified
object using the binary search algorithm.
binarySearch(T[] a, int fromIndex, int toIndex, T key): Searches a range of the
specified array of objects for the specified object using the binary search algorithm.
binarySearch(int[] a, int key): Searches the specified array of ints for the specified
value using the binary search algorithm.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 78/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
equals(T[] a, T[] a2): Returns true if the two specified arrays of objects are equal to
one another.
equals(int[] a, int[] a2): Returns true if the two specified arrays of ints are equal to
one another.
deepEquals(Object[] a1, Object[] a2): Returns true if the two specified arrays are
deeply equal to one another.
4. Fill Methods:
fill(T[] a, T val): Assigns the specified value to each element of the specified array
of objects.
fill(T[] a, int fromIndex, int toIndex, T val): Assigns the specified value to each
element of the specified range of the array of objects.
fill(int[] a, int val): Assigns the specified value to each element of the specified
array of ints.
fill(int[] a, int fromIndex, int toIndex, int val): Assigns the specified value to each
element of the specified range of the array of ints.
5. Copy Methods:
6. Other Methods:
Generics
It is an idea to allow reference types to be parameterized to methods and classes.
Types of Generics
1. Generic Methods:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 79/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Each type parameter section contains one or more type parameters separated by
commas.
The type parameters can be used to declare the return type.
Type parameters can represent only reference type, not primitive types.
Normal Method -
Here we need to create new fuction for every new datatype. So to resolve this probem
we have to create a generic method.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 80/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
Apple
Banana
Chiku
1
2
3
4
5
2.33
5.55
6.44
Generic Method -
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 81/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
Apple
Banana
Chiku
1
2
3
4
5
2.33
5.55
6.44
2. Generic Classes -
Normal Class -
Here we need to create different classes for every data type to implement the below
program. So therefore we need to generic class to reuse the same code.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 82/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
1 class DataCheck{
2 Integer i;
3
4 public void setData(Integer num){
5 i=num;
6 }
7
8 public Integer getData(){
9 return i;
10 }
11 }
12
13 public class GenericsClass {
14 public static void main(String[] args) {
15 DataCheck dc = new DataCheck();
16 Integer i1 = new Integer(10);
17 dc.setData(i1);
18 System.out.println(dc.getData());
19 setData("Rajat"); // if we need to set this data we have to create a
20 whole new class for string data type.
21 }
22
23 }
Generic Class -
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 83/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
OUTPUT:
10
Rajat
Advantages of Generics
Code reusability
Improved readability
Improved performance
Collection -
Collection is an interface which extends the different child interfaces.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 84/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Collections -
Collections is a utility class which includes static methods to perform different types
of manipulation on the collections.
Iterable Interface -
It includes a single method i.e. iterator() which is used to iterate the collections.
Iterator Interface -
Methods:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 85/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Collection Interface -
Extends Iterable interface i.e. public interface Collection<E> extends Iterable<E>
Methods:
List Interface -
Extends Collection interface.
Methods:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 86/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
ArrayList Class -
Implements list interface.
Allow heterogenous data <Object>
Similar to array but there is no size limit
Allow duplicates
Allow null values
Insertion order will be managed
Default size is 10 with no load factor and increased by (currentSize*3/2)+1
Declaration
Declaring variable arr of type ArrayList<Integer> and initialize it with a new instance of
ArrayList<Integer> using default constructor
Methods:
LinkedList Class -
Implements list interface and deque interface both.
Allow heterogenous data
Insertion order is managed but data is not stored in the sequential manner as like
ArrayList.
Allow null values
Allow duplicates
Default size empty i.e. it starts empty
Internally it uses the doubly linked list data structure
Methods:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 87/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Vector Class -
It is a legacy class i.e. introduced in 1st version of java.
Same as ArrayList but it has some extra methods that collection does not contain.
Slower operation than ArrayList. Due to Synchronization.
All methods of vector class are synchronized so therefore one process running at
time. So it affects the performance of the vector.
Allow null values
Allow duplicates
Insertion order managed
Default size is 10 and increases by 2X.
Allow heterogenous data.
Methods:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 88/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Stack Class -
Extends vector class
Allow duplicates
Allow null values
Heterogenous data allowed
Default size is 10 and increases by 2x.
Methods:
Queue Interface -
Extends collection interface and iterable interface
Methods:
Note
PriorityQueue Class -
Implements queue interface
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 89/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Methods:
Deque Interface -
Extends queue interface
Methods:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 90/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
ArrayDeque Class -
Double ended queue data structure is used.
We can add and remove elements from both the ends.
Null values are not allowed.
Methods:
All the methods from Iterable, Collection, Queue and Deque interface.
SET Interface -
Extends collection interface
Methods:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 91/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
HashSet Class -
Duplicates not allowed
Null allowed
Insertion order is not maintained.
HashSet used Hash Table data structure
Default size is 16
Load factor is 0.75
Increases by 2X
Hash Table:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16 18 20 8 25 10
If we take a first element as 10. So the calculation is like 10/16, so we get remainder as
10. Therefore the index position of the 10 is 10th index.
… and so on.
Methods:
LinkedHashSet Class -
Insertion order is maintained.
It is a combination of LinkedList and HashSet.
Otherwise, everything is the same as HashSet.
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 92/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Methods:
SortedSet Interface -
Methods:
TreeSet Class -
Null not allowed
Duplicate not allowed
Elements are stored in increasing order.
Used Binary Search Tree data structure
Parent node have zero, one and two nodes are allowed.
Smaller elements on left side
All elements are sorted.
Data: 4, 2, 3, 6, 5, 7, 1
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 93/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Methods:
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 94/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
Map Interface -
Everything is same as Set. Just difference is the values are stored in the form of key
value pair format.
We can use null values multiple times.
One key can be null.
Values can be stored duplicate but keys always unique.
Methods:
Collections Class -
Collections class in java is one of the utility class of java framework.
All methods in collections class are static.
Methods:
binarySearch(collection name, E)
reverse()
addAll()
copy()
replaceAll()
shuffle()
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 95/96
6/6/24, 9:19 AM Java Tutorials By Rajat Kotangale - HackMD
swap()
rotate()
And so on…
https://hackmd.io/WipMzhOVQOeuecVKoxNnIw 96/96