You are on page 1of 144

C++ vs Java

There are many differences and similarities between the C++ programming language and Java. A list of top
differences between C++ and Java are given below:

Comparison C++ Java


Index

Platform- C++ is platform-dependent. Java is platform-independent.


independent

Mainly used C++ is mainly used for system Java is mainly used for application
for programming. programming. It is widely used in
window, web-based, enterprise and
mobile applications.

Design Goal C++ was designed for systems Java was designed and created as an
and applications programming. It interpreter for printing systems but later
was an extension of C extended as a support network
programming language. computing. It was designed with a goal of
being easy to use and accessible to a
broader audience.

Goto C++ supports the goto statement. Java doesn't support the goto statement.

Multiple C++ supports multiple inheritance. Java doesn't support multiple inheritance
inheritance through class. It can be achieved
by interfaces in java.

Operator C++ supports operator Java doesn't support operator


Overloading overloading. overloading.

Pointers C++ supports pointers. You can Java supports pointer internally. However,
write pointer program in C++. you can't write the pointer program in
java. It means java has restricted pointer
support in java.

Compiler and C++ uses compiler only. C++ is Java uses compiler and interpreter both.
Interpreter compiled and run using the Java source code is converted into
compiler which converts source bytecode at compilation time. The
code into machine code so, C++ is interpreter executes this bytecode at
platform dependent. runtime and produces output. Java is
interpreted that is why it is platform
independent.
Call by Value C++ supports both call by value Java supports call by value only. There is
and Call by and call by reference. no call by reference in java.
reference

Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.

Thread C++ doesn't have built-in support Java has built-in thread support.
Support for threads. It relies on third-party
libraries for thread support.

Documentation C++ doesn't support Java supports documentation comment


comment documentation comment. (/** ... */) to create documentation for
java source code.

Virtual C++ supports virtual keyword so Java has no virtual keyword. We can
Keyword that we can decide whether or not override all non-static methods by
override a function. default. In other words, non-static
methods are virtual by default.

unsigned right C++ doesn't support >>> Java supports unsigned right shift >>>
shift >>> operator. operator that fills zero at the top for the
negative numbers. For positive numbers,
it works same like >> operator.

Inheritance C++ creates a new inheritance Java uses a single inheritance tree always
Tree tree always. because all classes are the child of Object
class in java. The object class is the root
of the inheritance tree in java.

Hardware C++ is nearer to hardware. Java is not so interactive with hardware.

Object- C++ is an object-oriented Java is also an object-oriented language.


oriented language. However, in C language, However, everything (except fundamental
single root hierarchy is not types) is an object in Java. It is a single
possible. root hierarchy as everything gets derived
from java.lang.Object.

Note
o Java doesn't support default arguments like C++.
o Java does not support header files like C++. Java uses the import keyword to include different
classes and methods.
C++ Example
File: main.cpp

1. #include <iostream>
2. using namespace std;
3. int main() {
4. cout << "Hello C++ Programming";
5. return 0;
6. }

Java Example
File: Simple.java

1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }

What happens at compile time?


At compile time, java file is compiled by Java Compiler (It does not interact with OS) and converts the java
code into bytecode.

What happens at runtime?


At runtime, following steps are performed:

Classloader: is the subsystem of JVM that is used to


load class files.

Bytecode Verifier: checks the code fragments for


illegal code that can violate access right to objects.

Interpreter: read bytecode stream then execute the


instructions.
Q) Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:

To compile: javac Hard.java

To execute: java Simple

Q) Can you have multiple classes in a java source file?


Yes, like the figure given below illustrates:

JVM (Java Virtual Machine) Architecture


1. Java Virtual Machine
2. Internal Architecture of JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in
which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM
It is:

1. A specification where working of Java Virtual Machine is specified. But implementation


provider is independent to choose the algorithm. Its implementation has been provided by Oracle and
other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the
java class, an instance of JVM is created.
What it does
The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine
etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is
loaded first by the classloader. There are three built-in classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension
classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang
package classes, java.net package classes, java.util package classes, java.io package classes, java.sql
package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of
System classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It
loads the classfiles from classpath. By default, classpath is set to current directory. You can change
the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.

1. //Let's see an example to print the classloader name


2. public class ClassLoaderExample
3. {
4. public static void main(String[] args)
5. {
6. // Let's print the classloader name of current class.
7. //Application/System classloader will load this class
8. Class c=ClassLoaderExample.class;
9. System.out.println(c.getClassLoader());
10. //If we print the classloader name of String, it will print null because it is an
11. //in-built class which is found in rt.jar, so it is loaded by Bootstrap classloader
12. System.out.println(String.class.getClassLoader());
13. }
14. }
Test it Now

Output:

sun.misc.Launcher$AppClassLoader@4e0e2f2a
null

These are the internal classloaders provided by Java. If you want to create your own classloader, you need
to extend the ClassLoader class.

2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the
code for methods.

3) Heap
It is the runtime data area in which objects are allocated.

4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation
and return.
Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.

5) Program Counter Register


PC (program counter) register contains the address of the Java virtual machine instruction currently being
executed.

6) Native Method Stack


It contains all the native methods used in the application.

7) Execution Engine
It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of
the byte code that have similar functionality at the same time, and hence reduces the amount of time
needed for compilation. Here, the term "compiler" refers to a translator from the instruction set of a
Java virtual machine (JVM) to the instruction set of a specific CPU.

8) Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to communicate with another
application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output
to the Console or interact with OS libraries.

Java Operator Precedence


Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof


equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=


>>>=

Java Unary Operator Example: ++ and --


1. class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}

Output:

10
12
12
10
Java Unary Operator Example 2: ++ and --
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}

Output:

22
21
Java Left Shift Operator Example
1. class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
7. }}

Output:

40
80
80
240

Java Right Shift Operator Example


1. class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}

Output:

2
5
2
Java Shift Operator Example: >> vs >>>
1. class OperatorExample{
2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}

Output:

5
5
-5
1073741819
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check second condition if first condition is false. It checks second condition
only if first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}

Output:

false
false

Java AND Operator Example: Logical && vs Bitwise &


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10. }}

Output:

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |


The logical || operator doesn't check second condition if first condition is true. It checks second condition
only if first one is false.

The bitwise | operator always checks both conditions whether first condition is true or false.

1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}

Output:

true
true
true
10
true
11
Java Ternary Operator
Java Ternary operator is used as one liner replacement for if-then-else statement and used a lot in java
programming. it is the only conditional operator which takes three operands.

Java Ternary Operator Example


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Output:

Another Example:

1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Output:

5
Java Assignment Operator
Java assignment operator is one of the most common operator. It is used to assign the value on its right to
the operand on its left.
Java Assignment Operator Example
1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}
Output:
14
16
Java Assignment Operator Example
1. class OperatorExample{
2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10. a/=2;//18/2
11. System.out.println(a);
12. }}
Output:
13
9
18
9
Java Assignment Operator Example: Adding short
1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}
Output:
Compile time error
After type cast:
1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }} Output: 20
Java Keywords
1. abstract: Java abstract keyword is used to declare abstract class. Abstract class can provide
the implementation of interface. It can have abstract and non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold
True and False values only.
3. break: Java break keyword is used to break loop or switch statement. It breaks the current
flow of the program at specified condition.
4. byte: Java byte keyword is used to declare a variable that can hold an 8-bit data values.
5. case: Java case keyword is used to with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It
must be used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode
characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current flow of
the program and skips the remaining code at the specified condition.
10. default: Java default keyword is used to specify the default block of code in a switch
statement.
11. do: Java do keyword is used in control statement to declare a loop. It can iterate a part of the
program several times.
12. double: Java double keyword is used to declare a variable that can hold a 64-bit floating-point
numbers.
13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are
always private or default.
15. extends: Java extends keyword is used to indicate that a class is derived from another class
or interface.
16. final: Java final keyword is used to indicate that a variable holds a constant value. It is applied
with a variable. It is used to restrict the user.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is
always executed whether exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point
number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some conditions become true. If the number of iteration is
fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and accessible to the
current source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance of the
specified class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
25. interface: Java interface keyword is used to declare an interface. It can have only abstract
methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native code
using JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything. It
removes the garbage value.
30. package: Java package keyword is used to declare a Java package that includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a method or
variable may be accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible within package
and outside the package but through inheritance only. It can't be applied on the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is
accessible anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class method.
The static keyword in Java is used for memory management mainly.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
38. super: Java super keyword is a reference variable that is used to refer parent class object. It
can be used to invoke immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code based on
test value. The switch statement tests the equality of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or methods
in multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is
mainly used to throw custom exception. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exception can be
propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try
block must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the
program several times. If the number of iteration is not fixed, it is recommended to use while loop.
Java-Programs:
Java Searching Programs: Linear search & Binary Search

Linear Search in Java


Linear search is used to search a key element from multiple elements. Linear search is less used today
because it is slower than binary search and hashing.

Algorithm:

o Step 1: Traverse the array


o Step 2: Match the key element with array element
o Step 3: If key element is found, return the index position of the array element
o Step 4: If key element is not found, return -1

Let's see an example of linear search in java where we are going to search an element sequentially from an
array.

1. public class LinearSearchExample{


2. public static int linearSearch(int[] arr, int key){
3. for(int i=0;i<arr.length;i++){
4. if(arr[i] == key){
5. return i;
6. }
7. }
8. return -1;
9. }
10. public static void main(String a[]){
11. int[] a1= {10,20,30,50,70,90};
12. int key = 50;
13. System.out.println(key+" is found at index: "+linearSearch(a1, key));
14. }
15. }
Test it Now

Output:

50 is found at index: 3

Linear Search in Java (Another way)


You can also use a method where array is not predefined. Here, user has to put the elements as input and
select one element to check its location.

1. import java.util.Scanner;
2.
3. class LinearSearchExample2
4. {
5. public static void main(String args[])
6. {
7. int c, n, search, array[];
8.
9. Scanner in = new Scanner(System.in);
10. System.out.println("Enter number of elements");
11. n = in.nextInt();
12. array = new int[n];
13.
14. System.out.println("Enter those " + n + " elements");
15.
16. for (c = 0; c < n; c++)
17. array[c] = in.nextInt();
18.
19. System.out.println("Enter value to find");
20. search = in.nextInt();
21.
22. for (c = 0; c < n; c++)
23. {
24. if (array[c] == search) /* Searching element is present */
25. {
26. System.out.println(search + " is present at location " + (c + 1) + ".");
27. break;
28. }
29. }
30. if (c == n) /* Element to search isn't present */
31. System.out.println(search + " isn't present in array.");
32. }
33. }

Output:

Binary Search in Java


Binary search is used to search a key element from multiple elements. Binary search is faster than linear
search.

In case of binary search, array elements must be in ascending order. If you have unsorted array, you can
sort the array using Arrays.sort(arr) method.

Binary Search Example in Java


Let's see an example of binary search in java.

1. class BinarySearchExample{
2. public static void binarySearch(int arr[], int first, int last, int key){
3. int mid = (first + last)/2;
4. while( first <= last ){
5. if ( arr[mid] < key ){
6. first = mid + 1;
7. }else if ( arr[mid] == key ){
8. System.out.println("Element is found at index: " + mid);
9. break;
10. }else{
11. last = mid - 1;
12. }
13. mid = (first + last)/2;
14. }
15. if ( first > last ){
16. System.out.println("Element is not found!");
17. }
18. }
19. public static void main(String args[]){
20. int arr[] = {10,20,30,40,50};
21. int key = 30;
22. int last=arr.length-1;
23. binarySearch(arr,0,last,key);
24. }
25. }
Test it Now

Output:

Element is found at index: 2

Binary Search Example in Java using Recursion


Let's see an example of binary search in java where we are going to search an element from an array using
recursion.

1. class BinarySearchExample1{
2. public static int binarySearch(int arr[], int first, int last, int key){
3. if (last>=first){
4. int mid = first + (last - first)/2;
5. if (arr[mid] == key){
6. return mid;
7. }
8. if (arr[mid] > key){
9. return binarySearch(arr, first, mid-1, key);//search in left subarray
10. }else{
11. return binarySearch(arr, mid+1, last, key);//search in right subarray
12. }
13. }
14. return -1;
15. }
16. public static void main(String args[]){
17. int arr[] = {10,20,30,40,50};
18. int key = 30;
19. int last=arr.length-1;
20. int result = binarySearch(arr,0,last,key);
21. if (result == -1)
22. System.out.println("Element is not found!");
23. else
24. System.out.println("Element is found at index: "+result);
25. }
26. }
Test it Now

Output:

Element is found at index: 2

Binary Search Example in Java using Arrays.binarySearch()


1. import java.util.Arrays;
2. class BinarySearchExample2{
3. public static void main(String args[]){
4. int arr[] = {10,20,30,40,50};
5. int key = 30;
6. int result = Arrays.binarySearch(arr,key);
7. if (result < 0)
8. System.out.println("Element is not found!");
9. else
10. System.out.println("Element is found at index: "+result);
11. }
12. }
Test it Now

Output:

Element is found at index: 2

Java Array Programs:


Program to copy all elements of one array into another array
In this program, we need to copy all the elements of one array into another. This can be accomplished by
looping through the first array and store the elements of the first array into the second array at the
corresponding position.

1. ARRAY 1
2. 1 2 3 4 5
3.
4. ARRAY 2
5. 1 2 3 4 5

Algorithm
o STEP 1: START
o STEP 2: INITIALIZE arr1[] ={1, 2, 3, 4, 5}
o STEP 3: CREATE arr2[] of size arr1[].
o STEP 4: COPY elements of arr1[] to arr2[]
o STEP 5: REPEAT STEP 6 UNTIL (i<arr1.length)
o STEP 6: arr2[i] =arr1[i]
o STEP 7: DISPLAY elements of arr1[].
o STEP 8: REPEAT STEP 9 UNTIL (i<arr1.length)
o STEP 9: PRINT arr1[i]
o STEP 10: DISPLAY elements of arr2[].
o STEP 11: REPEAT STEP 12 UNTIL (i<arr2.length)
o STEP 12: PRINT arr2[i].
o STEP 13: END

Program:
1. public class CopyArray {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr1 = new int [] {1, 2, 3, 4, 5};
5. //Create another array arr2 with size of arr1
6. int arr2[] = new int[arr1.length];
7. //Copying all elements of one array into another
8. for (int i = 0; i < arr1.length; i++) {
9. arr2[i] = arr1[i];
10. }
11. //Displaying elements of array arr1
12. System.out.println("Elements of original array: ");
13. for (int i = 0; i < arr1.length; i++) {
14. System.out.print(arr1[i] + " ");
15. }
16.
17. System.out.println();
18.
19. //Displaying elements of array arr2
20. System.out.println("Elements of new array: ");
21. for (int i = 0; i < arr2.length; i++) {
22. System.out.print(arr2[i] + " ");
23. }
24. }
25. }

Output:

Elements of original array


1 2 3 4 5
Elements of new array:
1 2 3 4 5

