UNIT- I
UNIT- I
● Direct mapping of concepts in the problem domain to software units and their interfaces
● Viewing the world as objects is more natural since it is closer to the way humans think
● Objects are more stable than functions…
● Supports information hiding, data abstraction, and encapsulation
● Easily modified, extended, and maintained
3. OBJECT-ORIENTED MODEL
● The fundamental idea behind object-oriented languages is to combine into a single program entity
both data and the functions that operate on that data. Such an entity is called an object.
● An object's functions, called member functions in C++ (because they belong to a particular class of
objects), typically provide the only way to access its data.
● If you want to read a data item in an object, you call a member function in the object. It will read the
item and return the value to you.
● You can't access the data directly.
● The data is hidden, so it is safe from accidental alteration.
● Data and its functions are said to be encapsulated into a single entity.
● Encapsulation and data hiding are key terms in the description of object-oriented languages.
2. History of JAVA:
● In 1995, Sun Microsystems officially announced the first version of java programming language and also
Hot Java ( Web-Runner) the firs web-browser to run java applications.
● Later several companies like Netscape INC., Microsoft have developed their own web-browsers which
would support java. Some of the web-browsers were Netscape Navigator, Internet Explorer etc.,.
Now-a-days, many other browsers like Google Chrome, Mozilla etc. are also being used.
● On 23rd January 1995, first version of Java i.e., jdk1.0 was released.
‘” jdk “ stands for “ java development toolkit “. After jdk1.0 we have jdk1.1, jdk1.2,…….jdk1.6 versions
• Every microprocessor can recognize a set of instructions known as Instruction Set of that micro processor.
These Instruction Sets will be different for each and every micro processor. That is, if we generate an
executable file (.exe) with Pentium processor then the code in .exe file can be understood only by Pentium
processor.
• If we try to execute that .exe file using another processor then we will not be successful. Similarly, if .exe
file is generated using unix Operating System then it cannot be executed on other operating system like
DOS. (Disc Operating System).
• Reason : Every Operating system stores data and instructions in various formats.
▪ Ex: addition of two numbers
• So, if we try to execute a add b instruction on DOS the it will not be executed.
• Thus it is not possible to execute same .exe file on all operating systems. That is, C/C++ programs cannot
be executed on a different configuration.
• Now, if we develop any software using C/C++ and distributes it on internet, then .exe files can be
downloaded from internet, but those files cannot run on our computer, since the configuration may not
be the same.
• Thus, in order to develop softwares for internet, we need System Independent Language and that is JAVA.
• Therefore, .class file contains BYTE CODE for the SOURCE CODE present in the program written by user.
• But, micro processor cannot understand these instructions and cannot execute them. Infact, these
instructions are meant for JVM i.e. JAVA VIRTUAL MACHINE.
• Byte code will be understood by JVM. JVM is a program written to understand byte code instructions and
convert them into machine code.
• JVM will be freely available on internet and can be downloaded for use.
• Ex: Name of the program 🡪 demo.java ( java programs with .java extension ).
⮚ Processor 🡪 Pentium
• demo.class is given to JVM. Now JVM converts this byte code into a format that is understood by the
pentium processor. So, Pentium processor executes the program and displays output. Also, JVM
understands the type of operating system in computer and performs the instructions according to it.
• Now if we send demo.class file to another computer having different processor and OS then JVM of that
computer will convert byte code into a format that is understood by the processor in that computer.
• Thus, the same .class file can be executed on any computer, with any processor and OS, provided if JVM is
available on that computer. Byte code is system independent. It can be created on any computer by using
these 200 instructions only.
• JVM is system dependent. Since it has to interact with the processor and OS of that computer, that is, if we
have windows version of OS in our computer then we should use windows version of JVM only.
• Since, java programs can be executed on any Processor/OS combination, therefore, JAVA is said to be
SYSTEM or PLATFORM INDEPENDENT PROGRAMMING LANGUAGE.
• Therefore, if a software is developed using JAVA then .class files can be downloaded from internet and can
be executed on any computer without any problem. Thus, in order to develop software for internet, JAVA
language is suitable.
• JAVA VIRTUAL MACHINE is a interpreter of byte code. Translating java program into byte code is very
useful to run program on any OS because though details of JVM differ from OS to OS, but all will interpret
the same byte code. Usage of byte code, enables java run-time system to execute program very fast.
6. JVM Architecture:
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent).
It is:
1. A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java class, and
instance of JVM is created.
What it does?
● Loads code
● Verifies code
● Executes code
● Provides runtime environment
● Memory area
● Class file format
● Register set
● Garbage-collected heap
● Fatal error reporting etc.
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.
1) Class loader:
● Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data,
the code for methods.
3) Heap:
4) Stack:
● Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation
and return.
● Each thread has a private JVM stack, created at the same time as thread.
● A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.
● PC (program counter) register. It contains the address of the Java virtual machine instruction currently
being executed.
7) Execution Engine:
It contains:
● A virtual processor
● Interpreter: Read byte code stream then execute the instructions.
● Just-In-Time(JIT) compiler: It is used to improve the performance.JIT compiles parts of the byte code that
have similar functionality at the same time, and hence reduces the amount of time needed for
compilation. Here the term ?compiler? refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.
7. Classification of JAVA :
⮚ JAVA Standard Edition contains basic core java concepts. This edition is used to develop applets.
⮚ JAVA Enterprise Edition contains many concepts and classes that are beyond Java SE. it concentrates
on providing business solutions on network.
⮚ JAVA Micro Edition is for developers, who develop code for portable devices such as cell phones. This
code should occupy less memory and small in size.
8. Features of JAVA:
1. Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important
key feature of java language that makes java as the most powerful language. Not even a single language is
idle to this feature but java is more closer to this feature. The programs written on one platform can run
on any platform provided the platform must have the JVM.
2. Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It provides the
powerful exception handling and type checking mechanism as compare to other programming languages.
Compiler checks the program whether there any error and interpreter checks any run time error and
makes the system secure from crash. All of the above features makes the java language robust.
3. Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet programmers can call
functions on these protocols and can get access the files from any remote machine on the internet rather
than writing codes on their local system.
4. Portable
The feature Write-once-run-anywhere makes the java language portable provided that the system must
have interpreter for the JVM. Java also have the standard data size irrespective of operating system or the
processor. These features makes the java as a portable language.
5. Secure
security is an important issue for a language that is used for programming on internet. Threat for several
viruses will be present always. Java programs not only verify all memory access but also ensures that there
are no viruses communicated with applet. The absence of pointers in java ensures that programs cannot
gain access to memory locations without proper authorization.
6. Dynamic
While executing the java program the user can get the required files dynamically from a local drive or from
a computer thousands of miles away from the user just by connecting with the Internet.
7. Compiled and Interpreted
A computer language is either compiled or interpreted in general. Java combines both these approaches
thus making java a two-stage system. First, java converts source code into byte code. Second java
interpreter (JVM) generates machine code that can be executed by the machine. Thus, java is both
compiled and interpreted.
8. Multi-Threaded
Multi-Threaded means handling multiple tasks simultaneously. Multi-Threaded programs are supported by
java. It means there is no need to wait for the application to finish one task before beginning the other
task.
Ex: we check our e-mails and at the same time we can run a movie clip.
This feature, greatly improves the interactive performance of graphical applications.
Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color, Button, System,
Thread etc.
interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote,
ActionListener etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(),
println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
Package statements
Import statements
Interface statements
Class definition
2. Package statement : is the 1st statement that is allowed in java program. This statement specifies or
declares that the classes defined in the program will belong to this particular package. Some of the
packages in java are :
java.lang, java.io, java.awt etc.,,,
3. Import statement : will be used in java in order to use the classes and methods of that package. Import
statement in java is similar to #include statement in c and c++.
ex: import java . io.*; now, all classes and methods of io package can be accessed in our program
Note: by default java.lang ( language) package will be imported into our java program.
● #include in c/c++ copies the entire code o the header file into our program (.exe file)
● import statement makes JVM to go to standard library , execute the program there and then
substitute the result in the program.
4. Interface statement : interface is like a class which includes only method declarations but not definitions.
5. Class definition and main() method class : after importing package we have to write classes. A java
program may contain multiple class definitions. Since java is OOP language any program in java cannot be
written without using class or object.
Source Code :
/* This is my first java program. This will print 'Hello World' as the output */
class MyFirstJavaProgram
{
Declaring Variables
• Variables hold one value at a time, but that value can change
• Syntax is:
dataType identifier;
or
dataType identifier1, identifier2, …;
Assigning Values to Variables
• Assignment operator =
– Value on the right of the operator is assigned to the variable on the left
– Value on the right can be a literal (text representing a specific value), another variable, or an
expression (explained later)
• Syntax:
dataType variableName = initialValue;
or
dataType variable1 = initialValue1, variable2 = initialValue2, …;
Types of Variable
● local variable
● instance variable
● static variable
Local Variable
A variable that is declared inside the method is called local variable.
Instance Variable
A variable that is declared inside the class but outside the method is called instance variable . It is not declared
as static.
Static variable
A variable that is declared as static is called static variable. It cannot be local.
Example:
class A
{
int data=50; //instance variable
static int m=100; //static variable
void method()
{
int n=90; //local variable
}
} //end of class
Constants
Note: assigning a value when the constant is declared is optional. But a value must be assigned before the constant
is used.
Note: string is a class but we are taking it as object also since, we consider every class is a user-defined data type.
14.Operators in Java
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following
groups:
● Arithmetic Operators
● Relational Operators
● Bitwise Operators
● Logical Operators
● Assignment Operators
● Other Operators
Arithmetic Operators:
⮚ Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
⮚ The following table lists the arithmetic operators:
Operator Description Example
Relational Operators:
Bitwise Operators:
Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and perform bit by bit operation. Assume if a = 60; and b = 13; Now in binary format
they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
& Binary AND Operator copies a bit to (A & B) will give 12 which is 0000 1100
the result if it exists in both operands.
^ Binary XOR Operator copies the bit if it (A ^ B) will give 49 which is 0011 0001
is set in one operand but not both.
~ Binary Ones Complement Operator is (~A ) will give -60 which is 1100 0011
unary and has the efect of 'flipping'
bits.
<< Binary Left Shift Operator. The left A << 2 will give 240 which is 1111 0000
operands value is moved left by the
number of bits specified by the right
operand.
>> Binary Right Shift Operator. The left A >> 2 will give 15 which is 1111
operands value is moved right by the
number of bits specified by the right
operand.
>>> Shift right zero fill operator. The left A >>>2 will give 15 which is 0000 1111
operands value is moved right by the
number of bits specified by the right
operand and shifted values are filled
up with zeros.
Logical Operators:
&& Called Logical AND operator. If both the operands (A && B) is false.
are non zero then then condition becomes true.
! Called Logical NOT Operator. Use to reverses the !(A && B) is true.
logical state of its operand. If a condition is true
then Logical NOT operator will make false.
Assignment Operators:
Other Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to
evaluate boolean expressions. The goal of the operator is to decide which value should be assigned to the variable.
The operator is written as :
Value of b is : 30
Value of b is : 20
instance Of Operator:
This operator is used only for object reference variables. The operator checks whether the object is of a particular
type(class type or interface type). instanceOf operator is wriiten as:
If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface
type on the right side then the result will be true. Following is the example:
This operator will still return true if the object being compared is the assignment compatible with the type on the
right. Following is one more example:
class Vehicle {
true
● while Loop
● do...while Loop
● for Loop
APART FROM THE ABOVE 3 WE HAVE ANOTHER LOOP CALLED AS for-each loop
While Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true then the actions inside the loop will be executed.
Here key point of the while loop is that the loop might not ever run. When the expression is tested and the result is
false, the loop body will be skipped and the first statement after the while loop will be executed.
do...while Loop:
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
Syntax:
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop execute once
before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute
again. This process repeats until the Boolean expression is false.
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific
number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:
1. The initialization step is executed first, and only once. This step allows you to declare and initialize any
loop control variables. You are not required to put a statement here, as long as a semicolon appears.
2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the
body of the loop does not execute and flow of control jumps to the next statement past the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the update statement. This
statement allows you to update any loop control variables. This statement can be left blank, as long as a
semicolon appears after the Boolean expression.
4. The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then update step,then Boolean expression). After the Boolean expression is false, the
for loop terminates.
for-each loop
Syntax:
for(declaration : expression)
{
//Statements
}
● Declaration . The newly declared block variable, which is of a type compatible with the elements of the
array you are accessing. The variable will be available within the for block and its value would be the same
as the current array element.
● Expression . This evaluate to the array you need to loop through. The expression can be an array variable
or method call that returns an array.
break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch
statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of code after the
block.
Syntax:
break;
Continue Keyword:
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to
the next iteration of the loop.
● In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.
● In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.
Syntax:
continue;
if Statement:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
if...else Statement:
An if statement can be followed by an optional else statement, which executes when the Boolean expression is
false.
Syntax:
if(Boolean_expression)
{
//Executes when the Boolean expression is true
}
Else
{
//Executes when the Boolean expression is false
}
When using if , else if , else statements there are few points to keep in mind.
● An if can have zero or one else's and it must come after any else if's.
● An if can have zero to many else if's and they must come before the else.
● Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
}
else if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
else if(Boolean_expression 3)
{
//Executes when the Boolean expression 3 is true
}
else
{
//Executes when the none of the above condition is true.
}
It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or
else if statement.
Syntax:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
Switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and
the variable being switched on is checked for each case.
Syntax:
switch(expression)
{
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
● The variable used in a switch statement can only be a byte, short, int, or char.
● You can have any number of case statements within a switch. Each case is followed by the value to be compared to
and a colon.
● The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
● When the variable being switched on is equal to a case, the statements following that case will execute until
a break statement is reached.
● When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following
the switch statement.
● Not every case needs to contain a break. If no break appears, the flow of control will fall throughto subsequent
cases until a break is reached.
● A switch statement can have an optional default case, which must appear at the end of the switch. The default case
can be used for performing a task when none of the cases is true. No break is needed in the default case.
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the
above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
You can create an array by using the new operator with the following syntax:
Array_name = new dataType[Size of the array];
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of
array the variable can reference. Here is the syntax for declaring an array variable:
dataType []array_name ; .
or
dataType array_name[];
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be
combined in one statement, as shown below:
dataType []Array_name = new dataType[Size of the array];
● Java array class comes up with length() property by which you can get size of java array.
● The java array length returns ( integer value) number of total elements in an array.
● Length property of array can be used while accessing arrays using loops.
class Array_Length
{
public static void main(String args[])
{
// Try with a int array
int[] num={10,20,30,40,50,60,70,80,90,100};
}
}
Output
------------------------------------
⮚ Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from one array into another:
public static void arraycopy(Object src, int src_Pos, Object dest, int dest_Pos, int length)
The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify
the starting position in the source array, the starting position in the destination array, and the number of array
elements to copy.
The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated". It
uses arraycopy to copy a subsequence of array components into a second array:
class ArrayCopyDemo
{
public static void main(String[] args)
{
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' };
System.out.println(new String(copyTo));
}
}
The output from this program is:
caffein
The user can enter command-line arguments when invoking the application.
When running the java program from java command, the arguments are provided after the name of the class
separated by space.
Program to demonstrate command line arguments
class command
{
public static final void main(String args[])
{
for (int i=0;i<args.length;++i)
{
System.out.println( args[i] );
}
}
}
Output
1. POP Vs. OOP
Data Moving In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other through
member functions.
Expansion To add new data and function in POP is OOP provides an easy way to add new
not so easy. data and function.
Data Access In POP, Most function uses Global data In OOP, data can not move easily from
for sharing that can be accessed freely function to function,it can be kept public
from function to function in the system. or private so we can control the access of
data.
Data Hiding POP does not have any proper way for OOP provides Data Hiding so
hiding data so it is less secure. provides more security.
I. OBJECT:
Anything that exists in the real world is said to be object
⮚ An object may be a name of person, place or thing etc.,,
⮚ Every object will have some property and behavior.
⮚ Object is a variable of type class.
II. CLASS:
⮚ Class is a collection of objects
⮚ Class is a common name given to a group of objects
⮚ For example: IT-2 is name of class. Each and every student present in IT-2 class is said to be a object.
⮚ In computer terminology class is called as collection of data and functions.
⮚ Properties of object are represented by data (variables)
⮚ Behavior of object is represented by functions of the class.
Example:
2.
objects class
I. INHERITANCE:
● One class using the properties of another class is said to be inheritance. Ex: parents - children
● Code reusability is achieved through inheritance
● Class whose properties are used by other class is called as SUPER CLASS.
● Class which uses the properties of other class is said to be SUB CLASS.
II. PLOYMORPHISM
⮚ Ability to exist in different forms is said to be polymorphism.
⮚ POLY means MANY
⮚ MORPHISM means FORMS
⮚ Example:
I. * is used for multiplication and also for declaring a pointer variable
II. >> and << are used for right and left shift of bit operations and also along with cin and cout in
CPP.
III. ABSTRACTION:
⮚ Hiding the actual content and showing only the required content is said to be abstraction.
⮚ Example: index of text book, google search engine etc.,,
⮚ Advantage of abstraction is every user will get his/her own view of the data.
IV. ENCAPSULATION:
⮚ Wrapping (combining) up of data and function into a single unit is called as encapsulation.
⮚ Data will be not accessible to external classes. Only those functions that are present in that class can
access that data.
class class_name
{
Variable declarations (properties)
Methods (actions)
}
Local variables are the variables that are declared with in a particular block.
Example:
void xyz()
{
int x; // x is a local variable
}
Instance variables are the variables which are accessed from the object.
Example:
class A
{
int k;
void xyz()
{
int x;
}
}
class B
{
public static void main(String args[])
{
A y = new A();
y.k=20;
y.xyz();
}
}
Static variables are the variables which can be accessed using the class name.
Example:
class A
{
static int x; // this can be accessed as A.x
}
I. Using methods
II. Using objects
III. Using constructors
class access
{
public static void main(String args[])
{
one k=new one();
k.getdata(10,20);
System.out.println("area="+k.area());
}
}
class one
{
int a,b;
}
class access1
{
public static void main(String args[])
{
one k=new one();
k.a=10; // passing values using objects
k.b=20; // passing values using objects
int c= k.a * k.b;
System.out.println(c); } }
3rd method of passing values to variables in using constructors
PROPERTIES OF CONSTRUCTOR:
5. Overloading of Constructors
OVERLOADING OF CONSTRUCTOR MEANS GIVING A DIFFERENT MEANING TO THE CONSTRUCTOR.
import java.io.*;
class box
{
double height , width , depth;
box()
{
height = 10;
width = 20;
depth = 30;
}
box( double h, double w, double d)
{
height = h;
width = w;
depth = d;
}
}
class overload
{
public static void main(String[] args) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter values");
double x = Double.parseDouble(br.readLine());
double y = Double.parseDouble(br.readLine());
double z = Double.parseDouble(br.readLine());
box b1 = new box();
box b2 = new box(x,y,z);
System.out.println("voulme is "+ b1.height * b1.width * b1.depth);
System.out.println("voulme is "+ b2.height * b2.width * b2.depth);
}
}
(initializing the object of one class through the another object of same class)
class first
{
int a,b;
float c;
first(int i, int j,float k)
{
a=i;
b=j;
c=k;
}
first(first d)
{
System.out.println(d.a + d.b +d.c);
}
void display()
{
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
class copy
{
public static void main(String[] args)
{
first f1 = new first(10,20,3.4f);
f1.display();
first f2 = new first(f1);
}
}
6. Overloading of Methods
⮚ 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.
A method definition consists of a method header and a method body. Here are all the parts of a method:
● Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type
of the method.
● Return Type: A method may return a value. The returnValueType is the data type of the value the method returns.
Some methods perform the desired operations without returning a value. In this case, the returnValueType is the
keyword void.
● Method Name: This is the actual name of the method. The method name and the parameter list together
constitute the method signature.
● Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of
the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
● Method Body: The method body contains a collection of statements that define what the method does.
Example:
Calling a method is done as follows:
⮚ There are two ways to call a method; the choice is based on whether the method returns a value or
not.
⮚ When a program calls a method, program control is transferred to the called method.
⮚ A called method returns control to the caller when its return statement is executed or when its
method-ending closing brace is reached.
If the method returns a value, a call to the method is usually treated as a value. For example:
If the method returns void, a call to the method must be a statement. For example, the method println returns
void. The following call is a statement:
System.out.println("Welcome to Java!");
Overloading of methods
Method name will be the same but different parameters will be passed
//METHOD OVERLOADING PROGRAM
class one
{
int a,b,c;
void demo()
{
System.out.println("no attributes");
}
void demo( int a)
{
System.out.println(a * a);
}
1. Overriding of methods
● If a class inherits a method from its super class, then there is a chance to override the method provided
that it is not marked final.
● The benefit of overriding is: ability to define a behavior that's specific to the sub class type. Which means
a subclass can implement a parent class method based on its requirement.
● In object oriented terms, overriding means to override the functionality of any existing method.
class demo1
{
void display()
{
System.out.println("base class");
}
}
class demo2 extends demo1
{
void display()
{
System.out.println("derived class");
} }
class overriding
{
public static void main(String[] args)
{
demo2 d2 = new demo2();
d2.display();
d2.display();
}
}
Following are rules of method overriding in java which must be followed while overriding any method. as stated
earlier private, static and final method can not be overridden.
1. Method signature must be same including return type, number of method parameters, type of
parameters and order of parameters
2. Overriding method can not throw higher Exception than original or overridden method. means if original
method throws IOException than overriding method can not throw super class of IOException e.g.
Exception but it can throw any sub class of IOException or simply does not throw any Exception. This rule
only applies to checked Exception in Java, overridden method is free to throw any unchecked Exception.
3. Overriding method can not reduce accessibility of overridden method , means if original or overridden
method is public than overriding method can not make it protected.
● A static method can access only static data. It can not access non-static data (instance variables)
● A static method can call only other static methods and can not call a non-static method from it.
● A static method can be accessed directly by the class name and doesn’t need any object
● Syntax : <class-name>.<method-name>
class StaticMethod
{
static int j = 0;
class TestStatic
{
public static void main(String args[])
{
StaticMethod.getVariable();
}
}
Static block
The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the
JVM
class staticblock
{
static
{
System.out.println("static block");
}
public static void main(String[] args)
{
System.out.println("static method");
}
}
3. finalize() method
⮚ It is possible to define a method that will be called just before an object's final destruction by the
garbage collector. This method is called finalize( ), and it can be used to ensure that an object
terminates cleanly.
⮚ For example, you might use finalize( ) to make sure that an open file owned by that object is closed.
⮚ To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that
method whenever it is about to recycle an object of that class.
⮚ Inside the finalize( ) method you will specify those actions that must be performed before an object is
destroyed.
⮚ Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside
its class.
⮚ This means that you cannot know when.or even if.finalize( ) will be executed. For example, if your
program ends before garbage collection occurs, finalize( ) will not execute.
4. Instance methods
Methods which act up on the instance variables are called as instance methods.
To call instance methods, object is required, since, instance variables are contained in the object.
Objectname.methodname()
1. Accessor methods
2. Mutator methods
Methods which can not only access instance variables but also modify them are called as mutator methods.
Methods which can only access instance variables but can not modify them are called as accessor methods.
class person
{
String name; int age;
void setname(String name)
{
this.name=name;
}
void setage(int age)
{
this.age=age;
}
String getname()
{
return name;
}
int getage()
{
return age;
}
}
class instancedemo
{
public static void main(String[] args)
{
person p1=new person();
p1.setname("james");
p1.setage(25);
System.out.println(p1.getname());
System.out.println(p1.getage());
}
}
Java includes two types of variables – primitive variables and reference variables. A primitive type refers
a primitive data type and reference type refers class. Observe the following:
public class Demo
{
int x = 10;
public static void main(String args[])
{
Demo d1;
// System.out.println(d1.x);
d1 = new Demo();
System.out.println(d1.x);
}
}
We have created and used many objects in all the previous programs. Now let us analyze the code of creating an
object.
The general way of creating an object is of the following format.
Demo d1 = new Demo();
In the above statement, we say, object d1 is instantiated.
What is an object and instance?
Generally a C++ programmer will say immediately, "an instance of a class is known as object". Of course, he is very
right but the statement will be very confusing to a novice. Let us be clearer through some common day-to-day
example. We cut a tree and get the wood. How to make use of the wood? Wood itself is waste as we cannot use it
straight away. The wood should be converted into objects like door, table and duster and then used. Without these
objects, simply, wood is waste. We say door, table and duster are the instances of wood. Door is an object of
wood or we can say, the door is an instance of wood.
Similarly we have a class containing constructors, variables and methods (all these are known as constructs of a
class). How to make use of them? We require objects of the class. Using these objects we can access the contents
of the class. The object is d1. With d1, all the contents of the class can be made use of. Now we can say, the
instance of a class is object. For this reason object creation is known as instantiation. No object, class is simply
waste.
System.out.println(d1.x); // prints 10
d2 = d1; // an object is assigned to a reference variable
System.out.println(d2.x);
// prints 10 as now reference variable works like an object
d1 = new Demo();
In the above statement, the right-side expression, new Demo(), is known asanonymous object. If an anonymous
object is not assigned a value, like d1, what happens to the anonymous object.
new Demo();
In the above statement, d1 is not assigned. The anonymous object is created and dies instantaneously. But, still
with anonymous objects work can be extracted before it dies as follows.
As you can observe in the code, the anonymous object can be used only once in the program. We can’t use twice or
more as the anonymous object dies immediately after doing its assigned task (here printing x and calling display()).
Java designers advice to use anonymous objects when the object is required only once in the program. The
advantage is to save memory, as anonymous object immediately. In I/O streams andAWT, we use many objects
only once in the program; for them, better go for anonymous objects as follows.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
g.setColor(new Color(100, 200, 80));
In the above two statements, anonymous objects of InpputStreamReader and Color are used.
Java also supports anonymous inner class objects; we used this in window closing.
INNER CLASS
There are 4 kind of classes that can be defined in a Java program, roughly can be termed as the inner classes.
-- Inner classes provides an elegant and powerful feature to the Java programming language.
-- These inner classes are referred by different names in different situations.
-- They are summarized here:
1. Static member classes
2. Member classes
3. Local classes
4. Anonymous classes
-- This is sometimes defined as a non-static member of an enclosing class. This type of inner class is
analogous to an instance method or field.
Local classes
-- This class is defined within a block of Java code so like a local variable, it is visible only within that block.
import java.io.*;
class bank
{
double bal;
bank(double b)
{
bal = b;
}
void contact(double r) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter password");
String pwd = br.readLine();
if(pwd.equals("xyz123"))
{
intrest in = new intrest(r);
in.calculateintrest();
}
else
{
System.out.println("u r unauthorized person");
return;
}
}
}
}
class innerclass
{
public static void main(String[] args) throws IOException
{
bank b = new bank(10000);
b.contact(9.5);
} }
STRING HANDLING
⮚ Strings, which are widely used in Java programming, are a sequence of characters. In the Java
programming language, strings are objects.
⮚ The Java platform provides the String class to create and manipulate strings.
⮚ In c and c++ string is a collection of characters that is terminated by a Null character. But it is not valid in
java.
⮚ In java, string which is declared is an object of String class. It is not a character array.
⮚ String class is a part of java.lang package, where all the necessary methods o work on strings are
available.
⮚ String class is a part of java.lang package but in java all classes can be considered as data types. So String
can be taken as a object. ( since, class is nothing but a user-defined data type)
Here we are converting string into character array. After the above declaration now create a string object
We can create an object to string class by allocating memory using new operator . this is similar to creating
an object to a class. In the above declaration first object is being declared the value is being stored into it.
OPERATIONS ON STRINGS
class string
{
public static void main(String[] args)
{
String s1= "wel come";
System.out.println(s1.length());
// output : 8 (white space is also counted )
} }
class string2
{
public static void main(String[] args)
{
String s1= "welcome";
String s2 = "to java lab";
System.out.println( s1+ s2 );
// ouput : welcometo java lab
}
}
3. Replace
class string3
{
public static void main(String[] args)
{
String s1= "welcome";
System.out.println( s1.replace('c','k'));
//output : welkome
}
}
4. Comparision
class string4
{
public static void main(String[] args)
{
String s1= "welcome";
String s2 = "to java lab";
System.out.println( s3 .equalsIgnoreCase(s4));
//output : true
}
}
5. trim : this method is used to remove white spaces on either sides of given string. If white spaces are
present in between string then they cannot be removed.
class string4
{
public static void main(String[] args)
{
String s3= " welcome ";
}
}
6. charAt : this method specifies the character at that particular position in a given string. Counting starts
from 0.
class string5
{
public static void main(String[] args)
{
String s4= "welcome to java lab";
System.out.println(s4.charAt(5)); //output : m
System.out.println(s4.charAt(8));//output: t
}
}
class string5
{
public static void main(String[] args)
{
String s4= "welcome to java lab";
System.out.println(s4.toUpperCase());
//output : WELCOME TO JAVA LAB
String s5= "WELCOME TO JAVA LAB";
System.out.println(s5.toLowerCase());
//output :welcome to java lab
}
}
8. indexOf : this method is used to find the position of first character in a given string.
class string5
{
public static void main(String[] args)
{
String s5= "welcome to java lab";
System.out.println(s5.indexOf("t")); //output : 8
System.out.println(s6.indexOf("n"));// output : -1
//If nothing is found then negative value is returned
}
}
9. lastIndexOf : prints position of last character in given string. If nothing is found it also returns negative
value. It returns the position of last occurrence of character in the given string.
class string5
{
public static void main(String[] args)
{
String s6= "madam";
System.out.println(s6.lastIndexOf("m")); //output : 4
}
}
10. substring : this method is useful to extract a part of the string from actual string.
class string5
{
public static void main(String[] args)
{
String s6= "this is notes on strings";
System.out.println(s6.substring(6)); // s notes on strings
System.out.println(s6.substring(6,12)); // s note
}
}
11. getChars : this method copies characters from a string into character array.
class string6
{
public static void main(String[] args)
{
String s6= "this is notes on strings";
char a[ ] = new char [15];
s6.getChars(2,10,a,0);
System.out.println(a); // is is no
}
}
12. split : this method is useful to break a string into pieces a places represented by delimiter. Te resultant
pieces are returned into string type array. Suppose if delimiter is comma then string is cut into pieces
where ever comma occurs in the string.
class stringg
{
public static void main(String[] args)
{
String s=" this is, ja,va lab";
String str[ ];
str = s.split( "," );
for(int i=0;i<str.length;i++)
{
System.out.println(str[i]);
}
}
}
IMMUTABILITY OF STRINGS
s1=s1+s2; using this statement we are modifying the contents of string object s1. String objects are
immutable. If it is true then why the output is hello world instead of hello.?
Reason:
Java Virtual machine creates 2 objects s1 and s2 separately
s1 🡪 hello
s2🡪world
when s1+s2 is written JVM creates a separate location to store the content of s1+s2.
(s1+s2) 🡪 hello world
But the content of s1 is not modified. Instead the location to which s1 is pointing to is changed but not
the content. The old object’s reference contains hello and now it as lost its reference. It is said to be
unreferenced object. It will be removed by garbage collector from memory.
❖ whenever we are creating a string object we are creating a string that cannot be changed.
❖ That is once string object is created it cannot be modified. But all kinds of string operations can
be performed.
❖ The difference is :- whenever a modification is made to string that modified string should be
assigned to a new string object.
❖ The original string is left unchanged.
❖ This approach is used because fixed strings can be implemented more efficiently than changed
one’s.
❖ If in some cases the original string has to be modified then java has 2 options :-
String Buffer & String Builder. Both o them can hold strings that are modified after creation.
Since both of them part of java.lang package they are automatically available to all java
programs
❖ For this purpose there are several methods available in string buffer class.
❖ Objects can be created for string buffer class in the following way :
Note : we may or may not mention size of stringbuffer object but it can be expanded dynamically
( since it is mutable).
1. append(): this method concatenates the string representation of any other type with the string buffer
object.
class stringbuffer
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("hello");
System.out.println(s.append("12345")); // output : hello12345
}
}
2. insert() : this method inserts one string into another string from the specified position.
class stringbuffer1
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("java lab");
StringBuffer s2 =s1.insert(5, "programming");
System.out.println(s1); // output : java programming lab
}
}
class stringbuffer2
{
public static void main(String[] args)
{
StringBuffer s1 = new StringBuffer("welcome");
s1.reverse();
System.out.println(s1); // output : emoclew
}
}
4. delete(int i, int j): this method deletes characters in a string from position ‘i’ to ‘j-1’.
class stringdelet
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("department");
System.out.println(s.delete(1,4)); // output : drtment
}
}
class LengthCapacity
{
public static void main(String args[])
{
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer("ObjectOne");
System.out.println("Length of sb1 = "+sb1.length());
System.out.println("Length of sb2 = " +sb2.length());
System.out.println("Capacity of sb1 = "+sb1.capacity());
System.out.println("Capacity of sb2 = "+sb2.capacity());
}
}