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

UNIT- I

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

UNIT- I

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

UNIT- I

Object Oriented System Development


1. HISTORY OF OBJECT-ORIENTED SYSTEM DEVELOPMENT
● Object-oriented programming is today what structured programming was in the 1970’s
● The Object and object attribute idea first conceived in the 1950’s for A.I. ( Artificial Intelligence )
● The real movement began in 1966 with the introduction of the Simula language
● Palo Alto Research Center (PARC) developed Smalltalk in the early 1970’s
o Smalltalk is considered the first truly object-oriented language
● Led other languages to support object-oriented programming
▪ examples: Objective-C, C++, Self, Eiffel, and Flavors
● In 1980 Grady Booch pioneered the concept of object-oriented design (OOD)

2. MOTIVATION FOR THE DEVELOPMENT OF OBJECT-ORIENTED SYSTEM

● 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.

Java Programming Fundamentals

1. Reason behind origin of JAVA:


● In 1990, Sun Microsystems (US) had initiated a project to develop a software for consumer electronic
devices which can be controlled by a remote.( Now-a-days we are able to control TV,AC etc., using remote.
The concept was similar to this.). This project of developing the software was given a name as STEALTH
PROJECT. Later it was named as GREEN PROJECT.
● In 1991, several computer experts like JAMES GOSLING, MIKE SHERADIN, PATRICK NAUGHTON, BILLY JOY
etc., started working on this project.
● James Gosling thought that C/C++ would be enough to develop this project. But the problem was, both C
and C++ were system dependent languages.
● So Gosling started to develop a totally new programming language, that was system independent. That
language was initially named as OAK. Since that name was already registered by some other company, the
name was changed to JAVA.

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

3. Why this programming language has got the name JAVA?


● James gosling and his team members were consuming lots of coffee, while working on this language.
● They felt that they were able to develop language in a better way, because of the good quality of coffee
they consumed.
● At that time period, coffee powder was exported to entire world from a place called as JAVA ISLAND.
● Hence, they fixed the name of the language as JAVA. Symbol for java language is coffee cup & saucer

4. Why C and C++ are called as System Dependent Languages?


• Consider a program written in C-language. It will be saved with .c extension.
• Ex: demo.c
• Then the instruction is given to compile the program that is, Alt+F9.(object code)
• After compilation .obj file is generated.
• In the next stage, .exe file is generated, program is loaded into RAM and then executed.
• In .obj file, first the statement will be :- #include<stdio.h>
• When we run the program, the C compiler goes to the standard library and searches for stdio.h header
file. If the file is found, then C compiler copies entire code in stdio.h ( Machine Level Language) into the
C-program.
• Suppose, if our program contains 25 lines of code and stdio.h file contains 500 lines of code then our
program in Machine Level Language contains 525 lines of code. This file is known as .exe file. This file is
full-fledged file hat contains total program in Machine Level Language format. These instructions will be
understood by the compiler micro-processor. It executes he program and gives the output. There are many
micro processors developed by many companies. Ex: intel processor.

• 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

⮚ Instruction format (set) in DOS : add a,b

⮚ Instruction format (set) in Unix : a add b

• 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.

5. Why Java is System Indepndent?


• After compiling the java program a .class is generated. This .class file contains byte code. Here the size of
each instruction is 1 byte that is 8-bits. People who have developed have java specified set of instructions,
to express any operations. There will be fixed number of byte code instructions say around 200. Any
program in java can be re-written using these instructions. A file re-written with these instructions in
known as .class file that is BYTE CODE.

• 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

⮚ After compiling 🡪 demo.class

• 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?

The JVM performs following operation:

● Loads code
● Verifies code
● Executes code
● Provides runtime environment

JVM provides definitions for the:

● Memory area
● Class file format
● Register set
● Garbage-collected heap
● Fatal error reporting etc.

Internal Architecture of JVM

Let's understand the internal architecture of JVM. It contains classloader, memory area, execution engine etc.
1) Class loader:

● Class loader is a subsystem of JVM that is used to load class files.

2) Class (Method) Area:

● Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data,
the code for methods.