Program to find the frequency of each element in the array


In this program, we have an array of elements to count the occurrence of its each element. One of the
approaches to resolve this problem is to maintain one array to store the counts of each element of the array.
Loop through the array and count the occurrence of each element as frequency and store it in another array
fr.

1. 1 2 8 3 2 2 2 5 1
In the given array, 1 has appeared two times so its frequency be 2 and 2 has appeared four times so have
frequency 4 and so on.

Algorithm
o STEP 1: START
o STEP 2: INITIALIZE arr[] ={1, 2, 8, 3, 2, 2, 2, 5, 1 }.
o STEP 3: CREATE fr[] of arr[] length.
o STEP 4: SET visited = -1.
o STEP 5: REPEAT STEP 6 to STEP 9 for(i=0;i<arr.length;i++)
o STEP 6: SET count = 1
o STEP 7: REPEAT STEP 8 for(j=i+1;j<arr.length;j++)
o STEP 8: if(arr[i]==arr[j]) then
count++
fr[j] =visited
o STEP 9: if(fr[i]!=visited) then
fr[i]=count
o STEP 10: PRINT "------------"
o STEP 11: PRINT "Element | Frequency"
o STEP 12: PRINT "-------------"
o STEP 13: REPEAT STEP 14 for(i=0;i<fr.length;i++)
o STEP 14: if(fr[i]!=visited) then
PRINT arr[i] and fr[i]
o STEP 15: PRINT "-------------"
o STEP 16: END

Program:
1. public class Frequency {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1};
5. //Array fr will store frequencies of element
6. int [] fr = new int [arr.length];
7. int visited = -1;
8. for(int i = 0; i < arr.length; i++){
9. int count = 1;
10. for(int j = i+1; j < arr.length; j++){
11. if(arr[i] == arr[j]){
12. count++;
13. //To avoid counting same element again
14. fr[j] = visited;
15. }
16. }
17. if(fr[i] != visited)
18. fr[i] = count;
19. }
20.
21. //Displays the frequency of each element present in array
22. System.out.println("---------------------------------------");
23. System.out.println(" Element | Frequency");
24. System.out.println("---------------------------------------");
25. for(int i = 0; i < fr.length; i++){
26. if(fr[i] != visited)
27. System.out.println(" " + arr[i] + " | " + fr[i]);
28. }
29. System.out.println("----------------------------------------");
30. }}

Output:

----------------------------------------
Element | Frequency
----------------------------------------
1 | 2
2 | 4
8 | 1
3 | 1
5 | 1
----------------------------------------

Program to left rotate the elements of an array


In this program, we need to rotate the elements of an array towards the left by the specified number of
times. In the left rotation, each element of the array will be shifted to its left by one position and the first
element of the array will be added to end of the list. This process will be followed for a specified number of
times.

Consider above array, if n is 1 then, all elements of the array will be moved to its left by one position such
that second element of the array will take the first position, the third element will be moved to the second
position and so on. The first element of the array will be added to the last of the array.

Algorithm
o STEP 1: START
o STEP 2: INITIALIZE arr[] ={1, 2, 3, 4, 5 }.
o STEP 3: SET n =3
o STEP 4: PRINT "Original Array"
o STEP 5: REPEAT STEP 6 for(i=0; i<arr.length; i++)
o STEP 6: PRINT arr[i]
o STEP 7: REPEAT STEP 8 to STEP 12 for(i=0; i<n; i++ )
o STEP 8: DEFINE j, first.
o STEP 9: first = arr[0]
o STEP 10: REPEAT STEP 11 for(j= 0; j<arr.length-1; j++)
o STEP 11: arr[j]= arr[j+1]
o STEP 12: arr[j]= first
o STEP 13: PRINT "Array after left rotation"
o STEP 14: REPEAT STEP 15 for(i=0; i<arr.length; i++)
o STEP 15: PRINT arr[i]
o STEP 16: END

Program:
1. class RotateLeft {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 5};
5. //n determine the number of times an array should be rotated
6. int n = 3;
7. //Displays original array
8. System.out.println("Original array: ");
9. for (int i = 0; i < arr.length; i++) {
10. System.out.print(arr[i] + " ");
11. }
12. //Rotate the given array by n times toward left
13. for(int i = 0; i < n; i++){
14. int j, first;
15. //Stores the first element of the array
16. first = arr[0];
17. for(j = 0; j < arr.length-1; j++){
18. //Shift element of array by one
19. arr[j] = arr[j+1];
20. }
21. //First element of array will be added to the end
22. arr[j] = first;
23. }
24. System.out.println();
25. //Displays resulting array after rotation
26. System.out.println("Array after left rotation: ");
27. for(int i = 0; i< arr.length; i++){
28. System.out.print(arr[i] + " ");
29. }
30. }
31. }

Output:

Original Array:
1 2 3 4 5
Array after left rotation:
4 5 1 2 3
Program to print the duplicate elements of an array
In this program, we need to print the duplicate elements present in the array. This can be done through two
loops. The first loop will select an element and the second loop will iteration through the array by comparing
the selected element with other elements. If a match is found, print the duplicate element.

In the above array, the first duplicate will be found at the index 4 which is the duplicate of the element (2)
present at index 1. So, duplicate elements in the above array are 2, 3 and 8.

Algorithm
o STEP 1: START
o STEP 2: INITIALIZE arr[]= {1, 2, 3, 4, 2, 7, 8, 8, 3}.
o STEP 3: PRINT "Duplicate elements in given array:"
o STEP 4: REPEAT STEP 5 to STEP 7 for(i=0; i<arr.length; i++)
o STEP 5: REPEAT STEP 6 and STEP 7 for(j=i+1; j<arr.length; j++)
o STEP 6: if(arr[i] == arr[j])
o STEP 7: PRINT arr[j]
o STEP 8: END

Program:
1. public class DuplicateElement {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
5. System.out.println("Duplicate elements in given array: ");
6. //Searches for duplicate element
7. for(int i = 0; i < arr.length; i++) {
8. for(int j = i + 1; j < arr.length; j++) {
9. if(arr[i] == arr[j])
10. System.out.println(arr[j]);
11. }
12. }
13. }
14. }

Output:

Duplicate elements in given array:


2
3
8
Program to print the elements of an array
This is a simple program to create an array and then to print it's all elements.

Now, just know about arrays.

Arrays are the special variables that store multiple values under the same name in the contiguous memory
allocation. Elements of the array can be accessed through their indexes.

Here, 1, 2, 3, 4 and 5 represent the elements of the array. These elements can be accessed through their
corresponding indexes, 1.e., 0, 1, 2, 3 and 4.

Algorithm
o STEP 1: START
o STEP 2: INITIALIZE arr[] = {1, 2, 3, 4, 5}.
o STEP 3: PRINT "Elements of given array:"
o STEP 4: REPEAT STEP 5 for(i=0; i<arr.length; i++)
o STEP 5: PRINT arr[i]
o STEP 6: END

Program:
1. public class PrintArray {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 5};
5. System.out.println("Elements of given array: ");
6. //Loop through the array by incrementing value of i
7. for (int i = 0; i < arr.length; i++) {
8. System.out.print(arr[i] + " ");
9. }
10. }
11. }

Output:

Elements of given array:


1 2 3 4 5
Program to print the elements of an array in reverse order
In this program, we need to print the elements of the array in reverse order that is; the last element should
be displayed first, followed by second last element and so on.

Above array in reversed order:

Algorithm
o STEP 1: START
o STEP 2: INITIALIZE arr[] = {1, 2, 3, 4, 5}
o STEP 3: PRINT "Original Array:"
o STEP 4: REPEAT STEP 5 for(i=0; i<arr.length ; i++)
o STEP 5: PRINT arr[i]
o STEP 6: PRINT "Array in reverse order"
o STEP 7: REPEAT STEP 8 for(i= arr.length-1; i>=0; i--)
o STEP 8: PRINT a[i]
o STEP 9: END

Program:
1. public class ReverseArray {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 5};
5. System.out.println("Original array: ");
6. for (int i = 0; i < arr.length; i++) {
7. System.out.print(arr[i] + " ");
8. }
9. System.out.println();
10. System.out.println("Array in reverse order: ");
11. //Loop through the array in reverse order
12. for (int i = arr.length-1; i >= 0; i--) {
13. System.out.print(arr[i] + " ");
14. }
15. }
16. }

Output:
Original array:
1 2 3 4 5
Array in reverse order:
5 4 3 2 1

Program to print the elements of an array present on even


position

Program:
1. public class EvenPosition {
2. public static void main(String[] args) {
3.
4. //Initialize array
5. int [] arr = new int [] {1, 2, 3, 4, 5};
6.
7. System.out.println("Elements of given array present on even position: ");
8. //Loop through the array by incrementing value of i by 2
9. //Here, i will start from 1 as first even positioned element is present at position 1.
10. for (int i = 1; i < arr.length; i = i+2) {
11. System.out.println(arr[i]);
12. }
13. }
14. }

Output:

Elements of given array present on even position:


2
4

Program to print the elements of an array present on odd


position

Program:
1. public class OddPosition {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 5};
5. System.out.println("Elements of given array present on odd position: ");
6. //Loop through the array by incrementing value of i by 2
7. for (int i = 0; i < arr.length; i = i+2) {
8. System.out.println(arr[i]);
9. }
10. }
11. }

Output:
Elements of given array present on odd position:
1
3
5

Program to print the largest element in an array

Program:

1. public class LargestElement_array {


2. public static void main(String[] args) {
3.
4. //Initialize array
5. int [] arr = new int [] {25, 11, 7, 75, 56};
6. //Initialize max with first element of array.
7. int max = arr[0];
8. //Loop through the array
9. for (int i = 0; i < arr.length; i++) {
10. //Compare elements of array with max
11. if(arr[i] > max)
12. max = arr[i];
13. }
14. System.out.println("Largest element present in given array: " + max);
15. }
16. }

Output:

Largest element present in given array: 75

Program to print the smallest element in an array

Program:
1. public class SmallestElement_array {
2. public static void main(String[] args) {
3.
4. //Initialize array
5. int [] arr = new int [] {25, 11, 7, 75, 56};
6. //Initialize min with first element of array.
7. int min = arr[0];
8. //Loop through the array
9. for (int i = 0; i < arr.length; i++) {
10. //Compare elements of array with min
11. if(arr[i] <min)
12. min = arr[i];
13. }
14. System.out.println("Smallest element present in given array: " + min);
15. }
16. }

Output:

Smallest element present in given array: 7

Java Program to print the number of elements present in an


array
Program:
1. public class CountArray {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 5};
5. //Number of elements present in an array can be found using the length
6. System.out.println("Number of elements present in given array: " + arr.length);
7. }
8. }

Output:

Number of elements present in given array: 5

Java Program to print the sum of all the items of the array
Program:
1. public class SumOfArray {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 5};
5. int sum = 0;
6. //Loop through the array to calculate sum of elements
7. for (int i = 0; i < arr.length; i++) {
8. sum = sum + arr[i];
9. }
10. System.out.println("Sum of all the elements of an array: " + sum);
11. }
12. }

Output:

Sum of all the elements of an array: 15


Java Program to right rotate the elements of an array
Program:
1. class RotateRight {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {1, 2, 3, 4, 5};
5. //n determine the number of times an array should be rotated.
6. int n = 3;
7.
8. //Displays original array
9. System.out.println("Original array: ");
10. for (int i = 0; i < arr.length; i++) {
11. System.out.print(arr[i] + " ");
12. }
13.
14. //Rotate the given array by n times toward right
15. for(int i = 0; i < n; i++){
16. int j, last;
17. //Stores the last element of array
18. last = arr[arr.length-1];
19.
20. for(j = arr.length-1; j > 0; j--){
21. //Shift element of array by one
22. arr[j] = arr[j-1];
23. }
24. //Last element of array will be added to the start of array.
25. arr[0] = last;
26. }
27.
28. System.out.println();
29.
30. //Displays resulting array after rotation
31. System.out.println("Array after right rotation: ");
32. for(int i = 0; i< arr.length; i++){
33. System.out.print(arr[i] + " ");
34. }
35. }
36. }

Output:

Original Array:
1 2 3 4 5
Array after right rotation:
3 4 5 1 2
Java Program to sort the elements of an array in ascending
order
In this program, we need to sort the given array in ascending order such that elements will be arranged from
smallest to largest. This can be achieved through two loops. The outer loop will select an element, and inner
loop allows us to compare selected element with rest of the elements.

Elements will be sorted in such a way that the smallest element will appear on extreme left which in this
case is 1. The largest element will appear on extreme right which in this case is 8.

Algorithm
o STEP 1: START
o STEP 2: INITIALIZE arr[] ={5, 2, 8, 7, 1 }.
o STEP 3: SET temp =0
o STEP 4: PRINT "Elements of Original Array"
o STEP 5: REPEAT STEP 6 UNTIL i<arr.length
//for(i=0; i<arr.length; i++)
o STEP 6: PRINT arr[i]
o STEP 7: REPEAT STEP 8 to STEP 9 UNTIL i<arr.length
//for(i=0; i<arr.length; i++ )
o STEP 8: REPEAT STEP 9 UNTIL j<arr.length
//for(j=i+1;j<arr.length;j++)
o STEP 9: if(arr[i]>arr[j]) then
temp = arr[i]
arr[i]=arr[j]
arr[j]=temp
o STEP 10: PRINT new line
o STEP 11: PRINT "Elements of array sorted in ascending order"
o STEP 12: REPEAT STEP 13 UNTIL i<arr.length
//for(i=0;i<arr.length;i++)
o STEP 13: PRINT arr[i]
o STEP 14: END

Program:
1. public class SortAsc {
2. public static void main(String[] args) {
3.
4. //Initialize array
5. int [] arr = new int [] {5, 2, 8, 7, 1};
6. int temp = 0;
7.
8. //Displaying elements of original array
9. System.out.println("Elements of original array: ");
10. for (int i = 0; i < arr.length; i++) {
11. System.out.print(arr[i] + " ");
12. }
13.
14. //Sort the array in ascending order
15. for (int i = 0; i < arr.length; i++) {
16. for (int j = i+1; j < arr.length; j++) {
17. if(arr[i] > arr[j]) {
18. temp = arr[i];
19. arr[i] = arr[j];
20. arr[j] = temp;
21. }
22. }
23. }
24.
25. System.out.println();
26.
27. //Displaying elements of array after sorting
28. System.out.println("Elements of array sorted in ascending order: ");
29. for (int i = 0; i < arr.length; i++) {
30. System.out.print(arr[i] + " ");
31. }
32. }
33. }

Output:

Elements of original array:


5 2 8 7 1
Elements of array sorted in ascending order:
1 2 5 7 8
Java Program to sort the elements of an array in descending
order
In this program, we need to sort the given array in descending order such that elements will be arranged
from largest to smallest. This can be achieved through two loops. The outer loop will select an element, and
inner loop allows us to compare selected element with rest of the elements.

