0% found this document useful (0 votes)
44 views43 pages

Advanced Prog-Java Unit1 Study Material 24-25

This document outlines the fundamentals of Java programming, including key concepts such as object-oriented programming principles, inheritance, polymorphism, and encapsulation. It also covers the history of Java, its version history, and various Java buzzwords that highlight its features like portability, security, and robustness. Additionally, it provides an overview of data types in Java, including primitive and non-primitive types, as well as comments and their usage in Java code.

Uploaded by

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

Advanced Prog-Java Unit1 Study Material 24-25

This document outlines the fundamentals of Java programming, including key concepts such as object-oriented programming principles, inheritance, polymorphism, and encapsulation. It also covers the history of Java, its version history, and various Java buzzwords that highlight its features like portability, security, and robustness. Additionally, it provides an overview of data types in Java, including primitive and non-primitive types, as well as comments and their usage in Java code.

Uploaded by

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

Advanced Programming

Unit-1

Syllabus: - UNIT 1
Introduction to Java: Java buzzwords, bytecode. Java

Programming Fundamentals: Application program using simple java program, data types, variables,
arrays, operators, expressions, control statements, type conversion and casting, concepts of classes,
objects, constructors, methods, access control, this keyword, garbage collection, overloading
methods and constructors, introducing access control, static, final, nested and inner classes,
exploring string class, using command-linear arguments.

Inheritance: Inheritance concept, types of inheritance, Member access rules, use of super and final.
Polymorphism - dynamic binding, method overriding, abstract classes and methods.

Introduction
Object Oriented Programming is a paradigm that provides many concepts such as inheritance, data
binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming paradigm
where everything is represented as an object is known as truly object-oriented programming language.
Smalltalk is considered as the first truly object-oriented programming language.
OOPS (Object Oriented Programming System) concepts:
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software development
and maintenance by providing some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Object: Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard,
bike etc. It can be physical and logical.
Class: Collection of objects is called class. It is a logical entity.
Inheritance: When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Benefits of Inheritance:
One of the key benefits of inheritance is to minimize the amount of duplicate code in an application by
sharing common code amongst several subclasses. Where equivalent code exists in two related classes, the
hierarchy can usually be refactored to move the common code up to a mutual superclass. This also tends to
result in a better organization of code and smaller, simpler compilation units.
 Inheritance can also make application code more flexible to change because classes that inherit from a
common superclass can be used interchangeably. If the return type of a method is superclass
 Reusability - facility to use public methods of base class without rewriting the same.
 Extensibility - extending the base class logic as per business logic of the derived class.
 Data hiding - base class can decide to keep some data private so that it cannot be altered by the derived
class.
Polymorphism: When one task is performed by different ways i.e. known as polymorphism.
For example: to convince the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction: Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing. In java, we use abstract class and interface to achieve abstraction.
Encapsulation: Binding (or wrapping) code and data together into a single unit is known as encapsulation.
For example: capsule, it is wrapped with different medicines. A java class is the example of
encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

PRINCIPLES OF OBJECT ORIENCTED PROGRAMMING


Encapsulation. Encapsulation is the mechanism of hiding of data implementation by restricting access to public
methods.
Abstraction. Abstract means a concept or an Idea which is not associated with any particular instance. Using
abstract...
Inheritance. Inheritances expresses is-a and/or has-a relationship between two objects. Using
Inheritance, In...
Polymorphism. It means one name many forms. It is further of two types static and dynamic. Static
polymorphism is achieved using method overloading and dynamic polymorphism using method overriding. It is
closely related to inheritance. We can write a code that works on the superclass, and it will work with any
subclass type as well.

BENEFITS OF OBJECT ORIENTED PROGRAMMING

 We can build the programs from standard working modules that communicate with one another, rather than
having to start writing the code from scratch which leads to saving of development ...
 OOP language allows to break the program into the bit-sized problems that can be solved easily (one object at a
time).
 The new technology promises greater programmer productivity, better quality of software and lesser
maintenance cost.
 OOP systems can be easily upgraded from small to large systems.
 It is possible that multiple instances of objects co-exist without any interference,
 It is very easy to partition the work in a project based on objects.
 It is possible to map the objects in problem domain to those in the program.
 The principle of data hiding helps the programmer to build secure programs which cannot be invaded by the
code in other parts of the program.
 By using inheritance, we can eliminate redundant code and extend the use of existing

Procedural and object oriented programming paradigms:


History of Java:
The history of java starts from Green Team. Java team members (also known as Green Team), initiated
a revolutionary task to develop a language for digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for internet
programming. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There are
given the major points that describes the history of java.
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
 Originally designed for small, embedded systems in electronic appliances like settop boxes.
 Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
 After that, it was called Oak and was developed as a part of the Green project.
 It took 18 months to develop the first Working version. This language was initially called ―Oak‖ but
was renamed ―Java‖in 1995. Between the initial implementation of Oak in the fall of 1992 and the public
Announcement of Java in the spring of 1995, many more people contributed to the designand evolution of the
language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lind Holm were key contributors to
the maturing of the original prototype.
 The trouble With C and C++ (and most other languages) is that they are designed to be compiled For a
specific target. Although it is possible to compile a C++ program for just about Any type of CPU, to do so
requires a full C++ compiler targeted for that CPU. The Problem is that compilers are expensive and time-
consuming to create. An easier—and more costefficient—solution was needed. In an attempt to find such a
solution,Gosling and others began work on a portable, platform-independent language thatcould be used to
produce code that would run on a variety of CPUs under differing Environments. This effort ultimately led to
the creation of Java. As mentioned earlier, Java derives much of its character from C and C++. This is by intent.
The Java designers knew that using the familiar syntax of C and echoing the objectoriented features of C++
would make their language appealing to the legions of experienced C/C++ programmers. In addition to the
surface similarities, Java shares some of the other attributes that helped make C and C++ successful. First, Java
was designed, tested, and refined by real, working programmers.

