0% found this document useful (0 votes)
58 views88 pages

MCA OOPJ Unit-1 Material

The document provides an overview of Object-Oriented Programming (OOP) and Java basics, detailing the history, version history, and applications of Java. It contrasts Procedure-Oriented Programming (POP) with OOP, highlighting key principles such as encapsulation, inheritance, and polymorphism. Additionally, it outlines Java's features, compilation and execution process, and the role of the Java Virtual Machine (JVM).

Uploaded by

anitha
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)
58 views88 pages

MCA OOPJ Unit-1 Material

The document provides an overview of Object-Oriented Programming (OOP) and Java basics, detailing the history, version history, and applications of Java. It contrasts Procedure-Oriented Programming (POP) with OOP, highlighting key principles such as encapsulation, inheritance, and polymorphism. Additionally, it outlines Java's features, compilation and execution process, and the role of the Java Virtual Machine (JVM).

Uploaded by

anitha
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/ 88

UNIT-1

Introduction to OOP and Java Basics


History of Java:

 Java is an efficient powerful Object-Oriented Programming language developed in the


year of 1991 by James Gosling and his team members at Sun micro systems.
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
projectin June 1991. The small team of sun engineers called Green Team.
 Initially Java is called with a name Oak is a symbol of strength and choosen as a national
tree of many countries like U.S.A., France, Germany, Romania etc.
 In 1995, Oak was renamed as "Java" .
 Java is an island of Indonesia where first coffee was produced (called java coffee).
 Sun micro systems purchased by Oracle Corporation in the year of 2010.
 JDK (Java Development tool Kit) 1.0 released in (January 23, 1996).

Java Version History

There are many java versions that has been released. Current stable release of Java is Java SE 8.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)

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

Need for Object Oriented Programming paradigm:

 Computer programs consist of two elements: code and data. Furthermore, a


program can be conceptually organized around its code or around its data.
 These are the two paradigms that govern how a program is constructed.
1) Procedure-Oriented Programming model.
2) Object-Oriented Programming model.
Procedure Oriented Programming (POP):
 In the Procedure oriented programming model importance is not given to data butto
functions as well as sequence of actions to be done.
 C, Pascal, Fortran etc are called procedure-oriented programming languages.
 In POP a programmer uses procedures or functions to perform a task.
 When the programmer wants to write a program, he will first divide the task into
separate sub tasks i.e as functions.
 In C programming several functions are controlled from a main() function.

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

class3 data methods

***********

Difference Between Procedure Oriented Programming (POP) & Object Oriented


Programming (OOP):

Procedure Object Oriented Programming


Oriented
Programming
Divided Into In POP, program is divided into In OOP, program is divided into parts
small parts called functions. called objects.
Importance In POP, Importance is not In OOP, Importance is given to the
given to data but to functions data rather than procedures or
as well as sequence of actions functions because it works as a real
to be done. world.

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’.

Ex: class Sample


{
int a;
float b;
public void add()
{
//body of method
}
}

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.

Java Characteristics (or) Features of java (or) Java Buzz words:


There is given many features of java. They are also known as java buzzwords. The Java Features
given below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed

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

A platform is the hardware or software environment in which a program runs.


There are two types of platforms software-based and hardware-based. Java provides
software- based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms. It has two
components:
 Runtime Environment
 API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris,
Mac/OS etc. Java code is compiled by the compiler and converted into bytecode.
This bytecode is a platform- independent code because it can be run on multiple
platforms i.e. Write Once and Run Anywhere(WORA).
Secured
Java is secured because:
 No explicit pointer
 Java Programs run inside virtual machine sandbox
Robust
Robust simply means strong. Java uses strong memory management. There are lack
of pointers that avoids security problem. There is automatic garbage collection in
java. There is exception handling and type checking mechanism in java. All these
points makes java robust.
Architecture-neutral
There are no implementation dependent features e.g. size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.
Portable: We may carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since byte code is "close" to native code
still somewhat slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating
distributed applications. We may access files by calling the methods from any machine on
the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi- threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web
applications etc.
Java program Compilation and Execution Process:
Sample java program:
import java.lang.*; // package import section
class Sample // creating a class
{
public static void main(String args[]) // main() execution starts from here
{
System.out.println(“Hello world”); // writing “Hello world” on console
}
}
 Save the above program with an extension .java i.e Sample.java in a specific location.

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

 JVM (Java Virtual Machine) is an abstract machine. It is a specification that