Elements will be sorted in such a way that largest element will appear on extreme left which in this case is 8.
The smallest element will appear on extreme right which in this case is 1.

Algorithm
o STEP 1: START
o STEP 2: INITIALIZE arr[] ={5, 2, 8, 7, 1 }.
o STEP 3: SET temp =0
o STEP 4: PRINT "Elements of Original Array"
o STEP 5: REPEAT STEP 6 UNTIL i<arr.length
//for(i=0; i<arr.length; i++)
o STEP 6: PRINT arr[i]
o STEP 7: REPEAT STEP 8 to STEP 9 UNTIL i<arr.length
//for(i=0; i<arr.length; i++ )
o STEP 8: REPEAT STEP 9 UNTIL j<arr.length
//for(j=i+1;j<arr.length;j++)
o STEP 9: if(arr[i]<arr[j]) then
temp = arr[i]
arr[i]=arr[j]
arr[j]=temp
o STEP 10: PRINT new line
o STEP 11: PRINT "Elements of array sorted in descending order"
o STEP 12: REPEAT STEP 13 UNTIL i<arr.length
//for(i=0;i<arr.length;i++)
o STEP 13: PRINT arr[i]
o STEP 14: END
Program:
1. public class SortDsc {
2. public static void main(String[] args) {
3. //Initialize array
4. int [] arr = new int [] {5, 2, 8, 7, 1};
5. int temp = 0;
6.
7. //Displaying elements of original array
8. System.out.println("Elements of original array: ");
9. for (int i = 0; i < arr.length; i++) {
10. System.out.print(arr[i] + " ");
11. }
12.
13. //Sort the array in descending order
14. for (int i = 0; i < arr.length; i++) {
15. for (int j = i+1; j < arr.length; j++) {
16. if(arr[i] < arr[j]) {
17. temp = arr[i];
18. arr[i] = arr[j];
19. arr[j] = temp;
20. }
21. }
22. }
23.
24. System.out.println();
25.
26. //Displaying elements of array after sorting
27. System.out.println("Elements of array sorted in descending order: ");
28. for (int i = 0; i < arr.length; i++) {
29. System.out.print(arr[i] + " ");
30. }
31. }
32. }

Output:

Elements of original array:


5 2 8 7 1
Elements of array sorted in descending order:
8 7 5 2 1
Java Program to find Third Largest Number in an Array
We can find the third largest number in an array in java by sorting the array and returning the 3nd largest
number. Let's see the full example to find the third largest number in java array.

1. public class ThirdLargestInArrayExample{


2. public static int getThirdLargest(int[] a, int total){
3. int temp;
4. for (int i = 0; i < total; i++)
5. {
6. for (int j = i + 1; j < total; j++)
7. {
8. if (a[i] > a[j])
9. {
10. temp = a[i];
11. a[i] = a[j];
12. a[j] = temp;
13. }
14. }
15. }
16. return a[total-3];
17. }
18. public static void main(String args[]){
19. int a[]={1,2,5,6,3,2};
20. int b[]={44,66,99,77,33,22,55};
21. System.out.println("Third Largest: "+getThirdLargest(a,6));
22. System.out.println("Third Largest: "+getThirdLargest(b,7));
23. }}
Test it Now

Output:

Third Largest:3
Third Largest:66

Find 3rd Largest Number in Array using Arrays


Let's see another example to get third largest element or number in java array using Arrays.

1. import java.util.*;
2. public class ThirdLargestInArrayExample1{
3. public static int getThirdLargest(int[] a, int total){
4. Arrays.sort(a);
5. return a[total-3];
6. }
7. public static void main(String args[]){
8. int a[]={1,2,5,6,3,2};
9. int b[]={44,66,99,77,33,22,55};
10. System.out.println("Third Largest: "+getThirdLargest(a,6));
11. System.out.println("Third Largest: "+getThirdLargest(b,7));
12. }}
Test it Now

Output:

Third Largest: 3
Third Largest: 66

Find 3rd Largest Number in Array using Collections


Let's see another example to get third largest number in java array using collections.

1. import java.util.*;
2. public class ThirdLargestInArrayExample2{
3. public static int getThirdLargest(Integer[] a, int total){
4. List<Integer> list=Arrays.asList(a);
5. Collections.sort(list);
6. int element=list.get(total-3);
7. return element;
8. }
9. public static void main(String args[]){
10. Integer a[]={1,2,5,6,3,2};
11. Integer b[]={44,66,99,77,33,22,55};
12. System.out.println("Third Largest: "+getThirdLargest(a,6));
13. System.out.println("Third Largest: "+getThirdLargest(b,7));
14. }}
Test it Now

Output:

Third Largest: 3
Third Largest: 66
String Programs

Java Program to count the total number of characters in a


string
In this program, we need to count the number of characters present in the string:

The best of both worlds

To count the number of characters present in the string, we will iterate through the string and count the
characters. In above example, total numbers of characters present in the string are 19.

For programming, follow the algorithm given below:

Algorithm
o STEP 1: START
o STEP 2: DEFINE String string = "The best of both worlds".
o STEP 3: SET count =0.
o STEP 4: SET i=0. REPEAT STEP 5 to STEP 6 UNTIL i<string.length
o STEP 5: IF (string.charAt(i)!= ' ') then count =count +1.
o STEP 6: i=i+1
o STEP 7: PRINT count.
o STEP 8: END

Program:
1. public class CountCharacter
2. {
3. public static void main(String[] args) {
4. String string = "The best of both worlds";
5. int count = 0;
6.
7. //Counts each character except space
8. for(int i = 0; i < string.length(); i++) {
9. if(string.charAt(i) != ' ')
10. count++;
11. }
12.
13. //Displays the total number of characters present in the given string
14. System.out.println("Total number of characters in a string: " + count);
15. }
16. }

Output:
Total number of characters in a string: 19

Java Program to count the total number of vowels and


consonants in a string
In this program, our task is to count the total number of vowels and consonants present in the given string.

As we know that, the characters a, e, i, o, u are known as vowels in the English alphabet. Any character
other than that is known as the consonant.

To solve this problem, First of all, we need to convert every upper-case character in the string to lower-case
so that the comparisons can be done with the lower-case vowels only not upper-case vowels, i.e.(A, E, I, O,
U). Then, we have to traverse the string using a for or while loop and match each character with all the
vowels, i.e., a, e, i, o, u. If the match is found, increase the value of count by 1 otherwise continue with the
normal flow of the program. The algorithm of the program is given below.

Algorithm
o STEP 1: START
o STEP 2: SET vCount =0, cCount =0
o STEP 3: DEFINE string str = "This is a really simple sentence".
o STEP 4: CONVERT str to lowercase
o STEP 5: SET i =0.
o STEP 6: REPEAT STEP 6 to STEP 8 UNTIL i<str.length()
o STEP 7: IF any character of str matches with any vowel then
vCount = vCount + 1.
STEP 8: IF any character excepting vowels lies BETWEEN a and z then
cCount = cCount =+1.
o STEP 9: i = i + 1
o STEP 10: PRINT vCount.
o STEP 11: PRINT cCount.
o STEP 12: END

Program:
1. public class CountVowelConsonant {
2. public static void main(String[] args) {
3.
4. //Counter variable to store the count of vowels and consonant
5. int vCount = 0, cCount = 0;
6.
7. //Declare a string
8. String str = "This is a really simple sentence";
9.
10. //Converting entire string to lower case to reduce the comparisons
11. str = str.toLowerCase();
12.
13. for(int i = 0; i < str.length(); i++) {
14. //Checks whether a character is a vowel
15. if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str
.charAt(i) == 'u') {
16. //Increments the vowel counter
17. vCount++;
18. }
19. //Checks whether a character is a consonant
20. else if(str.charAt(i) >= 'a' && str.charAt(i)<='z') {
21. //Increments the consonant counter
22. cCount++;
23. }
24. }
25. System.out.println("Number of vowels: " + vCount);
26. System.out.println("Number of consonants: " + cCount);
27. }
28. }

Output:

Number of vowels: 10
Number of consonants: 17

Java Program to divide a string in 'N' equal parts.


Here, our task is to divide the string S into n equal parts. We will print an error message if the string cannot
be divisible into n equal parts otherwise all the parts need to be printed as the output of the program.

To check whether the string can be divided into N equal parts, we need to divide the length of the string by n
and assign the result to variable chars.

If the char comes out to be a floating point value, we can't divide the string otherwise run for loop to
traverse the string and divide the string at every chars interval.

The algorithm of the program is given below.

Algorithm
o STEP 1: START
o STEP 2: DEFINE str = "aaaabbbbcccc"
o STEP 3: DEFINE len
o STEP 4: SET n =3
o STEP 5: SET temp = 0.
o STEP 6: chars = len/n
o STEP 7: DEFINE String[] equalstr.
o STEP 8: IF (len%n!=0)
then PRINT ("String can't be divided into equal parts")
else go to STEP 9
o STEP 9: SET i =0.
o STEP 10: REPEAT STEP 11 to STEP 14 UNTIL i<len
o STEP 11: DEFINE substring part.
o STEP 12: equalstr [temp] = part
o STEP 13: temp = temp + 1
o STEP 14: i = i + chars
o STEP 15: PRINT n
o STEP 16: SET i=0. REPEAT STEP 17 to STEP 18 UNTIL i<equalstr.length
o STEP 17: PRINT equalstr[i]
o STEP 18: i = i + 1
o STEP 19: END

Program:
1. public class DivideString {
2. public static void main(String[] args) {
3. String str = "aaaabbbbcccc";
4.
5. //Stores the length of the string
6. int len = str.length();
7. //n determines the variable that divide the string in 'n' equal parts
8. int n = 3;
9. int temp = 0, chars = len/n;
10. //Stores the array of string
11. String[] equalStr = new String [n];
12. //Check whether a string can be divided into n equal parts
13. if(len % n != 0) {
14. System.out.println("Sorry this string cannot be divided into "+ n +" equal parts.");
15. }
16. else {
17. for(int i = 0; i < len; i = i+chars) {
18. //Dividing string in n equal part using substring()
19. String part = str.substring(i, i+chars);
20. equalStr[temp] = part;
21. temp++;
22. }
23. System.out.println(n + " equal parts of given string are ");
24. for(int i = 0; i < equalStr.length; i++) {
25. System.out.println(equalStr[i]);
26. }
27. }
28. }
29. }

Output:

3 equal parts of given string are


aaaa
bbbb
cccc
Java Program to find all subsets of a string
In this program, all the subsets of the string need to be printed. The subset of a string is the character or the
group of characters that are present inside the string.

All the possible subsets for a string will be n(n+1)/2.

For example, all possible subsets of a string "FUN" will be F, U, N, FU, UN, FUN.

To complete this program, we need to run two for loops. The outer loop is used to maintain the relative
position of the first character and the second loop is used to create all possible subsets and prints them one
by one.

The algorithm of the program is given below.

Algorithm
o STEP 1: START
o STEP 2: DEFINE string str = "FUN"
o STEP 3: DEFINE len = str.length()
o STEP 4: SET temp =0
o STEP 5: DEFINE String array having length: len*(len + 1)/2
o STEP 6: SET i =0. REPEAT STEP 7 to STEP 11 UNTIL i<len
o STEP 7: SET j =1. REPEAT STEP 8 to STEP 10 UNTIL j<len
o STEP 8: arr[temp] = str.substring(i, j+1)
o STEP 9: temp = temp + 1
o STEP 10: j =j + 1
o STEP 11: i =i +1
o STEP 12: PRINT ("All subsets for given string are: ")
o STEP 13: SET i = 0
o STEP 14: REPEAT STEP 14 UNTIL i<arr.length
o STEP 14: PRINT arr[i]
o STEP 15: END

Program:
1. public class AllSubsets {
2. public static void main(String[] args) {
3.
4. String str = "FUN";
5. int len = str.length();
6. int temp = 0;
7. //Total possible subsets for string of size n is n*(n+1)/2
8. String arr[] = new String[len*(len+1)/2];
9.
10. //This loop maintains the starting character
11. for(int i = 0; i < len; i++) {
12. //This loop adds the next character every iteration for the subset to form and add it to the arr
ay
13. for(int j = i; j < len; j++) {
14. arr[temp] = str.substring(i, j+1);
15. temp++;
16. }
17. }
18.
19. //This loop prints all the subsets formed from the string.
20. System.out.println("All subsets for given string are: ");
21. for(int i = 0; i < arr.length; i++) {
22. System.out.println(arr[i]);
23. }
24. }
25. }

Output:

All subsets for given string are:


F
FU
FUN
U
UN
N

Java Program to find the longest repeating sequence in a


string
In this program, we need to find the substring which has been repeated in the original string more than
once.

A b D F A A b d f

In the above string, the substring bdf is the longest sequence which has been repeated twice.

The algorithm of the program is given below.

Algorithm
main()

o STEP 1: START
o STEP 2: DEFINE string str = "acbdfghybdf"
o STEP 3: SET String lrs = " "
o STEP 4: CALCULATE length.
o STEP 5: SET i =0. REPEAT STEP 6 to STEP 10 UNTIL i<n.
o STEP 6: SET j =i+1. REPEAT STEP 7 to STEP 9 UNTIL j<n.
o STEP 7: CALL lcp() in String x.
o STEP 8: if(x.length()>lrs.length()) then lrs =x
o STEP 9: j =j + 1
o STEP 10: i =i +1
o STEP 11: PRINT lrs.
o STEP 12: END

lcp(String s, String t)

o STEP 1: START
o STEP 2: SET n = Math.min(s.length(), t.length())
o STEP 3: SET i =0. REPEAT STEP 4 to STEP 5 UNTIL i<n
o STEP 4: if(s.charAt(i) != t.charAt(i)) then RETURN s.substring(0, i)
o STEP 5: i= i+1
o STEP 6: RETURN s.substring(0,n)
o STEP 7: END

Program:
1. public class LongestRepeatingSequence {
2. //Checks for the largest common prefix
3. public static String lcp(String s, String t){
4. int n = Math.min(s.length(),t.length());
5. for(int i = 0; i < n; i++){
6. if(s.charAt(i) != t.charAt(i)){
7. return s.substring(0,i);
8. }
9. }
10. return s.substring(0,n);
11. }
12.
13. public static void main(String[] args) {
14. String str = "acbdfghybdf";
15. String lrs="";
16. int n = str.length();
17. for(int i = 0; i < n; i++){
18. for(int j = i+1; j < n; j++){
19. //Checks for the largest common factors in every substring
20. String x = lcp(str.substring(i,n),str.substring(j,n));
21. //If the current prefix is greater than previous one
22. //then it takes the current one as longest repeating sequence
23. if(x.length() > lrs.length()) lrs=x;
24. }
25. }
26. System.out.println("Longest repeating sequence: "+lrs);
27. }
28. }
Output:

Longest repeating sequence: bdf

Java Program to find all the permutations of a string


To solve this problem, we need to understand the concept of backtracking.

According to the backtracking algorithm:

o Fix a character in the first position and swap the rest of the character with the first character.
Like in ABC, in the first iteration three strings are formed: ABC, BAC, and CBA by swapping A with A,
B and C respectively.
o Repeat step 1 for the rest of the characters like fixing second character B and so on.
o Now swap again to go back to the previous position. E.g., from ABC, we formed ABC by fixing
B again, and we backtrack to the previous position and swap B with C. So, now we got ABC and ACB.
o Repeat these steps for BAC and CBA, to get all the permutations.

For programming, follow the algorithm given below:

Algorithm
main()

o STEP 1: START
o STEP 2: DEFINE string str = "ABC".
o STEP 3: len = str.length().
o STEP 4: PRINT "All the permutations of the string are:"
o STEP 5:CALL generatePermutation(str, 0, len).
o STEP 6: END

generatePermutation(String str, int start, int end)


o STEP 1: START
o STEP 2: if(start==end-1)
PRINT str
else go to STEP 3
o STEP 3: SET i = start. REPEAT STEP 4 to STEP 7 UNTIL i<end.
o STEP 4: str = swapstring(str, start, i).
o STEP 5: generatePermutation(str, start + 1, end).
o STEP 6: str = swapstring(str, start, i).
o STEP 7: i=i+1
o STEP 8: END

swapString(String a, int i, int j)

o STEP 1: START
o STEP 2: char[] b = a.toCharArray()
o STEP 3: DEFINE char ch
o STEP 4: ch =b[i]
o STEP 5: b[i] = b[j]
o STEP 6: b[j] = ch
o STEP 7: RETURN String.ValueOf(b)
o STEP 8: END

Program:
1. public class PermuteString {
2. //Function for swapping the characters at position I with character at position j
3. public static String swapString(String a, int i, int j) {
4. char[] b =a.toCharArray();
5. char ch;
6. ch = b[i];
7. b[i] = b[j];
8. b[j] = ch;
9. return String.valueOf(b);
10. }
11.
12. public static void main(String[] args)
13. {
14. String str = "ABC";
15. int len = str.length();
16. System.out.println("All the permutations of the string are: ");
17. generatePermutation(str, 0, len);
18. }
19.
20. //Function for generating different permutations of the string
21. public static void generatePermutation(String str, int start, int end)
22. {
23. //Prints the permutations
24. if (start == end-1)
25. System.out.println(str);
26. else
27. {
28. for (int i = start; i < end; i++)
29. {
30. //Swapping the string by fixing a character
31. str = swapString(str,start,i);
32. //Recursively calling function generatePermutation() for rest of the characters
33. generatePermutation(str,start+1,end);
34. //Backtracking and swapping the characters again.
35. str = swapString(str,start,i);
36. }
37. }
38. }
39. }

Output:

All the permutations of the string are:


ABC
ACB
BAC
BCA
CBA
CAB

Java Program to remove all the white spaces from a string


In this program, our task is to remove all the white-spaces from the string. For this purpose, we need to
traverse the string and check if any character of the string is matched with a white-space character or not. If
so, use any built-in method like replace() with a blank.

In C, we do not have any built-in method to replace. Therefore, we need to run for loop to traverse the
string and see if there is any white-space character or not. If so, then start the inner loop (j) from ith
character to len and keep replacing each element with its next adjacent element. Decrease the length of the
string by 1 on the termination of this loop. Repeat this process until all the white-spaces of the string are
removed.

The algorithm of the program is given below.

Algorithm
o STEP 1: START
o STEP 2: DEFINE string str1 = "Remove white spaces".
o STEP 3: REPLACE all space characters with blank using replaceAll().
o STEP 4: PRINT str1.
o STEP 5: END

Program:
1. public class removeWhiteSpace {
2. public static void main(String[] args) {
3.
4. String str1="Remove white spaces";
5.
6. //Removes the white spaces using regex
7. str1 = str1.replaceAll("\\s+", "");
8.
9. System.out.println("String after removing all the white spaces : " + str1);
10. }
11. }

Output:

String after removing all the white spaces: Removewhitespaces

Java Program to find Reverse of the string.

Program:
1. public class Reverse
2. {
3. public static void main(String[] args) {
4. String string = "Dream big";
5. //Stores the reverse of given string
6. String reversedStr = "";
7.
8. //Iterate through the string from last and add each character to variable reversedStr
9. for(int i = string.length()-1; i >= 0; i--){
10. reversedStr = reversedStr + string.charAt(i);
11. }
12.
13. System.out.println("Original string: " + string);
14. //Displays the reverse of given string
15. System.out.println("Reverse of given string: " + reversedStr);
16. }
17. }

Output:

Original string: Dream big


Reverse of given string: gib maerD
Java program to find the duplicate characters in a string
In this program, we need to find the duplicate characters in the string.

Great responsibility

To find the duplicate character from the string, we count the occurrence of each character in the string. If
count is greater than 1, it implies that a character has a duplicate entry in the string. In above example, the
characters highlighted in green are duplicate characters.

ALGORITHM
o STEP 1: START
o STEP 2: DEFINE String string1 = "Great responsibility"
o STEP 3: DEFINE count
o STEP 4: CONVERT string1 into char string[].
o STEP 5: PRINT "Duplicate characters in a given string:"
o STEP 6: SET i = 0. REPEAT STEP 7 to STEP 11 UNTIL i<string.length<
li=""></string.length<>
o STEP 7: SET count =1
o STEP 8: SET j = i+1. REPEAT STEP 8 to STEP 10 UNTIL j<string.length<
li=""></string.length<>
o STEP 9: IF (string[i] == string[j] && string[i] != ' ')
then
count = count + 1
string[j]= 0
o STEP 10: j = j + 1
o STEP 11: i = i + 1
o STEP 12: IF(count>1 && string[i] != 0) then PRINT string[i]
o STEP 13: END

Program:
1. public class DuplicateCharacters {
2. public static void main(String[] args) {
3. String string1 = "Great responsibility";
4. int count;
5.
6. //Converts given string into character array
7. char string[] = string1.toCharArray();
8.
9. System.out.println("Duplicate characters in a given string: ");
10. //Counts each character present in the string
11. for(int i = 0; i <string.length; i++) {
12. count = 1;
13. for(int j = i+1; j <string.length; j++) {
14. if(string[i] == string[j] && string[i] != ' ') {
15. count++;
16. //Set string[j] to 0 to avoid printing visited character
17. string[j] = '0';
18. }
19. }
20. //A character is considered as duplicate if count is greater than 1
21. if(count > 1 && string[i] != '0')
22. System.out.println(string[i]);
23. }
24. }
25. }

Output:

Duplicate characters in a given string:


r
e
t
s
i

Java program to find the duplicate words in a string


In this program, we need to find out the duplicate words present in the string and display those words.

Example: big black bug bit a big black dog on his big black nose

To find the duplicate words from the string, we first split the string into words. We count the occurrence of
each word in the string. If count is greater than 1, it implies that a word is duplicate in the string.