Java Version History:


There are many java versions that has been released. Current stable release of Java is Java SE 8. 1. JDK Alpha
and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10.Java SE 8 (18th March, 2014)

Java Buzzwords:
There is given many features of java. They are also known as java buzzwords. The Java Features given
below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12.Distributed
Simple:
Java was designed to be easy for the professional programmer to learn and use effectively. Assuming
that you have some programming experience, you will not find Java hard to master. If you already understand
the basic concepts of object-oriented programming, learning Java will be even easier. Best of all, if you are an
experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++
syntax and many of the objectoriented features of C++, most programmers have little trouble learning Java.
Object-Oriented:
Although influenced by its predecessors, Java was not designed to be source-code compatible with any
other language. Borrowing liberally from many seminal object-software 13 environments of the last few
decades, Java manages to strike a balance between the purist’s ―everything is an object‖ paradigm and the
pragmatist’s ―stay out of my way‖ model.

Robust:
The multi platformed environment of the Web places extraordinary demands on a program, because the
program must execute reliably in a variety of systems. Thus, the ability to create robust programs was given a
high priority in the design of Java.
To better understand how Java is robust, consider two of the main reasons for program failure: memory
management mistakes and mishandled exceptional conditions (that is, run-time errors). Memory management
can be a difficult, tedious ask in traditional programming environments. For example, in C/C++, the pro
grammer must manually allocate and free all dynamic memory. This sometimes leads to problems, because
programmers will either forget to free memory that has been previously allocated or, worse, try to free some
memory that another part of their code is still using. Java virtually eliminates these problems by managing
memory allocation and deallocation for you.

Multithreaded:
Java was designed to meet the real-world requirement of creating interactive, networked programs. To
accomplish this, Java supports multithreaded programming, which allows you to write programs that do many
things simultaneously. The Java run-time system comes with an elegant yet sophisticated solution for
multiprocess .synchronization that enables you to construct smoothly running interactive systems.

Architecture-Neutral :
A central issue for the Java designers was that of code longevity and portability. One of the main
problems facing programmers is that no guarantee exists that if you write a program today, it will run tomorrow
—even on the same machine. Operating system up grades, processor upgrades, and changes in core system
resources can all combine to make a program malfunction. The Java designers made several hard decisions in
the Java language and the Java Virtual Machine in an attempt to alter this situation. Their goal was ―write
once; run anywhere, any time, forever.‖ To a great extent, this goal was accomplished.

Interpreted and High Performance:


Java enables the creation of cross-platform programs by compiling into an intermediate representation
called Java bytecode. This code can be interpreted on any system that provides a Java Virtual Machine. Most
previous attempts at cross platform solutions have done so at the expense of performance. Other interpreted
systems, such as BASIC, Tcl, and PERL, suffer from almost insurmountable performance deficits. Java,
however, was designed to perform well on very low-power CPUs.

BYTECODE
Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an assembler
which is an alias representation of a C++ code. As soon as a java program is compiled, java
bytecode is generated. In more apt terms, java bytecode is the machine code in the form of
a .class file. With the help of java bytecode we achieve platform independence in java.
Distributed:
Java is designed for the distributed environment of the Internet, because it handles TCP/IP protocols.
In fact, accessing a resource using a URL is not much different from accessing a file. The original version of
Java (Oak) included features for intra address-space messaging. This allowed objects on two different
computers to execute procedures remotely. Java revived these interfaces in a package called Remote
MethodInvocation (RMI). This feature brings an unparalleled level of abstraction to client/server programming.

Dynamic:
Java programs carry with them substantial amounts of run-time type information that is used to verify
and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and
expedient manner. This is crucial to the robustness of the applet environment, in which small fragments of
bytecode may be dynamically updated on a running system.

Java Comments ( Java Command-Line Arguments):


The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or any statement.
It can also be used to hide program code for specific time.There are 2 types of comments in java.
1. Single Line Comment 2. Multi Line Comment

1. Single Line Comment :


The single line comment is used to comment only one line.
Syntax: // This is single line comment

2. Multi Line Comment: The multi line comment is used to comment multiple lines of code.
Syntax: /* This is multi line comment */

Data Types:

Data types represent the different values to be stored in the variable.


In java, there are two types of data types:
1. Primitive data types
2. Non-primitive data types
Integers :
Java defines four integer types: byte, short, int, and long.
All of these are signed, positive and negative values. Java does not support unsigned, positive-only
integers. Many other Computer languages, including C/C++, support both signed and unsigned integers.
Name Width Range
long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127

byte: The smallest integer type is byte. This is a signed 8-bit type that has a range from –128to 127. Variables of
type byte are especially useful when you’re working with a streamof data from a network or file. They are also
useful when you’re working with rawbinary data that may not be directly compatible with Java’s other built-in
types.
Syntax: byte b, c;
short: short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-used Java
type, since it is defined as having its high byte first (called big-endian format). This type is mostly applicable to
16-bit computers, which are becoming increasingly scarce. Here are some examples of short variable
declarations:
short s;
short t;
int: The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648
to 2,147,483,647. In addition to other uses, variables of type int are commonly employed to control loops and to
index arrays. Any time you have an integer expression involving bytes, shorts, ints, and literal numbers, the
entire expression Is promoted to int before the calculation is done.