providesruntime environment in which java bytecode can be executed.
 JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).
 The JVM performs following operations: Loads code,Verifies code, Executes code
andProvides runtime environment
 Internal Archietecture of JVM:

Classloader: Classloader is a subsystem of JVM that is used to load class files.


Class(Method) Area: Class(Method) Area stores per-class structures such as the runtime
constant pool, field and method data, the code for methods.
Heap: It is the runtime data area in which objects are allocated.
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.
Program Counter Register: PC (program counter) register. It contains the address of the
Java virtual machine instruction currently being executed.
Native Method Stack: It contains all the native methods used in the application.
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.

---------------------****************-------------------

A way of viewing world

A way of viewing the world is an idea to illustrate the object-oriented programming concept

with an example of a real-world situation.

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

my family members. Look at the following image.

Agents and Communities

To solve my food delivery problem, I used a solution by finding an appropriate agent

(Zomato) and pass a message containing my request. It is the responsibility of the

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.

An object-oriented program is structured as a community of interacting

agents, called objects. Where each object provides a service (data and

methods) that is used by other members of the community.

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

members like zomato, myself, and my family in the community.


Messages and Methods

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.

In object-oriented programming, every action is initiated by passing a


message to an agent (object), which is responsible for the action. The receiver

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

include any additional information as arguments.


anyadditionalinformationasarguments.
In our example, I send a request to zomato with a message that contains food items, the

quantity of food, and the hotel details. The receiver uses a method to food get delivered to my

home.
Responsibilities

In object-oriented programming, behaviors of an object described in terms of 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

enables more independence between the objects in solving complex problems.


Classes and Instances
In object-oriented programming, all objects are instances of a class. The method invoked by

an object in response to a message is decided by the class. All the objects of a class use the

same method in response to a similar message.

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

(objects) of a community. This graphical representation shows classes listed in a hierarchical

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 object-oriented programming, classes can be organized into a hierarchical


inheritance structure. A child class inherits properties from the parent class that

higher in the tree.


Method Binding, Overriding, and Exception

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.

Otherwise, an error message is issued.


Program Structure in Java

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.

In Java, there are three types of programs as follows:


Stand- aline application programs: These programs are made and run on users computers
Applet programs : These programs are meant to run in a web page on the Internet.
Java Servlets : These programs run in computers that provide web services. They are also called as
server-side programs or servlets.

Writing Simple Java Programs


Example:

import java.io.*;
class Sample
{
// Your program begins with a call to main().

public static void main(String args[])


{
System.out.println("This is a simple Java program.");
}
}
Java is an Object oriented language. In Java, all code must reside inside a class. Every java program
imports packages which provide necessary classes and interfaces.
import java.io.*;
This statement imports the classes needed for input, output into our program.
After import statement, every java program starts with the declaration of the class.

The next line of code in the program is shown here:

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:

// Your program begins with a call to main().

The next line of code is shown here:


public static void main(String args[ ]) {
This line begins the main( ) method. This is the method at which the program will begin executing.
The public keyword is an access modifier, which allows the programmer to control the
visibility of class members. When a class member is preceded by public, then that member may be
accessed by codeoutside the class in which it is declared.
The keyword static allows main( ) to be called without having to instantiate a particular instance
of the class. This is necessary since main( ) is called by the Java Virtual Machine before any objects are
made.The keyword void simply tells the compiler that main( ) does not return a value.
In main( ), String args[ ] declares a parameter named args, which is an array of instances of the
class String. In this case, args receives any command-line arguments present when the program is
executed.

System.out.println("This is a simple Java program.");

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.

Compiling and Running Java program

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.

For compiling the program, the Java compiler javac is used.

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.

C:\> java Sample


Output: This is a simple Java program

Here java command calls the Java interpreter which executes the Sample.class
(bytecode of Sample.java).

Elements or Tokens in Java Programs

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:

Identifiers or names: Identifier is the name of variables, methods, classes etc.

Rules for framing Names or Identifiers.

• It should be a single word which contains alphabets a to z or A to Z, digits 0 to 9,


underscore (_).
• It should not contain white spaces and special symbols.
• It should not be a keyword of Java.
• It should not be Boolean literal, that is, true or false.
• It should not be null literal.
• It should not start with a digit but it can start with an underscore.
• It can comprise one or more UNICODE characters which are characters as well as digits.

Some examples of valid identifiers are

Some Invalid identifiers are

Conventions for Writing Names


• Names of packages are completely in lower-case letters. Ex. java.lang.
• Names of classes and interfaces start with an upper-case letter. Ex: Student
• Names of methods start with a lower-case character. Ex: getData()
• Names of variables should start with a lower-case character. Ex: name, address

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.

Separators: These include comma, semicolon, period(.), Parenthesis (), Squarebrackets


[], etc
Operators: Operators are mostly represented by symbols such as +, -, *, 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

Increment / Decrement Operators:


Operator Description
++ Increment by one
-- Decrement by one
Bitwise Operators:
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise compliment
>> Shift Right
<< Shift Left
>>> Shift right with Zero fill

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)