ALGORITHM
o STEP 1: START
o STEP 2: DEFINE String string = "Big black bug bit a big black dog on his big black nose"
o STEP 3: DEFINE count
o STEP 4: CONVERT string into lower-case.
o STEP 5: INITIALIZE words[] to SPLIT the string.
o STEP 6: PRINT "Duplicate words in a given string:"
o STEP 7: SET i=0. REPEAT STEP 8 to 12 STEP UNTIL i<words.length< li=""></words.length<>
o STEP 8: SET count =1.
o STEP 9: SET j = i+1. REPEAT STEP 10 to STEP 11 UNTIL j<words.length<
li=""></words.length<>
o STEP 10: IF (words[i].equals(words[j])
then
count = count + 1
words[j]= 0
o STEP 11: j = j + 1
o STEP 12: i = i + 1
o STEP 13: IF(count>1 && words[i] != 0) then PRINT words[i]
o STEP 13: END

Program:
1. public class DuplicateWord {
2. public static void main(String[] args) {
3. String string = "Big black bug bit a big black dog on his big black nose";
4. int count;
5.
6. //Converts the string into lowercase
7. string = string.toLowerCase();
8.
9. //Split the string into words using built-in function
10. String words[] = string.split(" ");
11.
12. System.out.println("Duplicate words in a given string : ");
13. for(int i = 0; i < words.length; i++) {
14. count = 1;
15. for(int j = i+1; j < words.length; j++) {
16. if(words[i].equals(words[j])) {
17. count++;
18. //Set words[j] to 0 to avoid printing visited word
19. words[j] = "0";
20. }
21. }
22.
23. //Displays the duplicate word if count is greater than 1
24. if(count > 1 && words[i] != "0")
25. System.out.println(words[i]);
26. }
27. }
28. }

Output:

Duplicate words in a given string :


big
black

Java Program to find the frequency of characters

Program:
1. public class FrequencyCharacter
2. {
3. public static void main(String[] args) {
4. String str = "picture perfect";
5. int[] freq = new int[str.length()];
6. int i, j;
7.
8. //Converts given string into character array
9. char string[] = str.toCharArray();
10.
11. for(i = 0; i <str.length(); i++) {
12. freq[i] = 1;
13. for(j = i+1; j <str.length(); j++) {
14. if(string[i] == string[j]) {
15. freq[i]++;
16.
17. //Set string[j] to 0 to avoid printing visited character
18. string[j] = '0';
19. }
20. }
21. }
22.
23. //Displays the each character and their corresponding frequency
24. System.out.println("Characters and their corresponding frequencies");
25. for(i = 0; i <freq.length; i++) {
26. if(string[i] != ' ' && string[i] != '0')
27. System.out.println(string[i] + "-" + freq[i]);
28. }
29. }
30. }

Output:

Characters and their corresponding frequencies


p-2
i-1
c-2
t-2
u-1
r-2
e-3
f-1

Java Program to find the number of the words in the given


text file
In this program, we need to find the most repeated word present in given text file. This can be done by
opening a file in read mode using file pointer. Read the file line by line. Split a line at a time and store in an
array. Iterate through the array and count the word. The content of data.txt file used in the program is
shown below.

data.txt

A computer program is a collection of instructions that performs specific task when executed by a computer.

Computer requires programs to function.

Computer program is usually written by a computer programmer in programming language.

A collection of computer programs, libraries, and related data are referred to as software.
Computer programs may be categorized along functional lines, such as application software and system
software.

Algorithm
o STEP 1: START
o STEP 2: DEFINE String line
o STEP 3: SET count =0
o STEP 4: USE File Reader to open file in read mode.
o STEP 5: READ line from file
o STEP 6: REPEAT STEP 7 to STEP 8 UNTIL reach the end of file
o STEP 7: SPLIT lines into words and STORE in array string words[].
o STEP 8: count = count + words.length
o STEP 9: PRINT count.
o STEP 10: END

Program:
1. import java.io.BufferedReader;
2. import java.io.FileReader;
3.
4. public class CountWordFile
5. {
6. public static void main(String[] args) throws Exception {
7. String line;
8. int count = 0;
9.
10. //Opens a file in read mode
11. FileReader file = new FileReader("data.txt ");
12. BufferedReader br = new BufferedReader(file);
13.
14. //Gets each line till end of file is reached
15. while((line = br.readLine()) != null) {
16. //Splits each line into words
17. String words[] = line.split("");
18. //Counts each word
19. count = count + words.length;
20.
21. }
22.
23. System.out.println("Number of words present in given file: " + count);
24. br.close();
25. }
26. }

Output:

Number of words present in given file: 63


Java Program to separate the Individual Characters from a
String
Program:
1. public class IndividualCharacters
2. {
3. public static void main(String[] args) {
4. String string = "characters ";
5.
6. //Displays individual characters from given string
7. System.out.println("Individual characters from given string: ");
8.
9. //Iterate through the string and display individual character
10. for(int i = 0; i < string.length(); i++){
11. System.out.print(string.charAt(i) + " ");
12. }
13. }
14. }

Output:

Individual characters from given string:


c h a r a c t e r s

Java Program to swap two string variables without using


third or temp variable.

Program:
1. public class SwapStrings
2. {
3. public static void main(String[] args) {
4. String str1 = "Good ", str2 = "morning ";
5. System.out.println("Strings before swapping: " + str1 + " " + str2);
6.
7. //Concatenate both the string str1 and str2 and store it in str1
8. str1 = str1 + str2;
9. //Extract str2 from updated str1
10. str2 = str1.substring(0, (str1.length() - str2.length()));
11. //Extract str1 from updated str1
12. str1 = str1.substring(str2.length());
13.
14. System.out.println("Strings after swapping: " + str1 + " " + str2);
15. }
16. }

Output:
Strings before swapping: Good morning
Strings after swapping: morning Good

Program to print smallest and biggest possible palindrome


word in a given string

Program:
1. import java.io.BufferedReader;
2. import java.io.FileReader;
3.
4. public class CountWordFile
5. {
6. public static void main(String[] args) throws Exception {
7. String line;
8. int count = 0;
9.
10. //Opens a file in read mode
11. FileReader file = new FileReader("data.txt ");
12. BufferedReader br = new BufferedReader(file);
13.
14. //Gets each line till end of file is reached
15. while((line = br.readLine()) != null) {
16. //Splits each line into words
17. String words[] = line.split("");
18. //Counts each word
19. count = count + words.length;
20. }
21.
22. System.out.println("Number of words present in given file: " + count);
23. br.close();
24. }
25. }

Output:

Number of words present in given file: 63


Patterns:
Java program to print the following pattern
5432*
543*1
54*21
5*321
*4321

Algorithm:
o STEP 1: START
o STEP 2: DEFINE i, j.
o STEP 3: SET lines=5
o STEP 4: SET i=1. REPEAT STEP 5 to STEP 10 UNTIL i <= lines
o STEP 5: SET j=lines
o STEP 6: REPEAT STEP 7 and 8 UNTIL j >= 1
o STEP 7: IF j!=i then PRINT j
else PRINT *
o STEP 8: j=j-1
o STEP 9: PRINT new line.
o STEP 10: i=i+1
o STEP 11: END

Program:
1. public class Main{
2. public static void main(String []args){
3. int i,j,lines=5;
4. for(i=1;i<=lines;i++){// this loop is used to print the lines
5. for(j=lines;j>=1;j--){// this loop is used to print numbers in a line
6. if(j!=i)
7. System.out.print(j);
8. else
9. System.out.print("*");
10. }
11. System.out.println("");
12. }
13. }}

Output:

5432*
543*1
54*21
5*321
*4321
Java program to print the following pattern
*000*000*
0*00*00*0
00*0*0*00
000***000

Algorithm:
o STEP 1: START
o STEP 2: SET lines=4
o STEP 3: Define i, j
o STEP 4: SET i =1
o STEP 5: REPEAT STEP 6 to 15 UNTIL i <= lines
o STEP 6: SET j=1
o STEP 7: REPET STEP 8 and 9 UNTIL j <= lines
o STEP 8: IF i is equal to j PRINT * ELSE PRINT 0
o STEP 9: SET j = j + 1
o STEP 10: DECREMENT j by 1 and PRINT *
o STEP 11: REPEAT STEP 12 and 13 UNTIL j >=1
o STEP 12: IF i is equals to j PRINT * ELSE PRINT 0
o STEP 13: SET j = j - 1
o STEP 14: PRINT a new line
o STEP 15: SET i = i + 1
o STEP 16: END

Program:
1. public class pattern
2. {
3. public static void main(String[] args){
4. int lines=4;
5. int i,j;
6. for(i=1;i<=lines;i++){// this loop is used to print lines
7. for(j=1;j<=lines;j++){// this loop is used to print * in a line
8. if(i==j)
9. System.out.print("*");
10. else
11. System.out.print("0");
12. }
13. j--;
14. System.out.print("*");
15. while(j>=1){// this loop is used to print * in a line
16. if(i==j)
17. System.out.print("*");
18. else
19. System.out.print("0");
20. j--;
21. }
22. System.out.println("");
23. }
24. }
25. }

Output:

*000*000*
0*00*00*0
00*0*0*00
000***000

Java program to print the following pattern on the


console

Program:
1. class pattern
2.
3. public static void main(String[] args)
4. {
5. int i,j, n=7;
6. System.out.println("Right angle triangle");
7. for(i=1;i<n;i++)
8. {
9. for(j=1;j<=i;j++)
10. {
11. System.out.print(" *");
12. }
13. System.out.println("");
14. }
15. }

Output:
Singly linked list Examples in Java
o Linked List can be defined as a collection of objects called nodes that are randomly stored in
the memory.
o A node contains two fields, i.e. data stored at that particular address and the pointer which
contains the address of the next node in the memory.
o The last node of the list contains the pointer to the null.

Program:
1. public class LinkedListExamples
2. {
3. Node head; // head of list
4. static class Node {
5. int data;
6. Node next;
7. Node(int d) { data = d; next=null; }
8. }
9. /* This function prints contents of the linked list starting from head */
10. public void display()
11. {
12. Node n = head;
13. while (n != null)
14. {
15. System.out.print(n.data+" \n");
16. n = n.next;
17. }
18. }
19. /* method to create a simple linked list with 3 nodes*/
20. public static void main(String[] args)
21. {
22. /* Start with the empty list. */
23. LinkedListExamples list = new LinkedListExamples();
24.
25. list.head = new Node(100);
26. Node second = new Node(200);
27. Node third = new Node(300);
28.
29. list.head.next = second; // Link first node with the second node
30. second.next = third; // Link first node with the second node
31. list.display();
32. }
33. }

Output:

100
200
300
Java Program to create and display a singly linked list
The singly linked list is a linear data structure in which each element of the list contains a pointer which
points to the next element in the list. Each element in the singly linked list is called a node. Each node has
two components: data and a pointer next which points to the next node in the list. The first node of the list is
called as head, and the last node of the list is called a tail. The last node of the list contains a pointer to the
null. Each node in the list can be accessed linearly by traversing through the list from head to tail.

Consider the above example; node 1 is the head of the list and node 4 is the tail of the list. Each node is
connected in such a way that node 1 is pointing to node 2 which in turn pointing to node 3. Node 3 is again
pointing to node 4. Node 4 is pointing to null as it is the last node of the list.

Algorithm
o Create a class Node which has two attributes: data and next. Next is a pointer to the next
node.
o Create another class which has two attributes: head and tail.
o addNode() will add a new node to the list:
o Create a new node.
o It first checks, whether the head is equal to null which means the list is empty.
o If the list is empty, both head and tail will point to the newly added node.
o If the list is not empty, the new node will be added to end of the list such that tail's
next will point to the newly added node. This new node will become the new tail of the list.

a. display() will display the nodes present in the list:

o Define a node current which initially points to the head of the list.
o Traverse through the list till current points to null.
o Display each node by making current to point to node next to it in each iteration.

Program:
1. public class SinglyLinkedList {
2. //Represent a node of the singly linked list
3. class Node{
4. int data;
5. Node next;
6.
7. public Node(int data) {
8. this.data = data;
9. this.next = null;
10. }
11. }
12.
13. //Represent the head and tail of the singly linked list
14. public Node head = null;
15. public Node tail = null;
16.
17. //addNode() will add a new node to the list
18. public void addNode(int data) {
19. //Create a new node
20. Node newNode = new Node(data);
21.
22. //Checks if the list is empty
23. if(head == null) {
24. //If list is empty, both head and tail will point to new node
25. head = newNode;
26. tail = newNode;
27. }
28. else {
29. //newNode will be added after tail such that tail's next will point to newNode
30. tail.next = newNode;
31. //newNode will become new tail of the list
32. tail = newNode;
33. }
34. }
35.
36. //display() will display all the nodes present in the list
37. public void display() {
38. //Node current will point to head
39. Node current = head;
40.
41. if(head == null) {
42. System.out.println("List is empty");
43. return;
44. }
45. System.out.println("Nodes of singly linked list: ");
46. while(current != null) {
47. //Prints each node by incrementing pointer
48. System.out.print(current.data + " ");
49. current = current.next;
50. }
51. System.out.println();
52. }
53.
54. public static void main(String[] args) {
55.
56. SinglyLinkedList sList = new SinglyLinkedList();
57.
58. //Add nodes to the list
59. sList.addNode(1);
60. sList.addNode(2);
61. sList.addNode(3);
62. sList.addNode(4);
63.
64. //Displays the nodes present in the list
65. sList.display();
66. }
67. }

Output:

Nodes of singly linked list:


1 2 3 4

Java Program to insert a new node at the middle of the


singly linked list
In this program, we will create a singly linked list and add a new node at the middle of the list. To
accomplish this task, we will calculate the size of the list and divide it by 2 to get the mid-point of the list
where the new node needs to be inserted.

Consider the above diagram; node 1 represents the head of the original list. Let node New is the new node
which needs to be added at the middle of the list. First, we calculate size which in this case is 4. So, to get
the mid-point, we divide it by 2 and store it in a variable count. Node current will point to head. First, we
iterate through the list till current points to the mid position. Define another node temp which point to node
next to current. Insert the New node between current and temp

Algorithm
o Create a class Node which has two attributes: data and next. Next is a pointer to the next
node in the list.
o Create another class InsertMid which has three attributes: head, tail, and size that keep tracks
of a number of nodes present in the list.
o addNode() will add a new node to the list:
o Create a new node.
o It first checks, whether the head is equal to null which means the list is empty.
o If the list is empty, both head and tail will point to a newly added node.
o If the list is not empty, the new node will be added to end of the list such that tail's
next will point to a newly added node. This new node will become the new tail of the list.

a. addInMid() will add a new node at the middle of the list:

o It first checks, whether the head is equal to null which means the list is empty.
o If the list is empty, both head and tail will point to a newly added node.
o If the list is not empty, then calculate the size of the list and divide it by 2 to get mid-point of
the list.
o Define node current that will iterate through the list until current will point to the mid node.
o Define another node temp which will point to node next to current.
o The new node will be inserted after current and before temp such that current will point to the
new node and the new node will point to temp.
a. display() will display the nodes present in the list:

o Define a node current which will initially point to the head of the list.
o Traverse through the list till current points to null.
o Display each node by making current to point to node next to it in each iteration.

Program:
1. public class InsertMid {
2.
3. //Represent a node of the singly linked list
4. class Node{
5. int data;
6. Node next;
7.
8. public Node(int data) {
9. this.data = data;
10. this.next = null;
11. }
12. }
13.
14. public int size;
15. //Represent the head and tail of the singly linked list
16. public Node head = null;
17. public Node tail = null;
18.
19. //addNode() will add a new node to the list
20. public void addNode(int data) {
21. //Create a new node
22. Node newNode = new Node(data);
23.
24. //Checks if the list is empty
25. if(head == null) {
26. //If list is empty, both head and tail will point to new node
27. head = newNode;
28. tail = newNode;
29. }
30. else {
31. //newNode will be added after tail such that tail's next will point to newNode
32. tail.next = newNode;
33. //newNode will become new tail of the list
34. tail = newNode;
35. }
36. //Size will count the number of nodes present in the list
37. size++;
38. }
39.
40. //This function will add the new node at the middle of the list.
41. public void addInMid(int data){
42. //Create a new node
43. Node newNode = new Node(data);
44.
45. //Checks if the list is empty
46. if(head == null) {
47. //If list is empty, both head and tail would point to new node
48. head = newNode;
49. tail = newNode;
50. }
51. else {
52. Node temp, current;
53. //Store the mid position of the list
54. int count = (size % 2 == 0) ? (size/2) : ((size+1)/2);
55. //Node temp will point to head
56. temp = head;
57. current = null;
58.
59. //Traverse through the list till the middle of the list is reached
60. for(int i = 0; i < count; i++) {
61. //Node current will point to temp
62. current = temp;
63. //Node temp will point to node next to it.
64. temp = temp.next;
65. }
66.
67. //current will point to new node
68. current.next = newNode;
69. //new node will point to temp
70. newNode.next = temp;
71. }
72. size++;
73. }
74.
75. //display() will display all the nodes present in the list
76. public void display() {
77. //Node current will point to head
78. Node current = head;
79. if(head == null) {
80. System.out.println("List is empty");
81. return;
82. }
83.
84. while(current != null) {
85. //Prints each node by incrementing pointer
86. System.out.print(current.data + " ");
87. current = current.next;
88. }
89. System.out.println();
90. }
91.
92. public static void main(String[] args) {
93.
94. InsertMid sList = new InsertMid();
95.
96. //Adds data to the list
97. sList.addNode(1);
98. sList.addNode(2);
99.
100. System.out.println("Original list: ");
101. sList.display();
102.
103. //Inserting node '3' in the middle
104. sList.addInMid(3);
105. System.out.println( "Updated List: ");
106. sList.display();
107.
108. //Inserting node '4' in the middle
109. sList.addInMid(4);
110. System.out.println("Updated List: ");
111. sList.display();
112. }
113. }

Output:

Original list:
1 2
Updated List:
1 3 2
Updated List:
1 3 4 2

Java program to insert a new node at the beginning of the


singly linked list
In this program, we will create a singly linked list and add a new node at the beginning of the list. To
accomplish this task, we will store head to a temporary node temp. Make newly added node as the new head
of the list. Then, add temp (old head) after new head.

Consider the above list; node 1 represents the head of the original list. Let node New be the new node which
needs to be added at the beginning of the list. Node temp will point to head, i.e., 1. Make New as the new
head of the list and add temp after new head such that node next to New will be 1.

Algorithm
o Create a class Node which has two attributes: data and next. Next is a pointer to the next
node in the list.
o Create another class InsertStart which has two attributes: head and tail.
o addAtStart() will add a new node to the beginning of the list:
o It first checks, whether the head is equal to null which means the list is empty.
o If the list is empty, both head and tail will point to a newly added node.
o If the list is not empty then, create temporary node temp will point to head.
o Add the new node as head of the list.
o Temp which was pointing to the old head will be added after the new head.

a. display() will display the nodes present in the list:

o Define a node current which will initially point to the head of the list.
o Traverse through the list till current points to null.
o Display each node by making current to point to node next to it in each iteration.

Program:
1. public class InsertStart {
2.
3. //Represent a node of the singly linked list
4. class Node{
5. int data;
6. Node next;
7.
8. public Node(int data) {
9. this.data = data;
10. this.next = null;
11. }
12. }
13.
14. //Represent the head and tail of the singly linked list
15. public Node head = null;
16. public Node tail = null;
17.
18. //addAtStart() will add a new node to the beginning of the list
19. public void addAtStart(int data) {
20. //Create a new node
21. Node newNode = new Node(data);
22.
23. //Checks if the list is empty
24. if(head == null) {
25. //If list is empty, both head and tail will point to new node
26. head = newNode;
27. tail = newNode;
28. }
29. else {
30. //Node temp will point to head
31. Node temp = head;
32. //newNode will become new head of the list
33. head = newNode;
34. //Node temp(previous head) will be added after new head
35. head.next = temp;
36. }
37. }
38.
39. //display() will display all the nodes present in the list
40. public void display() {
41. //Node current will point to head
42. Node current = head;
43. if(head == null) {
44. System.out.println("List is empty");
45. return;
46. }
47. System.out.println("Adding nodes to the start of the list: ");
48. while(current != null) {
49. //Prints each node by incrementing pointer
50. System.out.print(current.data + " ");
51. current = current.next;
52. }
53. System.out.println();
54. }
55.
56. public static void main(String[] args) {
57.
58. InsertStart sList = new InsertStart();
59.
60. //Adding 1 to the list
61. sList.addAtStart(1);
62. sList.display();
63.
64. //Adding 2 to the list
65. sList.addAtStart(2);
66. sList.display();
67.
68. //Adding 3 to the list
69. sList.addAtStart(3);
70. sList.display();
71.
72. //Adding 4 to the list
73. sList.addAtStart(4);
74. sList.display();
75. }
76. }

Output:

Adding nodes to the start of the list:


1
Adding nodes to the start of the list:
2 1
Adding nodes to the start of the list:
3 2 1
Adding nodes to the start of the list:
4 3 2 1

Method Overloading in Java


1. Different ways to overload the method
2. By changing the no. of arguments
3. By changing the datatype
4. Why method overloading is not possible by changing the return type
5. Can we overload the main method
6. method overloading with Type Promotion

If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of the
program.

Suppose you have to perform addition of the given numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it
may be difficult for you as well as other programmers to understand the behavior of the method because its
name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In java, Method Overloading is not possible by changing the return type of the method only.

1) Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling methods.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Test it Now

Output:

22
33

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add method receives two
integer arguments and second add method receives two double arguments.

1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
Test it Now

Output:

22
24.9

Q) Why Method Overloading is not possible by changing the return type


of method only?
In java, method overloading is not possible by changing the return type of the method only because of
ambiguity. Let's see how ambiguity may occur:

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int a,int b){return a+b;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));//ambiguity
8. }}
Test it Now

Output:
Compile Time Error: method add(int,int) is already defined in class Adder

System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be
called?

Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time error if you
declare the same method having same parameters.

Can we overload java main() method?


Yes, by method overloading. You can have any number of main methods in a class by method overloading.
But JVM calls main() method which receives string array as arguments only. Let's see the simple example:

1. class TestOverloading4{
2. public static void main(String[] args){System.out.println("main with String[]");}
3. public static void main(String args){System.out.println("main with String");}
4. public static void main(){System.out.println("main without args");}
5. }
Test it Now

Output:

main with String[]

Method Overloading and Type Promotion


One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept by
the figure given below:

As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short
datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float or
double and so on.

Example of Method Overloading with TypePromotion


1. class OverloadingCalculation1{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. OverloadingCalculation1 obj=new OverloadingCalculation1();
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9.
10. }
11. }
Test it Now
Output:40
60
Example of Method Overloading with Type Promotion if matching
found
If there are matching type arguments in the method, type promotion is not performed.

1. class OverloadingCalculation2{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation2 obj=new OverloadingCalculation2();
7. obj.sum(20,20);//now int arg sum() method gets invoked
8. }
9. }
Test it Now
Output:int arg method invoked

