0% found this document useful (0 votes)
5 views118 pages

java pdf

The document provides an introduction to Java, highlighting its features such as simplicity, object-oriented nature, robustness, platform independence, and security. It explains key concepts of object-oriented programming (OOP), including classes, objects, inheritance, polymorphism, abstraction, and encapsulation, along with the differences between OOP and procedure-oriented programming. Additionally, it covers Java's data types, variables, operators, and the distinctions between JDK, JRE, and JVM.

Uploaded by

anilkatta639
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views118 pages

java pdf

The document provides an introduction to Java, highlighting its features such as simplicity, object-oriented nature, robustness, platform independence, and security. It explains key concepts of object-oriented programming (OOP), including classes, objects, inheritance, polymorphism, abstraction, and encapsulation, along with the differences between OOP and procedure-oriented programming. Additionally, it covers Java's data types, variables, operators, and the distinctions between JDK, JRE, and JVM.

Uploaded by

anilkatta639
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 118

UNIT-I

INTRODUCTION

Java is a general-purpose and object-oriented programming language developed for the


distributed environment and software development for consumer electronic devices such as TVs,
VCRs, toasters, etc.
Java Programming Language is a platform-independent language, which means there is no
limitation to any particular hardware or operating system. It providesss users the facility to ‘write
once, run anywhere’.
Many operating systems such as Sun Solaris, RedHat, Windows, etc., support Java. Java codes
are compiled into byte code or machine-independent code. This byte code is run on JVM (Java
Virtual Machine).
The syntax is Java is almost the same as C/C++. But java does not support low-level
programming functions like pointers. The codes in Java is always written in the form of Classes
and objects.
Features of Java
1. Simple:- It is a simple Language Because it contains many features of other Languages
like c and C++ and Java Removes Complexity because it doesn’t use pointers, Storage Classes
and Go to Statements and java Doesn’t support Multiple Inheritance.
2. Object Oriented:- In java, everything is an object which has some data and behavior.
Java can be easily extended as it is based on Object Model. Following are some basic concept of
OOP's.

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
3. Robust:- Java is robust as it is capable of handling run-time errors, supports automatic
garbage collection and exception handling, and avoids explicit pointer concept.

4. Platform Independent:- Unlike other programming languages such as C, C++ etc which
are compiled into platform specific machines. Java is guaranteed to be write-once, run-
anywhere language. On compilation Java program is compiled into bytecode. This
bytecode is platform independent and can be run on any machine, plus this bytecode
format also provide security. Any machine with Java Runtime Environment can run Java
Programs.
5. Secure:- Java is a more secure language as compared to C/C++, as it does not allow a
programmer to explicitly create pointers. Thus in Java, we can not gain access to a
particular variable if we do not initialize it properly. Programs run in a virtual machine
sandbox – A separate environment that allows users to execute their applications without
affecting the underlying system.
6. Architectural Neutral:- The program written on one platform or OS is independent of other
platforms or environments and can run on any other Operating System without recompiling
them. In other words, it is based on the ‘Write-once-run-anywhere’ (WORA) or ‘Write-once-
run-everywhere’ (WORE) approach.

7. Distributed:- Java is distributed because it encourages users to create distributed applications.


In Java, we can split a program into many parts and store these parts on different computers. A
Java programmer sitting on a machine can access another program running on the other
machine.
8. Multi-threaded and Interactive:- A thread is an independent path of execution within a
program, executing concurrently. Multithreaded means handling multiple tasks
simultaneously or executing multiple portions (functions) of the same program in
parallel.

9. Portable:- Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
10. High Performance:- Java is faster than other traditional interpreted programming
languages because Java bytecode is "close" to native code. It is still a little bit slower than
a compiled language (e.g., C++). Java is an interpreted language that is why it is slower
than compiled languages, e.g., C, C++, etc.
11. Dynamic:- Java is a dynamic language. It supports the dynamic loading of classes. It
means classes are loaded on demand. It also supports functions from its native languages,
i.e., C and C++.
Java OOPs Concepts:-
Object:- Any entity that has state and behavior is known as an object. For example, a chair, pen,
table, keyboard, bike, etc. It can be physical or logical. An Object can be defined as an instance
of a class. An object contains an address and takes up some space in memory.

Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.

Class:-Collection of objects is called class. It is a logical entity. A class can also be defined as a
blueprint from which you can create an individual object. Class doesn't consume any space.
Inheritance:- When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism:- If one task is performed in different ways, it is known as polymorphism. For


example: to convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism. Another
example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.

Abstraction:- Hiding internal details and showing functionality is known as abstraction. For
example phone call, we don't know the internal processing.In Java, we use abstract class and
interface to achieve abstraction.

Encapsulation:-Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.A java class is the
example of encapsulation. Java bean is the fully encapsulated class because all the data members
are private here.

Advantage of OOPs over Procedure-oriented programming language


1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented
programming language, it is not easy to manage if code grows as project size increases.
2) OOPs provides data hiding, whereas, in a procedure-oriented programming language, global
data can be accessed from anywhere.

Figure: Data Representation in Procedure-Oriented Programming


Figure: Data Representation in Object-Oriented Programming

3) OOPs provides the ability to simulate real-world event much more effectively. We can
provide the solution of real word problem if we are using the Object-Oriented Programming
language.

What is the difference between an object-oriented programming language and object-based


programming language?

Object-based programming language follows all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object-based programming languages.

Difference between JDK, JRE, and JVM

Java Virtual Machine:-JVM (Java Virtual Machine) is an abstract machine. It is called a virtual
machine because it doesn't physically exist. It is a specification that provides a runtime
environment in which Java bytecode can be executed. It can also run those programs which are
written in other languages and compiled to Java bytecode.
JVM, JRE, and JDK are platform dependent because the configuration of each OS is different
from each other.
The JVM performs the following main tasks:
 Loads code
 Verifies code
 Executes code
 Provides runtime environment
Java Runtime Environment:- JRE is an acronym for Java Runtime Environment. It is also
written as Java RTE. The Java Runtime Environment is a set of software tools which are
used for developing Java applications. It is used to provide the runtime environment. It
contains a set of libraries + other files that JVM uses at runtime.

Java Development Kit:- The Java Development Kit (JDK) is a software development
environment which is used to develop Java applications and applets. It physically exists. It
contains JRE + development tools. The JDK contains a private Java Virtual Machine (JVM) and
a few other resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (Javadoc), etc. to complete the development of a Java Application.

Java Variables :-

A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type. Variable is a name of memory location. There are three types of
variables in java: local, instance and static.

int data=50;//Here data is variable

Types of Variables

There are three types of variables in Java:


 local variable

 instance variable

 static variable
1) Local Variable:-A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in the class aren't even
aware that the variable exists.A local variable cannot be defined with "static" keyword.
2) Instance Variable:-A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static. It is called an instance variable because its
value is instance-specific and is not shared among instances.
3) Static variable:-A variable that is declared as static is called a static variable. It cannot be
local. You can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class is loaded in
the memory.

Example for types of variables:-


public class A
{
int data;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
}
}//end of class
Java Variable Example: Add Two Numbers
public class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Data Types in Java:-
There are two types of data types in Java:
Primitive data types:- The primitive data types include boolean, char, byte, short, int, long, float
and double.
Non-primitive data types:- The non-primitive data types include Classes, Interfaces, and
Arrays.
Java Primitive Data Types:- There are 8 types of primitive data types.
 boolean data type
 byte data type
 char data type

 short data type

 int data type

 long data type

 float data type


 double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte
float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type:- The Boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false conditions.
Example: boolean one = false

Byte Data Type:- The byte data type is an example of primitive data type. It isan 8-bit signed
two's complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum
value is -128 and maximum value is 127. Its default value is 0.

Example: byte a = 10, byte b = -20

Short Data Type:- The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.

Example: short s = 10000, short r = -5000

Int Data Type:- The int data type is a 32-bit signed two's complement integer. Its value-range
lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its default value is
0.

Example: int a = 100000, int b = -200000

Long Data Type:- The long data type is a 64-bit two's complement integer. Its value-range lies
between -9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).

Example: long a = 100000L, long b = -200000L

Float Data Type:- The float data type is a single-precision 32-bit IEEE 754 floating point. Its
default value is 0.0F.

Example:- float f1 = 234.5f

Double Data Type:- The double data type is a double-precision 64-bit IEEE 754 floating point.
Its value range is unlimited. The double data type is generally used for decimal values just like
float. Its default value is 0.0d.

Example: double d1 = 12.3


Char Data Type

The char data type is a single 16-bit Unicode character.

Example: char abc = 'A'

Operators in Java:- Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc. There are many types of operators in Java which are given below:

 Unary Operator,

 Arithmetic Operator,

 Shift Operator,

 Relational Operator,

 Bitwise Operator,

 Logical Operator,

 Ternary Operator and

 Assignment Operator.

Java Operator Precedence

Operator Category Precedence


Type

Unary postfix expr++ expr--

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

