Java Docs
Java Docs
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:
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.
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.
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.
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. }
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:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
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.
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.
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.
Arithmetic multiplicative * / %
additive + -
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
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
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
Output:
false
10
false
11
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.
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
Algorithm:
Let's see an example of linear search in java where we are going to search an element sequentially from an
array.
Output:
50 is found at index: 3
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:
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.
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:
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:
Output:
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:
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
----------------------------------------
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:
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:
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:
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:
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:
Output:
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:
Output:
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:
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 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:
Output:
Third Largest:3
Third Largest:66
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
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
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.
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
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
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.
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:
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.
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:
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.
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:
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.
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
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:
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.
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:
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:
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:
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:
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:
data.txt
A computer program is a collection of instructions that performs specific task when executed by a computer.
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:
Output:
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:
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:
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
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.
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:
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.
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
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.
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:
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.
In java, Method Overloading is not possible by changing the return type of the method only.
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
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
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.
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:
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.
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
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.
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.
Let's understand the problem that we may face in the program if we don't use method overriding.
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.
Output:
Java method overriding is mostly used in Runtime Polymorphism which we will learn in next pages.
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.
1. arrayRefVar=new datatype[size];
Output:
10
20
70
40
50
Output:
33
3
4
5
Let's see the simple example to get the minimum number of an array using a method.
Output:
Output:
10
22
44
66
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.
Output:
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;
Output:
1 2 3
2 4 5
4 4 5
Output:
0 1 2
3 4 5 6
7 8
Output:
Output:
caffein
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.
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.
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.
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.
Output:
Bike is created
The default constructor is used to provide the default values to the object like 0, null, etc., depending on the
type.
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.
The parameterized constructor is used to provide different values to the distinct objects. However, you can
provide the same values also.
Output:
111 Karan
222 Aryan
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.
Output:
111 Karan 0
222 Aryan 25
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 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.
Output:
111 Karan
111 Karan
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).
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.
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.
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.
Output:
Output:
1
1
1
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.
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
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:
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.
If local variables(formal arguments) and instance variables are different, there is no need to use this
keyword like in the following program:
Output:
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.
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.
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
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:
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.
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
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.
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.
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:
Output:
barking...
eating...
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...
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...
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.
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
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
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.
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.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.
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.
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.
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
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. }
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
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.
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.
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. 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
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...
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.
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.
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
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.
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.
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{}
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:
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:
Output:
drawing rectangle...
drawing circle...
drawing triangle...
Output:
eating bread...
eating rat...
eating meat...
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
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
Output:
Dog is eating
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.
1. int data=30;
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.
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.
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
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
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
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. 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).
The Collection framework represents a unified architecture for storing and manipulating a group of objects. It
has:
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.
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.
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.
There are only three methods in the Iterator interface. They are:
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.
1. Iterator<T> iterator()
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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