Example of Method Overloading with Type Promotion in case of


ambiguity
If there are no matching type arguments in the method, and each method promotes similar number of
arguments, there will be ambiguity.

1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
Test it Now
Output:Compile Time Error

One type is not de-promoted implicitly for example double cannot be depromoted to any type implicitly.

Method Overriding in Java


1. Understanding the problem without method overriding
2. Can we override the static method
3. Method overloading vs. method overriding

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been declared by
one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.

1. //Java Program to demonstrate why we need method overriding


2. //Here, we are calling the method of parent class with child
3. //class object.
4. //Creating a parent class
5. class Vehicle{
6. void run(){System.out.println("Vehicle is running");}
7. }
8. //Creating a child class
9. class Bike extends Vehicle{
10. public static void main(String args[]){
11. //creating an instance of child class
12. Bike obj = new Bike();
13. //calling the method with child class instance
14. obj.run();
15. }
16. }
Test it Now

Output:

Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is why we use
method overriding.

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method are the same, and there is IS-A
relationship between the classes, so there is method overriding.

1. //Java Program to illustrate the use of Java Method Overriding


2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16. }
Test it Now

Output:

Bike is running safely

A real example of Java Method Overriding


Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However, the
rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%,
and 9% rate of interest.

Java method overriding is mostly used in Runtime Polymorphism which we will learn in next pages.

1. //Java Program to demonstrate the real scenario of Java Method Overriding


2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{
9. int getRateOfInterest(){return 8;}
10. }
11.
12. class ICICI extends Bank{
13. int getRateOfInterest(){return 7;}
14. }
15. class AXIS extends Bank{
16. int getRateOfInterest(){return 9;}
17. }
18. //Test class to create objects and call the methods
19. class Test2{
20. public static void main(String args[]){
21. SBI s=new SBI();
22. ICICI i=new ICICI();
23. AXIS a=new AXIS();
24. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
25. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
26. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
27. }
28. }
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Can we override static method?
No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it
later.

Why can we not override static method?


It is because the static method is bound with class whereas instance method is bound with an object. Static
belongs to the class area, and an instance belongs to the heap area.

Can we override java main method?


No, because the main is a static method.

Difference between method Overloading and Method


Overriding in java
Click me for the difference between method overloading and overriding

More topics on Method Overriding (Not For Beginners)


Method Overriding with Access Modifier

Let's see the concept of method overriding with access modifier.

Exception Handling with Method Overriding

Let's see the concept of method overriding with exception handling.

Java Array
Normally, an array is a collection of similar type of elements that have a contiguous memory location.

Java array is an object which contains elements of a similar data type. 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 0 index.

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.

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

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java Array


Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse
an array.

1. //Java Program to illustrate how to declare, instantiate, initialize


2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}
Test it Now

Output:

10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array


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

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

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

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


2. //and initialization of Java array in a single line
3. class Testarray1{
4. public static void main(String args[]){
5. int a[]={33,3,4,5};//declaration, instantiation and initialization
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9. }}
Test it Now

Output:

33
3
4
5

Passing Array to Method in Java


We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get the minimum number of an array using a method.

1. //Java Program to demonstrate the way of passing an array


2. //to method.
3. class Testarray2{
4. //creating a method which receives an array as a parameter
5. static void min(int arr[]){
6. int min=arr[0];
7. for(int i=1;i<arr.length;i++)
8. if(min>arr[i])
9. min=arr[i];
10.
11. System.out.println(min);
12. }
13.
14. public static void main(String args[]){
15. int a[]={33,3,4,5};//declaring and initializing an array
16. min(a);//passing array to method
17. }}
Test it Now

Output:

Anonymous Array in Java


Java supports the feature of an anonymous array, so you don't need to declare the array while passing an
array to the method.

1. //Java Program to demonstrate the way of passing an anonymous array


2. //to method.
3. public class TestAnonymousArray{
4. //creating a method which receives an array as a parameter
5. static void printArray(int arr[]){
6. for(int i=0;i<arr.length;i++)
7. System.out.println(arr[i]);
8. }
9.
10. public static void main(String args[]){
11. printArray(new int[]{10,22,44,66});//passing anonymous array to method
12. }}
Test it Now

Output:

10
22
44
66

Returning Array from the Method


We can also return an array from the method in Java.

1. //Java Program to return an array from the method


2. class TestReturnArray{
3. //creating method which returns an array
4. static int[] get(){
5. return new int[]{10,30,50,90,60};
6. }
7.
8. public static void main(String args[]){
9. //calling method which returns an array
10. int arr[]=get();
11. //printing the values of an array
12. for(int i=0;i<arr.length;i++)
13. System.out.println(arr[i]);
14. }}
Test it Now

Output:

10
30
50
90
60

ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in
negative, equal to the array size or greater than the array size while traversing the array.

1. //Java Program to demonstrate the case of


2. //ArrayIndexOutOfBoundsException in a Java Array.
3. public class TestArrayException{
4. public static void main(String args[]){
5. int arr[]={50,60,70,80};
6. for(int i=0;i<=arr.length;i++){
7. System.out.println(arr[i]);
8. }
9. }}
Test it Now

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4


at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

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


2. dataType [][]arrayRefVar; (or)
3. dataType arrayRefVar[][]; (or)
4. dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

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

Example to initialize Multidimensional Array in Java

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

Example of Multidimensional Java Array


Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

1. //Java Program to illustrate the use of multidimensional array


2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}
Test it Now

Output:

1 2 3
2 4 5
4 4 5

Jagged Array in Java


If we are creating odd number of columns in a 2D array, it is known as a jagged array. In other words, it is
an array of arrays with different number of columns.

1. //Java Program to illustrate the jagged array


2. class TestJaggedArray{
3. public static void main(String[] args){
4. //declaring a 2D array with odd columns
5. int arr[][] = new int[3][];
6. arr[0] = new int[3];
7. arr[1] = new int[4];
8. arr[2] = new int[2];
9. //initializing a jagged array
10. int count = 0;
11. for (int i=0; i<arr.length; i++)
12. for(int j=0; j<arr[i].length; j++)
13. arr[i][j] = count++;
14.
15. //printing the data of a jagged array
16. for (int i=0; i<arr.length; i++){
17. for (int j=0; j<arr[i].length; j++){
18. System.out.print(arr[i][j]+" ");
19. }
20. System.out.println();//new line
21. }
22. }
23. }
Test it Now

Output:

0 1 2
3 4 5 6
7 8

What is the class name of Java array?


In Java, an array is an object. For array object, a proxy class is created whose name can be obtained by
getClass().getName() method on the object.

1. //Java Program to get the class name of array in Java


2. class Testarray4{
3. public static void main(String args[]){
4. //declaration and initialization of array
5. int arr[]={4,4,5};
6. //getting the class name of Java array
7. Class c=arr.getClass();
8. String name=c.getName();
9. //printing the class name of Java array
10. System.out.println(name);
11.
12. }}
Test it Now

Output:

Copying a Java Array


We can copy an array to another by the arraycopy() method of System class.

Syntax of arraycopy method

1. public static void arraycopy(


2. Object src, int srcPos,Object dest, int destPos, int length
3. )
Example of Copying an Array in Java
1. //Java Program to copy a source array into a destination array in Java
2. class TestArrayCopyDemo {
3. public static void main(String[] args) {
4. //declaring a source array
5. char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
6. 'i', 'n', 'a', 't', 'e', 'd' };
7. //declaring a destination array
8. char[] copyTo = new char[7];
9. //copying array using System.arraycopy() method
10. System.arraycopy(copyFrom, 2, copyTo, 0, 7);
11. //printing the destination array
12. System.out.println(String.valueOf(copyTo));
13. }
14. }
Test it Now

Output:

caffein

Addition of 2 Matrices in Java


Let's see a simple example that adds two matrices.

1. //Java Program to demonstrate the addition of two matrices in Java


2. class Testarray5{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,3,4},{3,4,5}};
6. int b[][]={{1,3,4},{3,4,5}};
7.
8. //creating another matrix to store the sum of two matrices
9. int c[][]=new int[2][3];
10.
11. //adding and printing addition of 2 matrices
12. for(int i=0;i<2;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=a[i][j]+b[i][j];
15. System.out.print(c[i][j]+" ");
16. }
17. System.out.println();//new line
18. }
19.
20. }}
Test it Now

Output:

2 6 8
6 8 10
Multiplication of 2 Matrices in Java
In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns of
the second matrix which can be understood by the image given below.

Let's see a simple example to multiply two matrices of 3 rows and 3 columns.

1. //Java Program to multiply two matrices


2. public class MatrixMultiplicationExample{
3. public static void main(String args[]){
4. //creating two matrices
5. int a[][]={{1,1,1},{2,2,2},{3,3,3}};
6. int b[][]={{1,1,1},{2,2,2},{3,3,3}};
7.
8. //creating another matrix to store the multiplication of two matrices
9. int c[][]=new int[3][3]; //3 rows and 3 columns
10.
11. //multiplying and printing multiplication of 2 matrices
12. for(int i=0;i<3;i++){
13. for(int j=0;j<3;j++){
14. c[i][j]=0;
15. for(int k=0;k<3;k++)
16. {
17. c[i][j]+=a[i][k]*b[k][j];
18. }//end of k loop
19. System.out.print(c[i][j]+" "); //printing matrix element
20. }//end of j loop
21. System.out.println();//new line
22. }
23. }}
Test it Now

Output:

6 6 6
12 12 12
18 18 18
Constructors in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
3. Does constructor return any value?
4. Copying the values of one object into another
5. Does constructor perform other tasks instead of the initialization

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the object is
created, and memory is allocated for the object.

It is a special type of method which is used to initialize the object.

When is a constructor called


Every time an object is created using new() keyword, at least one constructor is called. It calls a default
constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It is not
necessary to write a constructor for a class. It is because java compiler creates a default constructor if your
class doesn't have any.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other
words, we can have private, protected, public or default constructor in Java.

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of objec

1. //Java Program to create and call a default constructor


2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }
Test it Now

Output:

Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.


Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc., depending on the
type.

Example of default constructor that displays the default values


1. //Let us see another example of default constructor
2. //which displays the default values
3. class Student3{
4. int id;
5. String name;
6. //method to display the value of id and name
7. void display(){System.out.println(id+" "+name);}
8.
9. public static void main(String args[]){
10. //creating objects
11. Student3 s1=new Student3();
12. Student3 s2=new Student3();
13. //displaying values of the object
14. s1.display();
15. s2.display();
16. }
17. }
Test it Now

Output:

0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor. Here 0 and null values are provided by default constructor.

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to the distinct objects. However, you can
provide the same values also.

Example of parameterized constructor


In this example, we have created the constructor of Student class that have two parameters. We can have
any number of parameters in the constructor.

1. //Java Program to demonstrate the use of parameterized constructor


2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student4 s1 = new Student4(111,"Karan");
16. Student4 s2 = new Student4(222,"Aryan");
17. //calling method to display the values of object
18. s1.display();
19. s2.display();
20. }
21. }
Test it Now

Output:

111 Karan
222 Aryan

Constructor Overloading in Java


In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.

Constructor overloading in Java is a technique of having more than one constructor with different parameter
lists. They are arranged in a way that each constructor performs a different task. They are differentiated by
the compiler by the number of parameters in the list and their types.

Example of Constructor Overloading


1. //Java program to overload constructors in java
2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){System.out.println(id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. s1.display();
23. s2.display();
24. }
25. }
Test it Now

Output:

111 Karan 0
222 Aryan 25

Difference between constructor and method in Java


There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the behavior of
object. an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if The method is not provided by the compiler in
you don't have any constructor in a class. any case.

The constructor name must be same as the class The method name may or may not be same
name. as class name.
Java Copy Constructor
There is no copy constructor in java. However, we can copy the values from one object to another like copy
constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

o By constructor
o By assigning the values of one object into another
o By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

1. //Java program to initialize the values from one object to another


2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = s.id;
13. name =s.name;
14. }
15. void display(){System.out.println(id+" "+name);}
16.
17. public static void main(String args[]){
18. Student6 s1 = new Student6(111,"Karan");
19. Student6 s2 = new Student6(s1);
20. s1.display();
21. s2.display();
22. }
23. }
Test it Now

Output:

111 Karan
111 Karan

Copying values without constructor


We can copy the values of one object into another by assigning the objects values to another object. In this
case, there is no need to create the constructor.

1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }
Test it Now

Output:

111 Karan
111 Karan
Q) Does constructor return any value?
Yes, it is the current class instance (You cannot use return type yet it returns a value).

Can constructor perform other tasks instead of initialization?


Yes, like object creation, starting a thread, calling a method, etc. You can perform any operation in the
constructor as you perform in the method.

Java static keyword


1. Static variable
2. Program of the counter without static variable
3. Program of the counter with static variable
4. Static method
5. Restrictions for the static method
6. Why is the main method static?
7. Static block
8. Can we execute a program without main method?

The static keyword in Java is used for memory management mainly. We can apply java static keyword with
variables, methods, blocks and nested class. The static keyword belongs to the class than an instance of the
class.

The static can be:

1. Variable (also known as a class variable)


2. Method (also known as a class method)
3. Block
4. Nested class
1) Java static variable
If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of students,
etc.
o The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable


1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

Suppose there are 500 students in my college, now all instance data members will get memory each time
when the object is created. All students have its unique rollno and name, so instance data member is good in
such case. Here, "college" refers to the common property of all objects. If we make it static, this field will get
the memory only once.

Java static property is shared to all objects.

Example of static variable


1. //Java Program to demonstrate the use of static variable
2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
24. }
Test it Now

Output:

111 Karan ITS


222 Aryan ITS

Program of the counter without static variable


In this example, we have created an instance variable named count which is incremented in the constructor.
Since instance variable gets the memory at the time of object creation, each object will have the copy of the
instance variable. If it is incremented, it won't reflect other objects. So each object will have the value 1 in
the count variable.

1. //Java Program to demonstrate the use of an instance variable


2. //which get memory each time when we create an object of the class.
3. class Counter{
4. int count=0;//will get memory each time when the instance is created
5.
6. Counter(){
7. count++;//incrementing value
8. System.out.println(count);
9. }
10.
11. public static void main(String args[]){
12. //Creating objects
13. Counter c1=new Counter();
14. Counter c2=new Counter();
15. Counter c3=new Counter();
16. }
17. }
Test it Now

Output:

1
1
1

Program of counter by static variable


As we have mentioned above, static variable will get the memory only once, if any object changes the value
of the static variable, it will retain its value.

1. //Java Program to illustrate the use of static variable which


2. //is shared with all objects.
3. class Counter2{
4. static int count=0;//will get memory only once and retain its value
5.
6. Counter2(){
7. count++;//incrementing the value of static variable
8. System.out.println(count);
9. }
10.
11. public static void main(String args[]){
12. //creating objects
13. Counter2 c1=new Counter2();
14. Counter2 c2=new Counter2();
15. Counter2 c3=new Counter2();
16. }
17. }
Test it Now