3) Heap:

● It is the runtime data area in which objects are allocated.

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.

5) Program Counter Register:

● PC (program counter) register. It contains the address of the Java virtual machine instruction currently
being executed.

6) Native Method Stack:

● It contains all the native methods used in the application.

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 :

Sun Microsystems divided java into 3 parts:-

⮚ 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.

9. Naming Conventions in JAVA


Naming conventions in java specify the rules to be followed while declaring or writing names of packages, classes
or methods.

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.

10.GENERAL STRUCTURE OF A JAVA PROGRAM


Documentation section

Package statements

Import statements

Interface statements

Class definition

main method class


{
Definition of main method
}
1. Documentation section: contains set of comment lines giving name and explanation about program. This
increases readability of the program.

In java comments can be written in 2 ways :

⮚ Single-line comments (/*……….*/)


⮚ Double line comments(// )

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.

Difference between #include and import statement

● #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.

Difference between class in c++ and class in java

● “private” is the access specifier in c++ by default.


● In java class “public” is the default access specifier.
If string args[ ] is not written in main() then we can compile the program but can’t execute it since, JVM can’t
recognize main() method as starting point of execution with out string args[]. Values passed to string args[] are
called as ARGUMENTS.

11. Sample program:

Write a program to print a line of text

Aim : To print a line of text

Source Code :

/* This is my first java program. This will print 'Hello World' as the output */

class MyFirstJavaProgram
{

public static void main(String args[])


{
System.out.println("Hello World"); // prints Hello World
}
}

To save program : MyFirstJavaProgram.java

To compile program : javac MyFirstJavaProgram.java

To run the program : java MyFirstJavaProgram

12. Variables, Constants, Literals and Escape Sequences in Java

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

There are three types of variables in java

● 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

• Value cannot change during program execution


• Syntax:
final dataType constantIdentifier = assignedValue;

Note: assigning a value when the constant is declared is optional. But a value must be assigned before the constant
is used.

13.Data types in Java


● In Java, the data type used to store characters is char.
● char in Java is not the same as char in C or C++.
● In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java.
● Instead, Java uses Unicode to represent characters. Unicode defines a fully international character set that
can represent all of the characters found in all human languages.
● It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana,
Hangul, and many more.
● For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536.
There are no negative chars.
● The standard set of characters known as ASCII still ranges from 0 to 127 as always, and the extended 8-bit
character set, ISO-Latin-1, ranges from 0 to 255.
● Since Java is designed to allow applets to be written for worldwide use, it makes sense that it would use
Unicode to represent characters.
● Of course, the use of Unicode is somewhat inefficient for languages such as English, German, Spanish, or
French, whose characters can easily be contained within 8 bits. But such is the price that must be paid for
global portability.

String data types:

⮚ String is collection of characters.


Ex: String s=”hello’;
⮚ A class named String is present in java where all methods are provided to manipulate strings. Any string is
considered as an object of string class.
⮚ In c/c++ string is defined as array of characters terminated by null character.
⮚ But in java character and string data types separate.

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

+ Addition - Adds values on either A + B will give 30


side of the operator

- Subtraction - Subtracts right hand A - B will give -10


operand from left hand operand

* Multiplication - Multiplies values A * B will give 200


on either side of the operator

/ Division - Divides left hand B / A will give 2


operand by right hand operand

% Modulus - Divides left hand B % A will give 0


operand by right hand operand
and returns remainder

++ Increment - Increase the value of B++ gives 21


operand by 1

-- Decrement - Decrease the value of B-- gives 19


operand by 1

Relational Operators:

There are following relational operators supported by Java language

Operator Description Example

== Checks if the value of two operands (A == B) is not true.


are equal or not, if yes then
condition becomes true.

!= Checks if the value of two operands (A != B) is true.


are equal or not, if values are not
equal then condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right
operand, if yes then condition
becomes true.

< Checks if the value of left operand is (A < B) is true.


less than the value of right operand,
if yes then condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of
right operand, if yes then condition
becomes true.

<= Checks if the value of left operand is (A <= B) is true.


less than or equal to the value of
right operand, if yes then condition
becomes true.

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&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators:

Operator Description Example

& 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 OR Operator copies a bit if it (A | B) will give 61 which is 0011 1101


exists in eather operand.

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

The following table lists the logical operators:

Operator Description Example

&& Called Logical AND operator. If both the operands (A && B) is false.
are non zero then then condition becomes true.

|| Called Logical OR Operator. If any of the two (A || B) is true.


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

There are following assignment operators supported by Java language:

Operator Description Example

= Simple assignment operator, C = A + B will assigne value of A + B into C


Assigns values from right side
operands to left side operand

+= Add AND assignment operator, It C += A is equivalent to C = C + A


adds right operand to the left
operand and assign the result to
left operand

-= Subtract AND assignment C -= A is equivalent to C = C - A


operator, It subtracts right operand
from the left operand and assign
the result to left operand
*= Multiply AND assignment operator, C *= A is equivalent to C = C * A
It multiplies right operand with the
left operand and assign the result
to left operand

/= Divide AND assignment operator, It C /= A is equivalent to C = C / A


divides left operand with the right
operand and assign the result to
left operand

%= Modulus AND assignment C %= A is equivalent to C = C % A


operator, It takes modulus using
two operands and assign the result
to left operand

<<= Left shift AND assignment C <<= 2 is same as C = C << 2


operator

>>= Right shift AND assignment C >>= 2 is same as C = C >> 2


operator

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and C ^= 2 is same as C = C ^ 2


assignment operator

|= bitwise inclusive OR and C |= 2 is same as C = C | 2


assignment operator

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 :

variable x = (expression) ? value if true : value if false

Following is the example:

public class Test {


public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}

This would produce following result:

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:

( Object reference variable ) instanceOf (class/interface type)

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:

String name = = 'James';


boolean result = name instanceOf String;
// This will return true since name is type of String

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 {

public class Car extends Vehicle {


public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}

This would produce following result:

true

15. Precedence of operators in Java

Category Operator Associativity


Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

16. Loops in Java


Java has very flexible three looping mechanisms.

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

The syntax of a while loop is:

while(Boolean_expression)
{
//Statements
}

When executing, if the boolean_expression result is true then the actions inside the loop will be executed.

This will continue as long as the expression result is true.

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:

The syntax of a do...while loop is:

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.

for Loop: (index based retrieval)

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:

The syntax of a for loop is:

for(initialization; Boolean_expression; update)


{
//Statements
}

Here is the flow of control in a for loop:

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

It repeatedly executes a group of statements for each statement of collection.

It works in jdk1.5 and above versions. (object based retrieval)

Syntax:

The syntax of enhanced for loop is:

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:

The syntax of a break is a single statement inside any loop:

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:

The syntax of a continue is a single statement inside any loop:

continue;

WHY goto STATEMENTS ARE NOT AVAILABLE IN JAVA?

● Branch statements explicitly redirect the flow of program execution.


● The most infamous branch statement in the history of computing is goto.
● In Java, goto is an unimplemented keyword, so it cannot be used in Java programs. In other languages,
goto is used to redirect program execution to another line of code in the program by specifying a line
number or other type of label.
● In Java, break, continue, and label: fill the role of goto, but without many of goto's negatives.
● return is a branching statement that redirects execution out of the current method and back to the calling
method. It also returns a value to the calling method.
● This value is either a primitive, object, or void. void is used to return execution without returning a value.
● Also, whatever the return value is, its type must match the return type listed in the method declaration.

17. Selection or Decision making statements in Java

if Statement:

An if statement consists of a Boolean expression followed by one or more statements.


Syntax:

The syntax of an if statement is:

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:

The syntax of an if...else is:

if(Boolean_expression)
{
//Executes when the Boolean expression is true
}
Else
{
//Executes when the Boolean expression is false
}

if...else if...else Statement:


An if statement can be followed by an optional else if...else statement, which is very useful to test various
conditions using single if...else if statement.

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:

The syntax of an if...else is:

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.
}

Nested if...else Statement:

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:

The syntax for a nested if...else is as follows:

if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){

//Executes when the Boolean expression 2 is true


}
}

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:

The syntax of enhanced for loop is:

switch(expression)
{
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}

The following rules apply to a switch statement:

● 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.

18. Arrays in Java


An array is a container object that holds a fixed number of values of a single type. The length of an array is
established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in
the main method of the "Hello World!" application. This section discusses arrays in greater detail.

An array of ten elements

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.

⮚ How to declare an array ?

You can create an array by using the new operator with the following syntax:
Array_name = new dataType[Size of the array];

The above statement does two things:

● It creates an array using new dataType[Size of the array];


● It assigns the reference of the newly created array to the variable Array_name

⮚ Declaring Array Variables:

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];

Alternatively way of creating array is:

dataType[]Array_name = {value0, value1, ..., valuek};

⮚ Length property of 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.

Syntax of java length method is: Array_name.length()

Example of length property of array:

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};

// Print length of array


System.out.println("Length of int array in Java is: "+num.length);

// Print the array


for(int i=0;i<num.length;i++)
System.out.println(num[i]);

// Try with a char array


char[] c={'a','b','c','d','e','f','g','h','i','j','k'};

// Print the array


for(int i=0;i<c.length;i++)
System.out.println(c[i]);

// Print length of array


System.out.println("Length of char array in Java is: "+c.length);

}
}

Output
------------------------------------

Length of int array in Java is: 10


