Advanced Prog-Java Unit1 Study Material 24-25
Advanced Prog-Java Unit1 Study Material 24-25
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.
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
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.
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.
2. Multi Line Comment: The multi line comment is used to comment multiple lines of code.
Syntax: /* This is multi line comment */
Data Types:
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.
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.
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;
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.
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.
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.
Returning Array from the Method: We can also return an array from the method 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;
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:
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
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());
}}
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.
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 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:
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
Constructor Description
StringBuffer() creates an empty string buffer with the initial capacity of 16.
StringBuffer(int capacity) creates an empty string buffer with the specified capacity as length.
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 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)
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
}
}
Constructor Description
StringBuilder() creates an empty string Builder with the initial capacity of 16.
StringBuilder(int length) creates an empty string Builder with the specified capacity as length.
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 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.
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
}
}
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.
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
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.
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
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.
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
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%)