C:\> Java vehicle Car Cycle Motorbike


Car
Cycle
Motorbike
NOTE: All command line arguments are passed as strings. You must convert numeric values to their
internal forms manually.

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

User Input to Programs


• The class Scanner of package java.util is used to carry out input to the program.
• Java Scanner class is a text scanner that breaks the input into tokens using a delimiter.
The delimiter is whitespace by default.
• Importing the class is the first step.
import java.util.Scanner;
• The object of the class Scanner is declared as follows.
Scanner scaninput = new Scanner (System.in);
• The object “scaninput” invokes the method nextInt() to read an integer,
nextFloat() to read a float, nextDouble() to read double, nextLine() to read a string
etc.

Example: Illustration of a user's input from keyboard intoprogram

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

• For dealing with logical statements, variable of type boolean is supported.


• The value of boolean type variable is either true or false.
• The boolean type variables are unsigned as similar to char type variables.
• The variable may be declared as follows :
boolean a;
a = x > y;

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

Program 3.7: Illustration of type casting.


class TypeCast
{
public static void main (String args[])
{

int a=4, b = 8, c = 9, d,e;


double x= 3.0, y=6.5, z,k;

d=c/a;
k=a+y;
e = a + (int)y;
z=(double)c/a;

System.out.println("k = " + k +" and e =" +e);


System.out.println("d= "+ d + " and z = "+ z);
}
}
Output

C:\ >javac TypeCast.java

C:\ >java TypeCast


k = 10.5 and e =10
d= 2 and z = 2.25

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:

type identifier [ = value ][, identifier [= value ] …];

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.

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

Scope of Variable Identifier


The scope and lifetime of a variable is the part of the program in which it is visible and holds
the last entered value In Java, there are distinctly two types of scopes.
(a) class scope and
(b) method scope
• A variable declared in a class has class scope and scope of a variable declared in a
method has method scope.
• The variables declared in a block have block scope.
• Thus, the variables defined in main() at the beginning have scope in entire main() method,
however, those defined in a block have block scope.
• A block starts with the left brace ( { ) and ends with the right brace ( } ).
In the case of nested blocks of statements, the scope of variables is governed by the following
rules.

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 Variables and Methods


Static Block:
When the static keyword is attached to a block of code, the block is called a static block.

 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

Math.sqrt(5); // Finds square root of 5

The static method is called using the method name that is preceded by the class name; in this
case. Math and period ().

Program 3.18: illustration of using static methods of class Math

public class StaticMethods


{
public static void main (String args[])
{

System.out.println("The Square root root of 16 = "+ Math.sqrt(16));


System.out.println("The cubroot root of 27 = "+ Math.cbrt(27));
//printing five random variables
for(int i =1; i<=5;i++)
System.out.println("Random Number " + i + " = " +
(int)(100 *Math.random()));
}
}
E:\>javac StaticMethods.java

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.

-The different types of Java operators are,


a) Arithmetic operators
b) Relational operators
c) Logical operators
d) Increment or decrement operators
e) Assignment operators
f) Conditional operators
g) Bitwise operators
h) Special 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:

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

Similarly, this statement: x = x - 1; is equivalent to x--;


These operators are unique in that they can appear both in postfix form, where they follow the operand
as just shown, and prefix form, where they precede the operand.
In the foregoing examples, there is no difference between the prefix and postfix forms. However, when
the increment and/or decrement operators are part of a larger expression, then a subtle, yet powerful,
difference between these two forms appears. In the prefix form, the operand is incremented or
decremented before the value is obtained for use in the expression. In postfix form, the previous value is
obtained for use in the expression, and then the operand is modified.

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;