long: long is a signed 64-bit type and is useful for those occasions where an int type is notlarge enough to hold
the desired value. The range of a long is quite large. This makesit useful when big, whole numbers are needed.
For example, here is a program thatcomputes the number of miles that light will travel in a specified number of
days.

Floating-Point Types:
Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision. For example, calculations such as square root, or transcendentals such as sine and
cosine, result in a value whose precision requires a floating-point type. Their width and ranges are shown here:
Name Width Bits Approximate Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038

float:
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is faster
on some processors and takes half as much space as double precision, but will become imprecise when the
values are either very large or very small. Variables of type float are useful when you need a fractional
component, but don’t require a large degree of precision. For example, float can be useful when representing
dollars and cents. Here are some example float variable declarations: float hightemp, lowtemp;
double:
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is
actually faster than single precision on some modern processors that have been optimized for high-speed
mathematical calculations.
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi,
a = pi * r * r; // compute area

Characters:
In Java, the data type used to store characters is char. However, C/C++ programmers beware: char in
Java is not the same as char in C or C++. In C/C++, char is an integertype that is 8 bits wide. This is not the case
in Java. Instead, Java uses Unicode to representcharacters.. There are no negative chars. The standard set of
characters known asASCII still ranges from 0 to 127 as always, and the extended 8-bit character set, ISO-Latin-
1,ranges from 0 to 255.
Boolean:
Java has a simple type, called boolean, for logical values. It can have only one of twopossible values,
true or false. This is the type returned by all relational operators, suc has a < b. boolean is also the type required
by the conditional expressions that govern the control statements such as if and for.
Java Enum :
Enum in java is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The java
enum constants are static and final implicitly. It is available from JDK 1.5.
Java Enums can be thought of as classes that have fixed set of constants.

Literals
A constant value in Java is created by using a literal representation of it. For example, here are some literals:

Integer Literal
An integer literal can always be assigned to a long variable. However, to specify a long literal, you will need to
explicitly tell the compiler that the literal value is of type long. You do this by appending an upper- or lowercase
L to the literal. For example, 0x7ffffffffffffffL or 9223372036854775807L is the largest long. An integer can
also be assigned to a char as long as it is within range.
Floating Literals
Floating-point literals in Java default to double precision. To specify a float literal, you must append an F or f to
the constant. You can also explicitly specify a double literal by appending a Dor d. Doing so is, of course,
redundant. The default double type consumes 64 bits of storage, while the less-accurate float type requires only
32 bits.

Boolean Literals Boolean literals are simple. There are only two logical values that a boolean value can have,
true and false. The values of true and false do not convert into any numerical representation. The true literal in
Java does not equal 1, nor does the false literal equal 0. In Java, they can only be assigned to variables declared
as boolean, or used in expressions with Boolean operators.

Character Literals

Characters in Java are indices into the Unicode character set. They are 16-bit values that can be converted into
integers and manipulated with the integer operators, such as the addition and subtraction operators. Aliteral
character is represented inside a pair of single quotes. All of the visible ASCII characters can be directly entered
inside the quotes, such as ‘a’, ‘z’, and ‘@’. For characters that are impossible to enter directly, there are several
escape sequences that allow you to enter the character you need, such as ‘\’’ for the single-quote character itself
and ‘\n’for the newline character. Table 3-1 shows the character escape sequences.
String Literals
String literals in Java are specified like they are in most other languages—by enclosing a sequence of characters
between a pair of double quotes. Examples of string literals are
“Hello World”
“two\nlines”
“\”This is in quotes\””

Variables:

In Java, all variables must be declared before they can be used. The basic form of a variable declaration is
shown here: type identifier [ = value][, identifier [= value] ...] ;

Variable is a name of memory location. There are three types of variables in java: local, instance and
static.
Types of Variable There are three types of variables in java:
 local variable
 instance variable
 static variable
1)Local Variable: A variable which is declared inside the method is called local variable.

2) Instance Variable: A variable which is declared inside the class but outside the method, is called instance
variable . It is not declared as static.

3) Static variable: A variable that is declared as static is called static variable. It cannot be local.

Example to understand the types of variables in java:


class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class

Constants in Java:
A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.
Syntax:
final dataTypevariableName = value; //global constant
static final dataTypevariableName = value;

Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the time the variable is
declared. For example, here is a short program that computes the length of the hypotenuse of a right triangle
given the lengths of its two opposing sides: // Demonstrate dynamic initialization. class DynInit { public static
void main(String args[]) { double a = 3.0, b = 4.0; // c is dynamically initialized double c = Math.sqrt(a * a + b *
b); System.out.println("Hypotenuse is " + c); } } Here, three local variables—a, b, and c—are declared. The first
two, a and b, are initialized by constants. However, c is initialized dynamically to the length of the hypotenuse
(using the Pythagorean theorem). The program uses another of Java’s built-in methods, sqrt( ), which is a
member of the Mathclass, to compute the square root of its argument. The key point here is that the initialization
expression may use any element valid at the time of the initialization, including calls to methods, other
variables, or literals.

Scope and Life Time of Variables:


The scope of a variable defines the section of the code in which the variable is visible. As a general
rule, variables that are defined within a block are not accessible outside that block. The lifetime of a variable
refers to how long the variable exists before it is destroyed. Destroying variables refers to deallocating the
memory that was allotted to the variables when declaring it. We have written a few classes till now. You might
have observed that not all variables are the same. The ones declared in the body of a method were different from
those that were declared in the class itself. There are three types of variables: instance variables, formal
parameters or local variables and local variables.
Instance variables: Instance variables are those that are defined within a class itself and not in any
method or constructor of the class. They are known as instance variables because every instance of the class
(object) contains a copy of these variables. The scope of instance variables is determined by the access specifier
that is applied to these variables. We have already seen about it earlier. The lifetime of these variables is the
same as the lifetime of the object to which it belongs. Object once created do not exist for ever. They are
destroyed by the garbage collector of Java when there are no more reference to that object.
Argument variables: These are the variables that are defined in the header of constructor or a method.
The scope of these variables is the method or constructor in which they are defined. The lifetime is limited to the
time for which the method keeps executing. Once the method finishes execution, these variables are destroyed.

Local variables: A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the method itself. One important distinction between these three
types of variables is that access specifiers can be applied to instance variables only and not to argument or local
variables. In addition to the local variables defined in a method, we also have variables that are defined in bocks
life an if block and an else block. The scope and is the same as that of the block itself.
Static variables: A variable which is declared inside a class, outside all the blocks and is marked static
is known as a class variable. The general scope of a class variable is throughout the class and the lifetime of a
class variable is until the end of the program or as long as the class is loaded in memory.

Scopes can be nested. For example, each time you create a block of code, you are creating a new, nested scope.
When this occurs, the outer scope encloses the inner scope. This means that objects declared in the outer scope
will be visible to code within the inner scope. However, the reverse is not true. Objects declared within the inner
scope will not be visible outside it.
To understand the effect of nested scopes, consider the following program:
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
As the comments indicate, the variable x is declared at the start of main( )’s scope and is accessible to all
subsequent code within main( ). Within the if block, y is declared. Since a block defines a scope, y is only
visible to other code within its block. This is why outside of its block, the line y = 100; is commented out. If you
remove the leading comment symbol, a compile-time error will occur, because y is not visible outside of its
block. Within the if block, x can be used because code within a block (that is, a nested scope) has access to
variables declared by an enclosing scope

Operators:
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
 Unary Operator,
 Arithmetic Operator,
 shift Operator,
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator.

Operators Hierarchy:

Expressions:
Expressions are essential building blocks of any Java program, usually created to produce a new value,
although sometimes an expression simply assigns a value to a variable. Expressions are built using values,
variables, operators and method calls.

Expressions are constructed from operands and operators. The operators of an expression indicate
which operations to apply to the operands. The order of evaluation of operators in an expression is determined
by the precedence and associativity of the operators.

Types of Expressions:
While an expression frequently produces a result, it doesn't always. There are three types of expressions in Java:
 Those that produce a value, i.e. the result of (1 + 1)
 Those that assign a variable, for example (v = 10)
 Those that have no result but might have a "side effect" because an expression can include a wide
range of elements such as method invocations or increment operators that modify the state (i.e.
memory) of a program.
 For example:
 Double a = 2.2, b = 3.4, result;
 result = a + b - 3.4;
 Here, a + b - 3.4 is an expression.

Control Statements:The control flow statements in Java allow you to run or skip blocks of code when special
conditions are met.
The “if” Statement:
The if statement is Java’s conditional branch statement. It can be used to route program execution
through a condition. Here is the general form of the if statement:
if (condition)
statement1;
The “if-else” Statement:
The if-else statement is Java’s conditional branch statement. It can be used to route program execution
through two different paths. Here is the general form of the if statement:
if (condition)
statement1;
else
statement2;

Here, each statement may be a single statement or a compound statement enclosed in curly braces (that
is, a block). The condition is any expression that returns a boolean value. The else clause is optional.
int a, b;
// ...
if(a < b) a = 0;
else b = 0;

The if-else-if Ladder:


A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder. It
looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;

switch :
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch
execution to different parts of your code based on the value of an expression. As such, it often provides a better
alternative than a large series of if-else-if statements.
Here is the general form of a switch statement:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char; each of the values specified in the case
statements must be of a type compatible with the expression. Each case value must be a unique literal (that is, it
must be a constant, not a variable). Duplicate case values are not allowed.
Iteration Statements:
Java’s iteration statements are for, while, and do-while. These statements create what we commonly
call loops. As you probably know, a loop repeatedly executes the same set of instructions until a termination
condition is met. As you will see, Java has a loop to fit any programming need.
while:
The while loop is Java’s most fundamental looping statement. It repeats a statement or block while its
controlling expression is true.
Syntax:
while (condition)
{
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long as the
conditional expression is true. When condition becomes false, control passes to the next line of code
immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated.
do-while:
As you just saw, if the conditional expression controlling a while loop is initially false, then the body of
the loop will not be executed at all. However, sometimes it is desirable to execute the body of a while loop at
least once, even if the conditional expression is false to begin with.
Syntax:
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the
conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates.
for:
It is a powerful and versatile construct. Here is the general form of the for statement:
for(initialization; condition; iteration) {
// body
}
If only one statement is being repeated, there is no need for the curly braces.
The for loop operates as follows. When the loop first starts, the initialization portion of the loop is
executed. Generally, this is an expression that sets the value of the loop control variable, which acts as a counter
that controls the loop.. Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop
control variable against a target value. If this expression is true, then the body of the loop is executed. If it is
false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually an expression that
increments or decrements the loop control variable.
Break:
In Java, the break statement has two uses. First, as you have seen, it terminates a statement sequence in
a switch statement. Second, it can be used to exit a loop.
Return:
The last control statement is return. The return statement is used to explicitly return from a method.
That is, it causes program control to transfer back to the caller of the method. As such, it is categorized as a
jump statement.

Type casting and Type conversion:

Widening or Automatic Type Conversion:


Widening conversion takes place when two data types are automatically converted. This happens when:
 The two data types are compatible.
 When we assign value of a smaller data type to a bigger data type.
For Example, in java the numeric data types are compatible with each other but no automatic conversion is
supported from numeric type to char or boolean. Also, char and boolean are not compatible with each other.

Narrowing or Explicit Conversion:


If we want to assign a value of larger data type to a smaller data type we perform explicit type casting or
narrowing.
 This is useful for incompatible data types where automatic conversion cannot be done.
 Here, target-type specifies the desired type to convert the specified value to.
The Type Promotion Rules
Java defines several type promotion rules that apply to expressions. They are as follows: First,
all byte, short, and char values are promoted to int, as just described. Then, if one operand
is a long, the whole expression is promoted to long. If one operand is a float, the entire
expression is promoted to float. If any of the operands is double, the result is double.

The following program demonstrates how each value in the expression gets promoted to match the second
argument to each binary operator:
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}