Arithmetic multiplicative */%

additive +-

Shift shift <<>>>>>

Relational comparison <><= >= instanceof

equality == !=
Bitwise bitwise AND &

bitwise exclusive ^
OR

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

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


>>>=

Java Unary Operator:- The Java unary operators require only one operand. Unary operators are
used to perform various operations i.e.:
 incrementing/decrementing a value by one
 negating an expression
 inverting the value of a boolean
Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}}
Output:

10
12
12
10

Java Unary Operator Example: ~ and !


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);
System.out.println(~b);
System.out.println(!c);
System.out.println(!d);
}}
Output:
-11
9
false
true
Java Arithmetic Operators:- Java arithmetic operators are used to perform addition,
subtraction, multiplication, and division. They act as basic mathematical operations.

Example:-
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
System.out.println(a%b);
}}
Java Relational Operators:- Relational operators are used to check the relationship between
two operands. For example,

Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false

<= Less Than or Equal To 3 <= 5 returns true

Example:-
class Main {
public static void main(String[] args) {
int a = 7, b = 11;
System.out.println("a is " + a + " and b is " + b);
System.out.println(a == b);
System.out.println(a != b);
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a >= b);
System.out.println(a <= b);
}}
Logical Operators:- Logical operators are used to check whether an expression is true or false.
They are used in decision making.

Operator Example Meaning

&& (Logical expression1 && true only if both expression1


AND) expression2 and expression2 are true

|| (Logical expression1 || true if either expression1 or


OR) expression2 expression2 is true
! (Logical true if expression is false and
!expression
NOT) vice versa
Example:-
class Main {
public static void main(String[] args) {
System.out.println((5 > 3) && (8 > 5));
System.out.println((5 > 3) && (8 < 5));
System.out.println((5 < 3) || (8 > 5));
System.out.println((5 > 3) || (8 < 5));
System.out.println((5 < 3) || (8 < 5));
System.out.println(!(5 == 3));
System.out.println(!(5 > 3));
}}
Bitwise Operator in Java:- Bitwise operations directly manipulate bits. In all computers,
numbers are represented with bits, a series of zeros and ones.
Operator Description Example
& (AND) returns bit by bit AND of input a&b
| (OR) returns OR of input values a|b
^ (XOR) returns XOR of input values a^b
~
returns the one’s complement. (all bits reversed) ~a
(Complement)
Example:-
public class JavaOperators {
public static void main(String[] args) {
int a = 58; //111010
int b=13; //1101
System.out.println(a&b); //returns 8 = 1000
System.out.println(a|b); //63=111111
System.out.println(a^b); //55=11011
System.out.println(~a); //-59
} }
Java instanceof Operator:- The instanceof operator checks whether an object is an instanceof a
particular class.
Example:-
class Main {
public static void main(String[] args) {
String str = "Programiz";
result = str instanceof String;
System.out.println("Is str an object of String? " + result);
}}

Output:-
Is str an object of String? true

Java Ternary Operator:- The ternary operator (conditional operator) is shorthand for the if-
then-else statement. For example,

variable = Expression ? expression1 : expression2

Here's how it works.

If the Expression is true, expression1 is assigned to the variable. If the Expression is false,
expression2 is assigned to the variable.
Example:-
class Java {
public static void main(String[] args) {
int februaryDays = 29;
String result;
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}}
Java Type Casting:- Type casting is when you assign a value of one primitive data type to
another type. In Java, there are two types of casting:

o Widening casting

o Narrowing casting

Widening Casting (automatically) - converting a smaller type to a larger type size

byte -> short -> char -> int -> long -> float -> double

Narrowing Casting (manually) - converting a larger type to a smaller size type

double -> float -> long -> int -> char -> short -> byte

Widening Casting:- Widening casting is done automatically when passing a smaller size type to
a larger size type:
Example:-
public class Main {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt);
System.out.println(myDouble);
}}
Narrowing Casting:-Narrowing casting must be done manually by placing the type in
parentheses in front of the value
Example:-
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Explicit casting: double to int
System.out.println(myDouble);
System.out.println(myInt);
}}
Java Arrays:- Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value. To declare an array, define the variable type with square
brackets: For example,
String[] cars;
To insert values to it, we can use an array literal - place the values in a comma-separated list,
inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};
Access the Elements of an Array:- You access an array element by referring to the index
number.
Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
}}
Change an Array Element:- To change the value of a specific element, refer to the index
number.
Example:- cars[0] = "Opel";
Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
}}
Array Length:- To find out how many elements an array has, use the length property.
Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
}}
Loop Through an Array:- You can loop through the array elements with the for loop, and use
the length property to specify how many times the loop should run.
Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
} }}
Loop Through an Array with For-Each:- There is also a "for-each" loop, which is used
exclusively to loop through elements in arrays.
Syntax:-
for (type variable : arrayname)
{
...
}
Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
} }}
Example:-
public class TestArray
{
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (double element: myList)
{
System.out.println(element);
} }}
Output:-
1.9
2.9
3.4
3.5
Binary search example:-
class BinarySearchExample
{
public static void binarySearch(int arr[], int first, int last, int key)
{
int mid = (first + last)/2;
while( first <= last )
{
if ( arr[mid] < key ){

first = mid + 1;
}
else if ( arr[mid] == key )
{
System.out.println("Element is found at index: " + mid);
break;
}
Else
{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last )
{
System.out.println("Element is not found!");
}
}
public static void main(String args[])
{
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
} }
Example:-
public class TestArray
{
public static void main(String[] args)
{
double[] myList = {1.9, 2.9, 3.4, 3.5};
for (int i = 0; i < myList.length; i++)
{
System.out.println(myList[i] + " ");
}
double total = 0;
for (int i = 0; i < myList.length; i++)
{
total += myList[i];
}
System.out.println("Total is " + total);
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);
}}
Output:-
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Java program to demonstrate passing of array to method
class Test
{
public static void main(String args[])
{
int arr[] = {3, 1, 2, 5, 4};
sum(arr);
}
public static void sum(int[] arr)
{
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum+=arr[i];
System.out.println("sum of array values : " + sum);
}}
Output :
sum of array values : 15

Returning Arrays from Methods


As usual, a method can also return an array. For example, below program returns an array from
method m1.
Example:-
class Test
{
public static void main(String args[])
{
int arr[] = m1();
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
}
public static int[] m1()
{
return new int[]{1,2,3};
}}
Output:
123
Multidimensional Arrays:- A multidimensional array is an array of arrays. To create a two-
dimensional array, add each array within its own set of curly braces:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

Program:-
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x);
}}

Program:-
public class Main {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i)
{
for(int j = 0; j < myNumbers[i].length; ++j)
{
System.out.println(myNumbers[i][j]);
} } }}

Conditional Statements:-

 Use if to specify a block of code to be executed, if a specified condition is true


 Use else to specify a block of code to be executed, if the same condition is false
 Use else if to specify a new condition to test, if the first condition is false
 Use switch to specify many alternative blocks of code to be executed

The if Statement:-Use the if statement to specify a block of Java code to be executed if a


condition is true.

Syntax:-

if (condition)

// block of code to be executed if the condition is true

Example:-

public class Main {

public static void main(String[] args) {

if (20 > 18) {

System.out.println("20 is greater than 18"); // obviously

} }}

The else Statement:- Use the else statement to specify a block of code to be executed if the
condition is false.
Syntax:-

if (condition) {

// block of code to be executed if the condition is true

} else {

// block of code to be executed if the condition is false

Example:-
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
} }}
The else if Statement:-Use the else if statement to specify a new condition if the first condition
is false.
Syntax:-
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Example:-
public class Main {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
} }}
Java Switch:- Use the switch statement to select one of many code blocks to be executed.
Syntax:-
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example:-
public class Main {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
} }}
While Loop:-The while loop loops through a block of code as long as a specified condition is
true.

Syntax:-

while (condition) {

// code block to be executed

Example:-

public class Main {

public static void main(String[] args) {

int i = 0;

while (i < 5) {

System.out.println(i);

i++;

} }}

The Do/While Loop:-The do/while loop is a variant of the while loop. This loop will execute
the code block once, before checking if the condition is true, then it will repeat the loop as long
as the condition is true.

Syntax:-
do {
// code block to be executed
}while (condition);
Example:-
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
}}
For Loop:- When you know exactly how many times you want to loop through a block of code,
use the for loop instead of a while loop.
Syntax:-
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example:-
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
} }}
For-Each Loop:-There is also a "for-each" loop, which is used exclusively to loop through
elements in an array.

Syntax:-

for (type variableName : arrayName) {

// code block to be executed

Example:-
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
} }}
break:-You have already seen the break statement used in an earlier chapter of this tutorial. It
was used to "jump out" of a switch statement.The break statement can also be used to jump out
of a loop.
Example:-This example stops the loop when i is equal to 4.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
System.out.println(i);
} }}
continue:- The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
Example:-
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
} }}

CLASSES AND OBJECTS