However, when written like this,


x = 42;
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;

The following program demonstrates the increment operator.


// Demonstrate ++.
class IncDec {
public static void main(String args[])
{int a = 1;
int b = 2;
int c;
int d;
c =++b;
d = a++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

The output of this program follows:


a=2
b=3
c=3
d=1
The ? Operator (Conditional operator):
 Java includes a special ternary (three-way) operator that can replace certain types
of if-then-else statements.
 The ? has this general form:
expression1 ? expression2 : expression3
 In the above form expression1 results a Boolean value either true or false. If it is true
expression2 evaluated otherwise epression2 evaluated.
 Example:
class Ternary
{
public static void main(String args[])
{
int i, k;
i = 10;
k = i < 0 ? -i : i;
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}

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

Bit wise operators:


 Java defines several bitwise operators which can be applied to the integer types, long,
int, short, char, and byte. These operators act upon the individual bits of their
operands.
 They are summarized in the following table:
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment

BITWISE LOGICAL OPERATORS


 The bitwise logical operators are &, |, ^, and ~.
 The bitwise operators are applied to each individual bit within each operand.
A B A|B A&B A^B ~
A
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0
 The Bitwise NOT
Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of
its operand. For example,
00101010 becomes 11010101 (after the NOT operator is applied.)
 The Bitwise AND
The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced
in all other cases. Here is an example:
00101010 42
00001111 15

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.

b) member selection operator:


- The dot (.) operator is used to access the instance variables and methods of class objects.
Example:
person.age // Reference to the variable age
person.salary( ) // Reference to the method salary( )
- It is also used to access classes and sub packages from a package.

2. Precedence and Associativity of Operators


If the expression contains several operators with the same precedence level, the expression
is evaluated according to its associativity.
For example, in
Z = 6*4%5;
Both the operators * and % have same precedence level.
CONTROL STATEMENTS: (FLOW OF CONTROL)
- A Control statement is a statement used to control the flow of execution in a Java Program.

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

if Expression - also called as “ null else statement ”


Syntax:
if(condition)
{
statements;
}
next statement;
2. Nested if Expressions
-if within if is called as Nested-if.
Syntax:
if(condition-1)
{
if(condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
if(condition-3)
{
}
else
{

}
}

if–else Expressions Syntax:


if(condition)
{
true-block statements;
}
else
{
false-block statements;
}
next statement;

Example:
if(a>b)
{
System.out.println(“a is greater”);
}
else
{
System.out.println(“b is greater”);
}

else-if ladder statement:


Syntax:
if(condition-1)
{
Statement-1;
}
else if(condition-2)
{
Statement-2;
}
…………………
……………..…..
else if(condition n-1)
{
Statement-(n-1);
}
else
{
Statement-n;
}
next statement;
Example:
if(a>b&&a>c&&a>d)
{
System.out.println(“a is greater”);
}
else if(b>a&&b>c&&b>d)
{
System.out.println(“b is greater”);
}
else if(c>a&&c>b&&c>d)
{
System.out.println(“c is greater”);
}
else
{
System.out.println(“d 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;

• The first expression is the test condition.


• If it evaluates true, the Expression2 is executed; otherwise Expession3 is
executed.

Example-1:

public class Ternary


{
public static void main (String args[])
{

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

Outer loop body;


}
next statement;
For–Each Loop
The Java for-each loop or enhanced for loop. It provides an alternative approach to traverse the array
or collection in Java. It is mainly used to traverse the array or collection elements. The advantage of
the for-each loop is that it eliminates the possibility of bugs and makes the code more readable. It is
known as the for-each loop because it traverses each element one by one.
Advantages:
1. Less clutter in code, especially when iterators are used.
2. Less chances of errors.
3. Improves overall readability of program.
Limitations:
1. It is designed to iterate in forward direction only.
2. In iteration, it takes a single step at a time.
3. It cannot simultaneously traverse multiple arrays or collections.
Syntax:

for (Object obj : Collection_name)


{
Body of loop
}

Example:

public class ForEach


{
public static void main (String args[])
{

int myArray[] = {10,20,30,40,50};

for (int x:myArray)


{
System.out.println(" "+x);
}
}
}

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[])
{

//printing the values from 1 to 10


for(int i =0; i<10;i++)
{
if (i==5)
break; //Break Statement
System.out.println( i );
}
}
}
Output:
C:\>javac Break.java

C:\>java Break
0
1
2
3
4

Here loop is stopped due to break statement.


7. Continue Statement.
-The continue statement is used for continuing next iteration of loop statements.
-When it occurs in the loop, it does not terminate but it skips the statements after it.
-It is useful when we want to continue the program without executing any part of the program.
-The general format is
continue;

Example:

public class Continue


{
public static void main (String args[])
{

//printing the values from 1 to 10


for(int i =0; i<10;i++)
{
if (i==5)
continue; // Continue statement
System.out.println( i );
}
}
}
Output:

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

public class LabelledBreak


{
public static void main(String args[])
{

int i=7;

loop1:
while(i<20)
{
if(i==10)
break loop1;

System.out.println("i ="+i);
i++;
}

System.out.println("Out of the loop");

} //main method ends

}
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

mybox = new Box();


// allocate a Box object
Here new keyword is
allocating memory of Box
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:

Modifier class class_name


{
//class Members- instance variables,
methods, classes, and interfaces
}

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

Assigning Object Reference Variables:

 For example see the following code


Box b1 = new Box();
Box b2 = b1;

 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

Access Control for Class Members


The access to the class members can be controlled by placing the suitable
modifier/access specifier before the member in the class definition. There are three
access specifiers: public, private, and protected. The syntax for access specifiers will
be as follow:

Access specifier type identifier;


Example:
int x=25;

6
public int a=20;
private float f=3.45f;
protected double y=12.34;

Access Specifiers and Information Hiding


The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
Private: A class also provides a mechanism to hide information such as data and
methods from the user. This can be done by declaring the variables or methods as
private. The private members only accessed by the members of the same class.
class A{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

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

Access Modifier Within Class Within Package Outside Package Outside


By Subclass Only Package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

Accessing the Private Members of a Class


If we want to hide the methods from accessing by user outside the class, then the
methods are declared as private. Private members of a class, whether it may be
instance variable or method can be accessed by the other member of the same class.
The outside code cannot access the private members directly.
FarmTest.java
class Farm
{
//instance variables
private int length,width; //private data members
}
class FarmTest
{
public static void main(String arg[])
{
//create objects
Farm f1=new Farm();
f1.length=25; //accessing the private members outside the class
f1.width=40;
int area=f1.length*f1.width; //accessing private data
System.out.println("The area is :"+area);
}
}
Output:

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( { } ).

The general syntax of method would be as follow:


modifier type method_name (type par1,type par2,….type parn) //Header
{
Statements here // Body
}

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

Output: Volume is 3000.0

 Example program for return a value from method :


class Box
{
double width;
double height;
double depth;
double volume() // method return type is double
{
return width*height*depth;
}
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
double vol= mybox.volume();
System.out.printlln(“volume is” + vol);
}
}

Output: Volume is 3000.0


 Example program for method with parameters:

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

display(int a) display(double d) display(String s)

 Example for method overloading


class Overload
{
void dispaly()
{
System.out.println("No parameters");
}
void display(int a)
{
System.out.println("integer a: " + a);
}
void display(double d)
{
System.out.println("double d: " + d);
}
void display(String s)
{
System.out.println("String s:" + s);
}
}
13
class OverloadDemo
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
ob.display();
ob. display(10);
ob. display(10.325);
ob. display(“hello”);
}
}

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

Addition ad=new Addition();

new Addition( ) is calling the Addition( ) constructor.


 When we do not explicitly define a constructor for a class, then Java creates a default
constructor for the class.

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;

public void fenceCost()


{
double perim=2*(length+width);
System.out.println("The Cost of Fencing is :"+perim*cost);}
public void area()
{
int a=length*width;
System.out.println("The area is :"+a);
}
}
}
class MyFarmTest
{
public static void main(String arg[])
{
17
//Create object from Outer class
MyFarm mf=new MyFarm(20,5);
mf.display();
}
}
Important Points:
1. The inner class has access to all the outer class members.
2. The outer class doesn’t have direct access to inner class members. It is possible
through the reference of the inner class object.
3. The object of inner class may be declared in the scope of outer class.
4. The method of inner object may be accessed through the object of inner class
by the outer class object.

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

