0% found this document useful (0 votes)
222 views

Java Guide

The document summarizes the key features of the Java programming language, including that it is simple, object-oriented, secure, robust, distributed, platform independent, interpreted, multi-threaded, dynamic, and high performance. It describes Java's memory management, exception handling, bytecode execution, and use of just-in-time compilation to improve performance.

Uploaded by

satishkumaryadam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
222 views

Java Guide

The document summarizes the key features of the Java programming language, including that it is simple, object-oriented, secure, robust, distributed, platform independent, interpreted, multi-threaded, dynamic, and high performance. It describes Java's memory management, exception handling, bytecode execution, and use of just-in-time compilation to improve performance.

Uploaded by

satishkumaryadam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 192

JAVA

Features of java:
The features of any program language (or) their facilities (or) services provide by
the language.
The various features of java language are
1. Simple:
The learning and implementation of java language is simple based on the
following reasons.
* The syntax of java language is similar to other language like C, C++.
* The complex topics like pointers, templates of other languages are eliminated in java language
making it a simple program language. The pointer concept will head to confusion & they are
threat to the data.
* In java language the deallocation of the memory is done automatically by garbage collector &
as a programmer we need not worry about memory deallocation.
Object Oriented:
Java language is an object oriented program language. Any object oriented
program language will develop an application with the help classes and objects.
* An object can be anything that exist physically in the real world which requires some memory
(or) space.
* Every object will contain some properties & some actions. Using the properties we can
describe the object & the actions represents task performed by the object.
* A class can be considered as a plan (or) a model (or) a blueprint for creating the objects.
* A class doesn’t exist physically but it provides a logical explanation to the objects. For a class
we can create any number of objects.
* A class is a collection of common features of a group of objects.
class: student
object: surendra, srikanth, venkat etc.(Ex)
class: movie
object: Gamyam, Bommarillu etc.
Secured:
Security is one of the most important principle of any programming language.
When we develop applications in java, we need not specially provide any security programs for
protecting the data from unauthorized usage because the java language comes with by default
security programs. But in C++, we have to write security program to protect the data.

Robust:
The java language is said to be a robust (or) strong program language based on
the following reasons.
1. Memory Management:
The memory management in java is very efficient because there will be no
wastage of memory at the time of allocation and the unused memory will be deallocated
immediately by the garbage collector.
2. Exception Handling:
The errors that occur at the time of execution (Runtime Errors) are called
exceptions & the process of handling those errors is called as Exception Handling, which is very
efficient in java.

Distributed:
The java language is said to be a distributed language. With the help of this
distributed nature we can access the data available in multiple machines and provide it to the
user. Using the distributed nature we can improve the performance because of the more
availability and more accessibility of the data.
Platform Independent (or) Architecture Neutral:
The java language is said to be a platform independent language because it can be
executed on any machine irrespective of the operating system, their architecture, their hardware
(or) s/w etc.
When a ‘C’ program is compiled, the compiler will convert the ‘C’ language
instructions into machine level instructions. The machine level instructions generated by ‘C’
compiler can be executed only on that machine where it is compiled. If we want to execute on
another machine then we have to compile it once again. This nature of ‘C’ language makes it
“machine dependent”.

When a java program is compiled, the compiler will generate byte code
instructions which are called as Special java instructions.

The byte code instructions available in demo.class can be executed on any


machine with the help of JVM(Java Virtual Machine). This nature of java makes it machine
independent (or) platform independent.
Compiler:
It will compile all the code, while compiling if we get any errors, it will store all
the errors in memory. Once the code the code gets compiled, then it will generated all the errors
at a time.
Interpreter:
It will compile line by line, it doesn’t has memory to store the value. While
compiling, if we get any error, they will throw the error & stops the execution at that line once
error gets fixed, then continue execution with the next line.
The java language is said to be a portable language using which we can develop
applications which is a collection of small reusable and replacable components.
Interpreted:
The java language contains an interpreter along with the compiler which is
responsible for executing the code & therefore called as interpreted language.
Other language like C, C++ etc has compiler (or) Interpreter only.
High Performance:
In language the execution of a program is done by both compiler & interpreter
which reduce the execution time & thereby improving the performance of the application.
Multi Threaded:
A language that supports multiple threads will be called as multi threaded
language. Every thread can be considered as a part of a program which is controlling the
application. The multi thread concept will reduce the waiting time & improves the performance
of the application.

Dynamic:
The location of the memory in java language will be done at the time of
execution.
 In C, memory allocation will be done at the time of compilation.
 Every java program will have the extension has [.java].
 The [.java] file developed by the programmer will be provided to the compiler. The compiler
will take the (.java) file and verifies whether the java code is valid (or) not, if valid the compiler
will generate a (.class) file containing byte code instructions (Special java instructions)
 The (.class) file generated by the compiler will be provided to the JVM for the execution.
JVM Architecture:

The .class file will be provided as input to the class loader subsystem. The class
loader subsystem will perform the following operations.
* The class loader subsystem will load the (.class) file into the JVM.
* Before loading the (.class) file it will verify whether the bytecode is valid (or) not with the help
of bytecode verifier.
* If the bytecode is valid then it will load bytecode in different locations called as Runtime Data
Areas.
The various Runtime Data Areas are:
1. Method Area:
This area can be used for storing all the class code and the method code.
2. Heap:
This area can be used for storing the objects.
3. Java Stack:
This area can be used for storing all the methods that are required for execution.
The java stack can be considered as a collection of frames where each frame will contain the
information of one method.
4. PC Register (Program Counter):
This register will contain the address of the next instruction that has to be
executed.
5. Java Native Stack:
This area can be used for storing all the non-java code (Native code).

Execution Engine:
The execution engine is responsible for executing the byte code available in
runtime data areas. The execution engine contains two parts:
1. Interpreter.
2. JIT compiler (Just In Time).
Both the pass of the execution engine are responsible for executing the code
simultaneously which reduces the execution time & there by improves the performance of the
application.
The bytecode available in the runtime data areas will be shared by the interpreter
and JIT compiler. Most of the code will be used for executing the code whenever required.
The code executed by the JIT compiler is called as HOTSPOTS.
Native Library:
This interface will help the JVM to load the native library into the runtime data
errors.
OS:
The JVM has to interact with the operating system so that it can use the resources
available in that machine.

Note:
The bytecode available in (.class) file can be executed on any machine with the
help of JVM.
Comments:
The comments are used for explaining the code or they make the code more
understandable. The comments in a program will improve the readability of the code. Comments
are not part of the logic, they are non-executable statements.
In java language we have different types of comments. They are
1. Single Level Comments:
The single level comment can be used for writing a comment in a single line. The
single line comments begins with”//” symbols & end in the same line.
Ex: //this is a single line comment.
2. Multiline Comment:
Multiline comments can be used for writing the comments in multiple lines. The
multiple comments begins with “/*” ends with “*/”.
Ex:
/* this is a line one comment
this is a line two comment
this is a line three comment */
These comments can begin in a line & end in any other line.
 Single line & multiple comments are used purely for explaining the code only.

Multiple Comments:
These comments can be used for creating a document (Manual) for the software
that is developed i.e., using these comments we can create an API (Application Programming
Interface). These comments will begin with”/**” & ends with “*/”. These comments can begin
& end in any line.
Syntax: /**
Author: Srikanth
Created on:
Last modified on: */
(What are the classes & methods are used everything will
be describing about prg (or) software)
DATA TYPES
Data types will represent the type of data that can be stored into a memory location.
The data types in java can be classified into three types
1. Primitive Data Types:
These data types are predefined and they are designed to store a single value.
Ex: int char
2. Derived Data Types:
These data types are predefined and they are designed to store multiple values.
Ex: array
3. User Defined Data Types:
These data types are created by user or programmer according to the application
requirement. The user defined data type can contain any no of values and they can be of any
type.
Ex: class
1. Primitive Data Types:
These data types are predefined and they are used for sharing basic inputs
required for a program. These data types are also called as fundamental data types which can be
used for storing a single value.
The java language provides eight primitive data types classified into 4 categories.
i. Integer Category
ii. Floating point Category
iii. Character Category
iv. Boolean Category

i. Integer Category:
This category is used for storing numbers which can be either +ve or –ve without
decimal point. Under the integer category we have four primitive data types. They are
a) byte
b) short
c) int
d) long
The purpose of all the 4 types under integer category is to store same kind of data but
their size and ranges are different so that the memory can be utilized efficiently.
Data Type Size Range
byte 1byte -128 to 127
short 2bytes -32768 to 32767
int 4bytes -2147483648 to 2147483648
long 8bytes -9223372036854775808 to
9223372036854775807

byte  1 byte  8 bits

ii. Floating point Category:


This category is used for storing numbers which can be either +ve or –ve with
decimal point. Under the floating point category we have two primitive data types. They are
a) Float
b) Double
The purpose of both the primitive data types floating point category is to store same kind of data
but their size and ranges are different so that the memory can be utilized efficiently.
Data Type Size Range No of digits after decimal pts
float 4bytes -1.4e -45 to 3.4e 38 7
double 8bytes 4.9e-324 to 1.8e308 15

iii. Character category:


This category is used for storing single character. A character can be represented
by either an alphabet (lowercase or uppercase) or digit or special symbol.
* Under character category we have only 1 primitive data type.
a) char
Data Type Size Range
char 2bytes 0 to 65535
* In C 1byte because of ASCII.
* Here all languages can be used.
*** Why size of char 1byte in C & 2byte in java?
The application that are developed in C language and to store that characters of only
english language and to store that characters 1byte of memory is sufficient. The C language uses
ASCII character set.
The application developed java language use character of all foreign languages. To store
the characters of all the foreign languages 1byte of memory is not sufficient. Size of char is
increased to 2bytes. Java language uses UNICODE set.

iv. Boolean Category:


This category can be used for storing only 2 values and they are true & false.
Under the boolean category we have only one primitive data type and it is boolean.
Data Type Size Range
boolean JVM dependent true false
** Why it is JVM dependent?
The JVM that is used for executive java program can be implemented by any
organization. The size of the boolean will be decided by the organization that develops the JVM.
Therefore boolean size JVM dependent.
Variables
Variable is a name given to the memory location in which we can store some data or
value.
Ex:

Variable Declaration:
The process of specifying what type of data is to store into the memory is called as
variable declaration.
Syntax:
datatype variablename;
datatype var1,var2,var3,….;
Ex:
int age;
int rollno,accno;
double marks;
char grade;
boolean result;
When a variable is declared, the memory for the variable will be allocated and it
can contain some data. The amount of memory allocated to a variable will depend upon the data
type that is specified.
Once the memory for the variable is allocated it can hold some data. If we do not
provide any value to a variable then the memory location will automatically contain default value
of variable type.
Default Values
byte - 0
short - 0
int - 0
long - 0
float - 0.0
double - 0.0
char - space
boolean - false
string - null
student - null
Any class – null
If a variable is declared and if we do not provide any value then the variable will be
automatically initialized with their default value. If we do not want default values then we can
initialize the variable with our own values at the time of declaration.
Syntax:
datatype variablename;
datatype var1,var2,var3,….;

Initialization:
Process of providing value to a variable for the first time is called initialization. The value
of a variable can be changed any no of times during the execution of the program.

Assignment:
Process of providing value to a variable for the second time is called assignment.

Syntax:
int age = 20; Initialization
age = 21; Assignment
age = 22; Assignment
int rollno = 123;
double marks = 98.76;
char grade = ‘A’;
boolean result = false;

Keyword:
Words that are predefined meaning in java are whose meaning is already reserved
are called as keywords.

Literal:
Value that we store in the variable are called literals.

Identifier:
Any name that is used for the purpose of identification will be called as identifier.

Rules for identifier:


* The identifier is combination of _, $, alphabets, digits.
* Identifier should not begin with digit, alphabets, _, $.
* Identifier cannot have any space.
* Keywords of java cannot be used as identifiers.
* There is no restriction on the length of the identifier but recommended not to use more than 16
characters.
* The names of the identifier must be meaningful & appropriate to the application.
Ex:
int x = 25; Valid but not recommended
int age = 25; Valid & recommended
Structure of java program:
package statement
import statement
class<className>
{
Variables
Methods
Public static void main(String[] args)
{
Statements
}
}

* The package statement is an optional statement. A java program can contain atmost one
package statement. The package statement should be first executable statement in a java
program.
* The import statement is an optional statement. A java program can contain any no of import
statements. The import statement must be specified after the package statement before the class.
* Java program can contain any no of classes. Every class can contain variables & methods
which are together called as members of the class. A class can contain any no of variables & any
no of methods.
* The execution of a java program is done by main methods whose syntax must be as follows:
* The main method can contain any no of statements. A java program can have any no of
commands and they can be specified anywhere in the program. The comments are non-
executable statement of java program.

Procedure to Develop, Save, Compile & Execute java program:


Step1: Develop a java program. We require an editor like notepad, wordpad, vi editor etc.
Class FirstProgram{
Public Static Void Main(String[] args){
System.out.println(“Welcome to java@inetsolv”);
}
}

Step2: Saving a java program.


* A java program can be saved with any name but extension of java program must be java.
Syntax: Firstprg.java

Step3: Compiling a java program.


To compile a java program we require a command prompt and we use javac command.
Syntax: javac filename/programme with extension
Ex: javac firstprogram.java
When a java program is compiled the compiler will check whether java code is valid or
not, if valid then compiler generates .class file which contains byte code.

Step4: Executing a java program.


To execute a java program we require a command we use java command .class file
generated by compiler will be provided to the JVM for execution.
Syntax: java classname without extension
Ex: java Firstprogram
o/p Welcome to java@inetsolv
 To develop a java application we need to install java s/w. The java language is an open
source & freeware which can be downloaded free of cost.
 Once the java s/w is installed then we need to set the path. The path is called as an
environment variable. The operating system variables are called as environment
variables.
 The path variable should contain address or the location where the java is installed.

Syntax:
Set PATH = java installation folder
Set PATH = c:\program files\java\jdk1.6.0_12\bin;
* Setting the path means proving the address to java installation to OS.

Program 2:
Class secondprogram{
Public static void main(String[] arg){
System.out.println(“this is my second”);
System.out.println(“java program”);
System.out.println(“at inetsolv”);
}
}

Java Coding Conventions (Hungarian Notations)


Every predefined class, predefined method, variable follow java coding
conventions and we are also recommended to follow the same coding conventions. It is
always a good programming practice for developing applications following the conventions.

1. Conventions for a Class:


A class name can contain any no of words. The first letter of every word should
be specified in uppercase.
Ex: System StringBuffer FirstProgram.
2. Conventions for a Interface:
Interface name can contain any no of words. The first letter of every word should
be specified in uppercase.
Ex: Runnable WindowListener MyInterface.

3. Conventions for a Method:


A method name can contain any no of words. The first letter of every word should
be specified in lowercase. The first letter of remaining words if available should be specified in
uppercase.
Ex: main() tocharArray() areaOfTheCircle()

4. Conventions for a Variable:


The variable name should be any no of words. The first letter of every word
should be specified in lowercase. The first letter of remaining words if available should be
specified in uppercase.
Ex: length breadthOfRectangle numberOfStudents

5. Conventions for a Constant:


The constant name should be any no of words. All the letters of all words should
be specified in lowercase. It contains multiple words separated them by underscore.
Ex: MAX_VALUE MIN_PRIORITY

6. Conventions for a package:


The package name can contain any no of words. It should be specified completely
in lowercase.
Ex: java.lang java.io pack1.pack2

Note: The keywords of java should be specified in lowercase.

* java is case sensitive.


Operators
* Any symbol that is used for performing an operation will be called as an operator.
* The values on which the operator performs the operations will be called as operands.

* Based on the no of operands the operator considers they are classified into following
categories.
1. Unary Operators:
These operators will perform operations on single operand.
2. Binary Operators:
These operators will perform operations on two operands.
3. Ternary Operators:
These operators will perform operators on three operands.
* The operators of java language are classified into various categories based on task they
perform.

1. Arithematic Operators:
These operators can be used for calculating mathematical operations. The various
arithematic operators are
i. Addition (+)
ii. Subtraction (-)
iii. Multiplication (*)
iv. Division (/)
v. Modulus (%)
* If both operands are of integer type the result will be integer.
* If any one of operand is of float type the result is float.
Ex: 7 + 2 = 9
7-2=5
7 * 2 = 14
7 / 2 = 3 or 7 / 2.0 = 3.5
7%2=1
* An arithematic expression will be evaluated from left to right.
int x=10; O/P : 10
int y=x * 3 – 2; O/P : 28
* We can change order of evaluation by changing pair of parenthesis.
int x=10; O/P : 10
int y=x * (3 – 2); O/P : 10
* The arithematic expression will be evaluated from left to right. If operators have same
precedence otherwise evaluate the higher precedence operators first and then lower precedence
operators.
* The arithematic operators
* / %  higher precedence
+ -  lower precedence
Ex: int x=10; O/P: 10
int y=x * 5 / 2; O/P : 25
Ex: int x=10; O/P: 10
int y=x - 5 / 2; O/P : 8