Let’s look closely at the type promotions that occur in this line from the program:
double result = (f * b) + (i / c) - (d * s);
In the first subexpression, f * b, b is promoted to a float and the result of the subexpression
is float. Next, in the subexpression i/c, c is promoted to int, and the result is of type int. Then,
in d*s, the value of s is promoted to double, and the type of the subexpression is double.
Finally, these three intermediate values, float, int, and double, are considered. The outcome
of float plus an int is a float. Then the resultant float minus the last double is promoted to
double, which is the type for the final result of the expression.

APPLET AND APPLICATION PROGRAM USING SIMPLE JAVA PROGRAM


Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs
inside the browser and works at client side.
There are many advantages of applet. They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.

SIMPLE JAVA PROGRAM:


// Call this file "Example.java".
class Example {
// Your program begins with a call to main().
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}

Where
class is keyword or user defined datatype,
Example is class name
public is access modifier which is used to access the main method by JVM
static is a keyword which is used to access the method directly without using any object of that class.
void is a return type ,here main method doesnot return any values
main is a method
String is a class and datatype
args[] is an array of type string which stores the values entered by the user through keyboard
System is a classname
out is a variable
println is a method in System class.

OPERATORS
Operator in Java is a symbol that is used to perform operations
There are many types of operators in Java
 Unary Operator,
 Arithmetic Operator,
 Shift Operator
 Relational Operator,
 Bitwise Operator,
 Logical Operator,
 Ternary Operator and
 Assignment Operator.
Program: operatorexample.java
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Arrays:
Normally, an array is a collection of similar type of elements which have a contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can
store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st
index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use
the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array
in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages:
 Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
 Random access: We can get any data located at an index position.
Disadvantages:
 Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime.
To solve this problem, collection framework is used in Java which grows automatically.

Types of Array in java:


There are two types of array.
 Single Dimensional Array
 Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java:
dataType[] arr; (or)
dataType []arr; (or)
dataTypearr[];

Instantiation of an Array in Java:arrayRefVar=new datatype[size];

Example of Java Array:


Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
10
20
70
40
50

Declaration, Instantiation and Initialization of Java Array:


We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization

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


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

Passing Array to a Method in Java:


We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using a method.

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


//to method.
class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Output:
3

Anonymous Array in Java:


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

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


//to method.
public class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}
Output:
10
22
44
66

Returning Array from the Method: We can also return an array from the method in Java.

//Java Program to return an array from the method


class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}
Output:
10
30
50
90
60
Multidimensional Array in Java:
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java

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

Example of Multidimensional Java Array:


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

//Java Program to illustrate the use of multidimensional array


class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
123
245
445

Jagged Array in Java:


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

//Java Program to illustrate the jagged array


class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

//printing the data of a jagged array


for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output:
012
3456
78
Addition of 2 Matrices in Java:
Let's see a simple example that adds two matrices.

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


class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
Output:
268
6 8 10

OBJECTS
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical
entity only. An entity that has state and behavior is known as an object e.g: chair, bike.
An object has three characteristics:
 State: represents the data (value) of an object.

 Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.

 Identity: An object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. However, it is used internally by the JVM to identify each object
uniquely.

Program: simpleobject.java
public class simpleobject {
int x = 5;
public static void main(String[] args) {
simpleobject myObj = new Main(); // myObj is an object of class simpleobject
System.out.println(myObj.x);
}}
Constructors:
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for
the object that is why it is known as constructor.
There are basically two rules defined for the constructor.
 Constructor name must be same as its class name
 Constructor must have no explicit return type
Types of java constructors:

There are two types of constructors:

1. Default constructor (no-arg constructor)

2. Parameterized constructor
Default Constructor: A constructor that has no parameter is known as default constructor.
Syntax of default constructor:
classname()
{
//body
}
Example:
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time
of object creation.
class Bike1
{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[])
{
Bike1 b=new Bike1();
}
}
Output: Bike is created

Parameterized constructor: A constructor that has parameter is known as Parameterized constructor.


Syntax of default constructor:
classname(int x)
{
//body
}
Example:
In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.
class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan

Methods:

A Java method is a collection of statements that are grouped together to perform an operation. When
you call the System.out.println() method, for example, the system actually executes several statements in order
to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a method
with or without parameters, and apply method abstraction in the program design.
Creating Method:
the syntax of a method –
modifier returnTypenameOfMethod (Parameter List)
{
// method body
}
The syntax shown above includes –
 modifier − It defines the access type of the method and it is optional to use.
 returnType − Method may return a value.
 nameOfMethod − This is the method name. The method signature consists of the method name and the