Write a java program to demonstrate Final Method.


class A
{
final void disp()
{
System.out.println("Method of class A");
}
}
class B extends A
{
void disp()
{
System.out.println("Method of class B");
}
}
class FinalTest
{
public static void main(String arg[])
{
B b=new B();
b.disp();
}
}
Output:
C: >javac FinalTest.java
FinalTest.java:10: error: disp() in B cannot override disp() in A
void disp()
^
overridden method is final
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

Write a java program to demonstrate the abstract class.


import java.util.*;
abstract class Shape
{
abstract void shapeArea();
}
class Circle extends Shape
{
double r;
final double PI=31.4;
void shapeArea()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter radius:");
r=in.nextDouble();
System.out.println("The area of the Circle is:"+(PI*r*r));
}
}
class Square extends Shape
{
int a;
void shapeArea()
{
Scanner in=new Scanner(System.in);
System.out.println("Enter side value :");
a=in.nextInt();
System.out.println("The area of the Square is:"+(a*a));
}
}
class ShapeTest
{
public static void main(String arg[])
{
Circle c=new Circle();
c.shapeArea();
Square s=new Square();
s.shapeArea();
}
}
21
Output:
Enter radius:6
The area of the Circle is:1130.3999999999999
Enter side value :4
The area of the Square is:16
this keyword:
In java, this is a reference variable that refers to the current object. There may be a
situation where the names of the local variables and the instance variable names
could be same. In such a context the local variables will hide the instance
variables. To access the instance variables in such a situation is done with the help
of ‘this’ keyword. The ‘this’ keyword will provide the reference to the current
object. The ‘this’ keyword is used before the instance variable with dot
operator. (Ex this.instance_variable)
Usage of this keyword
 Here some usages of this keyword.