Output:

1
2
3
2) Java static method
If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

Example of static method


1. //Java Program to demonstrate the use of a static method.
2. class Student{
3. int rollno;
4. String name;
5. static String college = "ITS";
6. //static method to change the value of static variable
7. static void change(){
8. college = "BBDIT";
9. }
10. //constructor to initialize the variable
11. Student(int r, String n){
12. rollno = r;
13. name = n;
14. }
15. //method to display values
16. void display(){System.out.println(rollno+" "+name+" "+college);}
17. }
18. //Test class to create and display the values of object
19. public class TestStaticMethod{
20. public static void main(String args[]){
21. Student.change();//calling change method
22. //creating objects
23. Student s1 = new Student(111,"Karan");
24. Student s2 = new Student(222,"Aryan");
25. Student s3 = new Student(333,"Sonoo");
26. //calling display method
27. s1.display();
28. s2.display();
29. s3.display();
30. }
31. }
Test it Now
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Another example of a static method that performs a normal


calculation
1. //Java Program to get the cube of a given number using the static method
2.
3. class Calculate{
4. static int cube(int x){
5. return x*x*x;
6. }
7.
8. public static void main(String args[]){
9. int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12. }
Test it Now
Output:125

Restrictions for the static method

There are two main restrictions for the static method. They are:

1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.

1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Test it Now
Output:Compile Time Error

Q) Why is the Java main method static?


Ans) It is because the object is not required to call a static method. If it were a non-static method, JVM
creates an object first then call main() method that will lead the problem of extra memory allocation.

3) Java static block


o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading.

Example of static block


1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Output:static block is invoked
Hello main

Q) Can we execute a program without main() method?

Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not
possible to execute a java class without the main method.

1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }

Output:

static block is invoked

Since JDK 1.7 and above, output would be:


Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

this keyword in java


There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the
current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

Suggestion: If you are beginner to java, lookup only three usage of this keyword.
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is ambiguity between the
instance variables and parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:

1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
15. Student s2=new Student(112,"sumit",6000f);
16. s1.display();
17. s2.display();
18. }}
Test it Now

Output:

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we are using
this keyword to distinguish local variable and instance variable.

Solution of the above problem by this keyword


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. this.rollno=rollno;
7. this.name=name;
8. this.fee=fee;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis2{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Test it Now
Output:

111 ankit 5000


112 sumit 6000

If local variables(formal arguments) and instance variables are different, there is no need to use this
keyword like in the following program:

Program where this keyword is not required


1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int r,String n,float f){
6. rollno=r;
7. name=n;
8. fee=f;
9. }
10. void display(){System.out.println(rollno+" "+name+" "+fee);}
11. }
12.
13. class TestThis3{
14. public static void main(String args[]){
15. Student s1=new Student(111,"ankit",5000f);
16. Student s2=new Student(112,"sumit",6000f);
17. s1.display();
18. s2.display();
19. }}
Test it Now

Output:

111 ankit 5000


112 sumit 6000

It is better approach to use meaningful names for variables. So we use same name for instance variables and
parameters in real time, and always use this keyword.

2) this: to invoke current class method


You may invoke the method of the current class by using the this keyword. If you don't use the this
keyword, compiler automatically adds this keyword while invoking the method. Let's see the example
1. class A{
2. void m(){System.out.println("hello m");}
3. void n(){
4. System.out.println("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. A a=new A();
12. a.n();
13. }}
Test it Now

Output:

hello n
hello m
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse the
constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

1. class A{
2. A(){System.out.println("hello a");}
3. A(int x){
4. this();
5. System.out.println(x);
6. }
7. }
8. class TestThis5{
9. public static void main(String args[]){
10. A a=new A(10);
11. }}
Test it Now

Output:

hello a
10

Calling parameterized constructor from default constructor:

1. class A{
2. A(){
3. this(5);
4. System.out.println("hello a");
5. }
6. A(int x){
7. System.out.println(x);
8. }
9. }
10. class TestThis6{
11. public static void main(String args[]){
12. A a=new A();
13. }}
Test it Now

Output:

5
hello a
Real usage of this() constructor call
The this() constructor call should be used to reuse the constructor from the constructor. It maintains the
chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below
that displays the actual use of this keyword.

1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this(rollno,name,course);//reusing constructor
12. this.fee=fee;
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis7{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
22. }}
Test it Now

Output:

111 ankit java null


112 sumit java 6000

Rule: Call to this() must be the first statement in constructor.

1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10. Student(int rollno,String name,String course,float fee){
11. this.fee=fee;
12. this(rollno,name,course);//C.T.Error
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15. }
16. class TestThis8{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
22. }}
Test it Now
Compile Time Error: Call to this must be first statement in constructor
4) this: to pass as an argument in the method
The this keyword can also be passed as an argument in the method. It is mainly used in the event handling.
Let's see the example:

1. class S2{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }
Test it Now

Output:

method is invoked
Application of this that can be passed as an argument:

In event handling (or) in a situation where we have to provide reference of a class to another one. It is used
to reuse one object in many methods.

5) this: to pass as argument in the constructor call


We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple
classes. Let's see the example:

1. class B{
2. A4 obj;
3. B(A4 obj){
4. this.obj=obj;
5. }
6. void display(){
7. System.out.println(obj.data);//using data member of A4 class
8. }
9. }
10.
11. class A4{
12. int data=10;
13. A4(){
14. B b=new B(this);
15. b.display();
16. }
17. public static void main(String args[]){
18. A4 a=new A4();
19. }
20. }
Test it Now
Output:10

6) this keyword can be used to return current class instance


We can return this keyword as an statement from the method. In such case, return type of the method must
be the class type (non-primitive). Let's see the example:

Syntax of this that can be returned as a statement


1. return_type method_name(){
2. return this;
3. }
Example of this keyword that you return as a statement from the
method
1. class A{
2. A getA(){
3. return this;
4. }
5. void msg(){System.out.println("Hello java");}
6. }
7. class Test1{
8. public static void main(String args[]){
9. new A().getA().msg();
10. }
11. }
Test it Now

Output:

Hello java
Proving this keyword
Let's prove that this keyword refers to the current class instance variable. In this program, we are
printing the reference variable and this, output of both variables are same.

1. class A5{
2. void m(){
3. System.out.println(this);//prints same reference ID
4. }
5. public static void main(String args[]){
6. A5 obj=new A5();
7. System.out.println(obj);//prints the reference ID
8. obj.m();
9. }
10. }
Test it Now

Output:

A5@22b3ea59
A5@22b3ea59
Inheritance in Java
1. Inheritance
2. Types of Inheritance
3. Why multiple inheritance is not possible in Java in case of class?

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.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

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


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

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.
Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type
of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e.
code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.
Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example


File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating...

Multilevel Inheritance Example


File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B
classes have the same method and you call it from child class object, there will be ambiguity to call the
method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2
classes. So whether you have same method or different, there will be compile time error.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Compile Time Error
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.

Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains
one more object named address, which contains its own informations such as city, state, country, zipcode
etc. as given below.

1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }

In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.

Why use Aggregation?


o For Code Reusability.

Simple Example of Aggregation

In this example, we have created the reference of Operation class in the Circle class.

1. class Operation{
2. int square(int n){
3. return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);
22. System.out.println(result);
23. }
24. }
Test it Now
Output:78.5

When use Aggregation?


o Code reuse is also best achieved by aggregation when there is no is-a relationship.
o Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of
the objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation


In this example, Employee has an object of Address, address object contains its own informations such as
city, state, country etc. In such case relationship is Employee HAS-A address.

Address.java
1. public class Address {
2. String city,state,country;
3.
4. public Address(String city, String state, String country) {
5. this.city = city;
6. this.state = state;
7. this.country = country;
8. }
9.
10. }
Emp.java
1. public class Emp {
2. int id;
3. String name;
4. Address address;
5.
6. public Emp(int id, String name,Address address) {
7. this.id = id;
8. this.name = name;
9. this.address=address;
10. }
11.
12. void display(){
13. System.out.println(id+" "+name);
14. System.out.println(address.city+" "+address.state+" "+address.country);
15. }
16.
17. public static void main(String[] args) {
18. Address address1=new Address("gzb","UP","india");
19. Address address2=new Address("gno","UP","india");
20.
21. Emp e=new Emp(111,"varun",address1);
22. Emp e2=new Emp(112,"arun",address2);
23.
24. e.display();
25. e2.display();
26.
27. }
28. }
Test it Now
Output:111 varun
gzb UP india
112 arun
gno UP india

Java Polymorphism: (Method Overloading and Overriding already covered above)

Covariant Return Type


The covariant return type specifies that the return type may vary in the same direction as the subclass.

Before Java5, it was not possible to override any method by changing the return type. But now, since Java5,
it is possible to override method by changing the return type if subclass overrides any method whose return
type is Non-Primitive but it changes its return type to subclass type. Let's take a simple example:

Note: If you are beginner to java, skip this topic and return to it after OOPs concepts.

Simple example of Covariant Return Type


1. class A{
2. A get(){return this;}
3. }
4.
5. class B1 extends A{
6. B1 get(){return this;}
7. void message(){System.out.println("welcome to covariant return type");}
8.
9. public static void main(String args[]){
10. new B1().get().message();
11. }
12. }
Test it Now
Output:welcome to covariant return type

As you can see in the above example, the return type of the get() method of A class is A but the return type
of the get() method of B class is B. Both methods have different return type but it is method overriding. This
is known as covariant return type.
How is Covariant return types implemented?
Java doesn't allow the return type based overloading but JVM always allows return type based overloading.
JVM uses full signature of a method for lookup/resolution. Full signature means it includes return type in
addition to argument types. i.e., a class can have two or more methods differing only by return type. javac
uses this fact to implement covariant return types.

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.

Usage of Java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance


variable.
We can use super keyword to access the data member or field of parent class. It is used if parent class and
child class have same fields.

1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
Test it Now

Output:

black
white

In the above example, Animal and Dog both classes have a common property color. If we print color
property, it will print the color of current class by default. To access the parent property, we need to use
super keyword.

2) super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if subclass contains
the same method as parent class. In other words, it is used if method is overridden.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Test it Now

Output:

eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog
class, it will call the eat() method of Dog class by default because priority is given to local.

To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:

1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
Test it Now

Output:

animal is created
dog is created

Note: super() is added in each class constructor automatically by compiler if there is no super() or this().

As we know well that default constructor is provided by compiler automatically if there is no constructor. But,
it also adds super() as the first statement.

Another example of super keyword where super() is provided by the compiler implicitly.

1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. class TestSuper4{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }}
Test it Now

Output:

animal is created
dog is created

super example: real use


Let's see the real use of super keyword. Here, Emp class inherits Person class so all the properties of Person
will be inherited to Emp by default. To initialize all the property, we are using parent class constructor from
child class. In such way, we are reusing the parent class constructor.

1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name;
7. }
8. }
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
14. }
15. void display(){System.out.println(id+" "+name+" "+salary);}
16. }
17. class TestSuper5{
18. public static void main(String[] args){
19. Emp e1=new Emp(1,"ankit",45000f);
20. e1.display();
21. }}
Test it Now

Output:

1 ankit 45000
Instance initializer block
1. Instance initializer block
2. Example of Instance initializer block
3. What is invoked firstly instance initializer block or constructor?
4. Rules for instance initializer block
5. Program of instance initializer block that is invoked after super()

Instance Initializer block is used to initialize the instance data member. It run each time when object of the
created.

The initialization of the instance variable can be done directly but there can be performed extra operations whi
the instance variable in the instance initializer block.

Que) What is the use of instance initializer block while we can directly assign a value in
instance data member? For example:
1. class Bike{
2. int speed=100;
3. }

Why use instance initializer block?


Suppose I have to perform some operations while assigning value to instance data member e.g. a for loop to f
array or error handling etc.

Example of instance initializer block


Let's see the simple example of instance initializer block that performs initialization.

1. class Bike7{
2. int speed;
3.
4. Bike7(){System.out.println("speed is "+speed);}
5.
6. {speed=100;}
7.
8. public static void main(String args[]){
9. Bike7 b1=new Bike7();
10. Bike7 b2=new Bike7();
11. }
12. }
Test it Now
Output:speed is 100
speed is 100

There are three places in java where you can perform operations:

1. method
2. constructor
3. block

What is invoked first, instance initializer block or


constructor?
1. class Bike8{
2. int speed;
3.
4. Bike8(){System.out.println("constructor is invoked");}
5.
6. {System.out.println("instance initializer block invoked");}
7.
8. public static void main(String args[]){
9. Bike8 b1=new Bike8();
10. Bike8 b2=new Bike8();
11. }
12. }
Test it Now
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked

In the above example, it seems that instance initializer block is firstly invoked but NO. Instance intializer block
the time of object creation. The java compiler copies the instance initializer block in the constructor after the fi
super(). So firstly, constructor is invoked. Let's understand it by the figure given below:
Note: The java compiler copies the code of instance initializer block in every constructor.

Rules for instance initializer block :


There are mainly three rules for the instance initializer block. They are as follows:

1. The instance initializer block is created when instance of the class is created.
2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after
super() constructor call).
3. The instance initializer block comes in the order in which they appear.

Program of instance initializer block that is invoked after


super()
1. class A{
2. A(){
3. System.out.println("parent class constructor invoked");
4. }
5. }
6. class B2 extends A{
7. B2(){
8. super();
9. System.out.println("child class constructor invoked");
10. }
11.
12. {System.out.println("instance initializer block is invoked");}
13.
14. public static void main(String args[]){
15. B2 b=new B2();
16. }
17. }
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked

Another example of instance block


1. class A{
2. A(){
3. System.out.println("parent class constructor invoked");
4. }
5. }
6.
7. class B3 extends A{
8. B3(){
9. super();
10. System.out.println("child class constructor invoked");
11. }
12.
13. B3(int a){
14. super();
15. System.out.println("child class constructor invoked "+a);
16. }
17.
18. {System.out.println("instance initializer block is invoked");}
19.
20. public static void main(String args[]){
21. B3 b1=new B3();
22. B3 b2=new B3(10);
23. }
24. }
Test it Now
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked 10
Final Keyword In Java
1. Final variable
2. Final method
3. Final class
4. Is final method inherited ?
5. Blank final variable
6. Static blank final variable
7. Final parameter
8. Can you declare a final constructor

The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank final
variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can
be static also which will be initialized in the static block only. We will have detailed learning of these. Let's
first learn the basics of final keyword.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
Output:Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.

Example of final method


1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7.
8. public static void main(String args[]){
9. Honda honda= new Honda();
10. honda.run();
11. }
12. }
Test it Now
Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.

Example of final class


1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
Test it Now
Output:Compile Time Error
Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:

1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Test it Now
Output:running...

Q) What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final variable.

If you want to create a variable that is initialized at the time of creating object and once initialized may not
be changed, it is useful. For example PAN CARD number of an employee.

It can be initialized only in constructor.