10
20
30
40
50
60
70
80
90
100
a
b
c
d
e
f
g
h
i
j
k
Length of char array in Java is: 11

⮚ 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' };

char[] copyTo = new char[7];

System.arraycopy(copyFrom, 2, copyTo, 0, 7);

System.out.println(new String(copyTo));
}
}
The output from this program is:

caffein

19. Command Line Arguments


Java application can accept any number of arguments directly from the command line.

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

Procedure Oriented Programming Object Oriented Programming


(POP) (OOP)
Divided Into In POP, program is divided into small In OOP, program is divided into parts
parts calledfunctions. called objects.

Importance In POP,Importance is not given In OOP, Importance is given to the data


to data but to functions as well rather than procedures or functions
as sequence of actions to be done. because it works as a real world.
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access POP does not have any access specifier. OOP has access specifiers named Public,
Specifiers Private, Protected, etc.

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.

Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the


form of Function Overloading and
Operator Overloading.
Examples Example of POP are : C, VB, FORTRAN, Example of OOP are : C++, JAVA, VB.NET,
Pascal. C#.NET.
2. OOPS Properties

OOPS means Object Oriented Programming System

Properties of OOPS are:

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:

1. Consider “student” as object

Properties of student: name, roll no, marks, height.weight, gender,color etc.,,

Behavior of student: writing, reading, listening etc.,,

2.

objects class

Apple, mango,grapes,orange etc.,, fruit

Pink,blue,black,yellow etc.,, color

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.

Syntax to declare class in java:

class class_name
{
Variable declarations (properties)
Methods (actions)
}

Syntax to declare object in java:

class_name object_name = new class_name();

1. TYPES OF VARIABLES IN JAVA


I. Instance variables (object variables)
II. Local variables
III. Static variables (class variables)

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
}

2. Ways to pass values to variables

In 3 ways values can be passed to variables

I. Using methods
II. Using objects
III. Using constructors

⮚ Passing values to variables using methods


class one
{
int x,y;
void getdata(int m,int n) // values are being passes using methods
{
x=m;
y=n;
}
int area()
{
return x*y;
}
}

class access
{
public static void main(String args[])
{
one k=new one();
k.getdata(10,20);
System.out.println("area="+k.area());
}
}

⮚ Passing values to variables using objects

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

⮚ Constructor is a special member function that is called automatically when an object is


created to a class.

PROPERTIES OF CONSTRUCTOR:

⮚ Constructor is a member function with same name as class.


⮚ Constructor can take values as arguments
⮚ Constructor will not have any return type since it can’t return values.

⮚ Syntax of constructor is:


class_name()
{
….
….
}

⮚ Types of constructors are:


