MCA OOPJ Unit-1 Material
MCA OOPJ Unit-1 Material
There are many java versions that has been released. Current stable release of Java is Java SE 8.
Where it is used?According to Sun, 3 billion devices run java. There are many devices
wherejava is currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in, javatpoint.com etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
Types of Java Applications
There are mainly 4 type of applications that can be created using java programming:
1) Standalone Application
It is also known as desktop application or window-based application. An application that we
need to install on every machine such as media player, antivirus etc. AWT and Swing are used in
java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web application.
Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the advantage
of high level security, load balancing and clustering. In java, EJB is used for creating enterprise
applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.
***********
function1
main() function2
method
function3
Even though POP is a efficient approach but if program size increases the
Complexity(readability is difficult) also increased.
In the POP approach there is no data hiding concept i.e security for the data is less.
Object Oriented Programming(OOP):
In OOP, Importance is given to the data rather than procedures or functions because
it works as a real world.
In the object oriented programming classes and objects are used inside programs.
A class is a module or template contains data and methods (functions) to achieve
the task.
The main task is divided into several modules, these modules are called classes,
each class can perform some tasks for which several methods are written in a class.
In the OOP approach we can achieve security for the data using data hiding concept.
In java we can develop efficient programs using the concepts encapsulation,
polymorphism and inheritance etc.
class1 data methods
class with
main() class2 data methods
method
***********
Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access POP does not have any access OOP has access specifiers named
Specifiers specifier. public, private, protected, etc.
Data Moving In POP, Data can move freely from In OOP, objects can move
function to function in the system. and communicate with each
other through member
functions.
Expansion To add new data and function in OOP provides an easy way to add
POP is not so easy. new data and function.
Data Access In POP, Most function uses In OOP, data cannot move easily
Global data for sharing that can be from function to function, it can be
accessed freely from function to kept public or private so we can
function in the system. control the access of data.
Data POP does not have any proper OOP provides Data Hiding so
Hiding way for hiding data so it is less provides more security.
secure.
Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the
form of Function Overloading and
Operator Overloading.
Examples Examples of POP are: C, Examples of OOP are: C++,
VB,FORTRAN and Pascal. JAVA,VB.NET, C#.NET.
Principles of OOP:
Object-Oriented Programming (OOP) is a programming language model organized
around objects rather than actions and data. An object-oriented program can be characterized as data
controlling access to code.
Concepts of OOPS
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object:
Object means a real word entity such as pen, chair, table etc. Any entity that has state and behavior is
known as an object. Object can be defined as an instance of a class. An object contains an address and
takes up some space in memory.
An object has three characteristics:
state: represents data (value) of an object.
behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify each object uniquely.
Class:
Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint from
which you can create an individual object. A class consists of Data members and methods. The primary
purpose of a class is to hold data/information. The member functions determine the behavior of the class,
i.e. provide a definition for supporting various operations on data held in the form of an object. Class
doesn’t store any space.
Abstraction:
Abstraction means hiding the implementation details from the user and gives only
functionality details.
For example, when you drive your car you do not have to be concerned with the exact
internal working of your car. What you are concerned with is interacting with your car
via its interfaces like steering wheel, brake pedal, accelerator pedal etc. Here the
knowledge you have of your car is abstract.
In java abstraction can be achieved using abstract class and interfaces.
Encapsulation:
Wrapping data(variables) and methods(code acting on data) within classes in
combination with implementation hiding (through access control) is often called
encapsulation.
In java encapsulation can be achieved using classes.
Using this encapsulation we can provide security for the data inside a class using object
reference, this is called ‘Data hiding’.
Inheritance:
Inheritance can be defined as the procedure or mechanism of acquiring all the properties and
behavior of one class to another, i.e., acquiring the properties and behavior of child class from the
parent class. When one object acquires all the properties and behaviours of another object, it is
known as inheritance. It provides code reusability and establishes relationships between different
classes.
A class which inherits the properties is known as Child Class(sub-class or derived class)
whereas a class whose properties are inherited is known as Parent class(super-class or base class).
Types of inheritance in java:
Single, multilevel and hierarchical inheritance. Multiple and hybrid inheritance is supported through
interface only.
In java inheritance is also called as IS-A relationship, and it can be achieved using
“extends” key word.
Example:
class A
{
//members of a class A
}
class B extends A
{
// members of class B
}
Polymorphism:
The word polymorphism came from two greek words ‘poly’ meaning ‘many’ and
‘morphos’ meaning ‘forms’.
Polymorphism represents the ability to assume several different forms.
Polymorphism is the ability by which, we can create functions or reference variables
which behaves differently in different programmatic context.
In java language, polymorphism is essentially considered into two versions:
Compile time polymorphism (static binding or method overloading)
Runtime polymorphism (dynamic binding or method overriding)
Method Overloading(Compile time Polymorphism)
Method Overloading is a feature that allows a class to have two or more methods having the same name
but the arguments passed to the methods are different. Compile time polymorphism refers to a process in
which a call to an overloaded method is resolved at compile time rather than at run time.
Method Overriding(Run time Polymorphism)
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java. In other words, If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
Simple
According to Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading
etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection in
java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of objects
that incorporates both data and behaviour.
Object-oriented programming(OOPs) is a methodology that simplify software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation.
Platform Independent
Compilation:
for compilation of java program we use “javac” keyword.
javac Sample.java
Execution:
After successful compilation of java program .class file will be created. This is
calledbytecode.
for executing java program we use .class file name with “java” keyword as follows.
JVM
Sample.java Compiler (java Output
Sample.class virtual
Machine)
******* -----------*******
Java Virtual Machine(JVM):
---------------------****************-------------------
A way of viewing the world is an idea to illustrate the object-oriented programming concept
Let us consider a situation, I am at my office and I wish to get food to my family members
who are at my home from a hotel. Because of the distance from my office to home, there is
no possibility of getting food from a hotel myself. So, how do we solve the issue?
To solve the problem, let me call zomato (an agent in food delevery community), tell them
the variety and quantity of food and the hotel name from which I wish to delever the food to
agent(Zomato) to satisfy my request. Here, the agent uses some method to do this. I do not
need to know the method that the agent has used to solve my request. This is usually hidden
from me.
So, in object-oriented programming, problem-solving is the solution to our problem which
requires the help of many individuals in the community. We may describe agents and
communities as follows.
agents, called objects. Where each object provides a service (data and
In our example, the online food delivery system is a community in which the agents are
zomato and set of hotels. Each hotel provides a variety of services that can be used by other
To solve my problem, I started with a request to the agent zomato, which led to still more
requestes among the members of the community until my request has done. Here, the
members of a community interact with one another by making requests until the problem has
satisfied.
is the object to whom the message was sent. In response to the message ,the
receiver performs some method to carry out the request. Every message may
quantity of food, and the hotel details. The receiver uses a method to food get delivered to my
home.
Responsibilities
In our example, my request for action indicates only the desired outcome (food delivered to
my family). The agent (zomato) free to use any technique that solves my problem. By
discussing a problem in terms of responsibilities increases the level of abstraction. This
an object in response to a message is decided by the class. All the objects of a class use the
In our example, the zomato a class and all the hotels are sub-classes of it. For every request
(message), the class creates an instance of it and uses a suitable method to solve the problem.
Classes Hierarchies
A graphical representation is often used to illustrate the relationships among the classes
tree-like structure. In this more abstract class listed near the top of the tree, and more specific
classes in the middle of the tree, and the individuals listed near the bottom.
In the class hierarchy, both parent and child classes may have the same method which
implemented individually. Here, the implementation of the parent is overridden by the child.
Or a class may provide multiple definitions to a single method to work with different
arguments (overloading).
The search for the method to invoke in response to a request (message) begins with the class
of this receiver. If no suitable method is found, the search is performed in the parent class of
it. The search continues up the parent class chain until either a suitable method is found or the
parent class chain is exhausted. If a suitable method is found, the method is executed.
Introduction
Java is an Object Orient and high-level programming language, originally developed by Sun
Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS,
Linux etc.
import java.io.*;
class Sample
{
// Your program begins with a call to main().
class Sample {
This line uses the keyword class to declare that a new class is being defined. Sample is an identifier that is
the name of the class. The entire class definition, including all of its members, will be between the
opening curly brace ({) and the closing curly brace (}).
The next line in the program is the single-line comment, shown here:
This line outputs the string "This is a simple Java program." followed by a new line on the
screen. Output is actually accomplished by the built-in println( ) method. In this case, println( )
displays the string which is passed to it. System is a predefined class that provides access to the system,
and out is the output stream that is connected to the console.
Notice that the println( ) statement ends with a semicolon. All statements in Java end with a
semicolon. The first } in the program ends main( ), and the last } ends the Sample class definition.
Java compiler first converts the source code into an intermediate code, known as bytecode or
virtual machine code. To run the bytecode, we need the Java Virtual Machine (JVM). JVM exists
only inside the computer memory and runs on top of the Operating System. The bytecode is not
machine specific. The Java interpreter converts the bytecode into Machine code. The following
diagram illustrates the process of compiling and running Java programs.
javac Sample.java
The Java compiler creates a file called Sample.class containing the bytecode version of the
program. The java interpreter in JVM executes the instructions contained in this intermediate Java
bytecode version of the program. The Java interpreter is called with “java” at the command prompt.
Here java command calls the Java interpreter which executes the Sample.class
(bytecode of Sample.java).
Java program contains different types of elements like white spaces, comments andtokens. A
token is the smallest program element which is recognized by the compiler and which treats them as
defined for the compiler. A program is a set of tokens which comprise the following elements:
Keywords: These are special words defined in Java and represent a set of instructions.
• The keywords represent groups of instructions for the compiler.
• These are special tokens that have a predefined meaning and their use is restricted.
• Keywords cannot be used as names of variables, methods, classes, or packages.
• These are written in the lower case.
• Keywords of Java Language are as follows:
Literals: These are constant values represented in a program by a set of character, digits, etc.
• A literal represents a value which may be of primitive type, String type, or null
type.
• The value may be a number (either whole or decimal point number) or a sequence of
characters which is called String literal, Boolean type, etc.
• A literal is a constant value.
Types of Literals:
i. Integer literals
• Sequences of digits.
• The whole numbers are described by different number systems such as decimal
numbers, hexadecimal numbers, octal numbers, and binary numbers.
• Each number has a different set of digits.
Decimal Integer Literals
• These are sequences of decimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
• Examples of such literals are 6, 453, 34789, etc.
Hex Integral Literals
• These are sequences of hexadecimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
A, B, C, D, E, and F.
• The values 10 to 15 are represented by A, B, C, D, E, and F or a, b, c, d, e, and
f.
• The numbers are preceded by 0x or 0X. Examples are 0x56ab o0X6AF2, etc.
Octal Integer Literals
• These are sequences of octal digits which are 0, 1, 2, 3, 4, 5, 6, and 7.
• These numbers are preceded by 0. Examples of literals are 07122, 04, 043526.
Binary Literal
• These are sequences of binary digits.
• Binary numbers have only two digits—0 and 1 and a base 2.
• Examples of such literals are 0b0111001, 0b101, 0b1000, etc.
ii. Floating point literal
• These are floating decimal point numbers or fractional decimal numbers
with base 10. Examples are 3.14159, 567.78, etc.
iii. Boolean literal
• These are Boolean values. There are only two values—true or false.
iv. Character literal
• These are the values in characters.
• Characters are represented in single quotes such as ‘A’, ‘H’, ‘k’, and so on.
v. String literal
• These are strings of characters in double quotes. Examples are “Delhi”,
“John”, “AA”, etc.
Types of Operators:
Arithmetic Operators:
Operator Description
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulus
Relational Operators:
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
Logical Operators:
Operator Description
&& Logical AND
|| Logical OR
! NOT
Assignment Operators:
Operator Description
+= Add and assign to
-= Subtract and assign to
*= Multiply and assign to
/= Divide and assign to
%= Modulus and assign to
Conditional Operators:
Operator Description
?: Used to construct Conditional expression
Java Statements
A Statement is a instruction to the computer. A program is a set of statements or instructions. The
statements specify the sequence of actions to be performed when some method or constructor is
invoked. The statements are executed in the sequence in the specified order. The important Java
statements are as follows.
Statement Description
Empty statement These are used during program development.
Variable declaration It defines a variable that can be used to store the values.
statement
Labeled statement A block of statements is given a label. The labels should not
be keywords, previously used labels, or already declared
local variables.
Expression statement Most of the statements come under this category. There are
seven types of expression statements that include
assignment, method call and allocation, pre-increment, post
increment, pre-decrement, and post decrement statements.
Control statement This comprises selection, iteration, and jump statements.
Selection statement In these statements, one of the various control flows is
selected when a certain condition expression is true. There
are three types of selection statements including if, if-else,
and switch.
Iteration statement These involve the use of loops until some condition for the
termination of loop is satisfied. There are three types of
iteration statements that make use of while, do, and for
Jump statement In these statements, the control is transferred to the
beginning or end of the current block or to a labeled
statement. There are four types of Jump statements including
break, continue, return, and throw.
Synchronization These are used with multi-threading
statement
Guarding statement These are used to carry out the code safely that may cause
exceptions (such as division by zero, and so on). These
statements make use of try and catch block, and finally
Command Line Arguments
• Arguments that are passed to the main function through command line are called command line
arguments.
• A Java application can accept any number of arguments from the command line.
• These arguments can be passed at the time of running the program. This enables
the programmer to check the behavior of a program for different values of inputs.
• When a Java application is invoked, the runtime system passes the command line
arguments to the application's main method through an array of strings.
class vehicle
public static void main(String args[])
{
int x = args.length;
for(int i=0; i<x; i++)
{
System.out.println(args[i]);
}
}
Output:
(After compiling, type the following lines on the command prompt. It produces the output as)
Variables:
The variable is the basic unit of storage in a Java program.
A variable is defined by the combination of an identifier, a type, and an optional
initializer.
In addition, all variables have a scope, which defines their visibility, and a lifetime.
Declaring a Variable:
In Java, all variables must be declared before they can be used. The basic form of
a variable declaration is shown here:
type identifier [ = value], identifier [= value], ... ;
Here are several examples of variable declarations of various types. Note that some
include an initialization.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi
char x = 'x'; // the variable x has the value 'x'.
Types of Variable:
There are three types of variables in java:
local variable: declared inside the method is called local variable.
instance variable: declared inside the class but outside the method, is called
instance variable . It is not declared as static.
static variable: 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
}
}
import java.util.Scanner;
public class Arithmetic
{
public static void main(String[] args)
{
Scanner scaninput = new Scanner (System.in);
int n;
int m;
System.out.print( "Enter the value of n : ");
n=scaninput.nextInt();
System.out.print( "Enter the value of m : ");
}
}
Data Types in Java
• Data Type is the type of the data which computer accepts. Every variable and expression
has a data type that is known at the compile time.
• The declaration of data type with a variable or expression limits the types of values that a
variable can have or the expression it can evaluate.
• Java is an object-oriented programming language based on classes and interfaces.
• Java defines some primitive (basic) data types that are not reference types of any class or
interface. Eight primitive (basic) types of data are defined in Java.
Integral types—byte, short, int, long
Floating point types - float, double
Character type -char
Boolean type – boolean values – True, False
There is a non-data type called void and no data can be of type void. This type is used for
methods that do not return any value.
Non-primitive Types
These are the class and interface types. The name of a class or interface is the name of type. A
class object is declared as
Class_identifier object_identifier;
Similarly, an interface reference is declared as
Interface_identifier reference_identifier;
Data Types
i. Integers
Integers are whole numbers, that is, they represent numbers that do not have a fractional part.
The integers can be declared in four types according to the size of memory allocated for them
ii. Characters
• A variable may have value in terms of a character in which the type of variable is char.
• These characters represent integer values.
• Java supports Unicode for the representation of characters.
• Unicode supports all the character sets of all the major languages of the world.
• The initial version of Unicode allocated 2 bytes for storing characters.
• The range of values for characters in the initial version of Unicode comprised from
‘\u0000’ to ‘\uffff ’ that is from 0 to 65535 both end values inclusive.
iii. Floating Point Numbers
• The numbers that are not whole numbers, or those that have fractional part, Examples are
3.141, 476.6, and so on.
• Java supports two types of such numbers.
float: This type is used for single-precision decimal floating point numbers, that is, 7 digits
after the decimal point. These numbers are stored on 4 bytes.
Double : This type is used for double-precision decimal floating point numbers, that is, 10
digits after the decimal point. These numbers are stored on 8bytes.
iv. Boolean Data Type
Type Casting
Converting one data type to another data type is called as Type Casting. There are two types
of type casting. They are,
i. Implicit Type casting
ii. Explicit Type casting
Implicit typecasting:
Compliler perform implicit typecasting automatically when smaller data type value
into larger data type.
In implicit type casting there is no loss of information.
Implicit typecasting also called as widening or up casting.
Example:
int n=’a’;
System.out.println(n); //97
Explicit typecasting:
Programmer performs explicit typecasting when larger data type value into smaller data
type.
In explicit type casting there may be chance of loss of information.
Implicit typecasting also called as narrowing or down casting.
type variable = (new_type) variable;
Example: double d=10.5;
int n=(int)d; // n becomes 10
d=c/a;
k=a+y;
e = a + (int)y;
z=(double)c/a;
Declaration of Variables
The variable is the basic unit of storage in a Java program. A variable is a container which holds the
value and that can be changed during the execution of the program. A variable is assigned
with a datatype. A variable is defined by the combination of an identifier, a type, and an optional
initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime.
In Java, all variables must be declared before they can be used. The basic form of a variable declaration
is shown here:
The type is one of Java’s atomic types, or the name of a class or interface. The identifier is the name of the
variable. You can initialize the variable by specifying an equal sign and a value. Declaration and
Initialization of the variable is as follows.
1. The scope starts from the point the variable is defined in the block (declared and value
assigned to it).
2. Although the variable may be defined anywhere in a block, it can be used only in the
statements appearing after its definition Therefore, there is no use in defining a variable at
the end of block.
If there are nested blocks, a variable defined in the outer block is visible in the inner blocks
also and it cannot be redefined with the same name in the inner blocks
Static blocks in Java are executed automatically when the class is loaded in memory.
Static blocks are executed before the main() method.
Static blocks are executed only once as the class file is loaded to memory.
A class can have any number of static initialization blocks.
The execution of multiple static blocks will be in the same sequence as written in the program. For
example, the static blocks are executed from top to bottom.
Static blocks cannot access instance (non-static) variables and methods.
Ex:
class staticdemo
{
static
{
System.out.println(“Static Block 1”);
}
static
{
System.out.println(“Static Block 1”);
}
public static void main(String args[])
{
System.out.println(“hello world”);
}
}
OutPut:
Static Block 1
Static Block 2
hello world
Static Variables:
• The static variables are class variables. Only one copy of such variables is kept in the
memory and all the objects share that copy.
• The static variables are accessed through class reference, whereas the instance
variables are accessed through class object reference
• The static variables in a class can be declared by modifier static.
• The non-static variables declared in a class are instance variables. Each object of the
classkeeps a copy of the values of these variables.
Static Methods:
• The static methods are similar to class methods and can be invoked without any reference
of object of class, however, class reference (name of class) is needed, as in the following
example The method like sqrt() is declared as static method in Math class and is called
The static method is called using the method name that is preceded by the class name; in this
case. Math and period ().
E:\>java StaticMethods
The Square root root of 16 = 4.0
The cubroot root of 27 = 3.0
Random Number 1 = 77
Random Number 2 = 69
Random Number 3 = 83
Random Number 4 = 2
Random Number 5 = 66
Operators
An operator is a symbol that tells the computer to perform certain mathematical and
logical calculations.
Relational Operators:
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering.
The relational operators are shown here:
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
The outcome of these operations is a boolean value. The relational operators are most
frequently used in the expressions that control the if statement and the various loop
statements.
Any type in Java, including integers, floating-point numbers, characters, and
Booleans can be compared using the equality test, ==, and the inequality test,
!=.
int a = 4;
int b = 1;
boolean c = a < b; // c is false
Logical operators:
The logical ! operator inverts the Boolean state: !true == false and !false == true.
Short-Circuit Logical Operators(&&, ||):
Java provides two interesting Boolean operators not found in many other computer
languages.
These are secondary versions of the Boolean AND and OR operators, and are known as
short-circuit logical operators. As you can see from the preceding table,
the OR operator results in true when A is true, no matter what B is. Similarly, the
AND operator results in false when A is false, no matter what B is.
Increment and Decrement
The ++ and the – – are Java’s increment and decrement operators.
The increment operator increases its operand by one. The decrement operator decreases its operand by
one. For example, this statement:
x = x + 1; can be rewritten like this by use of the increment operator: x++;
For example:
x = 42;
y = ++x;
In this case, y is set to 43 as you would expect, because the increment occurs before x is
assigned to y. Thus, the line y = ++x; is the equivalent of these two statements:
x = x + 1;
y = x;
the value of x is obtained before the increment operator is executed, so the value of y is 42.
Of course, in both cases x is set to 43. Here, the line y = x++; is the equivalent of these two
statements:
y = x;
x = x + 1;
}
Output :
Absolute value of i is 10
Assignment operators:
-Assignment operators are used to assign the result of an expression to a variable.
Operator Meaning
= Assignment
-In addition, java has a set of short-hand assignment operators of the form
V OP=EXP;
- It is equivalent to
V=V OP EXP;
-The short-hand assignment operators are += , -= , *= , /= , %=
Example:
a+=b a=a+b
00001010 10
The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1,then
the resultant bit is a 1, as shown here:
00101010 42
| 00001111 15
00101111 47
The Bitwise XOR
The XOR operator, ^, combines bits such that if exactly one operand is 1, then the
resultis 1. Otherwise, the result is zero.
00101010 42
^ 00001111 15
………………………..
00100101 37
One’s complement:
-The one’s complement (~) is a unary operator applied to an integral value.
-The result is 1 when the original bit is 0 and it is 0 when the original bit is 1.
Original bit Result( ~ )
0 1
1 0
Left Shift
The left shift operator, <<, shifts all of the bits in a value to the left a specified number
oftimes.
It has this general form:
value << num
Here, num specifies the number of positions to left-shift the value in value. That is, the
<< moves all of the bits in the specified value to the left by the number of bit positions
specified by num.
For each shift left, the high-order bit is shifted out (and lost), and a zero is brought in
on the right.
byte a = 64, b;
int i;
i = a << 1;
b = (byte) (a << 2);
After shifting operation i =128 and b=0 ( because byte takes only 8-
bits)
Right Shift
The right shift operator, >>, shifts all of the bits in a value to the right a
specified number of times.
Its general form is shown here:
value >> num
Here, num specifies the number of positions to right-shift the value in value.
That is, the >> moves all of the bits in the specified value to the right the number of
bit positions specified by num.
The following code fragment shifts the value 32 to the right by two positions,
resulting in a being set to 8:
int a = 32;
a = a >> 2; // a now contains 8
Bitwise Zero Fill Right Shift Operator(>>>) : shifts the bits of the number towards the right a
specified n number of positions. The sign bit filled with 0's. The symbol >>> represents the Bitwise
Zero Fill Right Shift Operator. When we apply >>> on a positive number, it gives the same output as
that of >>. It gives a positive number when we apply >>> on a negative number. MSB is replaced by
a 0.
Bitwise Operator Assignments:
All of the binary bitwise operators have a shorthand form similar to that of the algebraic
operators, which combines the assignment with the bitwise operation.
For example, the following two statements, which shift the value in a right by four
bits,are equivalent:
a = a >> 4;
a >>= 4;
Special Operators:
- Java supports some special operators such as,
a) instanceof operator
b) member selection operator
a) instanceof operator:
- The instanceof is an object reference operator and returns true if the object on the left-hand
side is an instance of the class given on the right hand side.
- This operator allows us to determine whether the object belongs to a particular class or not.
Example:
person instanceof student
- It is true if the object person belongs to the class student, otherwise it is false.
SELECTION STATEMENTS:
-Also called as conditional or decision-making control statements.
-There are two types in Selection control statements.
i) Two-way selection control statements
ii) Multi-way selection control statements
i) Two-way selection control statements:
-The different two-way selection statements are,
a) if-else statement
b) null else statement
c) Nested-if statement
}
}
Example:
if(a>b)
{
System.out.println(“a is greater”);
}
else
{
System.out.println(“b is greater”);
}
3. Ternary Operator?:
In Java, the ternary operator is a type of Java conditional operator. The meaning
of ternary is composed of three parts.
The ternary operator (? :) consists of three operands. It is used to evaluate Boolean
expressions. The operator decides which value will be assigned to the variable. It is the only
conditional operator that accepts three operands.
It can be used instead of the if-else statement. It makes the code much more easy, readable,
and shorter.
Syntax:
Expression1 ? Expression2 : Expression3;
Example-1:
int a=10;
int b = (a<20)? 100 :200; // a < 20 if statement
System.out.println("b= "+b);
}
}
4. Switch Statement
Syntax:
switch(expression)
{
case value-1:statement-1;break;
case value-2:statement-2;break;
………………………….
………………………….
case value-n:statement-n;break;
default: default statement;
}
next statement;
Example:
switch(digit)
{
case 0: System.out.println(“ZERO”);break;
case 1: System.out.println(“ONE”);break;
case 2: System.out.println(“TWO”);break;
case 3: System.out.println(“THREE”);break;
case 4: System.out.println(“FOUR”);break;
case 5: System.out.println(“FIVE”);break;
case 6: System.out.println(“SIX”);break;
case 7: System.out.println(“SEVEN”);break;
case 8: System.out.println(“EIGHT”);break;
case 9: System.out.println(“NINE”);break;
default: System.out.println(“Enter between 0-9”);
}
Iteration Statements
LOOP STATEMENTS:
-The iteration control statements are also called as Repetition or Iteration control statements.
-A looping process includes the following four steps.
-Setting and initialization of a counter.
-Execution of the statements in the loop body.
-Test for a specified condition (loop control expression) for execution of a loop
-Incrementing or Decrementing counter.
i) Pretest and Posttest loops:
-In a Pretest loop, the condition is checked before we execute a loop body.
-It is also called as entry-controlled loop.
-In the Posttest loop, we always execute the loop body atleast once.
-It is also called as exit-controlled loop.
a) while statement:
Syntax:
while(condition)
{
loop body;
}
next statement;
Example:
n=10,i=1,sum=0;
while(i<=n)
{
sum=sum+i;
i++;
}
System.out.println(“sum=”+sum);
do–while Loop
Syntax:
do
{
loop body;
}while(condition);
next statement;
Example:
n=10,i=1,sum=0;
do
{
sum=sum+i;
i++;
} while(i<=n);
System.out.println(“sum=”+sum);
for statement:
Syntax:
for(initialization; condition; inc or dec)
{
loop body;
}
next statement;
Example:
n=10,i,sum=0;
for(i=1;i<=n;i++)
{
sum=sum+i;
}
System.out.println(“sum=”+sum);
5. Nested for Loop
Syntax:
for(initialization;condition; inc or dec)
{
for(initialization;condition;inc or dec)
{
Inner loop body;
}
Example:
Output:
C:\>javac ForEach.java
C:\>java ForEach
10
20
30
40
50
6. Break Statement
Unconditional control statements:
-The unconditional control statements are,
a) break statement
b) continue statement
break statement:
-The break statement skips from the loop or block in which it is defined.
-The control then automatically goes to the first statement after the loop or block.
-The general format is
break;
Example:
public class Break
{
public static void main (String args[])
{
C:\>java Break
0
1
2
3
4
Example:
C:\>javac Break.java
C:\>java Continue
0
1
2
3
4
6
7
8
9
Here 5 is not printed because of continue statement. The Iteration at the condition i = =5 is
skipped or jumped to next statement.
Labeled Break and Labeled Continue Staements:
n Java, we can label the loops and give them names. These named or labeled loops help in the
case of nested loops when we want to break or continue a specific loop out of those multiple
nested loops.
The simple break statement in Java terminates only the immediate loop in which it is specified. So
even if we break from the inner loop, it will still continue to execute the current iteration of the outer
loop.
When this break statement is encountered with the label/name of the loop, it skips the execution any statement
after it and takes the control right out of this labelled loop.
And, the control goes to the first statement right after the loop.
//Labelled break example with while loop
int i=7;
loop1:
while(i<20)
{
if(i==10)
break loop1;
System.out.println("i ="+i);
i++;
}
}
Output:
7
8
9
Out of the loop
In the same way, we can use the labeled continue statements to jump to the next iteration of any
specific loop in the hierarchy of nested loops.
continue outer_loop;
Classes, Objects and Methods
CLASS: Java is a pure object-oriented language. The class is the basis of an object-oriented
programming language.
A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created.
Simple classes may contain only code or only data, most real-world classes contain both.
A class is declared by use of the class keyword.
The general form of a class is
class classname
{
type instance-variable1;
type instance-variable2;
// …….
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
The data, or variables, defined within a class are called instance variables.
The code is contained within methods. Collectively, the methods and variables defined
within a class are called members of the class.
The object is an instance of class. We can create any number of objects from a class.
Simple Class like as bellow
class Box
{
double width;
double height;
double depth;
}
In the above, a class defines a new type of data. In this case, the new data type is called
Box. You will use this name to declare objects of type Box.
A class declaration only creates a template; it does not create an actual object.
For creating a Box object we use,
Box mybox = new Box(); // create a Box object called mybox
1
Here mybox will be an instance of Box.
To access variables, methods inside a class we have to use .(dot) operator.
The dot operator links the name of the object with the name of an instance variable.
To assign the width variable of mybox the value 100, you would use the following
statement:
mybox.width=100;
Example:
class Box
{
double width;
double height;
double depth;
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
The above program must save with BoxDemo.java ( because BoxDemo contains main())
After compiling the program two class files are created one is Box.class and other one is
BoxDemo.class
At the time of running BoxDemo.class file will be loaded by JVM
For compilation: javac BoxDemo.java
For Running: java BoxDemo
Output:
Volume is 3000.0
We can create multiple objects for the same class
Example
class Box
{
double width;
double height;
double depth;
}
class BoxDemo
{
public static void main(String args[])
2
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol1,vol2;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
vol1 = mybox1.width * mybox1.height * mybox1.depth;
mybox2.width = 10;
mybox2.height = 15;
mybox2.depth = 5;
vol2= mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume of mybox1 is " + vol1);
System.out.println("Volume of mybox2 is " + vol2);
}
}
Output
Volume of mybox1 is 3000.0
Volume of mybox2 is 750.0
Objects:
Class is a template or blueprint from which objects are created. So object is the
instance(result) of a class.
for creating objects we have to use following code.
Box mybox;
// declare reference to object
3
Class Declaration and Modifiers
The class declaration starts with the “Modifier”. Sometimes a class may be declared without
“Modifier”. In case a “modifier” is present it is followed by keyword “class”, which is followed by “class
name”. The body of the class is enclosed between pair of curly braces { }. The declaration of the class
will be as follow:
Class Modifiers
The class modifiers are used to control the access to the class and its inheritance characteristics. The
Java has number of packages. The packages contain sub-packages and classes. The java has various
modifiers as follow:
Modifiers Description
No modifier The class declared without modifier is accessible to the classes in its
own package.
public When a class is declared as public, it is accessible to all the classes in
all the packages.
private Class is not accessible to other members of the Outer class
protected Class is accessible to other members of the Outer class as well as by
classes derived from the outer class.
final When a class is declared as final, it cannot be inherited.
abstract The abstract class can contain abstract methods and non-abstract
methods. The abstract methods contain method declaration, body
will be implemented by the derived class. Non-abstract method
contains body also.
Class Members
The members that are declared inside the class are called class members. These members
include fields, methods, nested classes, and interfaces. The field can be instance variable and class
variable.
The instance variables belong to an object, and every object keeps a copy of these variables. These are
used to represent specific properties of every object.
The class variables are declared with modifier static. These are used to represent common
properties of all objects. These are also known as static variables. These are not copied to objects, they
always stay with class. Only one copy of memory is allocated for class variables. All the objects will
share the class variables.
Write a java Program to demonstrate the difference between instance variable
and class variable.
class EmpData
{
String name;
4
int id;
static int count=0;
EmpData(String s,int n)
{
name=s;
id=n;
count=count+1;
}
void display()
{
System.out.println("Employee name:"+name);
System.out.println("Employee Id is:"+id);
//class variable is accessed here
System.out.println("Number of Employees in the Company are:"+count);
}
}
class EmpTest
{
public static void main(String arg[])
{
EmpData e1=new EmpData("rohan",1);
e1.display();
EmpData e2=new EmpData("radha",2);
e2.display();
}
}
Output:
Employee name:rohan
Employee Id is:1
Number of Employees in the Company are:1
Employee name:radha
Employee Id is:2
Number of Employees in the Company are:2
In the above code b1 and b2 will both refer to the same object.
The assignment of b1 to b2 did not allocate any memory or copy any part of the original
object.
It simply makes b2 refer to the same object as does b1.
5
Thus, any changes made to the object through b2 will affect the object to which b1 is
referring, since they are the same object.
Example:
class Box
{
//instance variables
int length,width,height;
}
class FarmTest
{
public static void main(String arg[])
{
//create objects
Box b1=new Box();
Box b2;
//initialize instance variables of f1 object
b1.length=25;
b1.width=40;
b1.height=20;
System.out.println("The width of b1 before assigning is :"+b1.width);
b2=b1;
b2.width=100;
System.out.println("The width of b2 is :"+b2.width);
System.out.println("The width of b1 is :"+b1.width);
}
}
OutPut: The width of b1 before assigning is :40
The width of b2 is :100
The width of b1 is :100
6
public int a=20;
private float f=3.45f;
protected double y=12.34;
Default Access Modifier: If you don't use any modifier, it is treated as default by default. The
default modifier is accessible only within package.
Protected Access Modifier: The protected access modifier is accessible within package and outside
the package but through inheritance only.
The members declared as protected are same as private, but can be accessed by the derived
class also.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
Example:
In this example, we have created the two packages pack and mypack. The A class of pack package
is public, so can be accessed from outside the package. But msg method of this package is
declared as protected, so it can be accessed from outside the class only through inheritance.
7
//save by A.java
package pack;
public class A{
protected void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void
main(String args[])
{
B obj = new B();
obj.msg();
}
}
Output:
Hello
Public Access Modifier: The public access modifier is accessible everywhere. It has the widest
scope among all other modifiers.
Example:
//save by A.java
package pack;
public class A {
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[])
{
A obj = new A();
8
obj.msg();
}
}
Output:
Hello
9
E:\JAVA>javac FarmTest.java
FarmTest.java:12: error: length has private access in Farm
f1.length=25; //accessing the private members outside the class
^
FarmTest.java:13: error: width has private access in Farm
f1.width=40;
^
FarmTest.java:14: error: length has private access in Farm
int area=f1.length*f1.width;
^
FarmTest.java:14: error: width has private access in Farm
int area=f1.length*f1.width;
^
4 errors
If we want to access private method, it could be done with the help of the public
method. A call to the private method is made inside the public method definition.
This is shown in the following program.
class Farm
{
//instance variables
private int length,width; //private data members
private void setSides(int l,int w) //private method
{
length=l;
width=w;
}
public void area(int l, int w)
{
setSides(l,w); //call to the private method
System.out.println("The area of the Farm is :"+(length*width));
}
}
class FarmTest
{
public static void main(String arg[])
{
//create objects
Farm f1=new Farm();
//access public method here with object f1
f1.area(25,4);
}
10
}
Output:
E:\JAVA>javac FarmTest.java
E:\JAVA>java FarmTest
The area of the Farm is :100
Methods:
In java, a method is like function i.e. used to expose behavior of an object.
A method definition contains two components:
1. Header that contains modifier, return type, method name, and list of
parameters. The parameters are enclosed in a pair of parentheses.
2. Body that contains declarations and executable statements and are enclosed in
curly braces( { } ).
Modifier: Here, the modifier can be any one such as public, private, protected,
final, static, abstract etc.
Return type: The method return type can be any one of the primitive types such
as int, float, double, char or class type, and void.
Method name:The name of the method is an identifier. If the name contains more
than one word, the first word starts with lower case, and remaining words begin
with capital letter. Space is not allowed. The keywords cannot be used as method
name.
Parameter list: The parameter list is enclosed in parentheses, and each
parameter is separated by the comma operator as shown in above syntax. If the
method has no parameters, then the parameter list will be empty.
Return statement: The method if it wants to return a value, then it can contain
return statement at the end. The return statement is used to return a value from
function definition to the function call.
return value;
Methods that have a return type other than void return a value to the calling routine
using the following form of the return statement:
Here, value is the value returned.
Example program for usage of method:
class Box
{
double width;
double height;
double depth;
11
void volume() // method
{
double vol=width*height*depth;
System.out.println("Volume is " + vol);
}
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
mybox.volume();
}
}
class Values
{
void add(int a,int b)
{
int c=a+b;
System.out.printlln(“addition of a, b is ”+c);
12
}
}
class Addition
{
public static void main(String args[])
{
Addition ad=new Addition();
ad.add(10,20);
}
}
Output: addition of a, b is 30
Method Overloading:
In Java it is possible to define two or more methods within the same class that share
the same name, as long as their parameter declarations are different.
The parameter list, or types, or order of the parameters are different.
These methods are said to be overloaded, and the process is referred to as method
overloading.
Method overloading is one of the ways that Java implements polymorphism.
Method overloading is also called as “ Static binding or Compile time polymorphism or
Early binding”.
display()
Output:
No parameters
integer a: 10
double d: 10.325
String s: hello
Constructors:
constructor is a special member function used to initialize values for the
variables.
The name of the constructor is same as the name of the class..
A constructor initializes an object immediately upon creation. It has the same name
as the class in which it resides and is syntactically similar to a method.
Once defined, the constructor is automatically called immediately after the object is
created, before the new operator completes.
It will not return any value
Constructors do not any return type, not even void.
This is because the implicit return type of a class’ constructor is the class type itself.
Constructers can be public, private, protected. They can not be static, abstract or final.
Example:
class Addition
{
Addition()
{
System.out.println(“This is Default constructor”);
}
}
class ConstructorDemo
{
public static void main(String args[])
{
Addition ad=new Addition();
}
}
Output: This is Default constructor
14
Now we can understand why the parentheses are needed after the class name. What isactually
happening is that the constructor for the class is being called. Thus, in the line
Constructor overloading:
In addition to overloading normal methods, you can also overload constructor methods.
In Java it is possible to define two or more constructors within the same class that share
the same name, as long as their parameter declarations are different. Their
parameters are different either in number or type or order of parameters.
Example
class Display
{
Dispaly()
{
System.out.println("No parameters");
}
Dispaly(int a)
{
System.out.println("integer a: " + a);
}
Dispaly(double d)
{
System.out.println("double d: " + d);
}
Display(String s)
{
System.out.println("String s:" + s);
}
}
15
class OverloadDemo
{
public static void main(String args[])
{
Display ds=new Display();
Display ds1=new Display(10);
Display ds2=new Display(10.325);
Display ds3=new Display(“hello”);
Output:
No parameters
integer a: 10
double d: 10.325
String s: hello
16
Nested Classes
A nested class is the one which is defined inside another class. The class which is
defined in another class is called nested class, or inner class. The class in which
another class is defined is called enveloping class or outer class. The scope of the
inner class is limited to the scope of outer class. The inner class can be static or non -
static class.
If the inner class is declared as static, it can be accessed without creating an
object of outer class. If the inner class is declared as non-static, then we have to
create object from the outer class first, and create object of inner class, and then
access the inner class object using the outer class object.
Write a java program to demonstrate non-static Inner class.
MyFarmTest.java
class MyFarm
{
int length,width;
MyFarm(int l,int w)
{
length=l;
width=w;
}
public void display()
{
//inner class object is created inside the outer class
Inner iner=new Inner();
iner.area();
iner.fenceCost();
}
//non-static Inner Class
class Inner
{
float cost=200.0f;
static keyword:
It is possible to create a member that can be used by itself, without reference to a specific
instance.
To create such a member, precede its declaration with the keyword static.
When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object.
We can declare both methods and variables to be static.
The most common example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist.
Instance variables declared as static are, essentially, global variables.
Methods declared as static have several restrictions:
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way.
We can declare a static block which gets executed exactly once, when the class is first
loaded.
Example
class UseStatic
{
static int a = 3;
static int b;
static void display(String s)
{
System.out.println(“Static method invoked String s= “+s);
}
static
{
System.out.println("Static block initialized.");
} b = a * 4;
}
18
class StaticDemo
{
public static void main(String args[])
{
System.out.println(“static variable a= ”+ UseStatic.a);
System.out.println(“static variable b= “+UseStatic.b);
UseStatic. Display(“JAVA”);
}
}
Ouput:
Static block initialized.
static variable a= 3
static variable b= 12
static method invoked String s= JAVA
Final Class and Final Methods
Final class: The class that is declared as final cannot be inherited. We cannot create
subclasses for a final class.
Final Method: It is also possible to declare a method as final. When a method is
declared as final, the subclass is not allowed to override it. Which means final
method prevents the method overriding.
Final Variable: A variable declared as final cannot be changed.
Write a java program to demonstrate Final class.
final class A
{
void dispA()
{
System.out.println("Method of class A");
}
}
class B extends A //here A cannot be inherited
{
void dispB()
{
System.out.println("Method of class B");
}
}
class FinalTest
{
public static void main(String arg[])
{
B b=new B();
b.dispA();
b.dispB();
} }
19
Output:
C:>javac FinalTest.java
FinalTest.java:8: error: cannot inherit from final A
class B extends A //here A cannot be inherited
^
1 error
Abstract Class
A class that is declared with abstract keyword, is known as abstract class in java. It can
have abstract and non-abstract methods (method with body). Abstraction is a process of
hiding the implementation details and showing only functionality to the user.
Abstraction lets you focus on what the object does instead of how it does it. It needs to be
extended and its method implemented. It cannot be instantiated.
20
The abstract class cannot be used to create objects. The sub class will implement the
abstract method. The object is created from the sub class only.
Abstract method: A method that is declared as abstract and does not have implementation is
known as abstract method.
abstract void printStatus();//no body and abstract
class CallByVal
{
}
Output:
Before method calling value=
20 Inside method value= 21
After method calling value= 20
Pass by Reference:
If a method is defined with parameters as Objects, and if method changes
values of the instance variables of the object, then the changed values are
retained by the object. That means, if the values are changed in parameters of
the method, it will affect the actual arguments also. This is called passing
arguments through reference.
class CallByRef
{
int x;
public static void main(String args[])
{
CalByRef c=new
CalByRef(); c.x=20;
System.out.println("Before method calling value= "+c.x);
display(c);
System.out.println("After method calling value= "+c.x);
}
public static void display(CalByRef m)
{
m.x=m.x+1;
System.out.println("Inside method value= "+m.x);
}
}
Output:
Before method calling value=
20 Inside method value= 21
After method calling value= 21
Overriding Methods
A method defined in the super class can be inherited by the subclass. This
feature allows to use the super class method as it is in the subclass. In some
cases subclass may define the same method that is defined in the super class,
but with different behaviour or purpose. Then, in that case, that method is
said be overridden. The method defined in the subclass will be executed and
will hide the method of the super class.
Example ProgramOrerriding.java
class A //Base Class or Super
{
void disp()
{
System.out.println("This is method class A");
}
}
class B extends A //Derived Class or Sub class
{
void disp()
{
System.out.println("This is method class B");
}
}
class MO
{
public static void main(String arg[])
{
B obj=new B();//object from subclass
obj.disp(); // Method overriding
}
}
Output:
This is method class B
ARRAYS
Introduction
An array is a collection of data of the same type. An array is a structure consisting of a group
of elements of the same type. When a large number of data values of the same type are to be
processed, it can be done efficiently by declaring an array of the data type. The complete data
gets represented by a single object with a single name in the computer memory.
An array is a sequence of objects of the same data type. The type of data that the array holds
becomes the type of the array, which is also called base type of the array. If the array
elements have values in whole numbers, that is, of type int, the type of array is also int.
When the elements of the array are again arrays, then the array is said to be
multidimensional array. A one-dimensional array has elements where each element is
accessed by an index value. Two-dimensional array is actually an array of one-dimensional
arrays.Each element of two-dimensional array needs two index values: one position of the
array in 2-D array, and other refers to the position in that array.
Examples:
int numbers []; // an array of whole numbers
char name []; // A name is an array of characters
float priceList []; // An array of floating point numbers.
An array can also be declared as
type [] arrayname;
Ex: int intArray[];
int[] intArray;
Initialization
With above declaration no memory is allocated. Memory is allocated when new operator is
used or when it is initialized with declaration as shown below.
dataType [] nameOfArray = new dataType [size]
dataType [ ] nameOfArray = {value1, value2, value3, value4}
One of the most powerful techniques that you can use to initialize your array involves using a
for loop to initialize it with some values.
Example:
for(inti=0;i<array_name.length;i++)
{
System.out.println(a[i] +”\n”);
}
Use of for–each Loop:
the for–each loop may be used to access each element of the array.
for (int x: numbers) { System.out.println(x);}
Example programs on Arrays
import java.util.*;
class ArrDemo
{
static void display(int a[])
{
System.out.println("The Elements of Array are:");
for(int x:a)
{
System.out.print(x+"\t");
}
System.out.println();
}
static void add(int a[],int b[])
{
System.out.println("Addition of two arrays:");
int c[]=new int[a.length];
for(int i=0;i<a.length;i++)
{
c[i]=a[i]+b[i];
}
for(int x:c)
{
System.out.print(x+"\t");
}
}
public static void main(String arg[])
{
int[] arr1,arr2,arr3;//declaration of array
int n,i;
Scanner in=new Scanner(System.in);
System.out.println("Enter size of Array:");
n=in.nextInt();
//create array
arr1=new int[n];
arr2=new int[n];
arr3=new int[n];
//read elements into array
System.out.println("Enter elements into array 1:");
for(i=0;i<n;i++)
{
System.out.printf("Enter %d element:",i);
arr1[i]=in.nextInt();
}
System.out.println("Enter elements into array 2:");
for(i=0;i<n;i++)
{
System.out.printf("Enter %d element:",i);
arr2[i]=in.nextInt();
}
display(arr1);//method call
display(arr2);
add(arr1,arr2); // arguments
}
}
Output:
Enter size of Array:4
Enter elements into array 1:
Enter 0 element:2
Enter 1 element:4
Enter 2 element:6
Enter 3 element:8
Enter elements into array 2:
Enter 0 element:12
Enter 1 element:14
Enter 2 element:16
Enter 3 element:18
The Elements of Array are:
2 4 6 8
The Elements of Array are:
12 14 16 18
Addition of two arrays:
14 18 22 26
Operations on Array Elements
An array element is a variable of the type declared with array. All the operations that are
commonly performed on that type of a variable are also can be applied to an array
element.The operations such arithmetic addition, subtraction, multiplication, and division
can be performed on the elements of two arrays.
Arrays as Parameters of Methods
We can pass Arrays as parameters similar to primitive data type and objects of class type.
Syntax:
display(arr1,arr2);
add(arr1,arr2);
These arguments in the method call are assigned to parameters in the method definition in the
order.
Assigning Array to Another Array
In Java an array can be assigned to another array of same type. This can be done as follow:
int arr1[]={2,4,6,8);
int arr2=arr1;
In this process, the 2nd array (arr2) becomes a reference to the assigned array (arr1).The
second array is not a new array, instead a second reference is created. In this context both
arr1 and arr2 are referring the same memory.
If a change is done on arr1, then it is reflected on arr2.Let us understand this with an example
program.
ArrOperations.java
import java.util.*;
class ArrOperations
{
public static void main(String arg[])
{
int[] arr1,arr2; //
arr1=new int[]{2,4,6,8};//memory allocation and initialization to array
arr2=arr1; // assigning arr1 to arr2
//display arr2
System.out.println("Elements of arr2 are:");
for(int x:arr2)
System.out.print(x+"\t");
for(int i=0;i<arr1.length;i++)
arr1[i]=arr1[i]*5; //modifying the arr1 elements
//display arr1
System.out.println("\nElements of arr1 after modification are:");
for(int x:arr1)
System.out.print(x+"\t");
//display arr2
System.out.println("\nElements of arr2 after modification are:");
for(int x:arr2)
System.out.print(x+"\t");
}
}
Example
int [][] array2d = new int [][] {{1, 2, 3}, {4, 5, 6}}; or as
int [][] array2D = {{1, 2, 3}, {4, 5, 6}};
import java.util.*;
class MatTest
{
public static void main(String arg[])
{
int[][] A,B;
intr,c,i,j;
Scanner in=new Scanner(System.in);
System.out.println("Enter rows and columns:");
r=in.nextInt();
c=in.nextInt();
A=new int[r][c];
B=new int[r][c];
//reading elements into matrix A
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.printf("Enter A[%d][%d] element:",i,j);
A[i][j]=in.nextInt();
}
}
//reading elements into matrix B
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.printf("Enter B[%d][%d] element:",i,j);
B[i][j]=in.nextInt();
}
}
//display arrays A and B
System.out.println("Matrix A is:");
System.out.println(Arrays.deepToString(A));
System.out.println("Matrix B is:");
System.out.println(Arrays.deepToString(B));
//matrix addition
C=new int[r][c];
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
C[i][j]=A[i][j]+B[i][j];
}
}
System.out.println("Matrix C is:");
System.out.println(Arrays.deepToString(C));
}
}
Matrix Multiplication
importjava.util.Arrays; Arrays2D.java
class Array2D
{
public static void main(String arg[])
{
int a[][]={{1,2},{4,5,6},{10,20,30,40,50}};
//display elements
for(inti=0;i<a.length;i++)
{
for(int j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
}
Three-dimensional arrays
When an array holds 2-dimensional arrays as its elements, it is called “Three-
dimensional Array”.
We need three index values to refer each element of three-dimensional array.
Three-dimensional array is represented as follow:
int a[][][]; //declaration
int a[][][]=new int[2][3][4]; //creation
String Handling
In Java a string is a sequence of characters. But, unlike many other languages that implement strings as
character arrays, Java implements strings as objects of type String. Java provides a set of methods that make
string handling convenient.
For example, Java has methods to compare two strings, search for a substring, concatenate two strings, and
change the case of letters within a string.
In Java, there are three classes that can create strings and process them with nearly similar methods.
Interface CharSequence
It is an interface in java.lang package.
It is implemented by several classes including the classes String, StringBuffer, and StringBuilder.
It has the following four methods.
i. charAt(int index): The method returns character value at specified index value.
ii. int length(): This method returns the length of this (invoking) character sequence.
iii. CharSequence subSequence(int startIndex, endIndex): The method returns a subsequence
from start index to end index of this sequence. Throws IndexOutOfBoundsException.
iv. String toString(): The method returns a string containing characters of the sequence in the
same.
Example:
class CharSeq
{
public static void main(String arg[])
{
CharSequence cs="Java Program";
System.out.println("The character at position 2 is:"+cs.charAt(2));
System.out.println("The length of the string is:"+cs.length());
System.out.println("Sub sequence of the string from index 3 to 7 is:"+cs.subSequence(3,7));
}
}
Output: The character at position 2 is:v
The length of the string is:12
Sub sequence of the string from index 3 to 7 is:a Pr
String class
The class String is used to represent strings in Java. It is declared as:
public final class String extends Object implements serializable, comparable<String>, charSequence
•startsWith( ) and endsWith( ): These methods determines whether a given String begins/ends with a
specified string.
boolean startsWith(String str)
boolean endsWith(String str)
boolean startsWith(String str, int startIndex)
Eg:
"Foobar".endsWith("bar")
"Foobar".startsWith("Foo")
"Foobar".startsWith("bar", 3)
regionMatches( ): Used to test if two string regions are matching or equal.
➢ boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)
➢ boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int
numChars)
Eg: String str1 = new String("Welcome to SACET");
String str2 = new String("SACET");
System.out.println(str1.regionMatches(11, str2, 0, 5));
if(s1==s2) {
System.out.println(“s1==s2 is TRUE”);
} else{
System.out.println(“s1==s2 is FALSE”);
}
if(s1.equals(s2)) {
System.out.println(“s1.equals(s2) TRUE”);
} else {
System.out.println(“s1.equals(s2) is FALSE”);
}
• The String class provides two methods that allow you to search a string for a specified character or
substring:
indexOf( ) Searches for the first occurrence of a character or substring.
lastIndexOf( ) Searches for the last occurrence of a character or substring.
• These two methods are overloaded in several different ways. In all cases, the methods return the index at
which the character or substring was found, or–1 on failure
replace( ):To replaces all occurrences of one character in the invoking string with another character.
trim( ): returns a copy of the invoking string from which any leading and trailing whitespace has been
removed.
String trim( )
Eg: String s = " Hello World ".trim();
StringBuffer:
• StringBuffer is a peer class of String that provides much of the functionality of strings.
• StringBuffer may have characters and substrings inserted in the middle or appended to the end.
• StringBuffer will automatically grow to make room for such additions and often has more characters pre-
allocated than are actually needed, to allow room for growth.
• StringBuffer(String str): Accepts a String argument that sets the initial contents of the StringBuffer
object and reserves room for 16 more characters without reallocation.
• StringBuffer(CharSequence chars): Creates an object that contains the character sequence contained in
chars.
length( ) and capacity( ): The current length of a StringBuffer can be found via the length( ) method, while
the total allocated capacity can be found through the capacity( ) method.
int length( )
int capacity( )
• charAt( )andsetCharAt( )
• getChars( )
• append()
insert( )
StringBuffer reverse( )
• delete( ) anddeleteCharAt( )
• replace( ):
Output:
Hello Java
Hello Java Programming
1 step Java Programming
step Java Programming
gnimmargorP avaJ pets
Current capacity is:46
StringBuilder
Method Description
public StringBuilder append(String s) is used to append the specified string with this string. The
append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
public StringBuilder insert(int offset, is used to insert the specified string with this string at the
String s) specified position. The insert() method is overloaded like
insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
public StringBuilder replace(int is used to replace the string from specified startIndex and
startIndex, int endIndex, String str) endIndex.
public StringBuilder delete(int is used to delete the string from specified startIndex and
startIndex, int endIndex) endIndex.
public void ensureCapacity(int is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) is used to return the character at the specified position.
public int length() is used to return the length of the string i.e. total number
of characters.
public String substring(int beginIndex) is used to return the substring from the specified
beginIndex.
public String substring(int beginIndex, is used to return the substring from the specified
int endIndex) beginIndex and endIndex.
Example:
class SBuilder
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
sb.insert(10," Programming");//inserting from a given position
System.out.println(sb);
sb.replace(0,5,"1 step");
System.out.println(sb);//prints 1 step before string and modifies
sb.delete(0,1);
System.out.println(sb);
sb.reverse();
System.out.println(sb);
System.out.println("Current capacity is:"+sb.capacity());
}
}
Output:
Hello Java
Hello Java Programming
1 step Java Programming
step Java Programming
gnimmargorP avaJ pets
Current capacity is:46