2. Unary Operators:
These operators will perform operations on single operand.
The various unary operators are -, ++, --.
i.Unary Minus (-):
Converts positive to negative & negative to positive.
Ex: int temp=23;
int temp= -23;
int temp= -(-23);
ii. Increment Operator (++):
This operator will increment value by 1.Based on the position of increment operator the
increment operator is classified into two types.
a) Pre-increment operator:
If increment operator is placed before the variable is called pre-increment
operator (++x). The pre-increment value will use the value after increasing it.
b) Post-increment operator:
If increment operator is placed after the variable is called post-increment operator
(x++). The post-increment value will use the value before increasing it.
ii. Decrement Operator (++):
This operator will decrement value by 1.Based on the position of decrement operator the
decrement operator is classified into two types.
a) Pre-decrement operator:
If decrement operator is placed before the variable is called pre-decrement
operator (--x). The pre-decrement value will use the value after decreasing it.
b) Post-decrement operator:
If decrement operator is placed after the variable is called post-decrement
operator (x--). The post-decrement value will use the value before decreasing it.
Ex:
Class Operators {
Public static void main(String[] args){
int a=7; //8 9
int b=++a; //8 7 6
int c=b--; //8 7
int d=a++ + --b - --c; //8 + 6 - 7 7
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
}
* The increment & decrement operators can be applied to all numeric data types. The numeric
data types are byte, short, int, long, double, float and char.
* Increment & decrement operators can be applied to only variables.
* Increment & decrement operators cannot be nested.
Ex: (++(++a));
3. Assignment Operators:
This operator is used for assigning value to a variable. The assignment operator is =.
* This operator will copy value from right to left.
* On the right side we can specify either a value (or) variable (or) an expression but left side we
can specify only variable.
x=5
y=x
z=x + y
* If the assignment operator is combined with other operator it is called compound assignment
operators.
+= , -= , *= , /= , %= .
Ex: x=x+3 x+=3
y=y-2 y-=2
4. Relational Operators:
These operators can be used for comparing the values. These operators are also called as
comparision operators.
The various relational operators are >, >=, <, <=, ==,! =.
* Using the relational operators we can create conditions.
** The result of all relational operators is of boolean type. If the condition is satisfied the result
is true otherwise false.
Rules:
* The relational operators <, <=,>,>= can applied to any combination of only numeric types.
* The relational operators ==,!= are also called equality operator .The equality operator are
applied to any combination of integer or boolean type.
5. Logical Operators:
These operators are used for combining or complementing result of a condition. The
various logical operators are &, &&,|, ||, ^, !.
* The result of all logical operators is of boolean type. i.e. Either true (or) false.
& (Single Ampercent)
This operator is used for combine multiple conditions.
Syntax: cond1 & cond2
* The result of & operator will be true only when all the conditions are true.
* The & operator will evaluate all the conditions then decide the result.

&& (Double Ampercent)


This operator is used for combine multiple conditions.
Syntax: cond1 && cond2
* The result of && operator will be true only when all the conditions are true.
** The && operator will evaluate first condition. If result of first condition is false then it will
skip the evaluation of remaining conditions and provide result as false.
** If the result of first condition is true then it will evaluate remaining conditions and then decide
the result.
** The double ampercent(&&) operator can be used to improve performance of application only
when result of first condition is false.
| (Single Pipe)
This operator is used for combining multiple conditions
Syntax: cond1 | cond2
* The result of single pipe operator will be true if atleast one of the condition is true.
* The single pipe operator will evaluate all the condition and then decide the result.

|| (Double Pipe)
This operator is used for combining multiple conditions.
Syntax: cond1 || cond2
* The result of double pipe operator will be true if atleast one of the condition is true.
* The single pipe operator will evaluate the first condition if the result of first condition is true
then it will skip the evaluation of remaining conditions provides the result as true.
* If the result of the first condition is true then it will evaluate the remaining conditions.
* The double pipe operator will improve the operator sometimes when the result of first
condition is true.

^ (Exclusive OR)
Used for combining multiple condition.
Syntax: cond1 ^ cond2
* The result of ^ operator will be true if the result of the condition are different.

! (Not)
This operator will complement the result of condition.
Syntax: ! (cond)
6. Bitwise Operators:
These operators will perform operations on bits of an number. The various bitwise
operators are ~, &, |, ^, >>, <<, >>>.

~ (Tilde):
This operator will convert bits from one to zeros and 0’s to 1.

Ex: ~ (Negation operator) (Tilde)

2’s compliment = 1’s compliment + 1

 ~x = - (x + 1)

& (Bitwise &):


This operator will perform operation on bitwise of a number.

| (Bitwise |):
This operator will perform operation on bits of a number.
^ (Bitwise ^):
This operator will perform operation on bits of a number.

<< (Left Shift)


This operator will shift bits of a number towards left side by the specified no of
positions.

Ex:

* Shifting the bits of a number towards left side by 1 position multiplying number by 2.
>> (Right Shift)
This operator will shift bits of a number towards right side by the specified no of
positions.

Ex:

* Shifting the bits of a number towards right side by 1 position dividing number by 2.

>>> (Unsigned Right Shift):


This operator will shift bits of a number towards right side by the specified no of
positions.

 Diff between >> and >>>?


* When the bits of a number are shifted towards right side by using >>,the sign bit will be copied
as it is into the resultant.
i.e., the positive input will give positive output & negative input will give negative output.
* When we shift bits of a number towards right side by using >>>,we always insert bit 0 into the
signed bit.
i.e., the result will be always positive whether the input is either negative or positive.
Rules for logical operator:
* Logical operators can be applied to combination of boolean type.
* Bitwise operators can be applied to an combination of numbers without decimal point. (Byte,
Short, int, long, char)
* The operators &, |, ^ can be applied any combination of boolean types or any combination of
numeric types with decimal points.

7. Conditional Operator: (?:)


This operator can perform task based on result of a condition. The condition
operator is ?:
Syntax: cond ? exp1 : exp2
This operator will be called as ternary operator. If the result of condition is true then it
will evaluate exp1 & if result of condition is false then it will evaluate exp2.
Ex: max = (x > y)? x : y
Diff = x > y ? x – y : y – x
* Conditional operator can be nested.
Ex: System.out.println(2<3?(2>3?:”hai”:”hello”):”bye”);

8. New Operator:
New operator is used for creating an object of a class means allocating memory
for members of class in the heap memory.
Ex: Class Sample{
}
Sample s = new sample();
* For every class in java language we can create any no of objects.
* Using new operator we can create object for any predefined or user defined class.
* S is called reference variable because they point to refer to object of the class.
* The name of the reference variable can be any valid java identifier.
9. Dot (.) Operator:
The dot operator can be used for accessing the members(variables,methods) from
a class from a package.

className.variable
reference.variable

className.method
reference.method

Package.className
Control Statements
The statements of a java program will always be executed in sequential order. If
we do not want to execute the statements in a sequential order then we need to take the help of
control statements.
The control statements will help the programmer to decide the flow of execution
in a program.
The control statements are classified into following categories.
1. Conditional Statements
1.1 if-else statement
1.2 Switch statement
2. Iterating Statements
2.1 for loop
2.2 while loop
2.3 do-while loop
2.4 for-each loop
1. Conditional Statements:
These statements can execute a group of statements based on a condition or a value.
1.1 If else statement:
The if-else stmt can be used for executing a group of statements based on
condition.
Syntax: if(condition){
Stmt1
}
else {
stmt2
}
* If the condition is satisfied then if block will be executed and if the condition is not satisfied
then execute else block.
Ex:
Class IfElseDemo
{
Public static void main (String [] args)
{
int n=2;
if (n%2=0)
{
System.out.println(“Even Number”);
}
else
{
System.out.println(“Odd Number”);
}
}
}
Rules:
* Specifying condition to the if statement is mandatory and it should be only Boolean type.
* Specifying an else block is optional.
* Specifying flower braces is optional. If we do not specify flower braces then it will consider
only one statement and that one statement is mandatory. If we want to consider multiple stmts
then specify the flower braces is mandatory and within the flower braces we can specify any no
of stmts (0 or more).
* In if-else stmt we can execute exactly one block either if block or else block. There is no
chance of slipping both the blocks and no chance of executing both the blocks.

1.2 Switch statement:


The switch stmt can be used for executing a group of stmts based on a value.
Syntax:
Switch (argument) {
Case label 1: statement1;
break;
Case label 2: statement2;
break;
Case label 3: statement3;
break;
default: statement;
}
* If an application contains less no of options then use if else. But if an application contain
multiple options then recommended to use switch statement because it improves the readability
of the code.
Ex:
Class SwitchDemo{
Public static void main(String[] args){
int ch=3;
Switch(ch){
Case 1: System.out.println(“first choice”);
break;
Case 2: System.out.println(“second choice”);
break;
Case 3: System.out.println(“third choice”);
break;
Case 4: System.out.println(“fourth choice”);
break;
default: System.out.println(“wrong choice”);
}
}
}
* Replace switch statement by if else ladder.
Class SwitchDemo
{
Public static void main (String[] args)
{
int ch=3;
if(ch==1){
System.out.println(“first choice”);
}
elseif(ch==2){
System.out.println(“second choice”);
}
elseif(ch==3){
System.out.println(“third choice”);
}
elseif(ch==4){
System.out.println(“fourth choice”);
}
else{
System.out.println(“wroong choice”);
}
}
}
Rules:
* Specifying the argument to switch stmt is mandatory and it should be either byte type, short
type, char type or int type.
* Specifying the case & default both are optional.
* Specifying the flower braces to the switch stmt is mandatory.
* The default stmt can be specified within the switch block. Generally the default stmt will be
specified after all the cases.
* A switch stmt can contain any no of case (0 or more).
* A switch stmt can contain atmost one default stmt.
* The case labels must be unique. Most not be empty and must not be repeated.

PROGRAM: To read data from keyboard.


import java.io.*;
class ReadData{
Public static void main (String[] args)
Throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print(“Enter first number:”);
String s1=br.readline();
int a=Integer.parseInt(s1);
System.out.print(“Enter second number:”);
String s2=br.readline();
int b=Integer.parseInt(s2);
System.out.print(“sum:”+(a+b));
}
}

Ex: Program to write the biggest number using If Else condition.