parameter list.
 Parameter List − The list of parameters, it is the type, order, and number of parameters of a method.
These are optional, method may contain zero parameters.
 method body − The method body defines what the method does with the statements.
There are two types of methods in Java:
Predefined Method: predefined methods are the method that is already defined in the
Java class libraries. Example: length(), equals(), compareTo(), sqrt()
User-defined Method: The method written by the user or programmer is known as a
user-defined method. These methods are modified according to the requirement.

Parameter passing:
There is only call by value in java, not call by reference. If we call a method passing a value, it is
known as call by value. The changes being done in the called method, is not affected in the calling method.
Example of call by value in java
In case of call by value original value is not changed. Let's take a simple example:
class Operation{
int data=50;
void change(int data)
{
data=data+100;//changes will be in the local variable only
}
public static void main(String args[])
{
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
}
}

Output:
before change 50
after change 50

Program: EvenOdd.java
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}}

ACCESS CONTROL
We can control the access level for class member variables and methods through access
specifiers.
Java's access specifiers are public, private, protected and a default access level.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) {
c = i;
} int getc() {
return c;
}}
public class Main {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 1;
ob.b = 2;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a +
" " + ob.b + " " + ob.getc());
}}

Static Fields and Methods:


The static keyword in java is used for memory management mainly. We can apply java static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the
class.
The static can be:
1. variable (also known as class variable)
2. method (also known as class method)
3. block
4. nested class
1. variable:
If you declare any variable as static, it is known static variable.
 The static variable can be used to refer the common property of all objects (that is not unique for each
object) e.g. company name of employees,college name of students etc.
 The static variable gets memory only once in class area at the time of classloading.
Advantage of static variable:
It makes your program memory efficient (i.e it saves memory).
Example of static variable
//Program of static variable
class Student8
{
int rollno;
String name;
static String college ="MECS";
Student8(int r,String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}
}
Output: 111 Karan MECS
222 Aryan MECS
Java static method:
If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.
Example of static method:
class Student9
{
int rollno;
String name;
static String college = "MECS";
static void change()
{
college = "MATRUSRI";
}
Student9(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan MATRUSRI
222 Aryan MATRUSRI
333 Sonoo MATRUSRI
Java static block:
 It is used to initialize the static data member.
 It is executed before main method at the time of class loading.
Example of static block
class A2
{
Static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}
Output:
static block is invoked
Hello main

Difference between constructor and method in java:

this keyword in java:


Here is given the 6 usage of java this keyword.
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly).
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.

1) this: to refer current class instance variable:


The this keyword can be used to refer current class instance variable. If there is ambiguity between the
instance variables and parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword:
Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,Stringname,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are using
this keyword to distinguish local variable and instance variable. Solution of the above problem by this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,Stringname,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display(); s2.display();
}}
Output:
111 ankit 5000
112 sumit 6000
If local variables(formal arguments) and instance variables are different, there is no need to use this
keyword like in the following program:
Program where this keyword is not required
class Student{
int rollno;
String name;
float fee;
Student(int r,Stringn,float f){
rollno=r;
name=n;
fee=f;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis3{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit 5000
112 sumit 6000

2) this: to invoke current class method:


You may invoke the method of the current class by using the this keyword. If you don't use the this
keyword, compiler automatically adds this keyword while invoking the method. Let's see the example
class A{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
Output:
hello n
hello m

3) this() : to invoke current class constructor:


The this() constructor call can be used to invoke the current class constructor. It is used to reuse the
constructor. In other words, it is used for constructor chaining.
calling default constructor from parameterized constructor:
class A{
A(){System.out.println("hello a");}
A(int x){
this();
System.out.println(x);
}
}
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
Output: hello a
10
Calling parameterized constructor from default constructor:
class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
Output: 5
hello a
Real usage of this() constructor call:The this() constructor call should be used to reuse the constructor from the
constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the
example given below that displays the actual use of this keyword.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,Stringname,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,Stringname,Stringcourse,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis7{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit java null
112 sumit java 6000

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


class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,Stringname,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,Stringname,Stringcourse,float fee){
this.fee=fee;
this(rollno,name,course);//C.T.Error
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis8{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
Output: compile Time Error: Call to this must be first statement in constructor
4) this: to pass as an argument in the method
The this keyword can also be passed as an argument in the method. It is mainly used in the event
handling. Let's see the example:
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Output: method is invoked

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


We can pass the this keyword in the constructor also. It is useful if we have to use one object in
multiple classes. Let's see the example:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Output:10

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


We can return this keyword as an statement from the method. In such case, return type of the method
must be the class type (non-primitive). Let's see the example:
Syntax of this that can be returned as a statement:
return_typemethod_name(){
return this;
}
Example of this keyword that you return as a statement from the method:
class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Output: Hello java

Proving this keyword:


Let's prove that this keyword refers to the current class instance variable. In this program, we are
printing the reference variable and this, output of both variables are same.
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
Output:
A5@22b3ea59
A5@22b3ea59

Super Keyword in Java:


The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable:


We can use super keyword to access the data member or field of parent class. It is used if parent class and child
class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print color
property, it will print the color of current class by default. To access the parent property, we need to use super
keyword.
2) super can be used to invoke parent class method:
The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method from Dog
class, it will call the eat() method of Dog class by default because priority is given to local.
To call the parent class method, we need to use super keyword.

3) super is used to invoke parent class constructor:


The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created
***** super() is added in each class constructor automatically by compiler if there is no super() or this().
As we know well that default constructor is provided by compiler automatically if there is no
constructor. But, it also adds super() as the first statement.
Another example of super keyword where super() is provided by the compiler implicitly.
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
System.out.println("dog is created");
}
}
class TestSuper4{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created

Java Garbage Collection:


In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words,
it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.
Advantage of Garbage Collection:
 It makes java memory efficient because garbage collector removes the unreferenced objects from heap
memory.
 It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
How can an object be unreferenced?
There are many ways:
1. By nulling the reference
2. By assigning a reference to another
3. By anonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();

finalize() method:
The finalize() method is invoked each time before the object is garbage collected. This method can be
used to perform cleanup processing. This method is defined in Object class as:
protected void finalize(){}
** The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have
created any object without new, you can use finalize method to perform cleanup processing (destroying
remaining objects).
gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.
public static void gc(){}
*** Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the
finalize() method before object is garbage collected.
Simple Example of garbage collection in java:
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
object is garbage collected
** Neither finalization nor garbage collection is guaranteed.

Method Overloading in Java:


If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the readability
of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments,
if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may
be difficult for you as well as other programmers to understand the behavior of the method because its name
differs.
So, we perform method overloading to figure out the program quickly.
Advantage of method overloading:
Method overloading increases the readability of the program.
Different ways to overload the method:
There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
1) Method Overloading: changing no. of arguments:
In this example, we have created two methods, first add() method performs addition of two numbers
and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,intb,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
2) Method Overloading: changing data type of arguments:
In this example, we have created two methods that differs in data type. The first add method receives
two integer arguments and second add method receives two double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9