Example of blank final variable


1. class Student{
2. int id;
3. String name;
4. final String PAN_CARD_NUMBER;
5. ...
6. }
Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }
12. }
Test it Now
Output: 70
static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It
can be initialized only in static block.

Example of static blank final variable


1. class A{
2. static final int data;//static blank final variable
3. static{ data=50;}
4. public static void main(String args[]){
5. System.out.println(A.data);
6. }
7. }

Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.

1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
Test it Now
Output: Compile Time Error

Q) Can we declare a constructor final?


No, because constructor is never inherited.
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs"
means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We
can perform polymorphism in java by method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time polymorphism. Here, we will focus
on runtime polymorphism in java.

Runtime Polymorphism in Java


Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:

1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting

For upcasting, we can use the reference variable of class type or an interface type. For Example:

1. interface I{}
2. class A{}
3. class B extends A implements I{}

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A Object.
Example of Java Runtime Polymorphism
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and
overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it
refers to the subclass object and subclass method overrides the Parent class method, the subclass method is
invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splendor();//upcasting
9. b.run();
10. }
11. }
Test it Now

Output:

running safely with 60km.

Java Runtime Polymorphism Example: Bank


Consider a scenario where Bank is a class that provides a method to get the rate of interest. However, the
rate of interest may differ according to banks. For example, SBI, ICICI, and AXIS banks are providing 8.4%,
7.3%, and 9.7% rate of interest.

Note: This example is also given in method overriding but there was no upcasting.
1. class Bank{
2. float getRateOfInterest(){return 0;}
3. }
4. class SBI extends Bank{
5. float getRateOfInterest(){return 8.4f;}
6. }
7. class ICICI extends Bank{
8. float getRateOfInterest(){return 7.3f;}
9. }
10. class AXIS extends Bank{
11. float getRateOfInterest(){return 9.7f;}
12. }
13. class TestPolymorphism{
14. public static void main(String args[]){
15. Bank b;
16. b=new SBI();
17. System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
18. b=new ICICI();
19. System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
20. b=new AXIS();
21. System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
22. }
23. }
Test it Now

Output:

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7

Java Runtime Polymorphism Example: Shape


1. class Shape{
2. void draw(){System.out.println("drawing...");}
3. }
4. class Rectangle extends Shape{
5. void draw(){System.out.println("drawing rectangle...");}
6. }
7. class Circle extends Shape{
8. void draw(){System.out.println("drawing circle...");}
9. }
10. class Triangle extends Shape{
11. void draw(){System.out.println("drawing triangle...");}
12. }
13. class TestPolymorphism2{
14. public static void main(String args[]){
15. Shape s;
16. s=new Rectangle();
17. s.draw();
18. s=new Circle();
19. s.draw();
20. s=new Triangle();
21. s.draw();
22. }
23. }
Test it Now

Output:

drawing rectangle...
drawing circle...
drawing triangle...

Java Runtime Polymorphism Example: Animal


1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. }
7. class Cat extends Animal{
8. void eat(){System.out.println("eating rat...");}
9. }
10. class Lion extends Animal{
11. void eat(){System.out.println("eating meat...");}
12. }
13. class TestPolymorphism3{
14. public static void main(String[] args){
15. Animal a;
16. a=new Dog();
17. a.eat();
18. a=new Cat();
19. a.eat();
20. a=new Lion();
21. a.eat();
22. }}
Test it Now

Output:

eating bread...
eating rat...
eating meat...

Java Runtime Polymorphism with Data Member


A method is overridden, not the data members, so runtime polymorphism can't be achieved by data
members.

In the example given below, both the classes have a data member speedlimit. We are accessing the data
member by the reference variable of Parent class which refers to the subclass object. Since we are accessing
the data member which is not overridden, hence it will access the data member of the Parent class always.
Rule: Runtime polymorphism can't be achieved by data members.

1. class Bike{
2. int speedlimit=90;
3. }
4. class Honda3 extends Bike{
5. int speedlimit=150;
6.
7. public static void main(String args[]){
8. Bike obj=new Honda3();
9. System.out.println(obj.speedlimit);//90
10. }
Test it Now

Output:

90

Java Runtime Polymorphism with Multilevel Inheritance


Let's see the simple example of Runtime Polymorphism with multilevel inheritance.

1. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating fruits");}
6. }
7. class BabyDog extends Dog{
8. void eat(){System.out.println("drinking milk");}
9. public static void main(String args[]){
10. Animal a1,a2,a3;
11. a1=new Animal();
12. a2=new Dog();
13. a3=new BabyDog();
14. a1.eat();
15. a2.eat();
16. a3.eat();
17. }
18. }
Test it Now

Output:

eating
eating fruits
drinking Milk

Try for Output


1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("dog is eating...");}
6. }
7. class BabyDog1 extends Dog{
8. public static void main(String args[]){
9. Animal a=new BabyDog1();
10. a.eat();
11. }}
Test it Now

Output:

Dog is eating

Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.

Static Binding and Dynamic Binding

Connecting a method call to the method body is known as binding.

There are two types of binding

1. Static Binding (also known as Early Binding).


2. Dynamic Binding (also known as Late Binding).
Understanding Type
Let's understand the type of instance.

1) variables have a type

Each variable has a type, it may be primitive and non-primitive.

1. int data=30;

Here data variable is a type of int.

2) References have a type


1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }
3) Objects have a type
An object is an instance of particular java class,but it is also an instance of its superclass.

1. class Animal{}
2.
3. class Dog extends Animal{
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. }
7. }
Here d1 is an instance of Dog class, but it is also an instance of Animal.

static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.

If there is any private, final or static method in a class, there is static binding.

Example of static binding


1. class Dog{
2. private void eat(){System.out.println("dog is eating...");}
3.
4. public static void main(String args[]){
5. Dog d1=new Dog();
6. d1.eat();
7. }
8. }

Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
1. class Animal{
2. void eat(){System.out.println("animal is eating...");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("dog is eating...");}
7.
8. public static void main(String args[]){
9. Animal a=new Dog();
10. a.eat();
11. }
12. }
Test it Now
Output:dog is eating...

In the above example object type cannot be determined by the compiler, because the instance of
Dog is also an instance of Animal.So compiler doesn't know its type, only its base type.

Java instanceof
1. java instanceof
2. Example of instanceof operator
3. Applying the instanceof operator with a variable the have null value
4. Downcasting with instanceof operator
5. Downcasting without instanceof operator

The java instanceof operator is used to test whether the object is an instance of the specified type (class
or subclass or interface).

The instanceof in java is also known as type comparison operator because it compares the instance with
type. It returns either true or false. If we apply the instanceof operator with any variable that has null value,
it returns false.

Simple example of java instanceof


Let's see the simple example of instance operator where it tests the current class.

1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple1);//true
5. }
6. }
Test it Now
Output:true

An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of
Dog can be referred by either Dog or Animal class.
Another example of java instanceof operator
1. class Animal{}
2. class Dog1 extends Animal{//Dog inherits Animal
3.
4. public static void main(String args[]){
5. Dog1 d=new Dog1();
6. System.out.println(d instanceof Animal);//true
7. }
8. }
Test it Now
Output:true

instanceof in java with a variable that have null value


If we apply instanceof operator with a variable that have null value, it returns false. Let's see the example
given below where we apply instanceof operator with the variable that have null value.

1. class Dog2{
2. public static void main(String args[]){
3. Dog2 d=null;
4. System.out.println(d instanceof Dog2);//false
5. }
6. }
Test it Now
Output:false

Downcasting with java instanceof operator


When Subclass type refers to the object of Parent class, it is known as downcasting. If we perform it directly,
compiler gives Compilation error. If you perform it by typecasting, ClassCastException is thrown at runtime.
But if we use instanceof operator, downcasting is possible.

1. Dog d=new Animal();//Compilation error

If we perform downcasting by typecasting, ClassCastException is thrown at runtime.

1. Dog d=(Dog)new Animal();


2. //Compiles successfully but ClassCastException is thrown at runtime
Possibility of downcasting with instanceof
Let's see the example, where downcasting is possible by instanceof operator.

1. class Animal { }
2.
3. class Dog3 extends Animal {
4. static void method(Animal a) {
5. if(a instanceof Dog3){
6. Dog3 d=(Dog3)a;//downcasting
7. System.out.println("ok downcasting performed");
8. }
9. }
10.
11. public static void main (String [] args) {
12. Animal a=new Dog3();
13. Dog3.method(a);
14. }
15.
16. }
Test it Now
Output:ok downcasting performed

Downcasting without the use of java instanceof


Downcasting can also be performed without the use of instanceof operator as displayed in the following
example:

1. class Animal { }
2. class Dog4 extends Animal {
3. static void method(Animal a) {
4. Dog4 d=(Dog4)a;//downcasting
5. System.out.println("ok downcasting performed");
6. }
7. public static void main (String [] args) {
8. Animal a=new Dog4();
9. Dog4.method(a);
10. }
11. }
Test it Now
Output:ok downcasting performed

Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we downcast
it, it is fine. But what will happen if we write:

1. Animal a=new Animal();


2. Dog.method(a);
3. //Now ClassCastException but not in case of instanceof operator

Understanding Real use of instanceof in java


Let's see the real use of instanceof keyword by the example given below.

1. interface Printable{}
2. class A implements Printable{
3. public void a(){System.out.println("a method");}
4. }
5. class B implements Printable{
6. public void b(){System.out.println("b method");}
7. }
8.
9. class Call{
10. void invoke(Printable p){//upcasting
11. if(p instanceof A){
12. A a=(A)p;//Downcasting
13. a.a();
14. }
15. if(p instanceof B){
16. B b=(B)p;//Downcasting
17. b.b();
18. }
19.
20. }
21. }//end of Call class
22.
23. class Test4{
24. public static void main(String args[]){
25. Printable p=new B();
26. Call c=new Call();
27. c.invoke(p);
28. }
29. }
Test it Now
Output: b method
Collections in Java
1. Java Collection Framework
2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface

The Collection in Java is a framework that provides an architecture to store and manipulate the group of
objects.

Java Collections can achieve all the operations that you perform on a data such as searching, sorting,
insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List,
Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a group of objects. It
has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Do You Know?
o What are the two ways to iterate the elements of a collection?
o What is the difference between ArrayList and LinkedList classes in collection framework?
o What is the difference between ArrayList and Vector classes in collection framework?
o What is the difference between HashSet and HashMap classes in collection framework?
o What is the difference between HashMap and Hashtable class?
o What is the difference between Iterator and Enumeration interface in collection framework?
o How can we sort the elements of an object? What is the difference between Comparable and
Comparator interfaces?
o What does the hashcode() method?
o What is the difference between Java collection and Java collections?
Hierarchy of Collection Framework
Let us see the hierarchy of Collection framework. The java.util package contains all the classes and
interfaces for the Collection framework.

Methods of Collection interface


There are many methods declared in the Collection interface. They are as follows:

No. Method Description

1 public boolean add(E e) It is used to insert an element in this collection.

2 public boolean addAll(Collection<? It is used to insert the specified collection


extends E> c) elements in the invoking collection.
3 public boolean remove(Object It is used to delete an element from the
element) collection.

4 public boolean It is used to delete all the elements of the


removeAll(Collection<?> c) specified collection from the invoking collection.

5 default boolean It is used to delete all the elements of the


removeIf(Predicate<? super E> collection that satisfy the specified predicate.
filter)

6 public boolean It is used to delete all the elements of invoking


retainAll(Collection<?> c) collection except the specified collection.

7 public int size() It returns the total number of elements in the


collection.

8 public void clear() It removes the total number of elements from


the collection.

9 public boolean contains(Object It is used to search an element.


element)

10 public boolean It is used to search the specified collection in the


containsAll(Collection<?> c) collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the
runtime type of the returned array is that of the
specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the


collection as its source.

16 default Stream<E> stream() It returns a sequential Stream with the collection


as its source.
17 default Spliterator<E> spliterator() It generates a Spliterator over the specified
elements in the collection.

18 public boolean equals(Object It matches two collections.


element)

19 public int hashCode() It returns the hash code number of the collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

No. Method Description

1 public boolean It returns true if the iterator has more elements otherwise it
hasNext() returns false.

2 public Object next() It returns the element and moves the cursor pointer to the next
element.

3 public void remove() It removes the last elements returned by the iterator. It is less
used.

Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection interface extends the
Iterable interface and therefore all the subclasses of Collection interface also implement the Iterable
interface.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.

Collection Interface
The Collection interface is the interface which is implemented by all the classes in the collection framework.
It declares the methods that every collection will have. In other words, we can say that the Collection
interface builds the foundation on which the collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll ( Collection c),
void clear(), etc. which are implemented by all the subclasses of Collection interface.

List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure in which we can
store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the elements from
the list.

The classes that implement the List interface are given below.

ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the duplicate element of
different data types. The ArrayList class maintains the insertion order and is non-synchronized. The elements
stored in the ArrayList class can be randomly accessed. Consider the following example.

1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }

Output:

Ravi
Vijay
Ravi
Ajay
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements. It
can store the duplicate elements. It maintains the insertion order and is not synchronized. In LinkedList, the
manipulation is fast because no shifting is required.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ravi
Vijay
Ravi
Ajay

Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is
synchronized and contains many methods that are not the part of Collection framework.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:
Ayush
Amit
Ashish
Garima

Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack
contains all of the methods of Vector class and also provides its methods like boolean push(), boolean
peek(), boolean push(object o), which defines its properties.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ayush
Garvit
Amit
Ashish

Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold
the elements which are about to be processed. There are various classes like PriorityQueue, Deque, and
ArrayDeque which implements the Queue interface.

Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the Queue interface, some of them are given below.

PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be
processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.
Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }

Output:

head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj

Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements from both the
side. Deque stands for a double-ended queue which enables us to perform the operations at both the ends.

Deque can be instantiated as:

1. Deque d = new ArrayDeque();

ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can
add or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }

Output:

Gautam
Karan
Ajay

Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It represents the
unordered set of elements which doesn't allow us to store the duplicate items. We can store at most one null
value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for storage.
Hashing is used to store the elements in the HashSet. It contains unique items.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection7{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Vijay
Ravi
Ajay

LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class
and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion
order and permits null elements.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ravi
Vijay
Ajay

SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements of the
SortedSet are arranged in the increasing (ascending) order. The SortedSet provides the additional methods
that inhibit the natural ordering of the elements.

The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();

TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also
contains unique elements. However, the access and retrieval time of TreeSet is quite fast. The elements in
TreeSet stored in ascending order.

Consider the following example:


1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ajay
Ravi
Vijay
What are we going to learn in Java Collections Framework

1. ArrayList class
2. LinkedList class
3. List interface
4. HashSet class
5. LinkedHashSet class
6. TreeSet class
7. PriorityQueue class
8. Map interface
9. HashMap class
10. LinkedHashMap class
11. TreeMap class
12. Hashtable class
13. Sorting
14. Comparable interface
15. Comparator interface
16. Properties class in Java

You might also like