class IfElseDemo
{
public static void main(String[] args)
{
int a=10, b=30, c=20, d=8;
if((a>b)&(a>c)&(a>d))
{
System.out.println("a is big);
}
elseif((b>c)&(b>c)&(b>d))
{
System.out.println("b is big);
}
if((c>a)&(c>b)&(c>d))
{
System.out.println("c is big);
}
else
{
System.out.println("d is big);
}
}
}
O/P: b is big

Ex: Write a program to perform mathematical calculations using switch statement.


Class SwitchDemo{
Public static void main(String[] args){
int a=8, b=4, c;
int ch=3;
Switch(ch){
Case 1: c=a+b;
System.out.println(“sum is:”+c);
break;
Case 2: c=a-b;
System.out.println(“subtraction is:”+c);
break;
Case 3: c=a*b;
System.out.println(“multiplication is:”+c);
break;
Case 4: c=a/b;
System.out.println(“division is:”+c);
break;
}
}
}
O/P: multiplication is: 32

* Switch argument & continues until it encounters a break statement (or) teachers end of the
switch statement.
* The break statements is a transfer statement which will transfer from inside switch to outside.
So that it stops (or) skips the execution of remaining cases. So that remaining statements are not
executed.
* Replacing switch with else if ladder.

Class SwitchDemo{
Public static void main(String[] args){
int ch=2;
if(ch==1){
System.out.println(“first choice”);
}
if(ch==2){
System.out.println(“second choice”);
}
if(ch==3){
System.out.println(“third choice”);
}
if(ch==4){
System.out.println(“fourth choice”);
}
else{
System.out.println(“wrong choice”);
}
}
}
O/P: Second choice
Replacing switch with else if ladder is not recommended to reduce the readability of the
program.

Iterating statements:
The iterating statements can be used if we want to execute a group of statements
repeatedly multiple times.

1. For Loop:
Purpose: A for loop has to be used if we want to execute a group of statements multiple
times & it should be used when we know the exact number of iterations.
Syntax:

* Program to write multiplication table using for loop:


Class forDemo{
public static void main(String[] args)
{
int n=6;
for(int i=1; i<=10; i++){
System.out.println(n+"*"+i+"="+(n*i));
}
}
}
O/P: 6 Multiplication table
Rules:
* All the three sections (initialization, condition, inc/dec) of for loop are optional.
* Specifying the section seperators (semicolons) is mandatory.
Ex: for(;;)
* If we do not specify initialization, inc/dec then the compiler will not provide any initialization
& will not provide inc/dec, but if we do not specify any condition then compiler will provide a
boolean value “true”.
for(;true;)
* for(;;) – infinite loop.
* The initialization & inc/dec section can contain any valid java statement but the condition
section must be of only boolean type.
* The initialization section can contain multiple initializations separated by comma, and all the
initializations must be of the same type & the datatype must be specified only one time.
* The inc/dec section can contain multiple inc/dec separated by comma.
* The condition section can contain multiple condition which has to be combined using logical
operators. Use only 5 operators (&, &&, |, ||, ^) but not use (!) operator this is complementing
not combining the condition.
* All the three sections of for loop are independent.
For(i=1; j<=6; k++)
* Specifying the flower braces is optional. If we do not specify the flower braces, it will consider
only one(first) statement & that statement is mandatory. If we want to consider multiple
statements specifying the flower braces is mandatory & within the flower braces we can specify
any number of statements.
* The variable that is declared inside a for loop can be used in for loop.
 Even Numbers from 1 to 100:
class EvenMumbers
{
public static void main(String[] args)
{
for(int n=2; n<=100; n++)
{
if(n%2==0)
{
System.out.println(n);
n++;
}
else
{
System.out.println(“odd numbers”);
}
}
}
}

2. while loop:
While loop can be used for executing a group statements responsibility multiple
times. The while loop should be used when we don’t know the exact no of iterations.

Syntax: while(condition)
{
Statements
}

* Multiplication table using while loop:


Ex: class WhileDemo
{
public static void main(String[] args)
{
int n=8, i=1;
while(i<=10)
{
System.out.println(n+"*"+i+"="+(n*i));
i++;
}
}
}
Rules:
* For a while loop, specifying the condition is mandatory and it must be of boolean type.
* In a while loop, specifying the flower braces is optional. If we donot specify the flower braces,
will consider only one statement & that one statement is mandatory.
* If we want to consider multiple statements then specifying the flower braces is mandatory.
Within the flower braces, we can specify any number of statements.
** Every statement in a java program has to be executed at some point of time. If the control is
unable to reach any statement in the program then the compiler would raise an error called
“unreachable statement”.

do-while loop:
The loop can be used for executing a group of statement repeatedly multiple
times. This loop should be used when we donot know the exact no of iterations.

Syntax:
do
{
Statements
} while(condition);
Program: To write multiplication table using do while loop.
class DoWhileDemo
{
public static void main(String[] args)
{
int n=8, i=10;
do
{
System.out.println(n+"*"+i+"="+(n*i));
i--;
}while(i>=1);
}
}
 Difference between while & do-while loop?
* In a while loop, the statements will be executed after the condition is checked. Where as in a
do-while loop, the statements will be executed before the condition is checked.
* In a while loop, if the condition is false for the first time then the statements will not be
executed where as in a do-while loop, if the condition is false for the first time then the
statements will be executed for one time.
* In a while loop, the statements will be executed for 0 (or) more times. In a do-while loop, the
statements will be executed for 1 (or) more times.

The loops can be nested:


class NestedloopDemo
{
psum(String[] args)
{
for(int i=1; i<=5; i++)
{
for(int j=1; j<=5; j++)
{
System.out.println("*");
}
System.out.println();
}
}
}
O/P: *****
*****
*****
*****
*****
* ASSIGNMENT *****
****
***
**
*

*
**
***
****
*****
Transfer Statement:
The transfer statement can be used for transferring the control from one location
to another location.
1. Break Statement:
The break statement can be used either in switch (or) in loops. The purpose of
break statement in switch is to transfer the control from inside the switch to outside the switch.
So that it skips the execution of remaining cases.
The purpose of break statement in a loop is to transfer the control from inside the
loop to outside the loop so that it skips the execution of remaining iterations.

Ex:
class BreakDemo
{
psum(String[] args)
{
int sum=0, capacity=234;
for(int i=1;i<=10;i++)
{
System.out.println(i);
sum=sum+i;
if(sum>=capacity)
break;
}
System.out.println(sum);
}
}
O/P: 1
2
3
'
'
'
13
sum=--

Alternative code for previous ex using while loop:


class BreakDemo
{
psum(String[] args)
{
int sum=0, capacity=234;
while(sum<capacity)
{
System.out.println(i);
sum=sum+i;
i++;
}
System.out.println(sum);
}
}
ASSIGNMENT:

Print 100 prime numbers from using loops.


Sum of digits of an number
Reverse of a number

 *
**
***
****
*****
class pyramid1
{
psum(String[] args)
{
for(int i=1; i<=5; i++)
{
for(int j=1; j<=i; j++)
{
System.out.println("*");
}
System.out.println();
}
}
}
 *****
****
***
**
*
class pyramid2
{
psum(String[] args)
{
for(int i=1; i<=5; i++)
{
for(int j=1; j<=5; j++)
{
if(i<=j)
System.out.println("*");
}
else
{
System.out.println("-");
}
System.out.println("-");
}
System.out.println();
}
}
}
2. Continue Statement:
The continue statement can be used for skipping the current iteration &
continuing with the next iteration.
Ex:
class continueDemo
{
psum(String[] args)
{
for(int i=1; i<=10; i++)
{
if(i==7|i==3)
continue;
System.out.println(i);
}
}
}

O/P: 1
2
4
5
6
8
9
10
Note: It is recommended to use the break & continue statement along with a condition.
ARRAYS
Array:
If an application requires multiple values then we can store those multiple values
by declaring multiple variables in a program. If the no of variables are increased in the program
then the code size will increase & it will reduce the readability of the code.
* To reduce the code size & to improve the readability of the code, we take the help of the
concept called an “Array”.
* An array is a derived data type using which we can store multiple values.
The arrays are classified into two types.
1. Single Dimension Array
2. Multi Dimension Array
1. Single Dimension Array:
Single Dimension Array can be used for representing a group of values either a
single row (or) single column.
Syntax:
datatype arrayname[];
* To represent an array we take the help of square braces[]. Each pair of square braces represents
one-dimension.
Rules:
* The pair of square braces can be specified either before the array name (or) after the array
name.
int rollNo[];
float[] percent;
char [] grade;
boolean result[];
* We must not specify the size of the array at the time of array declaration
boolean result[5];
* Percent is an array name where we can store multiple values of float datatype.
* The name of the array can be any valid java identifier.
int x[];
* Syntax for creating an array. We can use any way of both the two types.
1. datatype arrayname[] = new datatype[size];
or
2. datatype arrayname[];
arrayname = new datatype[size];
Ex: 1. int arr[] = new int[5];
or
2. int arr[];
arr = new int[5];
* At the time of array creation, specifying the size of the array is mandatory & it should be of
either byte (or) int (or) char type.
Ex: byte x = 10;
int y = 10;
long z = 10;
int[] arr1 = new int[x]; //valid because of byte type
int[] arr2 = new int[y]; //valid because of int type
int[] arr3 = new int[z]; //invalid because of long type
int[] arr4 = new int[10]; //valid because of int type
int[] arr5 = new int[-10]; //invalid [ Negative array size exception]
int[] arr6 = new int[1.0]; //invalid because of float
int[] arr7 = new int[‘z’]; //valid because of char
int[] arr8 = new int[0]; //valid but no result
int[] arr9 = new int[]; //invalid because of boolean
int[] arr10 = new int[]; //invalid because of size is missing

int[] arr = new int[10];


arrayname[index] = starting address of array + index * size of array type

arr[0] = 1000 + 0 * 4 = 1000


arr[1] = 1000 + 1 * 4 = 1004
arr[6] = 1000 + 6 * 4 = 1024

* When an array is created, the memory for that array will be allocated in continuous memory
locations. The allocation of the memory will be based on type of the array & size of the array.
* An array is a collection of multiple elements & to access those elements we take the help of
index positions.
* The index of an array always starts with ‘0’.
* The range of the index will be 0 to [size-1] why starts with ‘0’ means to reduce the wastage of
memory of ‘0’ if they starts with “1”.
* Once the memory for the array is allocated, all the elements in that array will be initialized
automatically with default values of the array type.
* Every array is internally an object which provides a variable called “length” which will specify
the size of the array.
Syntax for accessing the array elements:
arrayname[index]
Syntax for assigning the array elements:
arrayname[index] = value;
Ex: arr[0] = 11;
Note:
If we specify an index position which is outside the range of the array index then
we get a runtime error called as “ArrayIndexOutOfBandsException”.

for each loop (or) Enhanced for loop:


This loop is designed to work on arrays(collections). It is introduced in 1.5
version of java.
Syntax:
for(Variable declaration : arrayname)
{
Statements
}
Rules:
* The declaration of the variable in for each loop must be same as that of the array type.
Class ArrayDemo{
Psum (String[] args){
Int[] arr;
arr = new int[5];
System.out.println(arr[0]);
System.out.println (arr[1]);
System.out.println (arr[2]);
System.out.println (arr[3]);
System.out.println (arr[4]);
arr[0] = 12;
arr[1] = 23;
arr[2] = 34;
arr[3] = 45;
arr[4] = 56;
for(int i=0; i<arr.length; i++){
System.out.println (arr[j]);
}
for(int x : arr){
System.out.println (x);
}
}
}

Example:
Class Student{
Psum(String[] args){
int marks[];
marks = new int[5];

marks[0] = 99;
marks[1] = 100;
marks[2] = 94;
marks[3] = 39;
marks[4] = 90;

int total = 0;
boolean result = true;

for(int i=0;i<marks.length;i++){
System.out.println("subject"+(i+1)+"marks:"+marks[i]);

total = total + marks[i];


if(marks[i]<35)
boolean = false;
}
System.out.println("Total:"+total);
int avg = total/marks.length;
System.out.println("Average:"+avg);
if(result)
{
if(avg>=75){
System.out.println("grade:"+Distinction);
}
else if (avg>60){
System.out.println("Grade:"First class);
}
else if (avg>50){
System.out.println("Grade:"Second class);
}
else {
System.out.println("Grade:"Third class);
}
}
else
{
System.out.println("Welcome Again");
}
}
}

Declaring Creating & Initializing the array elements in a single line:


Syntax: datatype[] arrayname = {list of values};
Ex: int[] arr = {11,45,21,38,43,25};
With in the flower braces, we can specify any no of values separated by a comma.
* When we are declaring, creating & initializing the array elements in a single line then we must
not specify the size of the array. The size of the array will be decided automatically based on
number of elements specified within the flower braces.
int[] arr = {11,45,21,53,72,81}; 1
double[] arr = {10.5,4.8,3.9,11.5,13.3};
char[] ch = {‘a’, ‘b’, ‘c’,’d’};

Int[] arr; 2
arr = new int[6]; 3
arr[0] = 11; 4
arr[1] = 45; 5
arr[2] = 21; 6
arr[3] = 53; 7
arr[4] = 72; 8
arr[5] = 81; 9

* Instead of using 2 to 9 we can directly use 1.

Multi Dimension Arrays:


Multi dimension arrays in java are represented as array of arrays.

Syntax for declaring & creating a 2-D array:


datatype arrayname[][] = new datatype[size1][size2];
(or)
datatype arrayname[][];
arrayname = new datatype[size1][size2];

Rules:
* At the time of array declaration we can specify the pair of square braces either before array
name (or) after the array name.
int arr1[][];
int []arr2[];
int [][]arr3; //All are valid.
int[] arr4[];
` int[][] arr5;
int[][] arr6;
* At the time of array declaration, we must not specify the size of the array.
* At the time of array creation, specifying the first dimension is mandatory & the remaining
dimensions are optional.
int [][]arr = new int[3][4];
(or)
int [][]arr;
arr = new int[3][4];

* In multi dimensional array, the top level arrays will contain address of bottom level arrays.
* In a multi dimensional array, only the last level will contain values & remaining all top levels
will contain addresses.
* The bottom level arrays can contain either same number of elements (or) different number of
elements.

int arr[][] = new int[3][4];


(or)
int[][] arr = new int[3][];
arr[0] = new int[4];
arr[1] = new int[4];
arr[2] = new int[4];
 int[][] arr = new int[3][];
arr[0] = new int[3];
arr[1] = new int[2];
arr[2] = new int[4];

 int [][][] arr;


arr = new int[3][][];
arr[0] = new int[2][];
arr[0][0] = new int[2];
arr[0][1] = new int[3];
arr[1] = new int[3][2];
arr[2] = new int[2][1];
Declaring Creating & Initializing the array elements in a single line:
int [][] arr = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
double [][] arr = {{1.1,2.2,3.3},{4.4,5.5,6.6,7.7}};
Ex:
Class Test{
Psum (String[] args){
int[][] arr = {{1,2,3},{4,5,6},{7,8,9}};

for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
System.out.println(arr[i][j]+"");
}
System.out.println();
}

for(int[] x:arr){
for(int y:x){
System.out.println(y+"");
}
System.out.println();
}
}
}

Command Line Arguments:


The values that we pass into the program at the time of execution(runtime) are called as
command line arguments. The command line arguments can be used for passing the values
dynamically into the program & they can be used for avoiding “hardcoding”.
Hardcoding is the process of passing values to the variables with in the program. It is
recommended not to use hardcoding in a program.
class Addition {
public static void main(String[] abc){
int a = Integer.parseInt(abc[1]);
int b = Integer.parseInt(abc[1]);
System.out.println(a+b);
}
}
 Java Addition.java
Java Addition 11 22
o/p: 33
Java Addition 33 44
o/p: 77
Java Addition 55 66
o/p: 121
* The command line arguments will be passed at the time of execution, at the command prompt
& after the class name.
* We can pass any no of values & any type of values separated by a space.
* The command line arguments that we pass will be stored into the string array of the main
method.
* As a programmer, we are supposed to declaring the array i.e., we specify the array type & array
name.
* The creation of the array is done by JVM & array size will be decided by JVM based on the no
of arguments passed. Once the array is created, the arguments will be assigned into the array
elements.
String abc[]; //Done by the programmer in main method
abc = new String[2];
abc[0] = “11”;
abc[1] = “22”;
* If we do not pass any arguments then JVM will create an array of size “0”.
abc = new String[0]; //Where we can store ‘no’ values
* The creation of the array & the assignments of the values will be performed by the JVM just
before calling the main method.
* We can pass any type of values as command line arguments which will be stored in string
format. If we want to use those values in our program then we can convert the values from string
type to all primitive types except character, which is called as “parsing”.

Ex:
Integer.parseInt()
Float.parseFloat()
Double.parseDouble()
Long.parseLong()
Boolean.parseBoolean()
Short.parseShort()
Byte.parseByte()

Why should the main method take string array as the parameter?
If we pass int array to the main method then we can pass only integers, if we pass double
array to the main method, then we can pass only double, floating point values, if we pass boolean
array then we can pass boolean values but if we pass string array then we can pass integers,
floating points, boolean, character values. We can convert all values except character.

Program to read data from keyword:

import java.io.*;
class Addition {
public static void main(String abc[])throws IOException
{
BufferReader br = new BufferReader(new
InputStreamReader(System.in));
System.out.println("Enter First Number");
string fno = br.readline();
int a = Integer.parseInt(fno);
System.out.println("Enter Second Number");
string sno = br.readline();
int b = Integer.parseInt(sno);
System.out.println("sum:"+(a+b));
}
}
String
* The string is a predefined used for storing group of characters.
* The string class objects can be created in two ways.
i. by using new operator
String str = new String(“hello”);
ii. by enclosing group of characters directly within double codes.
String str = “hello”;
* The string objects created by both the mechanisms are immutable objects. Once the string
object is created which we cannot modify the content of the object, but the reference of the string
object can be modified.
String s1 = new String(“hai”);
s1 = new String(“bye”);

Difference between two mechanisms of creating string object?


1. String object created by new operator
i. location: The string object are created by using new operator then they are used in new
memory.
ii. Allocation: If we are storing string objects in heap memory then it will never verify
whether the heap contains objects with same content or not, it will always create a new object.
String s1 = new String(“hai”);
s1 = new String(“bye”);
String s2 = new String(“bye”);
Unreferenced Object:
If object does not have any live reference i.e., if an object is not pointed or
referenced by any vtariable then that object will be called as Unreferenced Object.
iii. Deallocation: If the heap memory contains unreferenced object then it will contain
garbage collector.

2. String object created by placing directly in “ ”:


i. location: If the string content is placed directly within “ ” then they are stored in string
content pool.
ii. Allocation: If string object are placed in string content pool then it will always verify
whether the string constant pool contains objects with same content or not. If available then refer
to the existing object otherwise create a new object.
String s1 = “hai”;
s2 = “bye”;
String s2 = “bye”;
iii. Deallocation: If string constant pool contains unreferenced object then it will be
deallocated by string constant pool when it is completely filled.
* If a string object is created by using new operator then the string object will be stored in both
heap memory location & string memory poll.
* But the reference will point to the object available in heap memory.
String str = new String(“hello”);

* If we create a string object by enclosing group of characters directly within “ ” then we store
only in string constant pool.

Methods of String Class:


1. int length():
This method will return the count of no of char available in a string.
Ex:
String str = new String(“java program”);
System.out.println(str);
System.out.println(str.length());
2. char charAt(int index):
This method will return a character available at specified index position.
Note: The index of a string begins from zero.
Ex:
String str = new String(“java program”);
System.out.println(str.charAt(1));
System.out.println(str.charAt(12));

3. String Concat(string):
This method can be used to append the contents of one string to another string.
Ex:
String s1 = new String(“java”);
String s2 = new String(“program”);
System.out.println(s1.concat(s2));
System.out.println(s1);
System.out.println(s2);
O/P: java program
java
program

4. int CompareTo(String):
This method can be used for comparing the unicode values of the characters
available in the string. This method will do the comparision by considering their case.
S1 < S2 -ve
S1 > S2 +ve
S1 == S2 0
5. int CompareToIgnoreCase(String):
This method can be used for comparing the unicode values of the characters
available in the string. This method will compare by ignoring their case.
Ex:
String s1 = new String(“A”);
String s2 = new String(“a”);
System.out.println(s1.compare(s2));
System.out.println(s1.compareToIgnoreCase(s2));
O/P: -32
0
6. boolean equals(String):
This method can be used for comparing contents of the strings by considering
their case.

7. boolean equalsIgnoreCase(String):
This method can be used for comparing contents of the strings by ignoring their
case.
Ex:
String s1 = new String(“ABCD”);
String s2 = new String(“abcd”);
System.out.println(s1.eqals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
O/P: false
True

8. boolean startswith(String):
This method can be used to check whether a string begins with specified string or
not.
9. boolean endswith(String):
This method can be used to check whether a string ends with specified string or
not.
Note: start with method & ends with methods are case sensitive.
Ex:
String s = new String(“java program”);
System.out.println(s.startswith("jav"));
System.out.println(s.startswith("JAV"));
System.out.println(s.endswith("ram"));
O/P: true
false
true
10. int indexOf(char):
This method will return the index of the first occurrence of the specified
character.

11. int lastindexOf(char):


This method will return the index of the last occurrence of the specified character.
Note: The index of method & last index of method will return -1, if specified character is not
available in the string.
Ex:
String s = new String(“java program”);
System.out.println(s.indexOf('a'));
System.out.println(s.indexOf('p'));
System.out.println(s.indexOf('t'));
System.out.println(s.lastindexOf('a'));
System.out.println(s.lastindexOf('p'));
System.out.println(s.lastindexOf('z'));
O/P: 1 5 -1 10 5 -1

12. string replace(char old, char new):


This method can be used for replacing all the occurrence of specified character
with new character.
Ex:
String s = new String(“java jug jungle”);
System.out.println(s.replace('j','b'));
O/P: bava bug bungle

13. string substring(int index):


This method will retrieve a part of string beginning from specified index position
upto the end of the string.

14. string substring(int index, int offset):


This method can be used to retrieve a part of string beginning from specified
index position upto the specified offset.
Note: The offset of a string represents a position of a character in a string.
* The offset starts from 1.
Ex:
String s = new String(“java program”);
System.out.println(s.substring(3));
System.out.println(s.substring(2,9));
O/P: va program
ava prog

15. string toLowerCase():


This method can be used to converting contents of string completely to lower
case.
16. string toUpperCase():
This method can be used to converting contents of string completely to upper
case.
Ex:
String s = new String(“java program”);
System.out.println(s);
System.out.println(s.toLowerCase());
System.out.println(s.toUpperCase());
O/P: java program
java program
JAVA PROGRAM

17. string trim(): leading trailing


This method can be used to remove the leading trailing space available in
a string.
Ex:
String s = new String(“java program”);
System.out.println(s+"bye");
System.out.println(s.trim()+"bye");

O/P: java program bye


java programbye

18. string inter():


This method can be used to refer an object available in string constant pool which
was placed at the time of object creation in heap memory.
Ex:
String s1 = new String(“program”);
String s2 = s1.intern();
System.out.println((s1));
System.out.println((s2));
* If any one of them is of string type it will perform concatenation.
* If both are of numeric type it will perform addition.

class Test{
public static void main(String[] args){
String str = "hello";
System.out.println(str);
System.out.println(str+1+2+3);
System.out.println(1+str+2+3);
System.out.println(1+2+str+3);
System.out.println(1+2+3+str);
System.out.println(str+(1+2+3));
System.out.println(1+str+(2+3));
System.out.println((1+2)+str+3);
System.out.println((1+2+3)+str);
}
O/P: hello
hello123
1hello23
3hello3
6hello
hello6
1hello5
3hello3
6hello

* The equals method is used for comparing contents of the string.


* The == operator will compare the reference (Address) of the string.
Ex: class Test{
public static void main(String[] args){
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = ("hello");
String s4 = ("hello");
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s3.equals(s4));
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s3==s4);
}
}
O/P: true
true
true
false
false
false
String Buffer
* It is a predefined class used for storing group of characters similar to string class.
* The string buffer objects can be created only in one mechanism i.e., by using new operator.
Syntax: String Buffer sb = new StringBuffer(“welcome”);
* The string buffer class objects are immutable objects i.e., the string buffer object content can
be modified.
String Buffer sb = new StringBuffer(“hai”);
sb = new StringBuffer(“bye”);

Methods of String Buffer:


1. int length():
This method will return the count of no of characters available in string buffer.
Ex:
String sb = new StringBuffer(“welcome”);
System.out.println(sb);
System.out.println(sb.length());
O/P: welcome
7

2. StringBuffer append(xxx):
This method can be used for appending the specified existing string buffer
content.
Ex:
String sb = new StringBuffer(“java”);
System.out.println(sb.append(1.6);
System.out.println(sb.append("program"));
3. StringBuffer deleteCharAt(int index):
This method will delete available at the specified index position

4. StringBuffer delete(int index, int offset):


This method will delete group of characters beginning from the specified index
position upto the specified offset.
Ex:
String sb = new StringBuffer(“java1.6program”);
System.out.println(sb.deleteCharAt(5);
System.out.println(sb.delete(4,10);
O/P: java16program
javaram

5. String substring(int index):


This method can be used for accessning or retrieving a part of string buffer
beginning from index upto the end of the string buffer.

6. String substring(int index,int offset):


This method can be used for retrieving a part of string beginning and upto
specified offset.
Ex:
String sb = new StringBuffer(“java1.6program”);
System.out.println(sb.substring(4));
System.out.println(sb.substring(3,7);
O/P: 1.6program
a1.6
6. StringBuffer insert(int index, int xxxx):
This method can be used for inserting specified content in specified index
position.
Ex:
String sb = new StringBuffer("program”);
System.out.println(sb.insert(0,"java"));
System.out.println(sb.insert(4,1.6);
O/P: javaprogram
java1.6program

8. StringBuffer replace(int index, xxxx):


This method can be used to replace group of characters beginning with specified
index position upto the specified offset with specified string.
Ex:
String sb = new StringBuffer("java1.6program”);
System.out.println(sb.replace(0,4"oracle"));
O/P: oracle1.6program

9. StringBuffer reverse():
This method can be used for reversing contents of string buffer.
Ex:
String sb = new StringBuffer("java1.6program”);
System.out.println(sb.reverse());
O/P: margorp6.1avaj
OOPS
Object Oriented Programming Concept:
An application developed in any language has to use one of the following concepts.
1. Procedure Oriented Programming Concepts
2. Object Oriented Programming Concepts
1. Procedure Oriented Programming Concepts:
The applications that are developed by using the concept of procedure or functions are
said to use procedure oriented programming concepts.
Examples of using POPC:
C, COBOL, FORTRAN, PASCAL follow popc.
Drawbacks (or) Limitations for Procedure Oriented Language:
* The application that are developed by using popc are difficult to maintain and debugging of the
application will take more time.
* The procedure oriented programming language gives more importance to the functions than to
the data.
* The application that are developed by using popc does not provide security to the data.
* The data available in the application developed by popc is open and they are accessible to the
entire application which is not suitable for developing distributed applications.
* The application that are developed by using popc are difficult to enhance.
* The procedure & functions used in procedure oriented language are the fundamental entities
for developing the application. The design of these fundamental entities is very week & they are
not suitable for developing complex & real time applications.
Note: The procedure oriented programming languages are also called as structured programming
languages.

2. Object Oriented Programming Concepts:


The applications that are developed with the help of classes and objects are said to use
object programming concepts.
Examples of using OOPC:
Java, C++, Python, .Net etc.,
Object:
Any entity that exists physically in the real world which requires some memory is called
an object.
* Every object contains some properties & actions. The properties will describe the object and
they are represented by variables.
* The actions are the tasks performed by the object and they are described by the methods.

Class:
A class is a specification of common properties & common actions of group of objects.
* A class can be considered as model or a plan or blueprint for creating the object.
* Without a class object creation is not possible.
* For every class we can create any no of objects. Even though C++ is an object oriented
programming language according to the programming language experts it is called partial object
oriented programming language because of following reasons.
i. In a C++ application we can write some code inside the class & outside the class.
ii. In a C++ language we can develop application without using any of the object oriented
programming concepts.
iii. In a C++ application using the concept of friend function we can violate any level of security.
iv. All the object oriented programming concepts are derived from the real world from the
human being lives so that the programmer understands the concept easily & implementation of
that concept will not be difficult.
v. The design of the oopc is very strong & they can be used for developing real time complex
application.
The various object oriented programming concepts are
1. Encapsulation
2. Abstraction
3. Inheritance
4. Polymorphism
1.Encapsulation:
The process of binding the variables & methods into a single entity is called as
encapsulation.
* We can achieve encapsulation in java program by using a class.
* Using encapsulation we can improve maintainance of application.
* Using encapsulation we can also achieve data hiding.
* Using encapsulation we can separate or isolate members from one class to another class.

2. Abstraction:
The process of hiding some information & presenting the required information is
called as abstraction.
* Using abstraction we achieve security i.e., we can protect the data from unauthorized usage.

3. Inheritance:
The process acquiring the members from one class to another class is called as
inheritance.
* Using inheritance we can achieve reusability, which will reduce the development time of the
application.

4. Polymorphism:
If a single entity shows multiple behaviors then it is called polymorphism.
* Using polymorphism we can achieve flexibility where a single entity can perform different
operations according to the required.

Class:
A class is a user defined data type using which we can store any no of values.
Syntax for declaring a class:
Class<className>{
datatype variable1;
datatype variable2;
datatype variable3;
returntype methodName1(parameters){
statements
}
returntype methodName1(parameters){
statements
}
:
}

* A class is a collection of variable & methods.


* A class can contain any no of variables & methods.
Student.java:
Class Student{
int rollno;
double marks;
string name;
void display(){
System.out.println(“rollno:”+rollno);
System.out.println(“marks:”+marks);
System.out.println(“name:”+name);
}
Public static void main(String[] args)
Student S=new student();
S.display();
}
}
* When we compile a java program the compiler will check whether the java code is valid (or)
not, if valid the compiler will generate a (.class) file.
* The (.class) file generated by the compiler will be given to the JVM for execution.
* The JVM will begin the execution from “main” method.
* In the above program student s=new student(); will create an object of student class.
* Creating an object means allocating memory for the instance variables of the class.
Instance Variables:
If a variable is declared inside the class & outside the methods, then those
variables are called as instance variables.
* If an instance variable is declared & not initialized then they will initialize automatically with
default values of that type.

Default Values
byte - 0
short - 0
int - 0
long - 0
float - 0.0
double - 0.0
char - space
boolean - false
string - null
student - null
Any class – null
It is the responsibility of the JVM for calling the main method & execution begins
from main method.
* If the class contains other methods then it is the responsibility of the programmer to call other
methods.[s.display()]
O/P: rollNo : 0
marks : 0.0
name : null
* Every class in java language will be represented in the form of a class diagram. A class
diagram will be represented in rectangular shape, divided into multiple partitions (3) as follows.

* Every class can contain variables & methods which are called as members of a class.
Variables:
The purpose of variable is to store (or) hold some data (or) value. A java program can
contain any number of variables.
* The declaration of the variables in a java program is dynamic i.e.,we can declare the variables
anywhere in the class.
* The java language is said to be strongly typed language. Any language can be said to be
strongly typed language if the variables are first declared & then used & the compiler for type
compatibility.
int x = 12; //valid
int x = true; //invalid incompatable
Methods:
The purpose of a method is to perform some task/operation.
* A java program can contain any no of methods. Inside the method, we can specify any no of
statements.
Syntax: returntype methodName(list of parameters){
Statements
}
* Every method available in a program will be divided into two parts.
1. Method Declaration/Header/Prototype
2. Method Definition/Body/Implementation
1. Method Declaration/Header/Prototype:
The method declaration includes three parts & they are
1 2 3
returntype methodName (list of parameters)
* The returntype & methodName is mandatory whereas the list of parameters is optimal. We can
pass any number of parameters & they can be of any type separated by a comma symbol.
* The return type of a method must be specified just before the method name.
* If we do not want the method to return any value then the return type of the method must be
specified as void. If we want the method to return a value then we should not specify the return
type as void. In that location, we can specify any datatype.
2. Method Definition/Body/Implementation:
The method definition includes a group of statements specified within the flower
braces.
{
Statements
}
* The method definition can contain any no of statements.
* If the method definition doesn’t contain any statements, then we call such kind of methods as
empty definition (or) null implementation.
* If the method declaration contains return type as void, then we must not specify return
statement in the method definition. But if the return type is not void, then we must specify return
statement in the method definition.
Syntax: return value;
Ex: return 123;
return 12.3;
return true;
return ‘d’;
return “hello”;
* The return statement will be generally specified as the last statement in the method definition
but it can be specified anywhere in the definition.
* A method can return atmost one value.
Types of methods:
1. Methods without returntype & without parameters:
class Addition {
void add {
int x = 12;
int y = 13;
int z = x+y;
System.out.println(“ sum of ” +x+ ”and” +y+ “is:” +z);
}
Public static void main(String[] args){
Addition a = new Addition();
a.add(); //method invocation (calling add method)
}
}

2. Methods without returntype & with parameters:

class Addition{
void add(int x, int y){
System.out.println("sum of"+x+ "and" +y+ "S:" +(x+y));
}
Psum(String[] arr){
Addition a = new Addition();
a.add(2,3);

(or)
Addition a = new Addition();
int m = Integer.parseInt(arr[0]);
int n = Integer.parseInt(arr[1]);
a.add(m,n);
}
}
3. Methods with returntype & without parameters:

class Addition {
int add() {
int x = 10;
int y = 20;
int z = x+y;
}
public static void main(String[] args){
Addition ad = new Addition();
int res = ad.add();
System.out.println("sum is:"+res);
}
}

4. Methods with returntype & with parameters:

class Addition{
int add(int x, inty){
return(x+y);
}
Psum(String[] arr){
Addition ad = new Addition();
int res = ad.add(3,4);
System.out.println("sum is:" +res);
res = ad.add(5,6);
}
}
 Why should we write logic in separate methods?
When we write the logic in separate methods we will be able to achieve Modular
Approach. Using the modular approach we can achieve reusability & reduce the development
time.

Recursion:
Recursion means calling the same method itself multiple times then we call it as
recursion & that method is called as recursive method.
class Factorial{
int fact(int n){
if(n == 1)
return 1;
int f=1;
f = n * (fact(n-1));
return f;
}
psum(String[] ar){
factorial f = new factorial();
for(int i=1;i<=10;i++){
int res = f.fact(i);
System.out.println(i+"!=" +res);
}
}
}
Java stack if n = 6 (6!)

Program to pass an array as a parameter:

class Sample{
void display(int[] nos){
for(int x: nos)
System.out.println(x);
}
Psum(String[] arr){
Sample S = new Sample();
int[] arr1 = {10,20,30,40,50};
S.display(arr1);
int[] arr2 = {100,200,300,400};
S.display(arr2);
}
}
Program to pass an object as a parameter to a method:
class Student{
int rollNo = 12;
double marks = 99;
}
class Display{
psum(String[] arr){
Display d = new Display();
Student S = new Student();
d.Show(S);
}
void show(Student Stu){
System.out.println(Stu.rollNo);
System.out.println(Stu.marks);
}
}
Constructors:
If a variable is declared inside the class & outside the methods then such kind of
variables are called as instance variables.
* If any instance variable is declared & not initialized then it will be automatically initialized
with default values.
* If we do not want the default values, then we can initialize the instance variables with our own
values in the following two locations.
1. At the time of declaration.
2. By using the constructor.
Constructor:
A constructor can be considered as a special method whose purpose is to initialize
the instance variables.
Rules:
* The name of the constructor name must be same as that of class name. (i.e., classname &
constructor name must be exactly same).
* A constructor should not contain any return type, not even void.

Note: If we specify a return type before the constructor then the code is valid but it will be
considered as a method not a constructor.
* A constructor can be executed at the time of object creation.
* A constructor will be executed one time for one object. (It create 10 objects, 10 times
constructor will be executed)
* A constructor can have parameters based on the no of parameters, constructors are classified
into two types.
1. Zero parameterized Constructor/Default Constructor.
2. Parameterized Constructor.

1. Zero parameterized Constructor:


If a constructor doesn’t contain any parameters, then we call it as zero
parameterized Constructor.
Syntax: class<ClassName>{
<className>{
}
}
2. Parameterized Constructor:
If a constructor contains some parameters, then we call it as parameterized
constructor.
Syntax: class<ClassName>{
<className>(list of parameters){
}
}
* To a parameterized constructor, we can pass any no of parameters which can be of any type
separated by comma.

** Every class in java will contain a constructor whether we specify (or) not.
** If the programmer does not specify any constructor then the compiler will provide a zero
parameterized constructor.

Note: compiler can never provide a parameterized constructor.

class Sample{
int x; //declared but not initialized
int y=10; //declared & initalized at the time of declaration
int z; //declared & intialized by using constructors
Sample(){
z=10;
}
void Show(){
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
Psum(String[] ar){
Sample S=new Sample();
S.show();
}
}
Psum(String[] ar){
Sample S=new Sample();
S.Show();
}
}
O/P: 0 10 20

int add(int []) //add all elements in array


int min(int []) //smallest element in array
int max(int []) //biggest element in array

Instance Variables:
If a variable is declared inside the class & outside the methods, then it is called as
instance variable.
* For every class, we can create any number of objects and every object will contain its own
copy of the instance variable.

* If an instance variable is declared & not initialized, then it will be automatically initialized with
default values.
* If we do not want the default values, then we can initialize the instance variables with our own
values, either at the time of declaration (or) by using any constructor.
* If we want all the instances(objects) to contain instance variables with same values then
initialize the instance variable either at the time of declaration (or) by using a zero parameterized
constructor.
* If we want all the instances (objects) to contain instance variables with different values then
initialize the instance variables by using a parameterized constructor.
“this” Keyword:
“this” keyword can be used to refer to the current instance (object) of the class.
* Using “this” keyword we can access the instance members (Variables & Methods) of the class.

Local Variables:
The variable which is declared inside the class & inside the blocks (Methods and
Constructors), then it is called as local variables.
* If there is no confusion between instance variable & local variable then specifying “this”
keyword is optional. In such case, if we do not specify “this” keyword before the variable so that
it refers to the instance variable.
* If there is confusion between instance variables & local variables then specifying “this”
keyword is mandatory. In such case, if we do not specify “this” keyword, compiler will not
specify “this” keyword then it gives preference to local variables.
* If we want to refer to the instance variable then the programmer has to explicitly specify “this”
keyword before the variable so that it refers to the instance variable.

class Student{
int rollNo;
Student(int rollNo){
this.rollNo = rollNo;
}
void display(){
System.out.println(this.rollNo);
}
Psum(String[] ar){
Student S1 = new Student(123);
S1.display();
Student S2 = new Student(456);
S2.display();
Student S3 = new Student(789);
S3.display();
}
}

Static Keyword:
* If an instance variable is declared in a class, then the memory for that instance variable will be
allocated one time for each object.
* If we do not want to allocate memory for a variable one time for each object then declare that
variable as “Static” i.e., preceed the instance variable declaration by “Static” keyword.
** If a static variable is declared then the memory for that variable will be allocated at class
loading time.
** The memory for the static variable will be allocated in method area.
** The memory for the static variable will be allocated only one time for the entire class.
All the objects of the class will share the same copy of the static variable. We can declare
both the variables & methods of a class as “Static” and they are together called as “Static
members”. The static members are also called as class members.
Syntax for Static Variable:
Static datatype varname;
Syntax for Static Method:
Static returntype methodName(list of parameters)
{
Statements
}
* The instance members(instance variables & static methods) of the class can be accessed only
by using reference variable.
* The static members(static variables & static methods) of the class can be accessed either by
using the reference variable (or) by using a classname.
* It is recommended always access the static members by using class name because we cannot
guarantee the existence of an object.

class Employee{
int empNo = 1234;
static int compcode = 2222;
psum(String[] args){
Employee e = new Employee();
System.out.println(e.empNo);
System.out.println(e.compcode);
System.out.println(Employee.compcode);
}
}

Rules:
* An instance methods can access both instance variables & static variables.
* A static method can access only static variables.
Ex: class Sample{
int x = 11;
Static int y = 22;
void show(){
System.out.println(x);
System.out.println(y);
}
Static void display(){
System.out.println(x);
System.out.println(y);
}
Psum(String[] ar) {
Sample S = new Sample();
S.Show();
Sample.display(); // (or) S.display();

* If the instance variables & static variables are not initialized, then they will be initialized
automatically with default values.
* For a static variable if we do not want the default value then we can initialize the same variable
without own value only at the time of decalaration.

Ex: class Sample{


int x;
Static int y;
Psum(String[] args){
Sample S1 = new Sample();
S1.x++;
S1.y++;
System.out.println(S1.x+” ”+S1,y);
Sample S2 = new Sample();
S2.x++;
S2.y++;
System.out.println(S2.x+” ”+S2,y);
Sample S3 = new Sample();
S3.x++;
S3.y++;
System.out.println(S3.x+” ”+S3,y);
}
}
O/P: 1 1
22
33

class Student {
int m1, m2, m3;
Student(int int int)
main()
}
class result{
int calculatetotal(Student S)
}
Rules for accessing instance & static members:

* An instance method can access members (Instance variables & Instance methods) directly
provided if they belong to same class otherwise they must be accessed only by using reference
variable(object).
* An instance method (or) access static members (static variables & static methods) directly
provided they belong to same class otherwise they must be accesed either by using reference
variable (or) classname.
* A static method can access static members (static variables & static methods) directly provided
if they belong to same class otherwise they must be accessed either by using reference varaiable
(or) class name.
* A static method can access instance members (instance variables & instance methods) only
using reference variable object whether they belong to the same class (or) different class.

Ex: Class Access1{


int x = 11;
static int y=22;
void m1(){
System.out.println("Instance method m1");
}
void m2(){
System.out.println(x); //Rule1
m1(); //Rule1
System.out.println(y); //Rule2
m3(); //Rule2
System.out.println("Instance method m2");
}
Static void m3(){
System.out.println("Static method m3");
}
Psum(String[] args){
Access1 a=new Access1();
System.out.println(a.x); //Rule4
a.m2(); //Rule4
System.out.println(a.y); //Rule3
m3(); //Rule3
}
}
O/P: 11
11
Instance method m1
22
Static method m3
Instance method m2
22
Static method m3
Class Access1{
void m4(){
Access1 c=new Access1();
System.out.println(x); //Rule1
c.m1(); //Rule1
System.out.println(c.y); //Rule2
Access.m3(); //Rule2
System.out.println("Instance method m4");
}
Psum(String[] args){
Access2 a=new Access2();
b.m4(); //Rule4
Access1 d=new Access1();
System.out.println(Access1.y); //Rule4
d.m3(); //Rule4
System.out.println(d.x); //Rule3
d.m2(); //Rule3
}
}
O/P: 11
Instance method m1
22
Static method m3
Instance method m4
22
Static method m3
11
11
Instance method m1

Explain public static void main(String[] args)

Public: (Access Specifier)


The main method has to be declared as public so that it can be accessed by any
class from any location.
Static (Modifier)
The main method has to be declared as static so that it can be accessed directly by
using class name, we did not create an object for accessing.
Void:
The JVM is responsible for executing the main method & it doesn’t expect any
value from the main method & therefore the return type must be void.
main:
It’s the name of the method which is a valid java identifier.
String[] args:
It is used for storing command line arguments & we can store any no of values,
the type of the array must be string only so that we can store any type of values.
Note: The name of the string array can be any valid java identifier.
* If a declaration contains multiple modifiers then we can specify them in any order (or)
sequence.

Static public void main(String[] args) //valid


Public static void main(String[] args) //valid
Class Employee{
int bsal;
Employee(int)
}

class calculate{
int netSalary(Employee)
}
class Display(){
main()
C.netSal();
}

Explain System.out.println(); :
“System” is a predefined class available in java.lang package.
“out” is a reference variable of printstream class referring to an object of print stream
class declared as “static” in system class.
“println” is a predefined instance method available in printstream class.
PrintStream is a predefined class available in java.io package.
* To access the “println” method we require an object of printstream class which is already
created & placed in system class.
“out” reference variable can be accessed directly by using class name because “out” is
declared as static(System.out)
“System.out” will provide the object of printstream class using which we can access
“println” method.
Predefined code:
java.lang
class System{
Static printStream out = new printSream();
}

java.io
class printStream{
void println() {
}
}
The reference variable of any class can be declared as either instance (or) static (or) local.
Ex: class Sample{
Sample S1 = new Sample(); //instance reference variable
Static Sample S2 = new Sample(); //static reference variable

void m1(){
Sample S3 = new Sample(); //local reference variable
}
}
 S1 is instance reference variable
S2 is static reference variable
S3 is local reference variable

Local Variables:
If variable is declared inside the class & inside the blocks (methods (or)
constructors) then that variable is called as local variable.

Allocate the memory for local variables in three ways:


* The memory for local variables will be allocated at the time of method (or) block invocation.
* The memory for local variables will be allocated in java stack.
* The memory for local variables will be allocated one time for every invocation.
Note: The scope (or) life of a local variable is limited to that block in which it is declared.
If an instance variable is declared & not initialized then the instance variable will be
automatically initialized with default values. If we do not want the default values, then we can
initialize the instance variables with our own values in the following two ways.
(1) At the time of declaration
(2) By using constructor
If a static variable is declared & not initialized then the static variable will be initialized
automatically with default values. If we do not want the default values, then we can initialize the
static variables without own values only at the time of declaration.
If a local variable is declared & not initialized then the local variable will NOT be
initialized automatically with default values. It is the responsibility of the programmer to
initialize the local variable either at the time of declaration (or) anywhere before using it.

class Sample{
int x = 10;
static int y = 20;
void Show(){
int z=30;
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
Static public void main(String[] args){
Sample S = new Sample();
S.show();
}
}
O/P: 10
20
30
class product{
product(int price){
}
}
class Sample{
getproduct(int price)
class product{
int price;
product(int price)
{
this.price = price;
}
int calculateTotal(int quant){
return 120;
}
}

Final Keyword:
The purpose of a variable is to hold (or) store a value. The value of a variable can be
changed any number of times during the program execution.
* If we do not want to change the value of a variable i.e., if we want to fix the value of a variable
then we take the help of “final” keyword.
* By declaring the variables as “final” we are creating constants in java language.
Syntax: final datatype variable = value;
Ex: final double PI = 3.14;
The final keyword can be applied to instance variables, static variables, local variables,
parameters & reference variables.
Instance variables:
If an instance variable is declared & not initialized then it will be initialized automatically
with default values. If we do not want the default values, then we can initialize the instance
variable without own values either at the time of declaration (or) by using a constructor.
Final Instance variables:
If an instance variable is declared as ”final” & not initialized then that variable will not be
initialized automatically with default values. It is the responsibility of the programmer to
initialize final instance variable explicitly either at the time of declaration (or) by using
constructor.
Ex: class Sample{
final int a; //Invalid : Variable 'a' might not have been initialized
final int b=22; //valid : initialized at the time of declaration
final int c; //valid : initialized using constructor
Sample (){
c=33;
}
}

Static Variable:
If a static variable is declared & not initialized then it will be initialized automatically
with default values. If we do not want the default values then we can initialize the static variable
without own values at the time of declaration only.
Final Static Variable:
If a static variable is declared as “final” & if it is not initialized then it will not be
initialized automatically with default values. It is the responsibility of the programmer to
initialize final static variable explicitly at the time of declaration only.

Ex: class Sample{


final int a; //Invalid: Variable 'a' might not have been initialized
Static final int b=22; //valid: declared & initialized at the time of declaration
final int c; //Invalid: declared & initialized using constructor
Sample (){
c=33;
}
}

Local Variable:
If a local variable is declared & not initialized automatically with default values.
It is the responsibility of the programmer to initialize the local variable at the time of declaration
(or) before using it.

Note: If a local variable is not used then it need not be initialized.

Final local variable:


If a local variable is declared as final & not initialized then it will not be initialized
automatically with default values. It is the responsibility of the programmer to initialize final
local variable either at the time of declaration (or) before using it.

class Sample{
Psum(String[] args){
final int a=11; //valid
final int b; //valid
final int c; //Invalid: declared & not initialized using it
final int d; //valid: declared & not initialized & not using it
b = 22;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
Parameters:
* The parameters are the values that are passed to a method (or) constructor.
* The parameters of a method (or) constructor has same scope (or) life as that of the local
variable.
* The parameters of a method (or) constructor will be initialized when they are involved with the
values that are passed.
* The value of a parameter can be changed any number of times within the method (or)
constructor.
* If we do not want to change the value of a parameter then we can declare the parameter as
“final”.
class Rectangle{
void area(int len, final int bre){
System.out.println("Area :" +(len*bre));
len=5;
System.out.println("Area :" +(len*bre));
}
}
Psum(String[] args){
Rectangle r = new Rectangle();
r.area(3,4);
}
}
O/P: Area: 12
Area: 20
Reference Variable:
A variable said to be a reference variable if it is pointing to (or) referring to an object of a
class.
* If a reference variable is declared as final then it cannot refer (or) point to another object.
* If a reference variable is declared as final then the content of that object referred by the
reference variable can be changed or modified.
Ex: class Sample{
int x = 10;
int y = 20;
psum(String[] args){
final Sample S = new Sample();
//S = new Sample();
System.out.println(S.x+” ”+S.y);
S.x = 30;
S.y = 40;
System.out.println(S.x+” ”+S.y);
}
}
Reflections
* It is a process of examining (or) checking (or) introspecting a class in a java program.

* Using Reflections, we can access the class information during the execution of the program.

* All the classes related to reflections are available in java.lang.reflect package.

Ex: import java.lang.reflect.*;

class Student{

class Employee extends Student{

public int empid = 123;

public int rating = 5;

public Employee(){

public Employee(int x){

public void m1(){

public void m2(){

class Sample{

Static Object getObject(){

return new Employee();

psum(String[] args)throws ClassNotFoundException{

Object o = getObject();

Class c = o.getClass();
//Class c = Class.forName("Employee");

System.out.println(c.getName());

System.out.println(c.getPackage());

System.out.println(c.getSuperClass());

Field[] f = c.getFields();

for(Field x:f){

System.out.println(x);

Constructor[] cons = c.getConstructor();

for(Constructor x:cons){

System.out.println(x);

Method[] m = c.getMethods();

for(Method x:m){

System.out.println(x);

}
INHERITANCE

It is the process of acquiring the members from one class to another class.
* The class that provides (or) gives the members that is called parent class/Super class/Base
class.
* The class that takes the members will be called as child class/sub class/derived class.
* Using inheritance, we can achieve re-usability, using which we can reduce the code size &
reducing development time.

The java language supports two types of inheritance.


1. Single level Inheritance:
If an inheritance contains one parent class & one child class then it is called as single
level inheritance.
Ex:

2. Multi level Inheritance:


If an inheritance contains one parent class & one child class & one (or) more intermediate
classes then it is called as multilevel inheritance.
Ex:
* Java language doesn’t support multiple inheritance.
Multiple Inheritance:
If a class inherits from two (or) more classes then it is called as multiple inheritance.

* Why doesn’t java language support multiple inheritance?


If both parent classes contain same members then it will be confusion to the child class
whether it has used from either 1st parent (or) from 2nd parent. To avoid this confusion we don’t
support multiple inheritance.
To achieve inheritance concept we take the help of “extends” keyword.
Syntax:
Class <parent class>{
}
Class <child class> extends <parent class>{
}
Ex: class Teacher{
}
Class Student extends Teacher{
}

class diagram showing Inheritance:


Ex: class Cone{
int x = 10;
void show() {
System.out.println("Cone class show method");
}
}
class Ctwo extends Cone{
int y = 20;
void display(){
System.out.println("Ctwo class display method");
}
}
class Inheritance{
psum(String[] ar){
Ctwo c = new Ctwo();
System.out.println(c.y);
c.display();
System.out.println(c.x);
c.show();
}
}
* Using the child class object we can access both child class members & parent class members
but we are using parent class object we can access only parent class members.

The object class is called as the “Supermost” class in java language. Every class in java
either user defined class (or) predefined class will be sub-class to object class either directly (or)
indirectly.

Ex:

When a class is compiled, the compiler checks whether the class is extending from any
other class (or) not.
* If the class is already extending from other class then the compiler not add any extends
keyword.
* If the class is not extending from any other class then the compiler will automatically place
extends keyword & makes that class as sub-class to object class.
* Every class in java either pre (or) user defined can access the members of object class.
When we create an object of any class it involves the constructor of that class. Before
executing that class constructor it checks whether the class is extending or inheriting from any
other class (or) not. If it is inheriting from another class then before executing child class
constructor it execute parent class constructor & this process will be continued until it reaches
the object class.
* The invocation of the constructor will be in the order of child to parent & the execution will be
parent to child.
Ex:
class Cone{
Cone(){
System.out.println("Cone Constructor");
class Ctwo extends Cone{
Ctwo(){
System.out.println("Ctwo Constructor");
}
class Cthree extends Ctwo{
Cthree(){
System.out.println("Cthree Constructor");
}
class Inheritance{
psum(String[] ar){
Cthree c = new Cthree();
}
}
Super Keyword:
The super keyword can be used or refer to access instance members of the parent class
(Instance variable, Instance method)
If there is confusion between current class instance variable & local variable then the
compiler will not place “this” keyword automatically & it is refer to local variable. In such case
we want to access instance variable then the programmer has to explicitly specify “this”
keyword.
If there is a confusion b/w parent class instance members & child class instance members
then the compiler will place “this” keyword & if refers to child class (or) current class instance
variable. In such case if we want to access parents class instance variable then the programmer
has explicitly specify “Super” keyword.
** When there is no confusion b/w instance variables & local variables then the compiler will
automatically place this keyword.
The compiler will never provide super keyword whether the parent class instance variable
& child class instance variable have confusion (or) not.
Super keyword can be used to refer to the instance members of only its parents. Super
keyword will work for only one level.
Ex:
class Cone{
int x = 10;
int z = 20;
}
class Ctwo extends Cone{
int x = 12;
int y = 45;
}
class Cthree extends Ctwo(
int x = 23;
int a = 30;
void show(){
int x = 34;
Cone c1 = new Cone;
System.out.println(c1.x);
System.out.println(Super.x);
System.out.println(this.x);
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(a);
}
}
class Inheritance{
Psum(String[] ar){
Cthree c = new Cthree();
C.show();
}
}
Relationships:
1. Is-A Relationship:
A class inherits from another class.
2. Has-A Relationship:
If a class contains object of another class.
Types of Relationships:
If a class is inheriting from another class then it is said to be Is-A Relationship.
Ex: class vehicles {
}
Class car extend vehicle{
}
 car Is-A vehicle
class House {
}
Class hut extend House{
}
2. Has-A Relationship:
If a class contains an object of another class then it is called as Has-A
Relationship.
Ex: class Engine{
}
class car{
Engine object
}
 Car Has-A Engine.
In java language, we can achieve reusability using Is-A (or) Has-A Relationship.
Polymorphism
If a single entity shows multiple behaviors then it is called as polymorphism.
* Using polymorphism we can achieve flexibility where a single entity can perform different
operations depending upon the requirement.
 There are two types of polymorphism.
1. Compile Time Polymorphism:
If the polymorphism nature of an entity is decided by compiler during the compilation
time then it is called as compile time polymorphism.
* To achieve the compile time polymorphism we take the help of concept called “Method
Overloading”.
Method Overloading:
It is a process of writing multiple methods (or) two or more methods with the same
method having different signature is called method overloading.
Method Signature:
The method signature includes four parts. They are
1. Method Name
2. No of Parameters
3. Types of Parameters
4. Order of Parameters
**Note:
The method signature doesn’t include return type of the method & the parameter
names.
In method overloading, the methods must have same name with either different no of
parameters (or) different order of parameters such kind of method called as Overloaded
Methods.
Ex: add(int x, int y)
add(int x, int y, int z)

add(int x, int y)
add(double x, double y)
add(int x, double y)
add(double x, int y)

add(double x, char y)
add(boolean x, int y,String s)

add(int x, int y)
sub(int x, int y)

add(int x, int y)
add(int a, int b)
Note:
A class can contain any no of methods. Every method can contain different signature.
API: E:\softwares\JSE API\docs\apI\index.html.
Ex: class Addition {
void add(int x, int y){
System.out.println("sum1:" +(x+y));
}
void add(int x, int y, int z){
System.out.println("sum2:" +(x+y+z));
}
void add(int x, double y){
System.out.println("sum3:" +(x+y));
}
void add(double x, int y){
System.out.println("sum4:" +(x+y));
}
psum(String[] args){
Addition ad = new Addition();
}
}
Ex: class Addition {
void add(int x, int y){
System.out.println("sum1:" +(x+y));
}
void add(int x, int y, int z){
System.out.println("sum2:" +(x+y+z));
}
void add(int x, double y){
System.out.println("sum3:" +(x+y));
}
void add(double x, int y){
System.out.println("sum4:" +(x+y));
}
psum(String[] args){
Addition ad = new Addition();
a.add(1,2);
a.add(1,2,3);
a.add(1,2.3);
a.add(1.2,3);
}
}
O/P: sum1: 3
sum2: 6
sum3: 3.3
sum4: 4.2

* When a program is compiled the compiler will perform linking (or) binding of method
invocation with method definition. Since the decision is taken by the compiler during
compilation time it is called as Compile time polymorphism.
* Once the binding is performed by the compiler it cannot be changed & therefore it is called as
static binding.
* Since the binding is performed before the execution of the program it is called as early binding.

Overloading of static methods:


class Sample{
Static void show(int x){
System.out.println(x);
}
Static void Show(double x){
System.out.println(x);
}
psum(String[] args){
Sample.Show(1);
Sample.Show(1.2);
}
}
O/P: 1
1.2

Overloading of main methods:


class Sample{
psum(String[] args){
System.out.println("string array");
main("valid");
main(12);
int[] arr = {1,2,3,4};
main(arr);
}
public static void main(String[] args){
System.out.println("string variable");
}
public static void main(int arr){
System.out.println("int array");
}
public static void main(int arr){
System.out.println("int variable");
}

}
O/P: string array
string variable
int variable
int array
* Method overloading can be implemented in one class (or) in two different classes that have “is-
a” relationship.

class Sample{
void show(int x){
System.out.println(x);
}
}
class test extends Sample{
void show(double x){
System.out.println(x);
}
}
Runtime Polymorphism:
The polymorphism nature of an entity that is decided by JVM at execution time (or)
runtime then it is called as runtime polymorphism.
* To achieve runtime polymorphism we take the help of a concept Method Overriding.
Method Overriding:
It is a process of writing two methods with same signature & same returntype in two
different classes that have “is-a” relationship.
Ex: class Parent{
void show(){
System.out.println("Good Morning");
}
}
class child extends Parent{
void show(){
System.out.println("Good Night");
}
}
class Sample{
psum(String[] args){
Parent P = new Parent();
P.show();

child c = new child();


c.show();

Parent p1 = new child();


P1.show();
}
}
* When a program is executed the JVM will decide which method to be executed at runtime &
therefore called as runtime polymorphism.
* The JVM will decide which method has to be executed & then performs linking (or) binding of
the method invocation with the method definitions & therefore this binding is called as dynamic
binding.
* Since the binding is performed after the execution begins & after the object is created it is
therefore called as late binding.

* Why should we implement method overriding?


Child class doesn’t want parent class method implementation then the child will override
that method in the child class to provide new implementation.
Search(int[])
Search(String[])
* If method overriding concept is applied to staic methods then we call it as method overhiding.
* If method overriding can be applied to only instance methods & method overhiding can be
applied to static methods.
* Both the methods (i.e., parent class method & child class method) must be either instance (or)
static.
* Method overriding & method overhiding can be implemented in two different classes that have
“is-a” relationship.

Constructor Overloading:
It is a process of writing multiple constructors with the same name having different
signature. i.e., the constructors that have either different no of parameters (or) different type of
parameters (or) different order of parameters.

class Rectangle {
int len;
int bre;
Rectangle() {
len = 3;
bre = 3;
}
Rectangle(int x){
len = bre = x;
}
Rectangle(int x, int y)
this.len = len;
this.bre = bre;
}
void area(){
System.out.println("Area = "+(len*bre));
}
public static void main(String[] args){
Rectangle r1 = new Rectangle();
r1.area();
Rectangle r2 = new Rectangle();
r2.area();
Rectangle r3 = new Rectangle();
r3.area();
}
}
O/P: Area = 9
Area = 16
Area = 30
this keyword:
this keyword will refer to the current object(instance) of a class.
* Using this keyword we can access the instance members of a class. (variables & methods)
* If there is no confusion between instance variables & local variables then specifying “this”
keyword is optimal. If the programmer doesn’t specify “this” keyword then the compiler will
place “this” keyword automatically referring to the instance variable.
* If there is confusion between instance variables & local variables & if the programmer doesn’t
specify “this” keyword then in such case the compiler will not place “this” keyword & gives
preference to local variable.
* If we want to refer to the instance variable then the programmer has to explicitly specify “this”
keyword.
class Sample {
int x = 11;
int y =33;
void show(){
int x = 22;
System.out.println(this.x); //mandatory
System.out.println(x);
System.out.println(this.y); //optional
this.msg(); //optional
}
void msg(){
System.out.println("very good morning");
}
Static public void main(String[] args){
Sample S= new Sample();
S.show();
}
}
O/P: 11
22
33
very good morning
this():
this() can be used to refer to the zero parameterized constructor of the current class.
this(…):
this(…) can be used to refer to the parameterized constructor of the current class.

Rules for both this() & this(…):


* this() / this(…) can be used to invoke other constructor of the same class.
* The invocation of the other constructors of the same class by using this() / this(…) must be
specified as the first statement in a constructor.
* The invocation of the other constructors of the same class by using this() / this(…) must not
form a cycle/loop.
* Every constructor can invoke atmost one constructor (0 or 1).
this:
Purpose:
this can be used to refer to the instance members (variables & methods) of a class.
Where to use:
this keyword should be used either in instance methods (or) in constructors.
Note: this keyword should not be used inside static methods.

this() / this(…):
this() / this(…) can be used to refer to the other constructors of the same class. this() /
this(…) should be used only inside constructors to invoke other constructors of the same class.
class Sample {
Sample() {
this(4,6);
System.out.println("Sample Zero Constructor");
Sample(int x){
this();
System.out.println("Sample int Constructor");
}
Sample(int x,int y){
this();
System.out.println("Sample int int Constructor");
}
psum(String[] args){
System.out.println("Sample main method");
Sample S = new Sample(5);
}
}
O/P: Sample main method
Sample int int Constructor
Sample int Constructor
Sample Zero Constructor

Super Keyword:
The super keyword can be used to access the parent class instance members (variables &
methods).
* Specifying the super keyword is sometimes optional & sometimes mandatory.
* If there is no confusion between parent class instance members & child class instance members
& if we do not specify super keyword then compiler will not specify super keyword
automatically. The compiler will access both parent class instance members & child class
instance members by placing “this” keyword.
* If there is confusion between parent class instance members & child class instance members &
if we do not specify super keyword then compiler will automatically place this keyword & gives
preference to child class instance members.
* If we want to access the parent class instance members then it is the responsibility of the
programmer to specify super keyword to access the parent class instance members.
class Sample {
int x = 11;
int y = 13;
void show(){
System.out.println(x);
System.out.println(y);
}
}
class Sample extends Demo {
int x = 12;
int z = 14;
void show(){
System.out.println("super.x");
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
void display(){
super.show();
show();
}
Psum(String[] args){
System.out.println("Sample main method");
Sample S= new Sample();
S.display();
}
}
O/P:
Sample main method
11
12
11
12
13
14
Super():
Super() will refer to the zero parameterized constructor of the parent class.
Super(…):
Super(…) will refer to the parameterized constructor of the parent class.
Note:
When an object of a child class is created, the child class constructor will be invoked,
before executing the child class constructor the compiler will invoke the parent class constructor
by placing Super() in every child class constructor.
class Parent {
Parent() {
System.out.println("Parent Zero Constructor");
}
}
class child extends Parent{
child(){
Super();
System.out.println("Child Zero Constructor");
}
psum(String[] args){
child c = new Child();
}
}

O/P: Parent Zero Constructor


Child Zero Constructor
Rules:
* Every constructor can invoke atmost one constructor, either one current class constructor by
using this()/this(…) or one parent class constructor by using Super()/Super(…).
* The invocation of current class constructor by using this()/this(…) or parent class constructor
by using Super()/Super(…) then the compiler will automatically place Super() in every child
class constructor.

Super:
* Super can be used to refer to the parent class instance members from the child class.
* Super should be specified only in child class instance blocks (instance methods (or)
constructors of child class).

Super() / Super(…):
Super() / Super(…) can be used to refer to the parent class constructors from the child
class.
Super() / Super(…) should be specified only in child class constructors.
 Compiler can automatically specify either “this” keyword (or) “Super()”.
class Parent {
Parent() {
this(4,6);
System.out.println("Parent Zero Constructor");
Parent(int x){
this();
System.out.println("Parent para Constructor");
}
class Child extends Parent {
Child(){
this(5);
System.out.println("Child zero Constructor");
}
Child(int x){
Super(5);
System.out.println("Child para Constructor");
psum(String[] args){
Child S = new Child();
}
}

O/P: Parent Zero Constructor


Parent para Constructor
Child zero Constructor
Child para Constructor

Final Keyword:
The final keyword can be applied to variables, methods & classes.
* If a variable is declared as final, then the value of that variable cannot be changed i.e., final
variable are constants.
* If a method is declared as final, then that method cannot be overridden in the child class.
* A method has to be declared as final if we do not want the subclasses to modify the
implementation, by declaring a method as final, we are providing security to the method logic.
* Final methods can be accessed & used in child but cannot be modified.

Final class:
* If a class is declared as final then that class cannot be inherited.
* If we want to protect the implementation of a method then we declare that method as “final”. If
we want to protect all the methods of a class then we can declare all the methods as final (or)
declare the class as “final”.
* Declaring the class as final is exactly equivalent to declaring all the methods as final.
* In a final class, only the methods of that class are final but the variables of that class are not
final.
final class Cone {
}
class Ctwo extends Cone{
}
Error: Cone cannot be inherited because Cone class is declared as ”final”.
By declaring the class as final, we are restricting “is-a” relationship. The final class
members can be accessed in other class by using “has-a” relationship only.
final class Cone {
int x = 10;
void show() {
System.out.println("Good Morning");
}
}
class Ctwo{
psum(String[] args)
Cone c = new Cone();
c.Show();
System.out.println(c.x);
c.x = 20;
System.out.println(c.x);
}
}
O/P: Good Morning
10
20

Final Variables: Value cannot be changed.


Final Method: Final method cannot be inherited.
Final Class: Final class cannot be inherited.
Instance Block:
If we specify a group of statements enclosed within the flower braces without any
keyword then it is called as instance block.
Syntax: {
Statements
}
The purpose of an instance block is to initialize the instance variables.
* If an interface variable is declared & not initialized then it will be initialized automatically with
default values.
* If we do not want the default values then we can initialize the instance variable with our own
values in the following three locations only.
1. At the time of declaration
2. By using instance block
3. By using constructor
A class can contain any number of instance blocks & they can be specified anywhere in
the class.
* All the instance blocks will be executed in sequence from top to bottom, one time for every
object before the constructor is executed.

Procedure followed by JVM during object creation:


* When an object is created, the JVM will allocate memory for instance variables & executes the
instance blocks in sequence from top to bottom. (Instance variables & Instance blocks have same
precedence (or) preference).
* Once the memory for instance variables is allocated & instance blocks are executed then it
executes the constructor that is specified at the time of object creation.
Static Block:
* If we specify a group of statements enclosed within the flower braces along with ‘static’
keyword then it is called a static block.
Syntax: Static {
Statements
}
* The purpose of a static block is to initialize the static variables.
* If a static variable is declared & not initialized then it will be automatically initialized with
default values.
* If we do not want that default values then we can initialize the static variables with our own
values in the following two locations only.
1. At the time of declaration
2. By using static block
* A class can contain any number of static blocks & they can be specified anywhere.
* All the static blocks will be executed in sequence from top to bottom at the time of class
loading.
* Static blocks will be executed only one time.

Procedure followed by JVM during class loading time:


* The JVM will allocate memory for static variables & executes the static blocks in sequence
from top to bottom. (Static Variables & Static blocks have same preference)
* Once the memory for the static variables is allocated & the static blocks are executed, the JVM
will look for main method & then begin the execution from main method.
class Sample{
System.out.println("instance block1");
}
Static {
System.out.println("static block1");
}
Sample() {
System.out.println("Sample zero Constructor");
}
Sample(int x) {
System.out.println("Sample para Constructor");
}
psum(String[] args){
System.out.println("Sample main method");
Sample s1 = new Sample();
Sample s2 = new Sample();
}
{
System.out.println("instance block2");
}
Static {
System.out.println("static block2");
}
O/P: 1. static block1
2. static block2
3. Sample main method
4. instance block1
5. instance block2
6. Sample zero Constructor
7. instance block1
8. instance block2
9. Sample para Constructor

Ex 1: Program without main method:-


class Sample{
Static {
int a = 10;
int b = 20;
int c = a+b;
System.out.println("sum:"+c);
}
}
O/P: sum : 30
Ex 2:
class Sample{
Static {
int c = add(11,22);
System.out.println("sum:"+c);
}
Static int add(int x, int y){
return(x+y);
}
O/P: sum : 30
Literals:
Literal is a value that is stored into a variable.
int Literals:
If we specify a number either positive (or) negative without a decimal point will
be by default considered as “int literal”.
Ex: 123 0 12767 -456
The int literal can be stored into all numeric types (byte, short, int, long, float,
double, char) provided they are within the range of the numeric type.
Long Literal:
The long literal can be created indirectly by converting int literal to long literal by
suffixing lower case “l” (or) uppercase “L” to int literal.
Ex: 12L 68768L 0l -456l
The long literal can be stored into long, float & double types.
*Note:
The byte literal & short literal cannot be created. (i.e., not possible to create)
Integer Category:
Default Value = 0
Default type = int type

Double Literal:
The double literals can be created in two ways.
1. The double literal can be created directly by specifying a number either positive (or) negative
with decimal point.
Ex: 1.2 457.57 0.007 -12.99
2. The double literals can be created indirectly by suffixing lowercase “d” (or) uppercase “D” to
int literals.
Ex: 12D 68768D 0d -456d
Note: We can suffix “D” (or) “d” to double literals. (Numbers with decimal point)
Ex: 1.2d 457.57d 0.007d -12.99d
The double literals can be stored only into double type.
Float Literals:
The float literals can be created in two ways & both are indirect ways.
* The float literals can be created indirectly by suffixing lowercase “f” (or) uppercase “F” to
either double literals (or) to int literals.
Ex: 1.2f 457.57f 0.007F -12.99F
1.2F 68768F 0f -456f
The float literals can be stored into either float type (or) double type.
Floating point category:
Default Value: 0
Default type : double
Character Literals:
The character literals can be created by specifying exactly one character enclosed within
a single quote.
The character specified within the single quotes can be either alphabet (or) digit (or) any
special symbol.
Ex: ‘a’ ‘B’ ‘8’ ‘#’.
* The character literal can be stored into all numeric datatypes.
* The character literals can be created by using UNICODE format.

UNICODE format:
The UNICODE format must begin with “\” (back slash) followed by lowercase “u”
followed by exactly 4 digit hexadecimal number, enclosed in single quotes.
Format: ‘\uxxxx’ 0-9 a-f(A-F).
Ex: char a = ‘\nabcd’; //Invalid
char b = ‘\b1234’; //Invalid
char c = ‘\uface’; //valid
char d = ‘\ubad’; //Invalid
char e = ‘\uA1B2’; //valid
char f = ‘\uCAFE’; //valid
char g = ‘\Uabcd’; //Invalid
char h = ‘\u12345’; //Invalid
char i = ‘\u123’; //Invalid
char j = ‘\uaAbB’; //Invalid
char k = ‘\u0000’; //valid
Escape Sequences (or) Characters:
The escape sequences will provide a special meaning to the compiler & there are ‘8’
escape sequences is java.
\n \t \r \f \b \\ \’ \”
Note: Escape sequences should be specified only in lower case.
Ex: char a = ‘\n’; //valid
char b = ‘\b’; //Invalid
char c = ‘\u’; //Invalid
char d = ‘\N’; //Invalid
char e = ‘\r’; //valid
char f = ‘\p’; //Invalid
char g = ‘\a’; //Invalid
char h = ‘\T’; //Invalid
Default value of char: space (‘\u0000’)
Boolean Literals:
In java language, there are only two boolean literals & they are true & false.
* The boolean literals can be stored only into boolean types. (other types not possible)
Predefined literals of java:
1. true
2. false Both are stored into boolean types.
3. null can be stored into reference variable of any class.
Type Casting:
It is the process of converting a value from one datatype to another datatype
which is compatible.
* If both the types are same then we need not perform type casting.’
* To perform type casting both types must be different & they must be compatible.
Type casting can be performed in two ways.
1. Type casting with respect to primitive types.
2. Type casting with respect to Reference types.

1. Type casting with respect to primitive types:


It is the process of converting a value from primitive datatype to another primitive
data type which is compatible.
* The compatible primitive datatypes are: Byte, short, int, long, float, double, char.
* Type casting with respect to primitive types can be done in two ways.
1. Widening:
It is a process of converting a value from smaller primitive datatype to a bigger
primitive data type.
Syntax: first datatype var = (first datatype) second type value;
* Specifying a datatype within the parenthesis is called as “Type Casting”.
* In widening, specifying the type casting is optional. If we do not specify type casting then
compiler will perform type casting automatically & therefore called as “Implicit Type casting”.
* In widening there will be no loss of data.
Ex: 1. int x = 12;
double d = (double)x;
2. char C = ‘d’;
int i = (int)c;
Narrowing:
It is a process of converting a value from bigger primitive type to smaller primitive data
type.
Syntax: first datatype var = (first datatype) Second type value;
* In narrowing, specifying the type casting is mandatory & it has to be performed explicitly by
the programmer & therefore called as Explicit Type casting.
* In narrowing, there is a chance of loosing data.
Ex: 1. double d = 12.34;
int x = (int)d;

2. int x = 101;
char c = (char)x;
Automatic Type Conversion:

2. Reference Type with respect to Reference Types:


It is a process of converting an object from one class type to another class type which is
compatible.
Two classes are said to be compatible if they have “is-a” relationship.
class parent{
void show(){
System.out.println(“parent class show method”);
}
void display() {
System.out.println(“parent class display method”);
}
}
class child extends parent{
void show(){
System.out.println(“child class show method”);
}
void print() {
System.out.println(“child class print method”);
}
}

Case 1: Test class


class Test {
public static void main(String[] args) {
parent p = new parent();
p.show();
p.display();
p.print();
}
}
In the above class, ‘p’ is the reference variable of parent class holding an object of
parent class holding an object of parent class. Using this ’p’ reference variable, we can access
only the members of parent class.
O/P: parent class show method
parent class display method.

Case 2:
class Test {
psum(String[] args) {
child c = new child();
c.show();
c.display();
c.print();
}
}
In the above class, ‘c’ is the references variable of child class holding an object of
child class. Using this ‘c’ reference variable, we can access both the members of parent class &
child class.

O/P: child class show method


parent class display method.
child class print method

up casting:
If the reference variable of parent class holding an object of any of its child class will be
called as up casting.
Syntax: parentclass ref = (parent class) child classObject;
In up casting, specifying the type casting is optional. If the programmer doesn’t specify
type casting, then the compiler will perform type casting automatically.
Ex: Object o = new Object();
Object o1 = new String();
Object o2 = new Sample();
Object o3 = new Demo();

Case 3:
class Test {
psum(String[] args) {
parent p = (parent)new child();
p.show();
p.display();
p.print();
}
}

In the above class, ‘p’ is the references variable of parent class holding an object of parent class.
Using this ‘p’ reference variable, we can access all the methods of parent class & those methods
from the child class which are overridden.
O/P: child class show method
parent class display method.

Down casting:
If a reference variable of child class holding an object of parent class is called
down casting.
Syntax: childclass ref = (childclass) parentObject;
In down casting, specifying the typecasting is mandatory. Down casting is valid
during compilation time and invalid during execution time & it gives a exception called
“classcastException”.

Case 4:
class Test {
psum(String[] args) {
child c = (child)new parent();
c.show();
c.display();
c.print();
}
}
O/P: valid at compilation time
Invalid during execution time “classcast Exception”
Case 5:
class Test {
psum(String[] args) {
parent p = new child();
child c = (child)p;
c.show();
c.display();
c.print();
}
}
O/P: child class show method
parent class display method.
child class print method

Up Casting:
If a child class object is refered by parent class reference variable then it is called
as Up Casting.

Down Casting:
If a parent class object is refered by child class reference variable then it is called
as Down Casting.
Type Casting with respect to reference types will not change the object, it only
changes the reference type.
Ex:

Animal a = (Animal) new Cat(); //upcasting (Allowed)


Cat c = (Cat) new Animal(); //Downcasting(Not allowed)
Abstract
* If a method contains both declaration and definition then that method will be called as
“Concrete Method”.
* A class can contain any number of methods & if all the methods of that class are concrete then
that class will be called as “Concrete Class”.
* We can create an object for concrete class and with the help of that object we can access the
members of that class.
* If a method contains only declaration then such kind of methods will be called as “Abstract
Methods”.
* If a class contains some abstract methods then that class will be called as “Abstract Class”.
* An abstract class can be a combination of abstract methods & non-abstract methods (concrete
methods).
Syntax for Abstract Method:
abstract returntype methodName(list of parameters);
Syntax for Abstract Class:
abstract class <AbstractClassName>{
}
* If a method doesn’t contain definition then those methods must end with semicolon & they
must be declared with abstract keyword.
* A class can contain any number of abstract methods & non-abstract methods.
* If a class contains zero (or) no abstract methods then declaring the class as abstract is optimal.
* If a class contains atleast one abstract method then declaring the class as abstract is mandatory.
* An abstract class cannot be instantiated i.e., we cannot create an object for abstract class.
To access the members of abstract class we need to inherit the abstract class into a
subclass & override the abstract methods (or) provide implementation to all the abstract methods
available in the abstract class.
abstract class <Abstractclass>{
}
class<subclass> extends<abstractclass>
{
}
* We can create the object of the subclass only when it provides implementation to all the
abstract methods.
* If the subclass doesn’t provide implementation to atleast one of the abstract method then
declare the subclass also as “abstract”, which cannot be instantiated.

1. abstract class Operation{


void msg(){
System.out.println("good morning");
}
abstract void twice(int x);
}

2. class programmer1 extends Operation{


void twice(int x){
System.out.println("result:" +(x+x));
}
}

3. class programmer2 extends Operation{


void twice(int x){
System.out.println("result:" +(x*2));
}
}

4. class AbstractDemo{
psum(String[] args){
//AbstractDemo a = new AbstractDemo();
Programmer1 p1 = new programmer1();
p1.twice(5);
p1.msg();
programmer p2 = new programmer2();
p2.twice(6);
p2.msg();
}
}
O/P: good morning
result: 10
good morning
result: 12
 An abstract class can contain main method & it can be executed.
abstract class Test{
abstract void m1();
Psum(String[] args){
System.out.println(“test main method”);
}
}
1. Every class in java (either abstract class (or) non-abstract class) will be directly (or) indirectly
subclass of object class.
2. Every class in java (either abstract (or) non-abstract class) will contain a constructor whether
we specify (or) not.
3. We cannot create an object of the abstract class but we can declare a reference variable of the
abstract class.

 The reference variable of an abstract class can hold on object of any of its child class which is
non-abstract.
1. Shape.java:
abstract class Shape {
int dim1, dim2;
Shape(int dim1, int dim2){
this dim1 = dim1;
this dim2 = dim2;
}
abstract double area();
}
2. Rectangle.java:
class Rectangle extends Shape{
Rectangle(int len, int bre)
Super(len, bre);
}
double area() {
return dim1*dim2;
}
}
3. Triangle.java:
class Triangle extends shape{
Triangle(int h, int b){
Super(h, b);
}
double area() {
return 0.5*dim1*dim2;
}
}

4. AreaDemo.java:
class AreaDemo {
psum(String[] args){
Shape S;
S = new Rectangle(2,3);
double res = S.area();
System.out.println("Rectangle Area = "+res);
S = new Triangle(4,5);
res = S.area();
System.out.println("Triangle Area = "+res);
}
}
O/P: Rectangle Area = 6
Triangle Area = 4

Illegal Combination of a Method:

1. A method cannot be declared as abstract & final because final keywords says we cannot
override that method & abstract keyword says we must override that method.
2. A method cannot be declared as static & abstract because if a method is declared as static, then
that method can be invoked directly by using class name & we don’t require an object. If we
invoke a method that doesn’t contain definition then it leads to a problem & therefore abstract
methods cannot be static.
Note: only instance methods cannot be abstract.
Illegal Combination of a Class:
1. A class cannot be declared as abstract & final because abstract keyword says we must inherit
that class & final keyword says we cannot inherit that class & therefore illegal combination.
Static: Static modifier can be applied to only methods, variables not for classes. We can apply
the static to inner classes.
Final: Final modifier can be applied to variables, methods & classes.
Abstract: abstract modifier can be applied to methods & classes.
Interface
* An interface is a collection of only abstract methods.
* An interface can be considered as a contract (or) an agreement for developing the softwares.
Syntax: interface <InterfaceName>{
Variables
Methods
}
* An interface can contain some variables & methods.
Ex: interface operation{
int x = 12;
void m1();
}
* When a java program is compiled, the compiler will generate(.class) file for every class
(concrete class (or) abstract class) & it also generates a (.class) file for every interface.
* When the above java program is compiled the compiler will generate “Operation.class” file.
javap Operation
interface Operation{
public static final x;
public abstract void m1();
}
* Every variable of an interface will be declared as public, static & final whether we specify (or)
not.
* Every method of an interface will be declared as public & abstract whether we specify (or) not.
Why public: The variables & methods are declared as public so that they can be accessed from
any class from any location.
Why static: The variables of an interface are declared as static so that they can be accessed
directly by using interface name.
Why final: The variables of an interface are declared as final so that the class which is accessing
that variable cannot change the value.
Why abstract: The methods of an interface are declared as abstract because they do not contain
the definition.
* We cannot create an object for an interface i.e., interfaces cannot be instantiated.
* To use the members of an interface, the interface must be inherited into a class.
* To inherit an interface into a class, we use “implements” keyword.
Syntax: interface <Interface Name>{
}
Class<Subclass> implements <InterfaceName>{
}
* Inheriting an interface into a class is also called as “is-a” relationship.
* The subclass which is inheriting from the interface should provide implementation to the
abstract methods available in the interface.
* If the subclass doesn’t provide implementation to atleast one of the abstract method then
declare the subclass as abstract.
* If the subclass doesn’t provide implementation to all the abstract methods of an interface then
such kind of classes are called as “Implementation Classes”.
* An interface (or) have any number of implementation classes.
Ex: interface Animal{ Animal.java
Void makeSand();
}
class cat implements Animal{ cat.java
public void makeSand() {
System.out.println(“Meow Meow “);
}
}
class dog implements Animal{ Dog.java
public void makeSand() {
System.out.println(“Bow Bow “);
}
}
class Sample { Sample.java
psum(String[] ar) {
Cat c = new cat();
c.makeSand();
Dog d = new dog();
d.makeSand();
}  javac Sample.java
}  java Sample
O/P: Meooew Meow
Bow Bow

 Cat Is-A Animal


Dog Is-A Animal
* Cat & Dog are implementation classes of animal interface.
* The variables of an interface must be initialized because they are declared as “final”.
* The variables of an interface can be accessed in a class directly by using the interface name
(or) by inheriting the interface into a class.

Ex: interface Operation1 {


int x = 12;
}
interface Operation2{
int y = 23;
}
class Sample implements Operation2 {
psum(String[] args){
System.out.println(Operation1.x);
System.out.println(y);
}
}
O/P: java Sample.java
java Sample
12
23
* The java language doesn’t support multiple inheritance but it can be achieved with the help of
an interface.
* A class can inherit (implement) from any number of interfaces.
* We cannot create an object for an interface but we can declare a reference variable to an
interface.
* The reference variable of an interface can hold an object of any of its implementation class.
Ex: interface Operation1{
int x = 11;
void msg();
}
interface Operation2{
int x = 22;
void msg();
}

class Sample implements Operation1, Operation2 {


public void msg() {
System.out.println(“multiple inheritance”);
}
Psum(String[] ar){
System.out.println(x);
System.out.println(y);

Sample S = new Sample();


S.msg();
Operation1 O1 = new Sample();
O1.msg();
Operation2 O2 = new Sample();
O2.msg();
}
}
O/P: javac Sample.java
java Sample
11
22
multiple Inheritance
multiple Inheritance
multiple Inheritance.
Rules:
* A class can extend atmost (0 or 1) one class.
* A class can implement any number of interface.
* A interface cab extend any number of interfaces.
* A class can extend from a class & implement any number of interfaces at the same time.

Marked Interface:
* An interface is said to be a marked interface (or) tagged interface if it doesn’t contain any
members. i.e., they will be empty.
* The purpose of marked interface is to provide some information to the JVM to perform a
special task. Examples of predefined marked interfaces are clonable, Serializable, Random
Access etc.
* We can create our own (user-defined) marked interfaces but they are of no use because JVM
has no meaning for user defined marked interfaces.
Abstract Interface
* An abstract class can be a combination of * An interface is a collection of only abstract
abstract methods & non-abstract methods. methods.
* An abstract class can contain instance * An interface can contain only abstract
methods, static methods, concrete methods, methods which are instance.
abstract methods.
* In an abstract class, specifying the abstract * In an interface, specifying the abstract
keyword to the abstract method is mandatory. keyword to an abstract method is optimal.

* An abstract class can contain both instance * An interface can contain only static
variables.
variables & static variables.
* The values of the variables in an abstract * The variables of an interface cannot be
class can be modified. changed because it is declared as final by
default.
* To inherit a class, we use extends keyword. * To inherit as interface, we use implements
keyword.
* Every class will be either directly (or) * There is no Super most interface.
indirectly subclass of object class. The object
class is called as the "Super most class".

* An abstract class will have a constructor * An interface doesn’t contain constructors.


whether we specify (or) not.
Packages
* A package is a collection of classes & interfaces that are related.
* A package can be considered as a folder (or) a directory.
Packages are classified into two types.
1. Pre-defined packages
2. User defined packages
1. Pre-defined packages:
The packages that are provided by an sun micro systems (or) any other organizations as
part of the java software are called as pre-defined packages.
The pre-defined packages are further classified into three types.

i. Core packages:
The packages that are provided by the sun micro systems & which are part of the java
software & which begin with the term “java” are called as “Core Packages”.
ii. Extended packages:
The packages that are provided by the sun micro systems & which are part of the java
software & which begin with the term “java” are called as “Extended Packages”.
ii. Third party packages:
The packages that are provided by the sun micro systems & which are part of the java
software & which begin with the term “java” are called as “Third party packages”.(VENDOR
Packages)
Examples of predefined packages:
1. java.lang:
The packages contain set of classes & interfaces required for basic programming.
Note: “java.lang” package will be called as default package & it will be available to every java
program.
2. java.io: (input output)
The packages contain set of classes & interfaces required for performing input ouput
operartions.
3. java.net: (Network)
The packages contain set of classes & interfaces required for developing networking
applications.
4. java.util: (utility)
The packages contain has set of classes & interfaces which are specially related to
collection framework
5. java.text:
The packages contain classes & interfaces which can be used for achieving
“internationalization(I18N)” (date & time).
6. java.awt:
This packages contains classes & interfaces required for developing a GUI(Graphical
user Interface) (radio button, textbox, checkbox etc).
7. javax.swing:
This package contains a set of classes & interfaces required for developing a GUI better
than awt.

2. User defined packages:


The packages that are created by the user (or) programmer are called as User defined
packages.
* To create a user defined package we need to take the help of “package” keyword.
Syntax: package packagename;
package package1[.package2.[.package3]];
Note: When we are creating a user defined package then we can specify the package name
containing any number of levels. Specifying atleast one package level is mandatory.
* A java program can contain atmost one package statement & the package statement must be
specified as the first executable statement in a java program.
The package statement is an optional statement.
Ex: package inetsolv;
class Sample{
psum(String[] ar){
System.out.println(“Hello Friends”);
}
}
Syntax for compiling a java program with package:
 java -d Sample.java
-d: This option will indicate the compiler to create a directory with a name i.e., specified in the
package statement of the program.
. : ‘.’ Indicates the compiler to create the directory in current working location.
Once directory (or) folder is created the compiler will generate a [.class] file & that
[.class] file will be placed in the specified folder.

The folder (or) package creation can be done in any location.


Ex: javac –d d:Sample.java
javac -d e:\test Sample.java
The packages that are created are designed to hold only [.class] files.
Syntax for executing a java program with a package:
 java packagename.classname
 java package1.[.package2[.package3]].classname
Ex: java inetsolv.Sample
Every program in java will contain two default packages. Default packages are
1. Current working directory.
2. java.lang package
Any class (or) interface available in these default packages can be accessed directly. To
access the user defined classes (or) pre-defined classes from other than default packages then we
have to use the following mechanisms.
1. Fully Qualified Name.
2. Import Statement.
1. Fully Qualified Name:
The fully qualified name can be used for accessing any class (or) interface from a
specified package.
Syntax:
packagename.classname
package1[.package2[.package3]].classname/InterfaceName
Ex: java.io.BufferedReader
java.util.Arraylist
java.util.Zip.DefaultInputStream
* If a class (or) interface is used multiple times then fully qualified name has to be specified
multiple times which increases the code size & releases the readability of the program.
* To reduce the code size & improve the readability of the code we use import statements.
Import Statement:
The import statement can be used for accessing either singles class/Interface from
package (or) can be used for accessing all the classes/Interfaces from a specified package.
* The import statement can be specified one time & we can use the class/Interface any no of
times in the program.
* The import statement is an optional statement. The import statement should be specified after
the package statement & before the class.

A java program, we can specify any no of import statements.


1. Accessing all the classes & interfaces from a package:
Syntax: import packagename.*;
import package1[.package2[.package3]].*
Ex: import java.io.*;
import java.util.*;
The above syntax can be used for accessing any class automatically & therefore
this kind of import will be called as “Implicit Import Statement”.
2. Accessing either single class/Interface from a specific package:
Syntax: import packagename.className/InterfaceName;
import package1[.package2[.package3]].className/InterfaceName;
Ex: import java.io.BufferReader;
import java.util.Arraylist;
import inetsolv.Sample;
The above syntax can be used for accessing only that class/Interface i.e.,
Specified by the programmer from the specified package. Therefore this kind of imports are
called as “Explicit Import Statement”.
Note: It is recommended to always use “Explicit Import Statement” because they improve the
readability of the code.

Difference between #include & import statement?


#include import statement
* A program uses #include stmt, then the * A program uses import stmt, then only those
entire headerfile will be loaded into the classes will be loaded that are required in the
program whether required (or) not. There by application. The import stmt will reduce the
increasing the code size & compilation time. code size & improve the readability of the
This kind of loading will be called as “Static code. This kind of loading will be called as
Loading” “Dynamic Loading (or) Load on Demand”.

Static Import:
A static imports is introduced in java 1.5 version & it can be used for accessing
static members from a class/interface.
Syntax: import static package.className.*; //implicit static import
import static package.className.Staticmember; //Explicit static import
Ex: import static java.lang.Math.*;
import static java.lang.Byte.MIN_VALUE;
import static java.lang.Byte.MAX_VALUE;

class Test{
psum(String[] args){
System.out.println(min(2,3)); //2.0
System.out.println(max(2,3)); //3.0
System.out.println(floor(4.9)); //4.0
System.out.println(ceil(4.9)); //5.0
System.out.println(round(4.9)); //5.0
System.out.println(random()); //0.00123 [range from 0.0 to 1.0]
System.out.println(sqrt(9)); //3
System.out.println(pow(2,3)); //
System.out.println(MIN_VALUE); //-128
System.out.println(MAX_VALUE); //127
}
}
Difference between general & static import statements?
General import statement is used for accessing a class/interface from a package. Whereas
static imports are used for accessing static members from a class/interface.

Access Specifiers:
The access specifiers will define the level of accessibility (or) visibility of a
class/interface in a package (or) they define the level of accessibility of the members of
class/interface.
* The access specifiers will define the scope(life) of the members in a class using which we can
provide security to the data.
In java language we have 4 levels of access specifiers, Specified with 3 keywords.
1. Public
2. Private
3. Protected
4. default (no access specifier)

1. Public:
If a member is declared as public then it can be accessed from any class in any package.
The public access specifier can be applied to classes, interaces, variables & constructors.
2. Private:
The private access specifier if applied to a member then it can be accessed only in that
class in which it is declared. The private access specifier can be applied to methods, variables &
constructors.

3. Protected:
If a member is declared as protected then it can be accessed from all the classes available
in that package & subclass available in other packages.
The protected access specifiers can be applied to a methods, variables & constructors.

4. Default: access:
A members is said to be default if it is not declared as private, public (or) protected
i.e., if you do not specify any access specifier then it will be called as default access. If a member
is declared as default then it is can be accessed from any class within the package & therefore the
default access is called as package level access.
* The default access can be applied to classes, interfaces, methods, variables & constructors.

Class Diagram:
Java Program:

If a variable x in class A is declared as public then it can be accessed A, B, C, D, & E


classes.
* If a variable x in class A is declared as private if it can be accessed only in class A.
* If a variable x in class A is declared as protected, it can be accessed A, B, C & D classes.
* If a variable x in class A declared as default, it can be accessed A, B, C classes.

The most restricted access is private & most accessible access specifier is public.
Mathematical Expression:
Private <default <protected <public
Overriding Rules:
However we are overriding a method, the child class method should have an access
specifier same as that of the parent class method access specifier on any bigger access specifier.
Illegal Combination of a method:
A method can’t be declared as private & abstract because a private method can be
accessed only in that class in which it is declared where as the abstract must be inherited into
other class & provide the implementation.
* A class can be declared as either public or default.
* If a class is declared as default then the name of the program can be any name.
* If a class is declared as public then class name & program must be same.
* A java program can contain any no of classes but it contains atmost one public class.
* The naming of java will be based on class declaration.
Note: The java program naming will not be based on main method (or) any other method.
Ex: public class A {
psum(String[] args){
System.out.println(“ class A main method”);
}
}
public class B {
psum(String[] args){
System.out.println(“class B main method”);
}
}
class C {
psum(“class C main method”);
}
}
class D {
//psum(“class D main method”);
}
}
* A java prg can contain any no of classes but recommended to write only one classes in a
program.
* The above java program contain 4 classes since all 4 classes are declared as default, the name
of java program can be any name.
A.java, B.java, C.java, D.java, Abcd.java, Sample.java.
Let us name the above program with Sample.java.
Syntax: javac programme with extension
javac Sample.java
When a java program is compiled, the compiler will generate a (.class) file. The
no of class files generated by the compiler will be exactly equal to no of classes available in the
program. The name of the (.class) file generated will be equal to the name of the class specified
in the program.

Syntax for executing a java program:


java className without extension
java A
O/P: class A main method
java B
O/P: class B main method
java C
O/P: class C main method
java D //run time error
error: No such method error
java Sample //runtime error
error: Noclass DeffandError

Every class in java will contain a constructor whether we specify or not. If the
programmer doesnot specify any constructor then the compiler will provide a zero parameterized
constructor.
* The declaration of the zero parameterized constructor provided by the compiler will be based
on class declaration i.e., if the class is declared as public then it provides public zero
parameterized constructor & if class is default then the compiler will provide default constructor.

Note: The compiler never provide parameterized constructor & they can’t be declare the
constructor as private or protected.
As a programmer we can provide or declared as zero parameterized constructor,
parameterized constructor or both & they can be declared as either private, public (or) protected
(or) default.

Singleton class:
If we are able to create only one object for a class then that would be called as singleton
class.
* To create a singleton class we need to declare the constructor as private & it should contain a
factory method.

Factory Method:
If a method returns an object of its own class then it is called as factory method.
Note: The factory method must be declared as “Static”.

Ex: class Sample {


Static Sample s;
Private Sample() {
}
void msg(){
System.out.println(“Hello Friends”);
}
Static Sample getObject(){
if(S ==null)
S = new Sample();
return S;
}
Psum(String[] args){
Sample S = new Sample();
S.msg();
}
}
class Demo {
psum(String[] args){
Sample S = new Sample();
S.msg();
}
}
Ex: How to import class?
Package Pack1;
public class Sample{
public void msg(){
System.out.println(“Hello Friends”);
}
psum(String[] args) File:
Sample S = new Sample(); Sample.java
S.msg(); pack1.Sample
} java pack1.Demo
} O/P: Hello Friend
class Demo {
psum(String[] args){
Sample S = new Sample();
S.msg();
}
}
package pack2;
import pack1.Sample;
class Demo{ Demo.java
psum(String[] args){ java pack2.Demo
Sample S = new Sample(); O/P: Hello Friends
S.msg();
}
}
Exception Handling
When an application is developed, it may contain some errors. It is the responsibility of
the programmer to debug the application so that the application doesn’t contain any error.
The errors are classified into two types.
1. Compile Time Errors
2. Runtime Errors
1. Compile Time Errors:
These errors will occur in a program during the compilation & they occur because
of the syntax of the program. These errors can be identified by the compiler & they can be
resolved.
2. Runtime Errors:
These errors will occur at runtime & they occur because of either logic failure (or)
JVM failure. These kinds of errors cannot be identified by the compiler.
The runtime errors that occur in a program will be called as “Exceptions”. A process of
handling the runtime errors is called as Exception Handling.
Hierarchy of Exception:

Object:
Object is the super most class of all classes in java.
Throwable:
Throwable is the super most class of all runtime errors in java.
Exception:
An exception is a runtime error which occurs because of the wrong logic (or) invalid
input provided by the programmer. The exception is the super most of all the exceptions.
The exceptions are further classified into two types based on when they are identified.
1. Compile Time Exception
2. Runtime Errors
1. Compile Time Exception:
The exceptions that occur at runtime & which can be identified before runtime i.e.,
during compilation time will be called as compile time exception.
2. Runtime Exception:
The exception that occur at runtime & which can be identified only at runtime are called
as runtime exception.
Error:
An error is a runtime error which occurs because of the JVM failure.
* The runtime errors are further classified into two types based on whether they are handled (or)
not.
1. Checked Exception:
If the handling of the runtime error is mandatory then it will be called as checked
exception.
2. Unchecked Exception:
If the handling of the runtime error is optimal then it will be called as unchecked
exception.
The runtime exceptions & its subclasses, error & its subclasses are called as unchecked
exceptions & the remaining exceptions are called as checked exceptions.
class Sample {
psum(String[] args){
System.out.println(“first line”);
System.out.println(10/0);
System.out.println(“third line”);
}
}

When an exception occurs in a program, an object of the exception type will be created
along with the exception information. The object that is created will be thrown to the JVM(Java
Runtime System). The java runtime system will catch the object that is thrown & reads the
information available in that object & then looks for exception handling code in that method
which has thrown the exception object. If the java runtime system is unable to find exception
handling code in that method then the JVM will invoke “Default Exception Handler”.
The default exception handler will display the exception information available in that
object & then terminates the application abnormally leading to incomplete execution.
O/P: first line
Exception in thread main:
Arithematic Exception : / by zero at Sample.main(Sample.java:4)
Exception Handling:
It is the process of finding an alternate solution so that the remaining code is executed &
leads to normal termination.
The code that is used for exception handling will be called as Exception Handler.
Try block:
The try block can be used for specifying the statements that may generate the exception.
Syntax: try{
error generation statements
problem in code
}
* The try block can contain any no of statements but recommended to write only those
statements that may generate the exception.
Catch block:
This block can be used for displaying the information of the exception that has occurred.
Syntax: catch(Exception ref)
{
exception displaying code
}
Every catch block must contain a reference variable of any one of the exception.
Finally block:
This block can be used for performing code cleanup activities. (Releasing resources,
memory etc)
Syntax: finally{
code cleanup activities
}
Rules:
* A try block must be followed by either catch block (or) a finally block.
* A catch block must be preceded by either try block (or) catch block.
* A catch block must be followed by either a catch block (or) try block.
* A finally block must be preceded by either try block (or) catch block.

Note: A catch block & finally block cannot exist without a try block.
* A try block can contain any no of catch block (0 or more).
* If the try block contains multiple catch blocks & if the exceptions specified in the catch blocks
have “is-a” relationship then the exceptions must be specified in the order of child to parent, but
if the exceptions specified in the catch block don’t have “is-a” relationship then the exceptions
can be specified in any order.
* A try block can contain atmost one finally block.
* We can specify some statements either before the blocks (or) after the blocks (or) inside the
blocks but not in-between the blocks.
* A try, catch & finally blocks can be nested in any of the blocks.
* We cannot guarantee the execution of a try block (or) catch block, but the execution of finally
block can be guaranteed.
* In a try block, if there is no exception (or) an exception has occurred which is not matching
then in such case, catch block will not be executed.
* A catch block will be executed only when an exception has occurred & it is matching.
* If a try block contains multiple catch blocks then only one of the catch block will be executed
which is matching.
* A finally block will be executed if there is a exception (or) the exception is handled (or) not.

Ex: class Sample {


psum(String[] args){
System.out.println("first line");
try{
String S1 = ar[0];
String S2 = ar[1];
int a = Integer.parseInt(S1);
int b = Integer.parseInt(S2);
System.out.println(a/b);
}
catch(ArithmeticException ae){
ae.printStackTrace();
}
catch(ArrayIndexOutOfBandsException aioobe)
aioobe.printStackTrace();
}
catch(NumberFormatException nfe)
nfe.printStackTrace();
}
finally{
System.out.println("Good Night");
}
System.out.println("third line");
}
}
O/P: 1. java Sample 20 5
first line
4
Good Night
third line
2. java Sample 20
first line
ArrayIndexOutOfBandsException
Good Night
third line
3. java Sample 20 two
first line
NumberFormatException
Good Night
third line

If a statement in a try block generates an exception then the control will be


immediately transferred out of the try block to the corresponding catch block. Once the control is
transferred out of the try, it will never return back to try block.

Throws:
The “throws” keyword is used to transfer (or) delegate the responsibility of
exception handling to its caller.
Syntax:
returntype methodName(parameters)throws Exception1, Exception2,.......{
statements
}
We can transfer the responsibility of exception handling to any of its caller
including JVM but it is recommended that we do not pass the responsibility of exception
handling to JVM.
Ex: class Sample{
psum(String[] args){
System.out.println ("main first line");
try{
methodOne();
}
catch(Arithematic Exception ae){
ae.printStackTrace();
}
System.out.println ("main last line");
}
public static void methodOn() throws Arithematic Exception{
System.out.println ("methodOne first line");
System.out.println ("10/0");
System.out.println ("methodOne last line");
}
}
O/P: main first line
methodOne first line
Arithematic Exception
methodOne first line
methodOne last line

In the above program an exception has occurred in methodOne & it is


responsibility of methodOne to handle the exception.
Instead of handling the exception, methodOne is transferring the responsibility of
exception handling to its caller (main method).
Throw:
The throw keyword can be used for throwing an exception object of an exception
explicitly.
Syntax: throw ExceptionObject;
Ex: throw ArrayIndexOutOfBandsException;

The throw keyword can be used to throw an object explicitly and test whether the
code is able to handle the exception (or) not.

Ex: class Sample{


psum(String[] args){
try{
throw new ArithmeticException();
}
catch(Arithematic Exception ae){
ae.printStackTrace();
}
}
}

 Different ways of displaying the exception information?


1. printStackTrace(): (Belongs to throwable class)
This method can be used to display the exception name, the reason for the
occurrence of the exception, the program name, the class name, the method name and line
number.
Ex: try{
System.out.println(10/0);
}
catch(Arithematic Exception ae){
ae.printStackTrace();
}
O/P: java.lang.ArithmeticException: / by zero
at Sample.main(Sample.java:7)

2. toString(): (Belongs to Object class)


This method can be used to display the exception name & the reason for
the occurrence of the exception.

Ex: try{
System.out.println(10/0);
}
catch(Arithematic Exception ae){
System.out.println(ae);
(or)
System.out.println(ae.toString());
}

O/P: java.lang.ArithmeticException: / by zero

3. getMessage(): (Belongs to throwable class)


This method can be used to display only the reason for the occurrence of the
exception.
Ex: try{
System.out.println(10/0);
}
catch(Arithematic Exception ae){
System.out.println(ae.getMessage());
}

O/P: / by zero
4. Customized message:
If we do not want to display the information of an exception by using the
predefined methods then we can display our own message.
Ex: try{
System.out.println(10/0);
}
catch(Arithematic Exception ae){
System.out.println("ArithmeticException has occured");
System.out.println("It is my own message");
}

O/P: ArithmeticException has occured


It is my own message

User defined Exceptions:


The exceptions that are created by the programmer (or) user will be called as user
defined exceptions.
The user defined exceptions has to be created when none of the predefined
exceptions are matching the application requirement.

Procedure to create user defined exceptions:


* Every predefined exception is a class when we create out own exception, it should also be a
class.
* Every predefined exception is a sub class of exception class either directly (or) indirectly, the
user defined should also be a subclass of exception class either directly (or) indirectly.
* If the user defined exception extends from exception class then the user defined exception will
be considered as “checked Exception”, if we want to consider the user defined exception as
unchecked exception, then extend the user defined exception from “Runtime Exception” class.
Note: It is recommended to create the user defined exceptions as unchecked exceptions.
* The user defined exception class objects will not be created automatically, it has to be done by
the programmer & the programmer has to explicitly throw the user defined exception object by
using “throw” keyword because the Java Runtime System doesn’t know when to generate which
user defined exception.
* In the user defined exception class we are recommended to provide two constructors, (zero
parameterized) & parameterized constructor taking one parameter of string type.

Example of user defined exceptions:


class SmallAgeException extends RuntimeException{
SmallAgeException(){
}
SmallAgeException(String str){
Super(str);
}
}
class BigAgeException extends RuntimeException{
BigAgeException(){
}
BigAgeException(String str){
Super(str);
}
}
class Sample{
psum(String[] args){
int age = Integer.parseInt(ar[0]);
try{
if(age<20)
throw new SmallAgeException("your age is less than 20");
}
elseif(age<20){
throw new BigAgeException("your age is more than 30");
}
else{
System.out.println("you are eligible");
}
}
catch(SmallAgeException sae){
sae.printStackTrace();
}
catch(BigAgeException bae){
bae.printStackTrace();
}
System.out.println("Have a good day");
}
}

java.lang Package:
This package is the default package available to every java program. Any class
available in java.lang package can be accessed directly.
Object class:
The object class belongs to java.lang package & it is called as super most class of
all classes in java.
* Every class in java either predefined (or) user defined will be a subclass of object class either
directly (or) indirectly.
* The members available in object class can be used (or) accessed in every class of java
language.

Methods of Object class:


1. String toString():
This method can be used to represent an object of a class in the form of string
representation. Whenever a reference variable of any class is displayed, the compiler will
automatically invoke toString() method.
Ex: class Sample{
psum(String[] args){
Sample S = new Sample();
System.out.println(S);
(or)
System.out.println(S.toString());
}
}
When a reference variable of any class is displayed, the toString() will be
automatically invoked which will execute the toString() of object class will always display
“classname followed by hash code” (className@hashcode).
O/P: Sample@3e25a5.

toString() logic available in Object class:


public String toString(){
return getClass().getName()+"@"+ Integer
toHexString(hashCode());
}

When the reference variable of any class is displayed & if it shows the output as
“classname followed by hashcode” then the user will not be able to understand the information &
therefore it is recommended to override toString() in every user defined class. So that we can
display a meaningful (or) understandable information.
Overriding of toString() in user defined class:
class Sample{
psum(String[] args){
Sample S = new Sample();
System.out.println(S);
Student Stu = new Student(12);
System.out.println(Stu.toString());
Student Stu1 = new Student(12);
System.out.println(Stu1);
}
public string toString(){
return "Sample class object";
}
}
class Student {
int rollNo;
Student(int rollNo){
this.rollNo = rollNo;
}
public String toString(){
return ""+rollNo";
}
}
O/P: Sample class object
12
34

2. int hashcode:
This method will provide (or) generate a number which will be used for
identifying an object.
* The hashcode value must be a unique number so that every object can be identified.
Note: Hashcode is not the address of the object.

class Sample{
psum(String[] args){
Sample S1 = new Sample();
System.out.println(S1.hashcode());
Sample S2 = new Sample();
System.out.println(S2.hashcode());
}
}
O/P: 4072869
1671711
If we don’t want the hashcode to be generated automatically by the predefined
logic available in hashcode() of the object class. Then we can override hashcode() in our clas to
generate our own hashcode.
* When we override the hashcode(), we are recommended to override the method in such a way
that it generates a unique number for every object.
Ex: class Sample{
static int count = 10;
psum(String[] args){
Sample S1 = new Sample();
System.out.println(S1.hashcode());
Sample S2 = new Sample();
System.out.println(S2.hashcode());
}
public int hashcode(){
return count++;
}
}
O/P: 10
11
class Student {
int rollNo;
Student(int rollNo){
this.rollNo = rollNo;
}
}
class Sample{
psum(String[] args){
String S1 = new String("hello");
String S2 = new String("hello");
System.out.println(S1.equals(S2));
String S3 = new String("hello");
String S4 = new String("hello");
System.out.println(S3.equals(S4));
}
}
O/P: true
true
If we do not want to compare the hashcodes of the objects then we can override equals()
& define the meaning of equality.

Ex: class Student {


int rollNo;
Student(int rollNo){
this.rollNo = rollNo;
}
}
public boolean equals(Object obj)
Student S = (Student)obj;
if(this.rollNo == S.rollNo)
return true;
else
return false;
}
}
class Sample{
psum(String[] args){
String S1 = new String("hello");
String S2 = new String("hello");
System.out.println(S1.equals(S2));
String S3 = new String("hello");
String S4 = new String("hello");
System.out.println(S3.equals(S4));
}
}
O/P: true
true

The overridden equals() is available to only student class that we have overridden from
object class. The overridden equals() will not be available for other class(ex: employee etc.) then
again override that equals() in emp class.

4. Object clone():
* This method can be used to take a backup of an object.
* This method can be used to create a duplicate copy for an existing object.
Procedure to create a duplicate copy:
* The clone method will throw CloneNotSupportedException, which must be handled because it
is an checked exception.
* The object whose duplicate copy has to be created, its corresponding class must implement
clonable interface.
* The return type of clone method is object & it has to be type casted to our required type.
Ex: class Sample implement Clonable{
int x = 11;
int y = 22;
psum(String[] args)throws cloneNotSupportException{
Sample S1 = new Sample();
System.out.println(S1.x+""+s1.y);
Object obj = S1.clone();
S1.x = 33;
S2.x = 44;
System.out.println(S1.x+""+s1.y);
Sample S2 = new Sample();
System.out.println(S2.x+""+s2.y);
}
}
O/P: 11 22
33 44
11 22
Wrapper Classes
* These classes can be used for converting a value from primitive type to class type.
* For every primitive type available in java we have one corresponding wrapper classes.
* All the wrapper classes (8) are available in java.lang package.

Creation of Wrapper Classes:


Every wrapper class contains two constructors taking one parameter each of
primitive datatype & String type.
Byte b = new Byte(byte);
Byte b = new Byte(String);

Short s = new short(short);


Short s = new short(String);

Integer i = new Integer(int);


Integer i = new Integer(String);

Long l = new Long(long);


Long l = new Long(String);

Float f = new Float(float);


Float f = new Float(double);
Float f = new Float(String);
Double d = new Double (double);
Double d = new Double(String);

Character c = new Character(char);

Boolean b = new Boolean(boolean);


Boolean b = new Boolean(String);

Ex: How to create our own wrapper classes.


int i = 12;
Integer j = new Integer(i);
System.out.println(i);
System.out.println(j);

Boolean class Examples:


in String type (or) boolean literals – It is allowed(true) otherwise display it as false.
Boolean b1 = new Boolean(true); //true
Boolean b2 = new Boolean(false); //true
// Boolean b3 = new Boolean(true); //false(because of T)
Boolean b4 = new Boolean(“true”); //true
Boolean b5 = new Boolean(“TRUE”); //true
Boolean b6 = new Boolean(“TRUE”); //true
Boolean b7 = new Boolean(“false”); //false
Boolean b8 = new Boolean(“hello”); //false
Boolean b9 = new Boolean(“”); //false
Boolean b10 = new Boolean(null); //false
* If we provide a boolean literal “true” then the boolean object will contain true, if we provide
boolean literal false then the boolean object will contain false.
* If we provide true as a string in any case(upper (or) lower (or) mixed case) (“true” “TRUE”
“TRUE” “TRUE”) then the boolean object will contain true and any other content that is
specified as string will store false into the boolean object.
Methods of Wrapper Classes:
1. Value Of():
This method can be used for converting a primitive type value (or) a string value
into wrapper type.
Syntax1: Static WrapperClass ValueOf(primitivetype)
The above syntax can be used to convert a primitive type to wrapper. The syntax
is available in all wrapper classes except character.

Ex: int i = 23;


Integer j = new Integer(i);
Integer k = new Integer("34");
2. xxxxValue:
This method can be used for converting wrapper type value to primitive type.
Syntax: primitivetype xxxValue()
Ex: byte byteValue()

byteValue()
shortValue() These 6 methods are available in each class of all
intValue() ‘6’ classes below Byte, Short, Integer, Long, Float, Double.
longValue()
floatValue()
doubleValue()

CharValue()  This method is available in Character class.


booleanValue()  This method is available in Boolean class.

Ex: Integer i = Integer.ValueOF("23");


int j = i.intValue();
double d = i.doubleValue();
long l = i.longValue();
3. parse xxxx():
This method can be used for converting String type to primitive type.
Syntax: Static primitivetype parsexxxx(String);
The parsexxx() is available in all wrapper classes except “character”.
Ex: String S = “11”;
int i = Integer.parseInt(S);
float f = Float.parsefloat(S);
byte b = Byte.parseByte(S);

4.
Static String toBinaryString(int/long)
Static String toOctalString(int/long)
Static String toHexaString(int/long)
* The above three methods can be used to convert a value from decimal number system to binary
system, octal system & Hexadecimal system respectively.
* The above three methods are available in Integer & long wrapper classes.
Ex: int i = 12;
System.out.println(i);
System.out.println(Integer.toBinaryString(i));
System.out.println(Integer.toOctalString(i));
System.out.println(Integer.toHexaString(i));
Hierarchy of Wrapper Classes:

Boxing:
It is the process of converting a value from primitive type to wrapper type. This
process is performed automatically by the compiler from 1.5 version & therefore called it as
AutoBoxing.

UnBoxing:
It is a process of converting a value from wrapper type to primitive type. This
process is performed automatically by the compiler from 1.5 version onwards & there called it as
Auto Unboxing.
Integer m = new Integer(45);
int n = m;
enum:
The enum keyword is introduced in java 1.5 version & the purpose of an enum
keyword is to create a group of named constants.
Syntax:
enum<EnumName>{
Constants
}

Convention for writing enum name:


 The enum name can contain any number of words & the first letter of every word should be
specified in UpperCase.
Ex: enum Day{
SUN, MON, TUE, WED, THU, FRI, SAT;
}
* When a java program is compiled, the compiler will generate a (.class) file for every class,
every interface & for every enum.
* When we compile the above program Day.java, the compiler will generate Day.class.
javac Day.java
javap Day
Final class Day extends Enum{
public static final Day SUN;
public static final Day MON;
.
.
.
.
public static Day[] Values();
}
* Every enum will be internally a final class which extends from Enum class.
* Enum class is a predefined class which is abstract & available in java.lang package & it
inherits from object class.
Rules:
* An enum in java is more powerful compare to enum in other languages, because an enum in
java can contain variables, methods & constructors along with the constants.
* If an enum contains only constants then specifying the semicolon is optional.
* If an enum contains other code along with constants then specifying the semicolon is
mandatory.
* If an enum contains other code along with constants then the constants must be specified as the
first statement in an enum.
* An enum can be empty (or) it can contain only constants (or) it can contain other code along
with costants but it cannot contain other code without the constants.
* An enum can contain main() & they can be executed.

Ex: enum with main():


enum Day{
SUN, MON, TUE, WED, THU, FRI, SAT;
Psum(String[] args){
System.out.println(“enum main method”);
}
}

javac Day.java
javap Day
O/P: enum main method
* Every enum will contain a constructor.
* An enum cannot be instantiated by the programmer i.e., the programmer cannot create the
object directly but an object of enum can be created by declaring a constant in an enum.
* The constructors of an enum will be executed one time for every constant that is declared.

enum Day{
SUN, MON, TUE, WED, THU, FRI, SAT;
Day(){
System.out.println(“enum main method”);
}
Psum(String[] args){
System.out.println(“enum main method”);
}
}

O/P: enum constructor


enum constructor
enum constructor
enum constructor
enum constructor
enum constructor
enum constructor
enum main method

Ex: enum Fruit{


Apple(30), MANGO(90), GRAPES, ORANGE(70), BANANA(40);
int Price;
Fruit(){
price = 50;
}
Fruit(int Price){
this.price = price;
}
int getPrice(){
return Price;
}
}
class Eat{
Psum(String[] args){
Fruit f = Fruit.MANGO;
System.out.println(f.Price);
Fruit[] fr = Fruit.Values();
for(Fruit x:fr){
System.out.println(x+":"+x.getPrice());
}
}
}

To the switch statement we can pass byte, short, int, char as an argument & it is
valid upto 1.4 version from 1.5 version onwards, we can pass byte, short, int, char primitive
types & its corresponding four wrapper classes(Byte, Short, Integer & Character) & enum.
enum Day{
SUN, MON, TUE, WED, THU, FRI, SAT;
}
class Work{
Psum(String[] args){
Day d = Day.SUN;
Switch(d){
Case MON:System.out.println(“Boring, back to office”);
break;
Case FRI:System.out.println(“preparing to enjoy”);
break;
Case SAT:System.out.println(“sleeping”);
break;
Case SUN:System.out.println(“eating”);
}
}
}
Note: The case labels must be exactly same as that of the constants available in enum.
Important Questions
* When do you allocate the memory for instance variables?
The memory for the instance variables will be allocated at the time of object
creation.
* Where?
The memory for the instance variables will be allocated in heap memory.
* How many times?
The memory for the instance variables will be allocated one time for each object.

* Why should we declare the method as abstract?


A method has to be declared as abstract when it has to be implemented by
different programmers with different logics.
* Can we declare a class as abstract if it contains all concrete methods & why?
Yes, we can declare a class as abstract even though it contains all concrete
methods & we do it when we don’t want other classes to create an object of our class.
By declaring the class as abstract we are restricting “has-a” relationship & forcing to use
“is-a” relationship.
* Why we cannot instantiate the abstract class?
Assume if we are allowed to create an object of the abstract class & by using that
object we can access all the members of that class.
Using that object if we invoke concrete method then their definition of concrete method
will be executed but if we invoke abstract method then it will lead to a problem because abstract
method doesn’t contain definition.
To avoid such kind of problem we are not allowed to instantiate the abstract class.

* When will an abstract class constructor be executed?


We cannot execute the constructor of an abstract class directly because we cannot
create an object for abstract class.
To execute the constructor of an abstract class we need to create the object of that
subclass. Which is non-abstract, when we create an object of the subclass it invokes the subclass
constructor & before executing the subclass constructor it invokes the parent class constructor.
* Why should we implement method overloading?
We implement method overloading when we want to provide flexibility to the
user so that the user can perform different operations by using the same method.
Method overloading can be applied to instance methods, static methods (or) both the methods.
Method overloading can be even applied to main method.
When a main method is overloaded & JVM begins the execution then in such case the
JVM will invoke only that main method which takes string array as the parameter, the remaining
main methods will not be invoked by the JVM. It is the responsibility of the programmer to
invoke the other main methods.
*Why should we constructor overloading?
We implement constructor overloading to provide flexibility to the user so that the user
can create the object in different ways by passing different number, different type (or) different
order of parameters.
Constructor overloading can be implemented only in a single class i.e., we cannot
implement constructor overloading in different classes whether they have “is-a” relationship (or)
not.
* The constructor of a class cannot be inherited into a subclass & therefore we cannot implement
constructor overriding.

You might also like