Constructor Overloading: In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types.
Example of Constructor Overloading:
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,Stringn,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25

String Handling:
string is basically an object that represents sequence of char values. An array of characters works same
as java string. For example:
 char[] ch={'j','a','v','a','t','p','o','i','n','t'};
 String s=new String(ch);
1. String s="javatpoint";
2. Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()etc.
3. The java.lang.String class implements Serializable, Comparable and CharSequence interface

The CharSequence interface is used to represent sequence of characters. It is implemented by String,


StringBuffer and StringBuilder classes. It means, we can create string in java by using these 3 classes.

The Java String is immutable which means it cannot be changed. Whenever we change any string, a
new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.
There are two ways to create String object:
1. By string literal
2. By new keyword

String Literal:
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
By new keyword:

1. String s=new String("Welcome");//creates two objects and one reference variable


In such case, JVM will create a new string object in normal (non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap (non
pool).

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}

Output:
java
strings
example

In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.

Let's try to understand the immutability concept by the example given below:

class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}}
Output:Sachin

class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}}
Output:Sachin Tendulkar

Java StringBuffer class:


Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is
same as String class except it is mutable i.e. it can be changed.Java StringBuffer class is thread-safe i.e. multiple
threads cannot access it simultaneously. So it is safe and will result in an order.
Important Constructors of StringBuffer class:

Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of 16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.

Important methods of StringBuffer class:

Modifier and Method Description


Type

public append(String s) is used to append the specified string with this string. The
synchronized append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float), append(double)
etc.

public insert(int offset, String is used to insert the specified string with this string at the
synchronized s) specified position. The insert() method is overloaded like
StringBuffer insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.

public replace(int startIndex, is used to replace the string from specified startIndex and
synchronized int endIndex, String str) endIndex.
StringBuffer

public delete(int startIndex, int is used to delete the string from specified startIndex and
synchronized endIndex) endIndex.
StringBuffer

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() is used to return the current capacity.

public void ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) is used to return the character at the specified position.

public int length() is used to return the length of the string i.e. total number of
characters.

public String substring(int is used to return the substring from the specified beginIndex.
beginIndex)

public String substring(int is used to return the substring from the specified beginIndex
beginIndex, int and endIndex.
endIndex)

What is mutable string:


A string that can be modified or changed is known as mutable string. StringBuffer and StringBuilder
classes are used for creating mutable string.

1) StringBuffer append() method: The append() method concatenates the given argument with this string.

class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

Java StringBuilder class:


Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is
same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

Important Constructors of StringBuilder class

Constructor Description

StringBuilder() creates an empty string Builder with the initial capacity of 16.

StringBuilder(String str) creates a string Builder with the specified string.

StringBuilder(int length) creates an empty string Builder with the specified capacity as length.

Important methods of StringBuilder class

Method Description

public StringBuilder is used to append the specified string with this string. The append()
append(String s) method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.

public StringBuilder is used to insert the specified string with this string at the specified
insert(int offset, String s) position. The insert() method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int, float), insert(int, double)
etc.

public StringBuilder is used to replace the string from specified startIndex and endIndex.
replace(int startIndex, int
endIndex, String str)

public StringBuilder is used to delete the string from specified startIndex and endIndex.
delete(int startIndex, int
endIndex)

public StringBuilder is used to reverse the string.


reverse()

public int capacity() is used to return the current capacity.


public void is used to ensure the capacity at least equal to the given minimum.
ensureCapacity(int
minimumCapacity)

public char charAt(int is used to return the character at the specified position.
index)

public int length() is used to return the length of the string i.e. total number of characters.

public String substring(int is used to return the substring from the specified beginIndex.
beginIndex)

public String substring(int is used to return the substring from the specified beginIndex and
beginIndex, int endIndex) endIndex.

Java StringBuilder Examples:


Let's see the examples of different methods of StringBuilder class.
1) StringBuilder append() method
The StringBuilder append() method concatenates the given argument with this string.

class StringBuilderExample{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}