1. To refer current class instance variable.
2. To Invoke current class constructor.
To refer current class instance variable:
 If there is ambiguity between the instance variable and parameter, this
keyword resolves the problem of ambiguity.
class Student
{
int
id;
String
name
;
Student (int id,String name)
{
this.id = id;
this.name =
name;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1 = new
Student10(111,"Karan"); Student s2
= new Student10(321,"Aryan");
s1.display();
s2.display();
}
}
Output: 111 Karan
321 Aryan

To invoke current class constructor


 The this() constructor call can be used to invoke the current class
constructor (constructor chaining).
 This approach is better if you have many constructors in the class and want to
reuse that constructor.
 Example:
class Student1
{
int id;
String
name
;
Stude
nt1()
{
System.out.println("default constructor is invoked");
}

Student1(int id,String name)


{
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
Student1 e1 = new
Student13(111,"karan"); Student1 e2
= new Student13(222,"Aryan");
e1.display();
e2.display();
}
}
Output:
default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
********** ----------- *********
Parameter passing techniques:
Pass by value:
When a method is defined with primitive variables, the values are passed by
value, that is, the values of actual arguments are copied to the formal
parameters. The method may manipulate these values without affecting the
actual arguments. This is called passing arguments by values.

 In call by value we are passing only value to the method.


 If we perform any changes inside method that changes will not
reflected to calling method.
 Example:

class CallByVal
{

public static void main(String args[])


{
int x=20;
System.out.println("Before method calling value=
"+x); display(x);
System.out.println("After method calling value= "+x);
}
public static void display(int y)
{
y=y+1;
System.out.println("Inside method value= "+y);
}

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

 In call by reference we are passing reference i.e an object to the method.


 In this case, If we perform any changes inside method that changes will be
reflected to main method.
 Example:

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.

Declaration and Initialization of Arrays


The declaration of array starts with array type, followed by an identifier, and square brackets
and ends with semicolon as shown below:

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}

int numbers []=new int[5]; //allocating memory with new


int numbers[]={ 3,4,12,8}; //allocating with initialization
Java allows us to initialize the array using the new keyword as well:

int[] intArray = new int[]{13, 14, 15};


String[] stringArray = new String[]{"abc", "de", "fgh"};
Java Array Loop Initialization

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:

int[] intAray = new int[10];

for (int i = 0; i < intArray.length; i++) {


int_array[i] = i;
}

Storage of Array in Computer Memory


The operator new, which is a keyword, allocates memory for storing the array elements. For
example, with the following declaration.
int[] numbers = new int[4];
Here, the compiler allocates 4 memory spaces, each equal to 4 bytes for storing the int type
values.When array is created as above the elements of the array are automatically initialized
to default values based on the type of array. Default values for int, float, char are 0,0.0, and
space respectively.

The declaration and initialization may as well be combined as:


int numbers [] = {20,10,30,50};

Accessing Elements of Arrays


The individual member of an array may be accessed by its index value. The index value
represents the place of element in the array. The first element space is represented by
numbers [0], and index value is 0. The memory space of the 2nd element is represented by
number[1], 3rd element is number[2], and son on, and last element is number[n-1].
Note: the value of an array element is different from its index value.
Determination of Array Size:
The size of length of the array is determined by the following code:
int size=array_name.length;
Here, length is an attribute of array object
This size or length can be used in the for loop to access the elements as shown below:

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

Dynamic Change of Array Size