Methods:- A method is a block of code which only runs when it is called. You can pass data,
known as parameters, into a method. Methods are used to perform certain actions, and they are
also known as functions.

Method Declaration:- In general, method declarations has six components :

Modifier-: Defines access type of the method i.e. from where it can be accessed in your
application. In Java, there 4 types of access specifiers.
public: accessible in all classes in your application.
protected: accessible within the class in which it is defined and in its subclass(es)
private: accessible only within the class in which it is defined.
default (declared/defined without using any modifier): accessible within the same class and
package within which its class is defined.
The return type: The data type of the value returned by the method or void if does not return a
value.
Method Name: the rules for field names apply to method names as well, but the convention is a
little different.
Parameter list: Comma separated list of the input parameters are defined, preceded with their
data type, within the enclosed parenthesis. If there are no parameters, you must use empty
parentheses ().
Exception list: The exceptions you expect by the method can throw, you can specify these
exception(s).
Method body: it is enclosed between braces. The code you need to be executed to perform your
intended operations.

Example:-
import java.io.*;
class Addition {
int sum = 0;
public int addTwoInt(int a, int b)
{
sum = a + b;
return sum;
}}
class GFG {
public static void main (String[] args)
{
Addition add = new Addition();
int s = add.addTwoInt(1,2);
System.out.println("Sum of two integer values :"+ s);
}}

Example:-
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);
}
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}}
Passing Parameters by Value to method:- While working under calling process, arguments is
to be passed. These should be in the same order as their respective parameters in the method
specification. Parameters can be passed by value or by reference.
Example:-
public class swappingExample {
public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}}
Example:-

public class Main {

public void checkAge(int age)

if (age < 18) {

System.out.println("Access denied - You are not old enough!");

else {
System.out.println("Access granted - You are old enough!");

} }

public static void main(String[] args) {

Main m=new Main();

m.checkAge(20);

}}
Return Value from method:-

public class Main {

public int myMethod(int x)

return 5 + x;

public static void main(String[] args)

Main m=new Main();

System.out.println(m.myMethod(3));

}}

Recursion:-Recursion is the technique of making a function call itself.


Example: Factorial of a Number Using Recursion

class Factorial {

static int factorial( int n ) {

if (n != 0) // termination condition

return n * factorial(n-1); // recursive call

else

return 1;

public static void main(String[] args) {

int number = 4, result;

result = factorial(number);

System.out.println(number + " factorial = " + result);

}}

Method Overloading:- With method overloading, multiple methods can have the same name
with different parameters.
Three ways to overload a method. In order to overload a method, the argument lists of the
methods must differ in either of these:

1. Number of parameters.

For example: This is a valid case of overloading

add(int, int)

add(int, int, int)

2. Data type of parameters.

For example:

add(int, int)

add(int, float)

3. Sequence of Data type of parameters.

For example:

add(int, float)
add(float, int)

Invalid case of method overloading:

When I say argument list, I am not talking about return type of the method, for example if two
methods have same name, same parameters and have different return type, then this is not a valid
method overloading example. This will throw compilation error.

int add(int, int)


float add(int, int)

Note:- Method overloading is an example of Static Polymorphism.Static Polymorphism is also


known as compile time binding or early binding. Static binding happens at compile time. Method
overloading is an example of static binding where binding of method call to its definition
happens at Compile time.

Example 1: Overloading – Different Number of parameters in argument list


class DisplayOverloading

public void disp(char c)

System.out.println(c);

public void disp(char c, int num)

System.out.println(c + " "+num);

}}

class Sample

public static void main(String args[])

DisplayOverloading obj = new DisplayOverloading();

obj.disp('a');

obj.disp('a',10);

}}

Output:-

a 10

Example 2: Overloading – Difference in data type of parameters


class DisplayOverloading2

public void disp(char c)

System.out.println(c);

public void disp(int c)

System.out.println(c );

}}

class Sample2

public static void main(String args[])

DisplayOverloading2 obj = new DisplayOverloading2();

obj.disp('a');

obj.disp(5);

}}

Output:-

Example3: Overloading – Sequence of data type of arguments


class DisplayOverloading3

public void disp(char c, int num)

System.out.println("I’m the first definition of method disp");

public void disp(int num, char c)

System.out.println("I’m the second definition of method disp" );

class Sample3

public static void main(String args[])

DisplayOverloading3 obj = new DisplayOverloading3();

obj.disp('x', 51 );

obj.disp(52, 'y');

}}

Output:-

I’m the first definition of method disp

I’m the second definition of method disp


Method Overloading and Type Promotion

When a data type of smaller size is promoted to the data type of bigger size than this is called
type promotion, for example: byte data type can be promoted to short, a short data type can be
promoted to int, long, double etc.

Type Promotion table:

The data type on the left side can be promoted to the any of the data type present in the right side
of it.

byte → short → int → long

short → int → long

int → long → float → double

float → double

long → float → double

Example:-

class Demo{

void disp(int a, double b){

System.out.println("Method A");

void disp(int a, double b, double c){

System.out.println("Method B");

public static void main(String args[]){

Demo obj = new Demo();

/* I am passing float value as a second argument but


* it got promoted to the type double, because there

* wasn't any method having arg list as (int, float) */

obj.disp(100, 20.67f);

}}

Output:

Method A

As you can see that I have passed the float value while calling the disp() method but it got
promoted to the double type as there wasn’t any method with argument list as (int, float).

Example:- Type promotion doesn’t happen

class Demo{

void disp(int a, double b){

System.out.println("Method A");

void disp(int a, double b, double c){

System.out.println("Method B");

void disp(int a, float b){

System.out.println("Method C");

public static void main(String args[]){

Demo obj = new Demo();

/* This time promotion won't happen as there isa method with arg list as (int, float)

*/

obj.disp(100, 20.67f);
}}

Output:Method C

Few Valid/invalid cases of method overloading

Case 1:

int mymethod(int a, int b, float c)

int mymethod(int var1, int var2, float var3)

Result: Compile time error. Argument lists are exactly same. Both methods are having same
number, data types and same sequence of data types.

Case 2:

int mymethod(int a, int b)

int mymethod(float var1, float var2)

Result: Perfectly fine. Valid case of overloading. Here data types of arguments are different.

Case 3:

int mymethod(int a, int b)

int mymethod(int num)

Result: Perfectly fine. Valid case of overloading. Here number of arguments are different.

Case 4:

float mymethod(int a, float b)

float mymethod(float var1, int var2)

Result: Perfectly fine. Valid case of overloading. Sequence of the data types of parameters are
different, first method is having (int, float) and second is having (float, int).

Case 5:

int mymethod(int a, int b)


float mymethod(int var1, int var2)

Result: Compile time error. Argument lists are exactly same. Even though return type of methods
are different, it is not a valid case. Since return type of method doesn’t matter while overloading
a method.

Constructors:-

Constructor is a block of code that initializes the newly created object. A constructor resembles
an instance method in java but it’s not a method as it doesn’t have a return type. In short
constructor and method are different. Constructor has same name as the class and looks like this
in a java code.

public class MyClass{

MyClass()

..

There are certain rules for writing constructor as follows:

 Constructor(s) of a class must have the same name as the class name in which it resides.


A constructor in Java can not be abstract, final, static and Synchronized.

Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.
When we create the object of MyClass like this:
MyClass obj = new MyClass()
The new keyword here creates the object of class MyClass and invokes the constructor to
initialize this newly created object.
Constructor Vs Method:-
Constructor Method

1. A Constructor has same name as of 1. A Method may or may not have


class. same name as of class.
2. A Constructor invoked implicitly. 2. A Method invoked explicitly.
3. A Constructor must not have any explicit 3. A Method must have a explicit
return type. return type.
4. A Constructor is used to initialize the 4. A Method is used to show object’s
object’s state. behavior.

Types of Java constructors

There are two types of constructors in Java:

 Default constructor (no-arg constructor)


 Parameterized constructor
Java Default Constructor: - A constructor is called "Default Constructor" when it doesn't have
any parameter.The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.
Syntax of default constructor:

<class_name>(){}
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
} }
Example of default constructor that displays the default values
class Student3{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
} }
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
Example of parameterized constructor

class Student4{

int id;
String name;

Student4(int i,String n)

id = i;

name = n;

void display()

System.out.println(id+" "+name);

public static void main(String args[])

Student4 s1 = new Student4(111,"Karan");

Student4 s2 = new Student4(222,"Aryan");

s1.display();

s2.display();

} }

Example for both default and parameterized constructors

class Example2

public int var;

//default constructor
public Example2()

var = 10;

//parameterized constructor

public Example2(int num)

var = num;

public int display()

return var;

public static void main(String args[])

Example2 obj = new Example2();

Example2 obj2 = new Example2(100);

System.out.println("var is: "+obj.display());

System.out.println("var is: "+obj2.display());

}}