1. Default constructor
o When a class is created then compiler automatically allocates a constructor called as
default constructor.
2. Non-parameterized constructor
o Constructor with no parameters
3. Parameterized constructor
o Constructor with parameters
4. Copy constructor
o Passing object as an argument.
o That is initializing object of one class with other object of same class is called copy
initialization. Such a constructor is called as copy constructor

5. Overloading of Constructors
OVERLOADING OF CONSTRUCTOR MEANS GIVING A DIFFERENT MEANING TO THE CONSTRUCTOR.

⮚ PROGRAM FOR CONSTRUCTOR OVERLOADING

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);
}
}

⮚ PROGRAM FOR COPY CONSTRUCTOR

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

In general, a method has the following syntax:

modifier returnValue Type methodName(list of parameters)


{
// Method body;
}

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:

⮚ In creating a method, you give a definition of what the method is to do.

⮚ To use a method, you have to call or invoke it.

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

int larger = max(30, 40);

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);
}

void demo(int p,int q,int r)


{
a=p;
b=q;
c=r;
}
void demo(float m,char n)
{
System.out.println(m+" "+n);
}
int average()
{
return (a+b+c)/3;
}
}
class method
{
public static void main(String[] args)
{
one d=new one();
d.demo();
d.demo(10);
d.demo(12,20,14);
int x = d.average();
System.out.println(x);
d.demo(68.34f,'h');
}
}

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.

PROGRAM FOR METHOD OVERRIDING

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();
}
}

Rules of Method Overriding in Java

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.

Difference between method overloading vs overriding in Java


o First and most important difference between method overloading and overriding is that, In case
of method overloading in Java, Signature of method changes while in case of method overriding it
remain same.
o Second major difference between method overloading vs overriding in Java is that You can
overload method in one class but overriding can only be done on subclass.
o You can not override static, final and private method in Java but you can overload static, final
or private method in Java.
4) Overloaded method in Java is bonded by static binding and overridden methods are subject
to dynamic binding.
o Private and final method can also be not overridden in Java.

2. Static method and Static block


Static method

● It is a method which belongs to the class and not to the object(instance)

● 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>

● A static method cannot refer to “this” or “super” keywords in anyway

//program for static method

class StaticMethod
{
static int j = 0;

static void getVariable()


{
j++;
System.out.println("Value of static variable j is"+j);
}
}

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

//program for static block

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.

The finalize( ) method has this general form:

protected void finalize( )


{
// finalization code here
}

⮚ 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.

Instance methods can be called as:

Objectname.methodname()

There are 2 types of instance methods:

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.

Program to demonstrate instance 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());
}
}

1. Relation between objects (inheritance, reference variables and


inner class)

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.

What is reference variable?


Demo d1 = new Demo();
The above statement can be split into two as follows.
Demo d1; // 1st
d1 = new Demo(); // 2nd
In the first statement, d1 is called a reference variable (not object). A variable that refers a class name is known as
reference variable. A reference variable cannot work like an object until it is converted into an object. In the second
statement, reference variable is converted into an object.
Who has converted the reference variable into an object?
d1 = new Demo();
There two words on the right side; new and Demo(). Demo() is a constructor. What a constructor returns?
Generally, it is said that constructor does not return a value, but still we do not write void. Why, because the
constructor really returns something. The constructor returns an object of a class, "class object". This "class object"
does not have a name. The nameless object in Java is known as "anonymous object". That is, a constructor returns
an anonymous object. An anonymous object is given a name called d1. Now d1 is called an object. When object
has a name, the newoperator allocates memory for the d1 object. Any object in Java takes four bytes of memory.
Now d1 object exist in the memory and can be used throughout the program to call a method or variable.
How can we use reference variables in the program?
Just we know, a reference variable cannot work like an object until it is converted. But still, reference variables can
be used to assign with an object. Observe the following.

Demo d1 = new Demo(); // an object


Demo d2, d3; // reference variables

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

d3 = d2; // reference to reference