 The number of elements (size) of the array may change during the execution of the
program. In Java, you may change the number of elements by dynamically retaining
the array name.
 In this process, the old array is destroyed along with the values of elements.

Int arr1[]=new int[4];

Example Program on Dynamic Change of Array Size


import java.util.*;
class DynArr
{ public static void main(String arg[])
{ int[] arr1; //declaration
arr1=new int[]{2,4,6,8};//memory allocation & initialization to array
System.out.println("Elements of arr1 are:");
for(int x:arr1)
System.out.print(x+"\t");
arr1=new int[6]; //dynamic change of array size
//display arr1
System.out.println("\nElements of arr1 after Size Change are:");
for(int x:arr1)
System.out.print(x+"\t");
}
}
Output:

Elements of arr1 are:


2 4 6 8
Elements of arr1 after Size Change are:
0 0 0 0 0 0
Two-dimensional array
A two-dimensional array needs two square brackets one for rows and other for columns and
may be initialized as follow:

type identifier [][];// declaration of array of arrays

Alternative Array Declaration Syntax

type [][] identifier; // declares two dimensional array

Example

int [][] numbers, items, marks; // declares three arrays

A two-dimensional array may be declared and initialized as,

int [][] array2d = new int [][] {{1, 2, 3}, {4, 5, 6}}; or as
int [][] array2D = {{1, 2, 3}, {4, 5, 6}};

Operations on 2-D Arrays


importjava.util.Arrays;

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

// Multiply the two marices

for (i = 0; i< r; i++) {


for (j = 0; j < c; j++) {
for (k = 0; k < r; k++)
C[i][j] += A[i][k] * B[k][j];
}
} //end of else

Arrays of varying lengths


 in Java, a two-dimensional array is treated as an array whose elements are one
dimensional arrays, which may have different sizes, that is, different number of
elements.
 In Java, we can declare a 2 dimensional array as follow :
Example
int a[][]=new int[3][];

The 2nd dimension may be declared as:


int a[0]=new int[2];
int a[1]=new int[4];
int a[2]=new int[6];
Example:
int a[][]={ {1,2},{4,5,6},{10,20,30,40,50}};
Example Program:

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.

(i) class String


(ii) class StringBuffer
(iii) class StringBuilder
 All the three classes are part of java.lang package

Java implements strings as objects of type String. It belongs to java.lang (java.lang.String)


Strings are immutable. Once a String object has been created, you cannot change the characters that
comprise that string. You can still perform all types of string operations. Each time you need to change an
existing string, a new String object is created that contains the modifications. The original string is left
unchanged(Immutable).
• Java provides two classes: StringBuffer and StringBuilder. Both hold strings that can be modified after
they are created.

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

 The String class is final, it cannot be extended.

The String Constructors:


The String class supports several constructors.
• To create an empty String, you call the default constructor.
Eg: String s = new String(); // instance with no characters
• To create strings that have initial values by an array of characters, String(char chars[ ])
Eg: char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
• Specify a sub-range of a character array as an initialize using,

String(char chars[ ], int startIndex, int numChars)

Eg: char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };


String s = new String(chars, 2, 3);
• To construct a String object that contains the same charactersequence as another String object using,
String(String strObj)
eg: String s1 = “abcd”;
String s2 = new String(s1);
•The String class provides constructors that initialize a string when given a byte array. Their forms are shown
here:
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int numChars)
Eg: byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
String s2 = new String(ascii, 2, 3);
Methods for Extracting Characters from Strings
charAt( ): To extract a single character from a String.
char charAt(int where)
Eg: char ch; ch = “abc”.charAt(1); // b is extracted
• getChars( ): To extract more than one character at a time.
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
eg: String str1="Vijayawada";
char []c=new char[4];
str1.getChars(2,6,c,0); //jaya
•toCharArray( ): Converts all the characters in a String object into a character array, it returns an array of
characters for the entire string.
char[ ] toCharArray( )
eg: String str1="Vijayawada";
char []c=str1.toCharArray();