Constructor Chaining:- When a constructor calls another constructor of same class then this is
called constructor chaining.
Constructor Overloading:-
Java Constructor overloading is a technique in which a class can have any number of
constructors that differ in parameter list. The compiler differentiates these constructors by taking
into account the number of parameters in the list and their type.
Examples of valid constructors for class Account are
Account(int a);
Account (int a,int b);
Account (String a,int b);
Example:-

class Box

double width, height, depth;

Box(double w, double h, double d)

{
width = w;

height = h;

depth = d;

Box()

width = height = depth = 0;

Box(double len)

width = height = depth = len;

double volume()

return width * height * depth;

}}

public class Test

public static void main(String args[])

Box mybox1 = new Box(10, 20, 15);

Box mybox2 = new Box();


Box mycube = new Box(7);

double vol;

vol = mybox1.volume();

System.out.println(" Volume of mybox1 is " + vol);

vol = mybox2.volume();

System.out.println(" Volume of mybox2 is " + vol);

vol = mycube.volume();

System.out.println(" Volume of mycube is " + vol);

}}
Static Keyword:-

static keyword is mainly used for memory management. It can be used with variables, methods,
blocks and nested classes. It is a keyword which is used to share the same variable or method of
a given class.In order to create a static member (block, variable, method, nested class), you need
to precede its declaration with the keyword static. When a member of the class is declared as
static, it can be accessed before the objects of its class are created, and without any object
reference.

In Java programming language, static keyword is a non-access modifier and can be used for the
following:

 Static Block
 Static Variable
 Static Method
 Static Classes

Static Block:- If you need to do the computation in order to initialize your static variables, you
can declare a static block that gets executed exactly once, when the class is first loaded.

Example:-

import java.util.*;

public class BlockExample{


// static variable

static int j = 10;

static int n;

static

System.out.println("Static block initialized.");

n = j * 8;

public static void main(String[] args)

System.out.println("Inside main method");

System.out.println("Value of j : "+j);

System.out.println("Value of n : "+n);

}}

Output:

Static block initialized

Inside main method

Value of j:10

Value of n : 80

Static Variable:- When you declare a variable as static, then a single copy of the variable is
created and divided among all objects at the class level. Static variables are, essentially, global
variables. Basically, all the instances of the class share the same static variable. Static variables
can be created at class-level only.

Example:-
import java.util.*;

public class VariableExample

static int j = n();

static {

System.out.println("Inside the static block");

static int n() {

System.out.println("from n ");

return 20;

public static void main(String[] args)

System.out.println("Value of j : "+j);

System.out.println("Inside main method");

}}

Output:

from n

Inside the static block

Value of j: 20

Inside main method

Static Methods:- When a method is declared with the static keyword, it is known as a static
method. The most common example of a static method is the main( ) method. Methods declared
as static can have the following restrictions:

 They can directly call other static methods only.


 They can access static data directly.
Example:-

public class StaticMethodExample

// static variable

static int j = 100;

// instance variable

int n = 200;

// static method

static void a()

a = 200;

System.out.println("Print from a");

n = 100; // compilation error

// Cannot make a static reference to the non-static method a2() from the type Test

a2(); // compilation error

// Cannot use super in a static context

System.out.println(super.j); // compiler error

// instance method

void a2()

System.out.println("Inside a2");

public static void main(String[] args)

{
// main method

}}

Static Class:- A class can be made static only if it is a nested class. Nested static class doesn’t
need a reference of Outer class. In this case, a static class cannot access non-static members of
the Outer class.

Example:-

class JavaExample{

private static String str = "BeginnersBook";

//Static class

static class MyNestedClass{

//non-static method

public void disp() {

/* If you make the str variable of outer class

* non-static then you will get compilation error

* because: a nested static class cannot access non-

* static members of the outer class.

*/

System.out.println(str);

} }

public static void main(String args[])

/* To create instance of nested class we didn't need the outer

* class instance but for a regular nested class you would need

* to create an instance of outer class first

*/

JavaExample.MyNestedClass obj = new JavaExample.MyNestedClass();


obj.disp();

}}

Output:-

BeginnersBook

this keyword:-In Java, this is a keyword which is used to refer current object of a class. we can
it to refer any member of the class. It means we can access any instance variable and method by
using this keyword.

Usage of Java this keyword:-

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

 this can be used to invoke current class method (implicitly)

 this can be used to invoke current class constructor.

 this can be passed as an argument in the method call.

 this can be passed as argument in the constructor call.

 this can be used to return the current class instance from the method.

this: 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:

class Student{

int rollno;

String name;

float fee;
Student(int rollno,String name,float fee){

rollno=rollno;

name=name;

fee=fee;

void display(){System.out.println(rollno+" "+name+" "+fee);}

class TestThis1{

public static void main(String args[]){

Student s1=new Student(111,"ankit",5000f);

Student s2=new Student(112,"sumit",6000f);

s1.display();

s2.display();

}}

Output:

0 null 0.0

0 null 0.0

Solution of the above problem by this keyword

class Student{

int rollno;

String name;

float fee;
Student(int rollno,String name,float fee){

this.rollno=rollno;

this.name=name;

this.fee=fee;

void display(){System.out.println(rollno+" "+name+" "+fee);}

class TestThis2{

public static void main(String args[]){

Student s1=new Student(111,"ankit",5000f);

Student s2=new Student(112,"sumit",6000f);

s1.display();

s2.display();

}}

Output:

111 ankit 5000.0

112 sumit 6000.0

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

Program where this keyword is not required

class Student{

int rollno;
String name;

float fee;

Student(int r,String n,float f){

rollno=r;

name=n;

fee=f;

void display(){System.out.println(rollno+" "+name+" "+fee);}

class TestThis3{

public static void main(String args[]){

Student s1=new Student(111,"ankit",5000f);

Student s2=new Student(112,"sumit",6000f);

s1.display();

s2.display();

}}

this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method.
class A{

void m(){System.out.println("hello m");}

void n(){

System.out.println("hello n");

this.m();

} }

class TestThis4{

public static void main(String args[]){

A a=new A();

a.n();

}}

this() : to invoke current class constructor

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

Calling default constructor from parameterized constructor:

class A{

A(){System.out.println("hello a");}
A(int x){

this();

System.out.println(x);

} }

class TestThis5{

public static void main(String args[]){

A a=new A(10);

}}

Calling parameterized constructor from default constructor:

class A{

A(){

this(5);

System.out.println("hello a");

A(int x){

System.out.println(x);

} }

class TestThis6{

public static void main(String args[]){

A a=new A();

}}

Real usage of this() constructor call


class Student{

int rollno;

String name,course;

float fee;

Student(int rollno,String name,String course){

this.rollno=rollno;

this.name=name;

this.course=course;

Student(int rollno,String name,String course,float fee){

this(rollno,name,course);//reusing constructor

this.fee=fee;

void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}

class TestThis7{

public static void main(String args[]){

Student s1=new Student(111,"ankit","java");

Student s2=new Student(112,"sumit","java",6000f);

s1.display();

s2.display();

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

this: to pass as an argument in the method

class S2{

void m(S2 obj){

System.out.println("method is invoked");

void p(){

m(this);

public static void main(String args[]){

S2 s1 = new S2();

s1.p();

} }

this: to pass as argument in the constructor call:- We can pass the this keyword in the
constructor also. It is useful if we have to use one object in multiple classes.

class B{

A4 obj;

B(A4 obj){

this.obj=obj;

void display(){

System.out.println(obj.data);//using data member of A4 class


} }

class A4{

int data=10;

A4(){

B b=new B(this);

b.display();

public static void main(String args[]){

A4 a=new A4();

} }

this keyword can be used to return current class instance

class A{

A getA(){

return this;

void msg(){System.out.println("Hello java");}

class Test1{

public static void main(String args[]){

new A().getA().msg();

} }
Garbage Collection:-In java, garbage means unreferenced objects. Garbage Collection is
process of reclaiming the runtime unused memory automatically. In other words, it is a way to
destroy the unused objects. An object is said to be unreachable if it doesn’t contain any reference
to it. To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.

How can an object be unreferenced?

There are many ways:

 By nulling the reference

 By assigning a reference to another

 By anonymous object etc.

1) By nulling a reference:

Employee e=new Employee();

e=null;

2) By assigning a reference to another:

Employee e1=new Employee();

Employee e2=new Employee();

e1=e2;//now the first object referred by e1 is available for garbage collection

3) By anonymous object:

new Employee();

finalize() method:- The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing. This method is defined in
Object class as:

protected void finalize()

{}
gc() method:- The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.

public static void gc()

{ }

Example:-

public class TestGarbage1{

public void finalize(){System.out.println("object is garbage collected");}

public static void main(String args[]){

TestGarbage1 s1=new TestGarbage1();

TestGarbage1 s2=new TestGarbage1();

s1=null;

s2=null;

System.gc();

} }
Final keyword:-Java final keyword is a non-access specifier that is used to restrict a class,
variable, and method. If we initialize a variable with the final keyword, then we cannot modify
its value. If we declare a method as final, then it cannot be overridden by any subclasses. And, if
we declare a class as final, we restrict the other classes to inherit or extend it. In other words, the
final classes cannot be inherited by other classes.
Final Variable:- Once we declare a variable with the final keyword, we can’t change its value
again. If we attempt to change the value of the final variable, then we will get a compilation
error. Generally, we can consider a final variable as a constant, as the final variable acts like a
constant whose values cannot be changed. We can’t just declare a variable as final without
initializing it. That is, we have to give it an initial value while declaring a final variable. If we
declare the final variable without initialization, then it is a blank final variable. But it is
mandatory to initialize a final variable either during declaration or after declaration. If we leave it
uninitialized, then we will get a compilation error.

Syntax of defining a final variable:


final int number = 10; //final variable
final float value; //blank final variable
static final double rate = 2.5; //final and static variable
Example:-
public class Vehicle {
//declaring and initializing a final variable
final int speedlimit = 60;
void controlSpeed() {
//Trying to change the value of the final variable will give an error
speedlimit = 150;
}
public static void main(String args[]) {
Vehicle obj = new Vehicle();
obj.controlSpeed();
}}

Output:

com.techvidvan.finalkeyword.Vehicle.java:9: error: cannot assign a value to final variable


speedlimit

speedlimit = 150;

^
1 error
blank final variable example:-

public class EmployeeDetails {

final int id; //Blank final variable

EmployeeDetails(int idNum) {
id = idNum;

void getDetails() {

System.out.println("Id of the Employee is: " + id);

public static void main(String args[]) {

EmployeeDetails emp = new EmployeeDetails(154);

emp.getDetails();

}}
Final Method:-We can declare Java methods as Final Method by adding the Final keyword before
the method name.The Method with Final Keyword cannot be overridden in the subclasses. The
purpose of the Final Method is to declare methods of how’s definition cannot be changed by a child or
subclass that extends it.
Example:-
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
} }
Output: Compile Time Error
Final Class:- When we declare a class as final, then we restrict other classes to inherit or extend it. In
short, Java final class can’t be extended by other classes in the inheritance. If another class attempts to
extend the final class, then there will be a compilation error.
Example:-
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
} }

Nested classes and inner classes:-

In Java, it is possible to define a class within another class, such classes are known as nested
classes. They enable you to logically group classes that are only used in one place, thus this
increases the use of encapsulation, and creates more readable and maintainable code.

Types of Nested classes:- There are two types of nested classes non-static and static nested
classes. The non-static nested classes are also known as inner classes.

 Non-static nested class (inner class)

o Member inner class

o Anonymous inner class

o Local inner class

 Static nested class


Type Description

Member Inner A class created within class and outside method.


Class

Anonymous Inner A class created for implementing an interface or extending


Class class. The java compiler decides its name.
Local Inner Class A class was created within the method.

Static Nested A static class was created within the class.


Class

Nested Interface An interface created within class or interface.

syntax:-

class OuterClass

...

class NestedClass

...

}}

Difference between nested class and inner class in Java:- An inner class is a part of a nested
class. Non-static nested classes are known as inner classes.

Member Inner class:- A non-static class that is created inside a class but outside a method is
called member inner class. It is also known as a regular inner class. It can be declared with
access modifiers like public, default, private, and protected.

Example:-

class TestMemberOuter1{

private int data=30;

class Inner{

void msg(){System.out.println("data is "+data);}

}
public static void main(String args[]){

TestMemberOuter1 obj=new TestMemberOuter1();

TestMemberOuter1.Inner in=obj.new Inner();

in.msg();

} }

Output:- data is 30

static nested class:-

A static class is a class that is created inside a class, is called a static nested class in Java. It
cannot access non-static data members and methods. It can be accessed by outer class name.

 It can access static data members of the outer class, including private.

 The static nested class cannot access non-static (instance) data members.

Example:-

class TestOuter1{

static int data=30;

static class Inner{

void msg(){System.out.println("data is "+data);}

public static void main(String args[]){

TestOuter1.Inner obj=new TestOuter1.Inner();

obj.msg();

} }

Output:- data is 30
Java static nested class example with a static method

If you have the static member inside the static nested class, you don't need to create an instance
of the static nested class.

Example:-

public class TestOuter2{

static int data=30;

static class Inner{

static void msg(){System.out.println("data is "+data);}

public static void main(String args[]){

TestOuter2.Inner.msg();//no need to create the instance of static nested class

} }

Local inner class: -

A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are
the inner classes that are defined inside a block.If you want to invoke the methods of the local
inner class, you must instantiate this class inside the method.Local inner class cannot be invoked
from outside the method.

Example: -

public class localInner1{

private int data=30;//instance variable

void display(){

class Local{

void msg(){System.out.println(data);}

}
Local l=new Local();

l.msg();

public static void main(String args[]){

localInner1 obj=new localInner1();

obj.display();

} }

Variable Length Arguments: -

Variable Arguments (Varargs) in Java is a method that takes a variable number of arguments.
Variable Arguments in Java simplifies the creation of methods that need to take a variable
number of arguments.

Syntax:-

public static void fun(int... a)

// method body

This syntax tells the compiler that fun( ) can be called with zero or more arguments.
Example:-
class Test1
{
static void fun(int... a)
{
System.out.println("Number of arguments: " + a.length);
for (int i : a)
System.out.print(i + " ");
System.out.println();
}
public static void main(String args[])
{
fun(100);
fun(1, 2, 3, 4);
fun();
}}

Note: A method can have variable length parameters with other parameters too, but one should
ensure that there exists only one varargs parameter that should be written last in the parameter
list of the method declaration. For example:
int nums(int a, float b, double… c)
Example:-

class Test2 {

static void fun2(String str, int... a)

System.out.println("String: " + str);

System.out.println("Number of arguments is: "+ a.length);

for (int i : a)

System.out.print(i + " ");

System.out.println();

public static void main(String args[])

fun2("GeeksforGeeks", 100, 200);

fun2("CSPortal", 1, 2, 3, 4, 5);

fun2("forGeeks");

}}

Erroneous Varargs Examples

Case 1: Specifying two Varargs in a single method:

void method(String... gfg, int... q)


{

// Compile time error as there are two varargs

Case 2: Specifying Varargs as the first parameter of the method instead of the last one:

void method(int... gfg, String q)

// Compile time error as vararg appear before normal argument

Inheritance:-

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 keyword
extends is used by the sub class to inherit the features of super class.

Terms used in Inheritance

Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.

Super Class/Parent Class:Superclass is the class from where a subclass inherits the features. It
is also called a base class or a parent class.

Syntax:

class subClass extends superClass

{
//methods and fields

Example:-

class Teacher {

String designation = "Teacher";

String collegeName = "Beginnersbook";

void does(){

System.out.println("Teaching");

}}

public class PhysicsTeacher extends Teacher{

String mainSubject = "Physics";

public static void main(String args[]){

PhysicsTeacher obj = new PhysicsTeacher();

System.out.println(obj.collegeName);

System.out.println(obj.designation);

System.out.println(obj.mainSubject);

obj.does();

}}

Note:- The derived class inherits all the members and methods that are declared as public or
protected. If the members or methods of super class are declared as private then the derived class
cannot use them directly. The private members can be accessed only in its own class. Such
private members can only be accessed using public or protected getter and setter methods of
super class as shown in the example below.

class Teacher {
private String designation = "Teacher";

private String collegeName = "Beginnersbook";

public String getDesignation() {

return designation;

protected void setDesignation(String designation) {

this.designation = designation;

protected String getCollegeName() {

return collegeName;

protected void setCollegeName(String collegeName) {

this.collegeName = collegeName;

void does(){

System.out.println("Teaching");

public class JavaExample extends Teacher{

String mainSubject = "Physics";

public static void main(String args[]){

JavaExample obj = new JavaExample();


System.out.println(obj.getCollegeName());

System.out.println(obj.getDesignation());

System.out.println(obj.mainSubject);

obj.does();

}}

Types of inheritance: -

 Single inheritance

 Multilevel inheritance

 Hierarchical inheritance

 Multiple inheritance

 Hybrid inheritance

Single Inheritance: refers to a child and parent class relationship where a class extends the
another class.

Example:-

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{


void bark(){System.out.println("barking...");}

class TestInheritance{

public static void main(String args[]){

Dog d=new Dog();

d.bark();

d.eat();

}}

Output:

barking...

eating...

Multilevel inheritance:- refers to a child and parent class relationship where a class extends the
child class. For example class C extends class B and class B extends class A.

Example:-

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{


void bark(){System.out.println("barking...");}

class BabyDog extends Dog{

void weep(){System.out.println("weeping...");}

class TestInheritance2{

public static void main(String args[]){

BabyDog d=new BabyDog();

d.weep();

d.bark();

d.eat();

}}

Output:

weeping...

barking...

eating...

Hierarchical inheritance:- refers to a child and parent class relationship where more than one
classes extends the same class. For example, classes B, C & D extends the same class A.
Example:-

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{

void bark(){System.out.println("barking...");}

class Cat extends Animal{

void meow(){System.out.println("meowing...");}

class TestInheritance3{

public static void main(String args[]){

Cat c=new Cat();

c.meow();

c.eat();

//c.bark();//C.T.Error

}}
Output:

meowing...

eating...

Multiple Inheritance:- refers to the concept of one class extending more than one classes,
which means a child class has two parent classes. For example class C extends both classes A
and B. Java doesn’t support multiple inheritance.

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.

class A{

void msg(){System.out.println("Hello");}

class B{

void msg(){System.out.println("Welcome");}

class C extends A,B{//suppose if it were

public static void main(String args[]){

C obj=new C();
obj.msg();//Now which msg() method would be invoked?

} }

Output:-

Compile time error

Hybrid inheritance:- Combination of more than one types of inheritance in a single program.
For example class A & B extends class C and another class D extends class A then this is a
hybrid inheritance example because it is a combination of single and hierarchical inheritance.

Access Modifiers (or) Access Control (or) Access specifiers:-

The access specifiers also determine which data members (methods or fields) of a class can be
accessed by other data members of classes or packages etc.

Modifiers in Java are of two types:

1) Access Modifiers:- Access modifiers in Java allow us to set the scope or accessibility or
visibility of a data member be it a field, constructor, class, or method.

2) Non-access Modifiers:- Java also provides non-access specifiers that are used with classes,
variables, methods, constructors, etc. The non-access specifiers/modifiers define the behavior of
the entities to the JVM.

Some of the non-access specifiers/modifiers in Java are:

 static
 final
 abstract
 transient
 volatile
 synchronized
 native

Types Of Access Modifiers In Java


Java provides four types of access specifiers that we can use with classes and other entities.
These are:
#1) Default: Whenever a specific access level is not specified, then it is assumed to be ‘default’.
The scope of the default level is within the package.
#2) Public: This is the most common access level and whenever the public access specifier is
used with an entity, that particular entity is accessible throughout from within or outside the
class, within or outside the package, etc.
#3) Protected: The protected access level has a scope that is within the package. A protected
entity is also accessible outside the package through inherited class or child class.
#4) Private: When an entity is private, then this entity cannot be accessed outside the class. A
private entity can only be accessible from within the class.
We can summarize the access modifiers in the following table.

Access Inside Inside Outside package Outside


Specifier Class Package subclass package

Private Yes No No No

Default Yes Yes No No

Protected Yes Yes Yes No

Public Yes Yes Yes Yes

Default Access Specifiers:- A default access modifier in Java has no specific keyword.
Whenever the access modifier is not specified, then it is assumed to be the default. The entities
like classes, methods, and variables can have a default access. A default class is accessible inside
the package but it is not accessible from outside the package i.e. all the classes inside the
package in which the default class is defined can access this class. Similarly a default method or
variable is also accessible inside the package in which they are defined and not outside the
package.

Example:-
class BaseClass

void display() //no access modifier indicates default modifier

System.out.println("BaseClass::Display with 'dafault' scope");

}}

class Main

public static void main(String args[])

//access class with default scope

BaseClass obj = new BaseClass();

obj.display(); //access class method with default scope

}}

Output:

Default Access Modifiers In Java

In the above program, we have a class and a method inside it without any access modifier. Hence
both the class and method display has default access. Then we see that in the method, we can
directly create an object of the class and call the method.

Public Access Modifier

A class or a method or a data field specified as ‘public’ is accessible from any class or package
in the Java program. The public entity is accessible within the package as well as outside the
package. In general, public access modifier is a modifier that does not restrict the entity at all.

Example:-

class A

public void display()


{

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

}}

class Main

public static void main(String args[])

A obj = new A ();

obj.display();

}}

Output:

Public access modifier in Java

Protected Access Specifier:-

The protected access specifier allows access to entities through subclasses of the class in which
the entity is declared. It doesn’t matter whether the class is in the same package or different
package, but as long as the class that is trying to access a protected entity is a subclass of this
class, the entity is accessible. Note that a class and an interface cannot be protected i.e. we
cannot apply protected modifiers to classes and interfaces. The protected access modifier is
usually used in parent-child relationships.

class A
{
protected void display()
{
System.out.println("SoftwareTestingHelp");
}}
class B extends A {}
class C extends B {}
class Main{
public static void main(String args[])
{
B obj = new B(); //create object of class B
obj.display(); //access class A protected method using obj
C cObj = new C(); //create object of class C
cObj.display (); //access class A protected method using cObj
} }
Output:-
SoftwareTestingHelp
SoftwareTestingHelp

Private Access Modifier:- The ‘private’ access modifier is the one that has the lowest
accessibility level. The methods and fields that are declared as private are not accessible outside
the class. They are accessible only within the class which has these private entities as its
members.Note that the private entities are not even visible to the subclasses of the class. A
private access modifier ensures encapsulation in Java.

Some points to be noted regarding the Private Access Modifier.

 Private access modifier cannot be used for classes and interfaces.


 The scope of private entities (methods and variables) is limited to the class in which they
are declared.
 A class with a private constructor cannot create an object of the class from any other
place like the main method.

Example:-

class TestClass{
//private variable and method
private int num=100;
private void printMessage(){System.out.println("Hello java");}
}
public class Main{
public static void main(String args[]){
TestClass obj=new TestClass();
System.out.println(obj.num);//try to access private data member - Compile Time Error
obj.printMessage();//Accessing private method - Compile Time Error
} }

The program above gives compilation error as we are trying to access private data members
using the class object.

But there is a method to access private member variables. This method is using getters and
setters in Java. So we provide a public get method in the same class in which private variable is
declared so that getter can read the value of the private variable. Similarly, we provide a public
setter method that allows us to set a value for the private variable.
Getter and Setter Methods:-
Example for getter and setter methods for private variables:-

class DataClass {
private String strname;

// getter method
public String getName() {
return this.strname;
}
// setter method
public void setName(String name) {
this.strname= name;
}
}
public class Main {
public static void main(String[] main){
DataClass d = new DataClass();

// access the private variable using the getter and setter


d.setName("Java Programming");
System.out.println(d.getName());
}}

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate parent class
object. Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java super Keyword

 super can be used to refer immediate parent class instance variable.


 super can be used to invoke immediate parent class method.
 super() can be used to invoke immediate parent class constructor.

super is used to refer immediate parent class instance variable


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

Example:-
class Animal{

String color="white";

class Dog extends Animal{

String color="black";

void printColor(){

System.out.println(color);//prints color of Dog class

System.out.println(super.color);//prints color of Animal class

} }

class TestSuper1{

public static void main(String args[]){

Dog d=new Dog();

d.printColor();

}}

Output:-

black

white

super can be used to invoke parent class method

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

Example:-

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{


void eat(){System.out.println("eating bread...");}

void bark(){System.out.println("barking...");}

void work(){

super.eat();

bark();

} }

class TestSuper2{

public static void main(String args[]){

Dog d=new Dog();

d.work();

}}

Output:

eating...

barking...

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

super is used to invoke parent class constructor

class Animal{

Animal(){System.out.println("animal is created");}

class Dog extends Animal{

Dog(){

super();

System.out.println("dog is created");

} }
class TestSuper3

public static void main(String args[]){

Dog d=new Dog();

}}

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

Example:-

class Person{

int id;

String name;

Person(int id,String name){

this.id=id;

this.name=name;

} }
class Emp extends Person{

float salary;

Emp(int id,String name,float salary){

super(id,name);//reusing parent constructor

this.salary=salary;

void display(){System.out.println(id+" "+name+" "+salary);}

class TestSuper5{

public static void main(String[] args){

Emp e1=new Emp(1,"ankit",45000f);

e1.display();

}}

Abstract class:-

A class that is declared using “abstract” keyword is known as abstract class. It can have abstract
methods(methods without body) as well as concrete methods (regular methods with body). A
normal class(non-abstract class) cannot have abstract methods.

An abstract class cannot be instantiated, which means you are not allowed to create an object of
it.

A class which contains 0 or more abstract methods is known as abstract class. If it contains at
least one abstract method, it must be declared abstract.

Abstract class declaration

An abstract class outlines the methods but not necessarily implements all the methods.

abstract class A

{
abstract void myMethod(); //abstract method

void anotherMethod() // concrete method

Following are some important observations about abstract classes in Java.

 An instance of an abstract class cannot be created.

 Constructors are allowed.

 We can have abstract class without any abstract method.

 Abstract classes can also have final methods

 We are not allowed to create object for any abstract class.

 We can define static methods in an abstract class

Abstract class Example

abstract class Animal

public abstract void sound();

public class Dog extends Animal

public void sound()

System.out.println("Woof");
}

public static void main(String args[])

Dog obj = new Dog();

obj.sound();

}}

Output:

Woof

Java abstraction

abstract class MotorBike

abstract void brake();

class SportsBike extends MotorBike

public void brake()

System.out.println("SportsBike Brake");

class MountainBike extends MotorBike

{
public void brake()

System.out.println("MountainBike Brake");

class Main

public static void main(String[] args)

MountainBike m1 = new MountainBike();

m1.brake();

SportsBike s1 = new SportsBike();

s1.brake();

}}

Example without abstract method in abstract class:-

abstract class MyClass {

public void display() {

System.out.println("This is a method of abstract class");

public class AbstractClassExample extends MyClass{

public static void main(String args[]) {


AbstractClassExample a=new AbstractClassExample();

a.display();

}}

Method Overriding:- Ifsubclass (child class) has the same method as declared in the parent
class, it is knownas method overriding in Java.
Rules for Java Method Overriding

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

Note:- Method overriding is used for runtime polymorphism

Example of method overriding

class Vehicle{

void run(){System.out.println("Vehicle is running");}

class Bike2 extends Vehicle{

void run(){System.out.println("Bike is running safely");}

public static void main(String args[])

Bike2 obj = new Bike2();

obj.run();

} }

A real example of Java Method Overriding

class Bank{

int getRateOfInterest(){return 0;}


}

class SBI extends Bank{

int getRateOfInterest(){return 8;}

class ICICI extends Bank{

int getRateOfInterest(){return 7;}

class AXIS extends Bank{

int getRateOfInterest(){return 9;}

class Test2

public static void main(String args[])

SBI s=new SBI();

ICICI i=new ICICI();

AXIS a=new AXIS();

System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());

System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());

System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());

} }

Runtime polymorphism (or) Dynamic Method Dispatch:-

It is a process in which a call to an overridden method is resolved at runtime rather than compile-
time. In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object being referred to
by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

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

class A{}

class B extends A{}

A a=new B();//upcasting

Example of Java Runtime Polymorphism

class Bike{

void run(){System.out.println("running");}

class Splendor extends Bike{

void run(){System.out.println("running safely with 60km");}

public static void main(String args[]){

Bike b = new Splendor();//upcasting

b.run();

} }

Output:- running safely with 60km

Java Runtime Polymorphism Example

class Bank{
float getRateOfInterest(){return 0;}

class SBI extends Bank{

float getRateOfInterest(){return 8.4f;}

class ICICI extends Bank{

float getRateOfInterest(){return 7.3f;}

class AXIS extends Bank{

float getRateOfInterest(){return 9.7f;}

class TestPolymorphism{

public static void main(String args[]){

Bank b;

b=new SBI();

System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());

b=new ICICI();

System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());

b=new AXIS();

System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());

} }

Output:

SBI Rate of Interest: 8.4

ICICI Rate of Interest: 7.3


AXIS Rate of Interest: 9.7

Java Runtime Polymorphism Example: Shape

class Shape{

void draw(){System.out.println("drawing...");}

class Rectangle extends Shape{

void draw(){System.out.println("drawing rectangle...");}

class Circle extends Shape{

void draw(){System.out.println("drawing circle...");}

class Triangle extends Shape{

void draw(){System.out.println("drawing triangle...");}

class TestPolymorphism2{

public static void main(String args[]){

Shape s;

s=new Rectangle();

s.draw();

s=new Circle();

s.draw();

s=new Triangle();

s.draw();

} }

Rule:Runtime polymorphism can't be achieved by data members.


class Bike{

int speedlimit=90;

class Honda3 extends Bike{

int speedlimit=150;

public static void main(String args[]){

Bike obj=new Honda3();

System.out.println(obj.speedlimit);

} }

Output:- 90

In the example given above, 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.

Static Binding and Dynamic Binding

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

There are two types of binding

Static Binding (also known as Early Binding).

Dynamic Binding (also known as Late Binding).

static binding:- When type of the object is determined at compiled time(by the compiler), it is
known as static binding. If there is any private, final or static method in a class, there is static
binding.

Example of static binding

class Dog{

private void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Dog d1=new Dog();

d1.eat();

} }

Dynamic binding

When type of the object is determined at run-time, it is known as dynamic binding.

Example of dynamic binding

class Animal{

void eat(){System.out.println("animal is eating...");}

class Dog extends Animal{

void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){

Animal a=new Dog();

a.eat();

} }

Output:- dog is eating...

Difference between method Overloading and Method Overriding

No. Method Overloading Method Overriding

1) Method overloading is used to Method overriding is used to provide the


increase the readability of the specific implementation of the method that
program. is already provided by its super class.

2) Method overloading is Method overriding occurs in two


performed within class. classes that have IS-A (inheritance)
relationship.
3) In case of method In case of method overriding, parameter
overloading, parameter must be must be same.
different.
4) Method overloading is the Method overriding is the example of run
example of compile time time polymorphism.
polymorphism.

Java Method Overloading example

class OverloadingExample{

static int add(int a,int b){return a+b;}

static int add(int a,int b,int c){return a+b+c;}

Java Method Overriding example

class Animal{

void eat(){System.out.println("eating...");}

class Dog extends Animal{

void eat(){System.out.println("eating bread...");}

Object class in Java


Object class is present in java.lang package. Every class in Java is directly or indirectly derived
from the Object class. If a Class does not extend any other class then it is direct child class
of Object and if extends other class then it is an indirectly derived. Therefore the Object class
methods are available to all Java classes. Hence Object class acts as a root of inheritance
hierarchy in any Java Program.
Using Object class methods
The following are the methods in Object class:
 toString() : toString() provides String representation of an Object and used to convert an
object to String.
 hashCode() : For every object, JVM generates a unique number which is
hashcode. It returns distinct integers for distinct objects.
 equals(Object obj) : Compares the given object to “this” object (the
object on which the method is called).
 getClass() : Returns the class object of “this” object and used to get actual runtime class of
the object.
Example:-

public class Test


 {
 public static void main(String[] args)
 {
 Object obj = new String("GeeksForGeeks");
 Class c = obj.getClass();
 System.out.println("Class of Object obj is : "+ c.getName());
 }
 }
Output:

Class of Object objis :java.lang.String

 finalize() method : This method is called just before an object is garbage collected. It is
called by the Garbage Collector on an object when garbage collector determines that there
are no more references to the object.
 clone() : It returns a new object that is exactly the same as this object. For clone() method
refer Clone()
 wait()-It tells the calling thread to give up the lock and go to sleep until some other
thread enters the same monitor and calls notify().
 notify()-It wakes up one single thread that called wait() on the same object. It should be
noted that calling notify() does not actually give up a lock on a resource.
 notifyAll()-It wakes up all the threads that called wait() on the same object.

Interface in Java:-
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.Along with abstract methods, an interface may also contain constants, default
methods, static methods, and nested types. Method bodies exist only for default methods and
static methods.Writing an interface is similar to writing a class. But a class describes the
attributes and behaviors of an object. And an interface contains behaviors that a class
implements.Unless the class that implements the interface is abstract, all the methods of the
interface need to be defined in the class.
Interface cannot be instantiated just like the abstract class. We can have default and static
methods in an interface.

Syntax:
interface <interface_name>
{

// declare constant fields


// declare methods that abstract
// by default.
}
Interface fields are public, static and final by default, and the methods are public and abstract.

The relationship between classes and interfaces


A class extends another class, an interface extends another interface, but a class implements an
interface.

Example:-

interface printable

void print();

class A6 implements printable

{
public void print(){System.out.println("Hello");

public static void main(String args[]){

A6 obj = new A6();

obj.print();

} }

Example:-

interface Polygon

void getArea(int length, int breadth);

class Rectangle implements Polygon

public void getArea(int length, int breadth)

System.out.println("The area of the rectangle is " + (length * breadth));

class Main

public static void main(String[] args)

Rectangle r1 = new Rectangle();

r1.getArea(5, 6);

}}
Example:-

interface Bank

float rateOfInterest();

class SBI implements Bank

public float rateOfInterest(){return 9.15f;}

class PNB implements Bank

public float rateOfInterest(){return 9.7f;}

class TestInterface2

public static void main(String[] args){

Bank b=new SBI();

System.out.println("ROI: "+b.rateOfInterest());

}}

Difference between class and interface in Java

Class Interface

A class can be instantiated An interface can never be instantiated


The class keyword is used to declare it The interface keyword is used

The members of a class can be declared as The members of an interface are always
private, public or protected declared as public

Contains the concrete methods i.e methods Contains abstract method i.e methods without
with body the body

The implements keyword is used to use an


The extends keyword is used to inherit a class
interface

Can contain final and static methods Cannot contain final or static methods

A Java class can have constructors An interface cannot have constructors

A class can extend only one class but can An interface can extend any number of
implement any number of interfaces interfaces but cannot implement any interface

Interface variables:-

In an interface, variables are static and final by default. All variables in an interface in java
should have only public access modifier.

interface Shape{

String shapes ="geometrical shape";

Note that if we don’t write public, static and final before interface variable, the compiler by
default understand it as below.

interface Shape

public static final String shapes ="geometrical shape";

Example:-

interface Math
{

public static final doublePI = 3.14;

public static final double ELUERNUMBER = 2.718;

public static final double SQRT = 1.41421;

public class Sample

public static void main(String[] args)

int radious =2;

double area = Math.PI*radious*radious;

System.out.println("Area of Circle ="+ area);

}}

Multiple inheritance in Java by interface

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known


as multiple inheritance.

Example:-

interface AnimalEat
{

void eat();

interface AnimalTravel

void travel();

class Animal implements AnimalEat, AnimalTravel

public void eat()

System.out.println("Animal is eating");

public void travel()

System.out.println("Animal is travelling");

}}

public class Demo

public static void main(String args[]) {

Animal a = new Animal();

a.eat();

a.travel();

}}

Hybrid Inheritance with Interfaces


public class ClassA

public void dispA()

System.out.println("disp() method of ClassA");

}}

public interface InterfaceB

public void show();

public interface InterfaceC

public void show();

public class ClassD extends ClassA implements InterfaceB,InterfaceC

public void show()

System.out.println("show() method implementation");

public void dispD()

System.out.println("disp() method of ClassD");

public static void main(String args[])


{

ClassD d = new ClassD();

d.dispD();

d.show();

}}

Interface inheritance

A class implements an interface, but one interface extends another interface.

Example:-

interface Printable

void print();

interface Showable extends Printable

void show();

class TestInterface4 implements Showable

public void print(){System.out.println("Hello");

public void show()

System.out.println("Welcome");

public static void main(String args[])


{

TestInterface4 obj = new TestInterface4();

obj.print();

obj.show();

} }

Nested interface:-An interface which is declared inside another interface or class is called
nested interface. They are also known as inner interface.we can only call the nested interface by
using outer class or outer interface name followed by dot( . ), followed by the interface name.

Example:-Nested interface declared inside another interface

interface MyInterfaceA{

void display();

interface MyInterfaceB{

void myMethod();

class NestedInterfaceDemo1 implements MyInterfaceA.MyInterfaceB{

public void myMethod(){

System.out.println("Nested interface method");

public static void main(String args[]){

MyInterfaceA.MyInterfaceB obj= new NestedInterfaceDemo1();

obj.myMethod();

} }

Example 2: Nested interface declared inside a class

class MyClass{

interface MyInterfaceB{
void myMethod();

}}

class NestedInterfaceDemo2 implements MyClass.MyInterfaceB

public void myMethod()

System.out.println("Nested interface method");

public static void main(String args[])

MyClass.MyInterfaceB obj=new NestedInterfaceDemo2();

obj.myMethod();

} }

Difference between abstract class and interface

Abstract class Interface

1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
5) The abstract keyword is used to The interface keyword is used to declare
declare abstract class. interface.

6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.

7) An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape public interface Drawable
{ {
public abstract void draw(); void draw();
} }

Packages:-

Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations) providing access protection and namespace management.

Some of the existing packages in Java are −

 java.lang − bundles the fundamental classes


 java.io − classes for input, output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces.


Creating a Package
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be placed in the current default package.
To compile the Java programs with package statements, you have to use -d option as shown
below.

javac -d Destination_folder file_name.java


Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder.
Example:-
package animals;
interface Animal {
public void eat();
public void travel();
}
Now, let us implement the above interface in the same package animals −
package animals;
/* File name : MammalInt.java */
public class MammalInt implements Animal {
public void eat() {
System.out.println("Mammal eats");
}
public void travel() {
System.out.println("Mammal travels");
}
public int noOfLegs() {
return 0;
}
public static void main(String args[]) {
MammalInt m = new MammalInt();
m.eat();
m.travel();
}}
Now compile the java files as shown below −
$ javac -d . Animal.java
$ javac -d . MammalInt.java

Example:- Circle.java

package p1;

public class Circle

int r;

public Circle(int radius)

r=radius;

public double area()

return 3.14*r*r;

public double perimeter()

return 2*3.14*r;

}}

Compile javac –d . Circle.java

PackTest.java
package p2;

import p1.Circle;

import java.util.Scanner;

class PackTest

public static void main(String args[])

System.out.println(“enter radius”);

Scanner sc=new Scanner(System.in);

int rad=sc.nextInt();

Circle c=new Circle(rad);

System.out.println("area of circle is"+c.area());

System.out.println("perimeter of circle is"+c.perimeter());

}}

Compile:- javac –d . PackTest.java

Run:- java p2.PackTest

Access Control Protection

Access within within outside package by outside


Modifier class package subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
Private:- The private access modifier is accessible only within the class.

Example:-

class A

private int data=40;

private void msg(){System.out.println("Hello java");

} }

public class Simple

public static void main(String args[])

A obj=new A();

System.out.println(obj.data);//Compile Time Error

obj.msg();//Compile Time Error

} }

Default: -If you do not use any modifier, it is treated as default by default. The default modifier
is accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.

//save by A.java

package pack;

class A{

void msg(){System.out.println("Hello");}

//save by B.java
package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();//Compile Time Error

obj.msg();//Compile Time Error

} }

In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

Protected:- The protected access modifier is accessible within package and outside the package
but through inheritance only.The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.It provides more accessibility than the
default modifier.

//save by A.java

package pack;

public class A{

protected void msg(){System.out.println("Hello");}

//save by B.java

package mypack;

import pack.*;

class B extends A{

public static void main(String args[]){

B obj = new B();

obj.msg();

} }
Public:-The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.

A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

B.java

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

} }

String Class

In java, string is an immutable object, which means it is constant and cannot be changed once it
has been created.

Creating a String:- There are two ways to create a String in Java

 String literal
 Using new keyword

String literal:- In java, Strings can be created like this: Assigning a String literal to a String
instance:

String str1 = "Welcome";

String str2 = "Welcome";

Using New Keyword:-

String str1 = new String("Welcome");


String str2 = new String("Welcome");

Example:-

public class Example

public static void main(String args[])

String str = "Beginnersbook";

char arrch[]={'h','e','l','l','o'};

String str2 = new String(arrch);

String str3 = new String("Java String Example");

System.out.println(str);

System.out.println(str2);

System.out.println(str3);

}}

String Methods:-

1. char charAt(int index): It returns the character at the specified index. Specified index value
should be between 0 to length() -1 both inclusive.
2. boolean equals(Object obj): Compares the string with the specified string and returns true if
both matches else false.
3. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t
consider the case while comparing strings. It does a case insensitive comparison.
4. int compareTo(String string): This method compares the two strings based on the Unicode
value of each character in the strings.
5. int compareToIgnoreCase(String string): Same as CompareTo method however it ignores
the case during comparison.
6. boolean startsWith(String prefix, int offset): It checks whether the substring (starting from
the specified offset index) is having the specified prefix or not.
7. boolean startsWith(String prefix): It tests whether the string is having specified prefix, if
yes then it returns true else false.
8. boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.
9. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the
string.
10. int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in
the string from the specified fromIndex.
11. int indexOf(String str): This method returns the index of first occurrence of specified
substring str.
12. String substring(int beginIndex): It returns the substring of the string. The substring starts
with the character at the specified index.
13. String substring(int beginIndex, int endIndex): Returns the substring. The substring starts
with character at beginIndex and ends with the character at endIndex.
14. String concat(String str): Concatenates the specified string “str” at the end of the string.
15. String replace(char oldChar, char newChar): It returns the new updated string after
changing all the occurrences of oldChar with the newChar.
16. boolean contains(CharSequence s): It checks whether the string contains the specified
sequence of char values. If yes then it returns true else false.
17. String toUpperCase(): Equivalent to toUpperCase(Locale.getDefault()).
18. public boolean isEmpty(): This method returns true if the given string has 0 length. If the
length of the specified Java String is non-zero then it returns false.
19. public static String join(): This method joins the given strings using the specified delimiter
and returns the concatenated Java String.

Example:-

import java.lang.String;
public class StringMethods
{
public static void main(String[] args)
{
String str = "Saket Saurav";
String str1 = "Software";
String str2 = "Testing";
System.out.println(str1 + str2);
System.out.println(str1.concat(str2));
System.out.println(str.length());
System.out.println(str.charAt(3));
System.out.println("index of 's' is "+ str2.indexOf('s'));
String str3 = "Softwaretestinghelp";
String str4 = "testing";
System.out.println("testing is a part of Softwaretestinghelp:" +
str3.contains(str4));
String str5 = "Thexyzwebsitexyzisxyzsoftwaretestingxyzhelp";
String[] split = str5.split("xyz");
for (String obj: split) {
System.out.println(obj);
}
String replace = str.replace('r', ou');
System.out.println(replace);
System.out.println(str.substring(3,6));
System.out.println(str2.compareTo(str4));
String str6= " hello ";
System.out.println(str6.trim());
String s1="HELLO HOW Are You?”;
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
String s1="hello how are you";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}}

You might also like