Core Java INTRO
https://hackmd.io/@ogTCgdqFSdq47hgZlb5Kqg/S1kFA0DXu
What you should already know
1 : what is JAVA?
2 : Why to Learn java Programming?
1. Object Oriented
1. Platform Independent
1. Simple
1. Secure
1. Architecture-neutral
1. Portable
1. Robust
3 :Differences between JDK, JRE and JVM // we will have more clarification
4 : How to setup a Local environment
Step 1 we need jdk (compiler ) 153 mb
https://www.oracle.com/java/technologies/downloads/#jdk18-windows
install and check
Step 2 we need a IDE (editor) 535 mb
https://spring.io/tools
install and check
5 : Some basic terminology and syntax
like what are class , object methods etc
Class - template/blueprint
Object − Objects have states and behaviors.
Methods − A method is basically a behavior.
Instance Variables − Each object has its unique set of instance variables.
6 : Basic rules of syntax
**Case Sensitivity** − Java is case sensitive
**Class Names**− For all class names the first letter should be in Upper Case.
Example: class MyFirstJavaClass
**Method Names** − All method names should start with a Lower Case letter.
Example: public void myMethodName()
7 : Java Modifiers
Access Modifiers − default, public , protected, private
Non-access Modifiers − final, abstract
8 : classification of variables
Local Variables
Class Variables (Static Variables)
Instance Variables (Non-static Variables)
9 : Lets begin with a Hello World program
```
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}
```
10 : Concepts of Object-Oriented Language
Rules for being fully Object Oriented
1. Encapsulation/Data Hiding
1. Inheritance
1. Polymorphism
1. Abstraction
1. All user defined types are objects
1. All operations performed on objects must be only through methods exposed at the objects.
2. All predefined types are objects
Java supports the following fundamental concepts
So basically it does not follow 2 of these rules
which are those and why?
11 : Local variables,Instance variables,Class variables
12 : Creating an Object
There are three steps when creating an object from a class −
1. Declaration − A variable declaration with a variable name with an object type.
1. Instantiation − The 'new' keyword is used to create the object.
1. Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object.
13 : Constructors
14: Primitive Datatypes
Primitive Data Types
There are eight primitive datatypes supported by Java. Primitive datatypes are predefined by the language and named by a keyword. Let us now look into the eight primitive data types in detail.
**byte**
Byte data type is an 8-bit signed two's complement integer
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an integer.
Example: byte a = 100, byte b = -50
**short**
Short data type is a 16-bit signed two's complement integer
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an integer
Default value is 0.
Example: short s = 10000, short r = -20000
**int**
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648 (-2^31)
Maximum value is 2,147,483,647(inclusive) (2^31 -1)
Integer is generally used as the default data type for integral values unless there is a concern about memory.
The default value is 0
Example: int a = 100000, int b = -200000
**long**
Long data type is a 64-bit signed two's complement integer
Minimum value is -9,223,372,036,854,775,808(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
This type is used when a wider range than int is needed
Default value is 0L
Example: long a = 100000L, long b = -200000L
**float**
Float data type is a single-precision 32-bit IEEE 754 floating point
Float is mainly used to save memory in large arrays of floating point numbers
Default value is 0.0f
Float data type is never used for precise values such as currency
Example: float f1 = 234.5f
**double**
double data type is a double-precision 64-bit IEEE 754 floating point
This data type is generally used as the default data type for decimal values, generally the default choice
Double data type should never be used for precise values such as currency
Default value is 0.0d
Example: double d1 = 123.4
**boolean**
boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for simple flags that track true/false conditions
Default value is false
Example: boolean one = true
**char**
char data type is a single 16-bit Unicode character
Minimum value is '\u0000' (or 0)
Maximum value is '\uffff' (or 65,535 inclusive)
Char data type is used to store any character
Example: char letterA = 'A'
15 : Variables along with who can access them
Local Variables
```
public class Test {
public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}
}
```
Gives error when not initialized
```
public class Test {
public void pupAge() {
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}
}
```
Instance Variables
```
import java.io.*;
public class Employee {
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
// The name variable is assigned in the constructor.
public Employee (String empName) {
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal) {
salary = empSal;
}
// This method prints the employee details.
public void printEmp() {
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
public static void main(String args[]) {
Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
```
Static Variables
```
import java.io.*;
public class Employee {
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
```
If the variables are accessed from an outside class, the constant should be accessed as Employee.DEPARTMENT
16 : Access Modifiers
Access Control Modifiers
Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are −
Visible to the package, the default. No modifiers are needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
Lets start playing around ...
17 Loops
1 while loop
```
while (boolean condition)
{
loop statements...
}
```

```
// Java program to illustrate while loop
class whileLoopDemo
{
public static void main(String args[])
{
int x = 1;
// Exit when x becomes greater than 4
while (x <= 4)
{
System.out.println("Value of x:" + x);
// Increment the value of x for
// next iteration
x++;
}
}
}
```
2 for loop
```
for (initialization condition; testing condition;
increment/decrement)
{
statement(s)
}
```

```
// Java program to illustrate for loop.
class forLoopDemo
{
public static void main(String args[])
{
// for loop begins when x=2
// and runs till x <=4
for (int x = 2; x <= 4; x++)
System.out.println("Value of x:" + x);
}
}
```
3 Enhanced For loop
```
for (T element:Collection obj/array)
{
statement(s)
}
```
```
// Java program to illustrate enhanced for loop
public class enhancedforloop
{
public static void main(String args[])
{
String array[] = {"Ron", "Harry", "Hermoine"};
//enhanced for loop
for (String x:array)
{
System.out.println(x);
}
/* for loop for same function
for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
*/
}
}
```
4 do while loop or Exit Control Loop.
```
do
{
statements..
}
while (condition);
```

```
// Java program to illustrate do-while loop
public class dowhileloopDemo
{
public static void main(String args[])
{
int x = 21;
do
{
// The line will be printed even
// if the condition is false
System.out.println("Value of x:" + x);
x++;
}
while (x < 20);
}
}
```
18 : Decision Making
if
if-else
nested-if
if-else-if
switch-case
jump – break, continue, return
```
// Java program to illustrate If statement
public class IfDemo
{
public static void main(String args[])
{
int i = 10;
if (i > 15)
System.out.println("10 is less than 15");
// This statement will be executed
// as if considers one statement by default
System.out.println("I am Not in if");
}
}
```
```
// Java program to illustrate if-else statement
public class IfElseDemo
{
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
```
```
// Java program to illustrate nested-if statement
public class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;
if (i == 10)
{
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
```
```
// Java program to illustrate if-else-if ladder
class ifelseifDemo
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
```
```
// Java program to illustrate switch-case
public class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}
}
```
**Break:** In Java, break is majorly used for:
Terminate a sequence in a switch statement (discussed above).
To exit a loop.
```
// Java program to illustrate using
// break to exit a loop
public class BreakLoopDemo
{
public static void main(String args[])
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++)
{
// terminate loop when i is 5.
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
```
Label
```
// Java program to illustrate using break with goto
public class BreakLabelDemo
{
public static void main(String args[])
{
boolean t = true;
// label first
first:
{
// Illegal statement here as label second is not
// introduced yet break second;
second:
{
third:
{
// Before break
System.out.println("Before the break statement");
// break will take the control out of
// second label
if (t)
break second;
System.out.println("This won't execute.");
}
System.out.println("This won't execute.");
}
// First block
System.out.println("This is after second block.");
}
}
}
```
**Continue:** Sometimes it is useful to force an early iteration of a loop.
```
// Java program to illustrate using
// continue in an if statement
public class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
// If the number is even
// skip and continue
if (i%2 == 0)
continue;
// If number is odd, print it
System.out.print(i + " ");
}
}
}
```
Return:The return statement is used to explicitly return from a method.
```
// Java program to illustrate using return
public class Return
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if (t)
return;
// Compiler will bypass every statement
// after return
System.out.println("This won't execute.");
}
}
```
19 : Strings
Strings, which are widely used in Java programming, are a sequence of characters. In Java programming language, strings are treated as objects.
```
public class StringDemo {
public static void main(String args[]) {
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
```
```
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
```
```
public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
```
20 : Arrays
provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type.
```
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
```
21 : Discussion on Methods
Syntax
```
public static int methodName(int a, int b) {
// body
}
```
Demo
```
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/** returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
```
The void Keyword
```
public class ExampleVoid {
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
}else if (points >= 122.4) {
System.out.println("Rank:A2");
}else {
System.out.println("Rank:A3");
}
}
}
```
**Method Overloading**
When a class has two or more methods by the same name but different parameters, it is known as method overloading.
```
public class ExampleOverloading {
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
```
**The this keyword**
this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor

```
public class This_Example {
// Instance variable num
int num = 10;
This_Example() {
System.out.println("This is an example program on keyword this");
}
This_Example(int num) {
// Invoking the default constructor
this();
// Assigning the local variable num to the instance variable num
this.num = num;
}
public void greet() {
System.out.println("Hi Welcome to session");
}
public void print() {
// Local variable num
int num = 20;
// Printing the local variable
System.out.println("value of local variable num is : "+num);
// Printing the instance variable
System.out.println("value of instance variable num is : "+this.num);
// Invoking the greet method of a class
this.greet();
}
public static void main(String[] args) {
// Instantiating the class
This_Example obj1 = new This_Example();
// Invoking the print method
obj1.print();
// Passing a new value to the num variable through parametrized constructor
This_Example obj2 = new This_Example(30);
// Invoking the print method again
obj2.print();
}
}
```
22: Exceptions
An exception (or exceptional event) is a problem that arises during the execution of a program.
we have three categories of Exceptions.
**Checked exceptions** − A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. these are not Errors
```
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
```
**Unchecked exceptions** − An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions.
```
public class Unchecked_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}
}
```
**Errors** − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
Catching Exceptions
```
// File Name : ExcepTest.java
import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
```
```
try {
file = new FileInputStream(fileName);
x = (byte) file.read();
} catch (IOException i) {
i.printStackTrace();
return -1;
} catch (FileNotFoundException f) // Not valid! {
f.printStackTrace();
return -1;
}
```
If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.
```
import java.io.*;
public class className {
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}
```
The Finally Block
The finally block follows a try block or a catch block. A finally block of code always executes, irrespective of occurrence of an Exception.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
```
public class ExcepTest {
public static void main(String args[]) {
int a[] = new int[2];
try {
System.out.println("Access element three :" + a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}finally {
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
```
23 : Inheritance
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another.
```
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
public class My_Calculation extends Calculation {
public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
```

The super keyword
Similar to This but call super (parent class)
```
class Super_class {
int num = 20;
// display method of superclass
public void display() {
System.out.println("This is the display method of superclass");
}
}
public class Sub_class extends Super_class {
int num = 10;
// display method of sub class
public void display() {
System.out.println("This is the display method of subclass");
}
public void my_method() {
// Instantiating subclass
Sub_class sub = new Sub_class();
// Invoking the display() method of sub class
sub.display();
// Invoking the display() method of superclass
super.display();
// printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:"+ sub.num);
// printing the value of variable num of superclass
System.out.println("value of the variable named num in super class:"+ super.num);
}
public static void main(String args[]) {
Sub_class obj = new Sub_class();
obj.my_method();
}
}
```
Super Class Constructor
```
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
public void getAge() {
System.out.println("The value of the variable named age in super class is: " +age);
}
}
public class Subclass extends Superclass {
Subclass(int age) {
super(age);
}
public static void main(String args[]) {
Subclass s = new Subclass(24);
s.getAge();
}
}
```
IS-A Relationship how to identify inheritence
HAS-A relationship
```
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle {
private Speed sp;
}
```

24: Overriding
The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which means a subclass can implement a parent class method based on its requirement.
```
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}
```
Object and reference variable creation
```
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
public void bark() {
System.out.println("Dogs can bark");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
b.bark();
}
}
```
```
TestDog.java:26: error: cannot find symbol
b.bark();
^
symbol: method bark()
location: variable b of type Animal
1 error
```
Invoking Hidden overiden methods
```
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}
```
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Static
Dynamic
```
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}
class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}
class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}
// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
// obtain a reference of type A
A ref;
// ref refers to an A object
ref = a;
// calling A's version of m1()
ref.m1();
// now ref refers to a B object
ref = b;
// calling B's version of m1()
ref.m1();
// now ref refers to a C object
ref = c;
// calling C's version of m1()
ref.m1();
}
}
```
step 1
```
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
```
What happens

Step 2
```
// ref refers to an A object
ref = a;
```

Step 3
```
ref = a; // r refers to an A object
ref.m1(); // calling A's version of m1()
```

Step 4
```
ref = b; // now r refers to a B object
ref.m1(); // calling B's version of m1()
```

Step 5
```
ref = c; // now r refers to a C object
ref.m1(); // calling C's version of m1()
```

In Java, we can override methods only, not the variables(data members), so runtime polymorphism cannot be achieved by data members
25: Encapsulation in Java
Encapsulation is defined as the wrapping up of data under a single unit.
```
// Java program to demonstrate encapsulation
class Encapsulate {
// private variables declared
// these can only be accessed by
// public methods of class
private String studentName;
private int studentRoll;
private int studentAge;
// get method for age to access
// private variable studentAge
public int getAge() { return studentAge; }
// get method for name to access
// private variable studentName
public String getName() { return studentName; }
// get method for roll to access
// private variable studentRoll
public int getRoll() { return studentRoll; }
// set method for age to access
// private variable studentage
public void setAge(int newAge) { studentAge = newAge; }
// set method for name to access
// private variable studentName
public void setName(String newName)
{
studentName = newName;
}
// set method for roll to access
// private variable studentRoll
public void setRoll(int newRoll) { studentRoll = newRoll; }
}
public class TestEncapsulation {
public static void main(String[] args)
{
Encapsulate obj = new Encapsulate();
// setting values of the variables
obj.setName("Harsh");
obj.setAge(19);
obj.setRoll(51);
// Displaying values of the variables
System.out.println("student's name: " + obj.getName());
System.out.println("student's age: " + obj.getAge());
System.out.println("student's roll: " + obj.getRoll());
// Direct access of studentRoll is not possible
// due to encapsulation
// System.out.println("student's roll: " +
// obj.studentName);
}
}
```
26 : Abstraction in Java
Data Abstraction is the property by virtue of which only the essential details are displayed to the user.
```
// Java program to illustrate the
// concept of Abstraction
abstract class Shape {
String color;
// these are abstract methods
abstract double area();
public abstract String toString();
// abstract class can have constructor
public Shape(String color)
{
System.out.println("Shape constructor called");
this.color = color;
}
// this is a concrete method
public String getColor() { return color; }
}
class Circle extends Shape {
double radius;
public Circle(String color, double radius)
{
// calling Shape constructor
super(color);
System.out.println("Circle constructor called");
this.radius = radius;
}
@Override double area()
{
return Math.PI * Math.pow(radius, 2);
}
@Override public String toString()
{
return "Circle color is " + super.getColor()
+ "and area is : " + area();
}
}
class Rectangle extends Shape {
double length;
double width;
public Rectangle(String color, double length,
double width)
{
// calling Shape constructor
super(color);
System.out.println("Rectangle constructor called");
this.length = length;
this.width = width;
}
@Override double area() { return length * width; }
@Override public String toString()
{
return "Rectangle color is " + super.getColor()
+ "and area is : " + area();
}
}
public class Test {
public static void main(String[] args)
{
Shape s1 = new Circle("Red", 2.2);
Shape s2 = new Rectangle("Yellow", 2, 4);
System.out.println(s1.toString());
System.out.println(s2.toString());
}
}
```
Collection framework
Any group of individual objects which are represented as a single unit is known as the collection of the objects.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection classes
Hierarchy of the Collection Framework

Interfaces which extend the Collections Interface
1. Iterable Interface
This is the root interface for the entire collection framework.
The main functionality of this interface is to provide an iterator for the collections.
2. Collection Interface
This interface extends the iterable interface and is implemented by all the classes in the collection framework.
This interface contains all the basic methods which every collection has like adding the data into the collection, removing the data, clearing the data, etc.
3. List Interface
This is a child interface of the collection interface. This interface is dedicated to the data of the list type in which we can store all the ordered collection of the objects. This also allows duplicate data to be present in it.
```
List <T> al = new ArrayList<> ();
List <T> ll = new LinkedList<> ();
List <T> v = new Vector<> ();
Where T is the type of the object
```
ArrayList:
```
// Java program to demonstrate the
// working of ArrayList in Java
import java.io.*;
import java.util.*;
class ArrayListDemo {
public static void main(String[] args)
{
// Declaring the ArrayList with
// initial size n
ArrayList<Integer> al
= new ArrayList<Integer>();
// Appending new elements at
// the end of the list
for (int i = 1; i <= 5; i++)
al.add(i);
// Printing elements
System.out.println(al);
// Remove element at index 3
al.remove(3);
// Displaying the ArrayList
// after deletion
System.out.println(al);
// Printing elements one by one
for (int i = 0; i < al.size(); i++)
System.out.print(al.get(i) + " ");
}
}
```
LinkedList:
```
// Java program to demonstrate the
// working of LinkedList in Java
import java.io.*;
import java.util.*;
class LinkedListDemo{
public static void main(String[] args)
{
// Declaring the LinkedList
LinkedList<Integer> ll
= new LinkedList<Integer>();
// Appending new elements at
// the end of the list
for (int i = 1; i <= 5; i++)
ll.add(i);
// Printing elements
System.out.println(ll);
// Remove element at index 3
ll.remove(3);
// Displaying the List
// after deletion
System.out.println(ll);
// Printing elements one by one
for (int i = 0; i < ll.size(); i++)
System.out.print(ll.get(i) + " ");
}
}
```
Vector:
```
// Java program to demonstrate the
// working of Vector in Java
import java.io.*;
import java.util.*;
class VectorDemo {
public static void main(String[] args)
{
// Declaring the Vector
Vector<Integer> v
= new Vector<Integer>();
// Appending new elements at
// the end of the list
for (int i = 1; i <= 5; i++)
v.add(i);
// Printing elements
System.out.println(v);
// Remove element at index 3
v.remove(3);
// Displaying the Vector
// after deletion
System.out.println(v);
// Printing elements one by one
for (int i = 0; i < v.size(); i++)
System.out.print(v.get(i) + " ");
}
}
```
Stack: The class is based on the basic principle of last-in-first-out.
```
// Java program to demonstrate the
// working of a stack
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.push("Geeks");
stack.push("For");
stack.push("Geeks");
stack.push("Geeks");
// Iterator for the stack
Iterator<String> itr
= stack.iterator();
// Printing the stack
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
stack.pop();
// Iterator for the stack
itr
= stack.iterator();
// Printing the stack
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}
```
4. Queue Interface: FIFO(First In First Out)
```
Queue <T> pq = new PriorityQueue<> ();
Queue <T> ad = new ArrayDeque<> ();
Where T is the type of the object.
```
5. Deque Interface: double-ended queue
```
Deque<T> ad = new ArrayDeque<> ();
Where T is the type of the object.
```
6. Set Interface: A set is an unordered collection of objects in which duplicate values cannot be stored.
```
Set<T> hs = new HashSet<> ();
Set<T> lhs = new LinkedHashSet<> ();
Set<T> ts = new TreeSet<> ();
Where T is the type of the object.
```
```
// Java program to demonstrate the
// working of a HashSet
import java.util.*;
public class HashSetDemo {
public static void main(String args[])
{
// Creating HashSet and
// adding elements
HashSet<String> hs = new HashSet<String>();
hs.add("this");
hs.add("session");
hs.add("for JAVA");
hs.add("Is");
hs.add("Very helpful");
// Traversing elements
Iterator<String> itr = hs.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
```
7. Sorted Set Interface:This interface is very similar to the set interface. The only difference is that this interface has extra methods that maintain the ordering of the elements.
```
SortedSet<T> ts = new TreeSet<> ();
Where T is the type of the object.
```
8. Map Interface:A map is a data structure which supports the key-value pair mapping for the data. This interface doesn’t support duplicate keys because the same key cannot have multiple mappings.
```
Map<T> hm = new HashMap<> ();
Map<T> tm = new TreeMap<> ();
Where T is the type of the object.
```
HashMap:
```
// Java program to demonstrate the
// working of a HashMap
import java.util.*;
public class HashMapDemo {
public static void main(String args[])
{
// Creating HashMap and
// adding elements
HashMap<Integer, String> hm
= new HashMap<Integer, String>();
hm.put(1, "hello");
hm.put(2, "how");
hm.put(3, "why");
// Finding the value for a key
System.out.println("Value for 1 is " + hm.get(1));
// Traversing through the HashMap
for (Map.Entry<Integer, String> e : hm.entrySet())
System.out.println(e.getKey() + " " + e.getValue());
}
}
```