Methods for Comparison of Strings


• equals( ) and equalsIgnoreCase( ): To compare two strings for equality.
➢ equals( ) //case-sensitive
boolean equals(Object str)
➢ equalsIgnoreCase( ) //ignores case differences
boolean equalsIgnoreCase(String s)

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

equals( ) Versus ==( )


• The equals( ) method compares the characters inside a String object.
if (str1.equals(str3))
• The == operator compares two object references to see whether they refer to the same instance.
if (str1==str2)

Ex: String s1=new String(“hello”);

String s2=new String(“hello”);

if(s1==s2) {
System.out.println(“s1==s2 is TRUE”);
} else{
System.out.println(“s1==s2 is FALSE”);
}

//The comparison’s output is FALSE

if(s1.equals(s2)) {
System.out.println(“s1.equals(s2) TRUE”);
} else {
System.out.println(“s1.equals(s2) is FALSE”);
}

//This comparison’s result is TRUE.

Methods for Searching Strings:

• 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

To search for the first/last occurrence of a character, use

int indexOf(int ch)


int lastIndexOf(int ch)

To search for the first/last occurrence of a substring, use

int indexOf(String str)


int lastIndexOf(String str)

You can specify a starting point for the search using

int indexOf(int ch, int startIndex)


int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
Here, startIndex specifies the index at which point the search begins. For indexOf( ), the search runs from
startIndex to the end of the string. For lastIndexOf( ), the search runs from startIndex to zero.

Methods for Modifying Strings


Because String objects are immutable, whenever you want to modify a String, you must either copy it into a
StringBuffer or StringBuilder, or use one of the following String methods, Which will construct a new copy
of the string with your modifications complete

substring( ): To extract a substring use, substring( ).


String substring(int startIndex)
String substring(int startIndex, int endIndex)
The string returned contains all the characters from the beginning index, up to, but not including, the
ending index.
concat( ): To concatenate two stings, performs the same function as +.
Eg: String s1 = "one";
String s2 = s1.concat("two"); // String s2 = s1 + "two";

replace( ):To replaces all occurrences of one character in the invoking string with another character.

String replace(char original, char replacement)


Eg: String str = “NEW".replace(‘E', ‘O')

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.

• String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents


growable and writeable character sequences.

• 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 defines these four constructors:

• StringBuffer( ): Reserves room for 16 characters without reallocation.


• StringBuffer(int size): Accepts an integer argument that explicitly sets the size of the buffer.

• 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( )

char charAt(int where)


void setCharAt(int where, char ch)

• getChars( )

void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

• append()

StringBuffer append(String str)


StringBuffer append(int num)
StringBuffer append(Object obj)

insert( )

StringBuffer insert(int index, String str)


StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
• reverse( ):

StringBuffer reverse( )

• delete( ) anddeleteCharAt( )

StringBuffer delete(int startIndex, int endIndex)


StringBuffer deleteCharAt(int loc)

• replace( ):

StringBuffer replace(int startIndex, int endIndex, String str)


String substring(int startIndex)
String substring(int startIndex, int endIndex)
Example program:
class SBuffer
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
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
StringBuilder

 The StringBuilder class is the subclass of Object in java.lang package.


 This class is used for creating and modifying strings.

Constructors of Class StringBuilder

1. StringBuilder()—Creates a StringBuilder object with no characters but with initial capacity of 16


characters.
2. StringBuilder(CharSequence chSeq)—Creates a StringBuilder object with characters as specified in
CharSequence chSeq.
3. StringBuilder(int capacity)—Creates a StringBuilder object with specified capacity. It throws
NegativeArraySizeException.
4. StringBuilder(String str)—Creates a StringBuilder object initialized with contents of a specified
string. It throws NullPointException if str is null.

Methods of StringBuilder Class

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 StringBuilder reverse() is used to reverse the string.

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

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

public int length() is used to return the length of the string i.e. total number
of characters.
public String substring(int 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

You might also like