System.out.println(d3.x); // prints 10
Now even through d2 and d3 are reference variables but still they are used as objects to call x value. What
happened? How they print? When assigned, d1, d2 and d3 refer the same location of x. What is the proof? See the
following code.
d2.x = 20;
System.out.println(d1.x); // prints 20
System.out.println(d2.x); // prints 20
System.out.println(d3.x); // prints 20
All prints 20 as all point to the same location. If one changes, others get affected.; no encapsulation.
How anonymous objects are useful in the program?

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.

1 public class Demo


2 {
3 int x = 10;
4 public void display()
5 {
6 System.out.println("Hello 1");
7 }
8 public static void main(String args[])
9 {
10 System.out.println(new Demo().x);
11 System.out.println(new Demo().x);
12 System.out.println(new Demo().x);
13 new Demo().display();
14 new Demo().display();
15 }
16 }

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

-- The term "nested classes" sometimes refers to these inner classes.

Static member classes


-- This class (or interface) is defined as a static member variable of another class.
Member 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.

Anonymous classes -- An anonymous class is a local class having no name;


-- Syntactically it combines the syntax required for defining a class and the syntax required to instantiate an object.

PROGRAM TO DEMONSTRATE INNER CLASS

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;
}
}

private class intrest


{
double rate;
intrest(double r)
{
rate = r;
}
void calculateintrest()
{
double i = bal * rate/100;
bal = bal+i;
System.out.println("updates balance = "+bal);
}

}
}
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.

IS STRING A CLASS OR DATA TYPE ?

⮚ 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)

DIFFERENT WAYS OF INITIALIZING A STRING :

⮚ Method – 1: String s = “ hello”;

⮚ Method – 2: String s = { ‘h’,’e’,’l’,’l’,’o’};

Here we are converting string into character array. After the above declaration now create a string object

and pass array name to it.

String x = new String (s);

⮚ Method – 3: String s = new String(“hello”);

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

1. Length of string : counts number of characters.

class string
{
public static void main(String[] args)
{
String s1= "wel come";
System.out.println(s1.length());
// output : 8 (white space is also counted )
} }

2. Concatenation of strings : combines 2 strings.

class string2
{
public static void main(String[] args)
{
String s1= "welcome";
String s2 = "to java lab";

System.out.println( s1 +" "+ s2 );


// ouput : welcome to java lab

System.out.println( s1+ s2 );
// ouput : welcometo java lab

System.out.println( s1 +" "+10+" "+20);


//output : welcome 10 20

}
}

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( s1 == s2); // output : false

System.out.println( s1 .equals(s2)); // output : false

String s3= "hello";


String s4 = "Hello";
System.out.println( s3 .equals(s4)); //output : false

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 ";

System.out.println(s3.trim()); //output : welcome

String s4= "wel come";

System.out.println(s4.trim()); // wel come

}
}

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

}
}

7. toUpperCase : converts given string into upper case letters.


toLowerCase : converts given string into lower case letters

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

String s6= "hello";

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.

getChars(int i1,int i2char a[],int i3)


the characters from position i1 to i2-1 are copied into array ‘a’ to a location starting from i3. Counting stars
from 0th position

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

String objects can be divided into :-


● mutable objects 🡪 contents can be modified
● immutable objects 🡪 contents cannot be modified.

String objects are immutable.


Consider the following program :
class str
{
public static void main(String[] args)
{
String s1="hello";
String s2="world";
s1=s1+s2;
System.out.println(s1); // hello world
}
}

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.

STRING BUFFER & STRING BUILDER

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

StringBuffer s = new stringBuffer(“hello”);


hello is being passed to string buffer object

StringBuffer s = new stringBuffer( );


Memory is allocated first in the above declaration. By default stringbuffer object will be created
with capacity of holding 16 characters.
StringBuffer s = new stringBuffer( 75);
‘s’ is created with a capacity of holding 75 characters

Note : we may or may not mention size of stringbuffer object but it can be expanded dynamically
( since it is mutable).

Methods in String Buffer class :

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
}
}

3. reverse(): this method reverses the given string

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
}
}

Program on finding the length and capacity of a StringBuffer object

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());
}
}

You might also like