Difference between String and StringBuffer:


There are many differences between String and StringBuffer. A list of differences between String and
StringBuffer are given below:

No. String StringBuffer

1 String class is immutable. StringBuffer class is mutable.


)

2 String is slow and consumes more memory when you StringBuffer is fast and
) concat too many strings because every time it creates consumes less memory when you
new instance. cancat strings.

3 String class overrides the equals() method of Object StringBuffer class doesn't
) class. So you can compare the contents of two strings by override the equals() method of
equals() method. Object class.

Difference between StringBuffer and StringBuilder:


Java provides three classes to represent a sequence of characters: String, StringBuffer, and
StringBuilder. The String class is an immutable class whereas StringBuffer and StringBuilder classes are
mutable. There are many differences between StringBuffer and StringBuilder. The StringBuilder class is
introduced since JDK 1.5.
A list of differences between StringBuffer and StringBuilder are given below:

No. StringBuffer StringBuilder

1 StringBuffer is synchronized i.e. thread safe. StringBuilder is non-synchronized i.e. not


) It means two threads can't call the methods thread safe. It means two threads can call the
of StringBuffer simultaneously. methods of StringBuilder simultaneously.

2 StringBuffer is less efficient than StringBuilder is more efficient than


) StringBuilder. StringBuffer.

Access Modifiers in Java:


There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifier in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the
class.
Default: The access level of a default modifier is only within the package. It cannot be accessed from outside
the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the package through child
class. If you do not make the child class, it cannot be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the
class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient,
etc. Here, we are going to learn the access modifiers only.
Understanding Java Access Modifiers:
Let's understand the access modifiers in Java by a simple table.

Access Modifier within class within package outside package by subclass only outside package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

1) Private:The private access modifier is accessible only within the class.


Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member and private
method. We are accessing these private members from outside the class, so there is a compile-time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor:
If you make any class constructor private, you cannot create the instance of that class from outside the class. For
example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
**A class cannot be private or protected except nested class.

2) Default:If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more accessibility than private.
But, it is more restrictive than protected, and public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside
the package.

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

Example of protected access modifier


In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as protected,
so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) Public:
The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example of public access modifier
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

Final Keyword in Java:


The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
variable
method
class
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only. We will have detailed learning of
these. Let's first learn the basics of final keyword.
1) Java final variable:
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output: Compile Time Error
2) Java final method:
If you make any method as final, you cannot override it.
Example of final method
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output: Compile Time Error
3) Java final class:

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

Example of final class:


final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output: Compile Time Error
Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Output :running...

Inheritance:
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Why use inheritance in java?
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.

Terms used in Inheritance:


Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also
called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields
and methods of the existing class when you create a new class. You can use the same fields and methods already
defined in the previous class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class
is called child or subclass.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee
class i.e. code reusability.
Types of inheritance in java:
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will
learn about interfaces later.

***Multiple inheritance is not supported in Java through class.


Single Inheritancee:
When a class inherits another class, it is known as a single inheritance. In the example given below,
Dog class inherits the Animal class, so there is the single inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance:
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:

weeping...
barking...
eating..

Hierarchical Inheritance:
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:

meowing...
eating...
Q) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and
B classes have the same method and you call it from child class object, there will be ambiguity to call the
method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit
2 classes. So whether you have same method or different, there will be compile time error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output: Compile Time Error

Using final with Inheritance:


If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Output:Compile Time Error
Is final method inherited?
Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Output:running..
Method Overriding:
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been declared
by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
 Method overriding is used to provide specific implementation of a method that is already provided by
its super class.
 Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


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

Example of method overriding

Class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){ Bike2 obj = new Bike2();
obj.run();
}
Output:Bike is running safely
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){ SBI s=new SBI();
ICICI i=new ICICI(); AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest()); System.out.println("ICICI Rate of Interest:
"+i.getRateOfInterest()); System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Abstract class:
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java:
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS
where you type the text and send the message. You don't know the internal processing about the message
delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)

Abstract class in Java:


A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember:
 An abstract class must be declared with an abstract keyword.
 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the method.
Example of abstract class:
abstract class A{}
Abstract Method in Java
A method which is declared as abstract and does not have implementation is known as an abstract method.
Example of abstract method:
abstract void printStatus();//no method body and abstract
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation
is provided by the Honda class.

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
OUTPUT:running safely
Understanding the real scenario of Abstract class:
In this example, Shape is the abstract class, and its implementation is provided by the Rectangle and
Circle classes.
Mostly, we don't know about the implementation class (which is hidden to the end user), and an object
of the implementation class is provided by the factory method.
A factory method is a method that returns the instance of the class. We will learn about the factory
method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.
abstract class Shape{
abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user
class TestAbstraction1{
public static void main(String args[]){
Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., getShape() method
s.draw();
}
}
OUTPUT: drawing circle

Abstract class having constructor, data member and methods.


An abstract class can have a data member, abstract method, method body (non-abstract method), constructor,
and even main() method.
//Example of an abstract class that has abstract and non-abstract methods
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
}
//Creating a Child class which inherits Abstract class
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
//Creating a Test class which calls abstract and non-abstract methods
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
OUTPUT:
bike is created
running safely..
gear changed
****If there is an abstract method in a class, that class must be abstract.
class Bike12{
abstract void run();
}
OUTPUT:compile time error
***If you are extending an abstract class that has an abstract method, you must either provide the
implementation of the method or make this class abstract.
The abstract class can also be used to provide some implementation of the interface. In such case, the end user
may not be forced to override all the methods of the interface.

You might also like