Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Object Oriented Programming with JAVA


(BCS306A)
ACADEMIC YEAR 2023 - 24

Lecture notes
Name Of the Programme B.E - CSE

Scheme 2022

Year and Semester II Year III Semester

S Subject Code BCS306A

Name of the Faculty K RADHIKA

MODULE I

An Overview of Java: Object-Oriented Programming (Two Paradigms, Abstraction, The Three OOP Principles),
Using Blocks of Code, Lexical Issues (Whitespace, Identifiers, Literals, Comments, Separators, The Java
Keywords).
Data Types, Variables, and Arrays: The Primitive Types (Integers, Floating-Point Types, Characters, Booleans),
Variables, Type Conversion and Casting, Automatic Type Promotion in Expressions, Arrays, Introducing Type
Inference with Local Variables.
Operators: Arithmetic Operators, Relational Operators, Boolean Logical Operators, The Assignment Operator,
The ?: Operator, Operator Precedence, Using Parentheses.
Control Statements: Java’s Selection Statements (if, The Traditional switch), Iteration Statements (while, do-
while, for, The For-Each Version of the for Loop, Local Variable Type Inference in a for Loop, Nested Loops), Jump
Statements (Using break, Using continue, return).

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
OBJECT-ORIENTED PROGRAMMING
• Object-Oriented Programming (OOP) is a programming language model organizedaround objects
rather than procedures.
• An object-oriented program can be characterized as data controlling access to code. Object oriented
programming (OOP) is the core of Java programming.
• OOP organizes a program around its data(i.e., objects) and a set of well- defined interfaces to that data .
• The data of an object can be accessed only by the functions associated with that object. However, functions
of one object can access the functions of other objects.

• Java is a general purpose, object-oriented programming language developed by Sun Microsystems. It was
invented by James Gosling and his team and was initially called as Oak.
• The most important feature that made Java very popular was the Platform-Independent approach.

• It was the first programming language that did not tie-up with any particular operating system (or
hardware) rather Java programs can be executed anywhere and on any system.

• Java was designed for the development of the software for consumer electronic devices like TVs, VCRs,
etc.
• In Java, there are three types of programs as follows:
• Stand-alone application programs: These programs are made and run on user 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 often called
server-side programs or servlets.
TWO PARADIGMS:
• Every program contains 2 components code and data.
• Two approaches are there to solve the problem and in program writing: Procedure oriented and
object oriented.
Procedure Oriented:
• Procedure oriented programs are written based on ―what’s happening around, where the code acts on
data. Ex: C etc.
• Problems increases in procedure oriented as the program grows larger and more complex.
Object Oriented:
• Object oriented programs are written based on ―Who is being affected around, which manages the
increasing complexity.
• It organizes program around data and well-defined interfaces of that data.

• Characterized as data controlling access to code. Ex: C++, JAVA, Small Talk etc.
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
Procedure-Oriented Programming Object-Oriented Programming
In POP, program is divided into small parts In OOP, program is divided into parts
called functions called objects.
In POP, importance is not given to data but to In OOP, importance is given to the data rather than
functions as well as sequence of actions to be procedures or functions because it works as
done. a real-world entity.
POP follows Top-Down approach. OOP follows Bottom-Up approach.
POP does not have any access specifier. OOP has access specifiers named Public, Private,
Protected, etc.
In POP, Data can move freely from function to In OOP, objects can move and communicate with
function in the system. each other through member functions.
To add new data and function in POP is not so OOP provides an easy way to add new data and
easy. function.
In POP, most functions use global data forsharing that In OOP, data cann ot move easily from function to
can be accessed freely from function. function, it can be kept public or private so we can
to function in the system. control the access of data.

POP does not have any proper way for hiding OOP provides Data Hiding so provides more
data so it is less secure. security.
In POP, Overloading is not possible. In OOP, overloading is possible in the form of
Function Overloading and Operator Overloading.
Example of POP are C, VB, FORTRAN, Pascal. Example of OOP are C++, JAVA, VB.NET, C#.NET.

CONCEPTS OF OOPS:
• Object
• Class

OBJECT
• An object is an entity in the real world, which has some attributes and exhibits some behavior.
• Objects are the basic run time entities in an object-oriented system.
• They may represent a person, a place, a bank account, a table of data or any item that the
program must handle.
• Objects take up space in the memory and have an associated address.
• Each object contains data and code to manipulate.
• When a program is executed, the objects interact with each other by sending messages to one
another.
• For example, if “customer” and “account” are two objects in a program, then the customer object
may send a message to the account object requesting for the bank balance.
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
• A class is a blueprint or prototype from which objects are created. It’s just a template for an object,
which describes an object. It is a logical entity.
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
• A class is a combination of common attributes and common behavior; thus, we can represent class as a
collection of similar type of objects.
• Object is an instance of a class.
• The entire set of data and code of an object can be made a user-defined data type with the help of
class. Objects are variables of the class type.
• Once a class has been defined, we can create any number of objects belonging to that class. Each object
is associated with the data of type class with which they are created.
• For example, Mango, Apple and Orange are objects from class fruit.
• 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’tstore any space.
PRINCIPLES OF OOP
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism

ABSTRACTION
• Abstraction refers to the “ act of representing essential features without including the
background details or explanation”.
• Abstraction is a process of hiding the implementation details and showing only functionality to the user.
• Ex: a database system hides certain details of how data is stored and created and maintained.

ENCAPSULATION

1. Encapsulation in Java is a process of wrapping code and data together into a single unit.
2. The process of binding together code and data it manipulates, to hide them from the outside world is called
Encapsulation.
3. Encapsulation is the most striking feature of a class. The data is not accessible to the outside world, and
only those functions which are wrapped in the class can access the data.
4. This insulation of the data from direct access by the program is called data hiding or information
hiding.

INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring all the properties
andbehavior 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 behaviors 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,

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
and hierarchical inheritance. Multiple and hybrid inheritance is supported through interface only.

Bird

Attributes:

Flying Bird NonFlying Bird

Attributes: Attributes:

Robin Swallow Penguin Kiwi

Attributes: Attributes: Attributes: Attributes:

POLYMORPHISM
• Polymorphism, a Greek term, means the ability to take more than one form .
• For example, an operation may exhibit different behavior at different instances. The behavior
depends upon the types of data used in the operation.
Consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are
strings, then the operationwould produce a third string by concatenation.

Polymorphism is classified into two ways:


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 classes, it is known as method overriding.
FEATURES OF JAVA
The main objective of Java programming language creation was to make it portable, simple, and secure
programming language. Apart from this, there are also some awesome features which play important role in

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
the popularity of this language. The features of Java are also known as java buzzwords.
A list of most important features of Java language are given below.
• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Platform Independent
• Multithreaded
• Architecture-neutral
• Interpreted and High performance
• Distributed
• Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean, and easy to understand. According to Sun,
Java language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many confusing and rarely used features e.g. explicit pointers, operator
overloading etc.
• There is no need to remove unreferenced objects because there is Automatic Garbage
Collection in Java.
Secure
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
o No explicit pointer
o Java Programs run inside virtual machine sandbox.
o Java security model focuses on protecting users from hostile programs downloaded from untrusted
sources across a network. Programs downloaded over the internet are executed in a sandbox ,
cannot take any action outside of the boundaries specified by the sandbox.
o By using a Java - compatible web browser, applets can be downloaded from internet without fear
of virus or malicious intent.

• Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which is used to
dynamically load Java classes into the Java Virtual Machine. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
• Security Manager: It determines what resources a class can access such as reading and writing to
the local disk.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
type of implementation.
• Portability is the major aspect of the internet because different types of computers and operating
systems are connected to it. The output of a Java compiler is not executable code. Rather, it is byte code.
• Translating a Java program into byte code makes it much easier to run a program in a wide variety of
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
environments.
• Java Programs can be easily moved from one computer system to another anywhere and at any time.
Object-oriented
Java is object-oriented programming language. Everything in Java is an object. Object-Oriented means we
organize our software as a combination of different types of objects that incorporates both data and
behavior. Everything in Java (constants, variables, and methods) are defined inside a class and accessed
through objects. Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.

Robust
• Robust simply means strong. Java is robust because:
• Java is a strictly typed language, it checks the code both at compile time and runtime. Has strict compile-
time checking which makes java programs morerobust and avoids run-time errors. The compiler also
ensures that a program does not access any uninitialized variables.
• The two of the main reasons for program failure are:
• Memory Management Mistakes and
• Mishandled Exceptional Conditions (that is, Run -Time errors).
• Java virtually eliminates memory Management Mistakes: Deallocation is completely automatic in Java
as it provides garbage collection for unused objects. There is automatic garbage collection in Java which
runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application
anymore.
• Java also incorporates the concept of handling the exceptional conditions that may arise in situations
such as division by zero or file not found, and thus eliminates the abnormal termination of program.

Platform Independent
Java is platform independent because it is different from other languages like C, C++ etc. which are
compiled into platform specific machines while Java is a write once, run anywhere language. 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:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
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).

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.
Architecture-neutral
• One of the main problems faced by programmers is that no guarantee exists that if
you write a program today, it will run tomorrow — even on the same machine.
• Operating system upgrades, processor upgrades, and changes in core system
resources can all make a program malfunction.
• The goal of Java designers was “ write once; run anywhere, anytime, forever.” This
goal was largely accomplished by bytecode, the output from java compiler .
Java is architecture neutral because 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.
Interpreted & High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close"
to native code. It is still a little bit slower than a compiled language (e.g. C++). Java is an interpreted
language that is why it is slower than compiled languages e.g. C, C++ etc.
Distributed
Java is distributed because it facilitates users to create distributed applications. RMI and EJB are used for
creating distributed applications. This feature of Java makes us able to access files by calling the methods
from any machine on the internet.
• Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols.
• Java also supports Remote Method Invocation (RMI). This feature enables a program to
invoke methods across a network.
• This enables multiple programmers at multiple remote locations can work together on a
single project.

Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand.
It also supports functions from its native languages i.e. C and C++. Java supports dynamic compilation
and automatic memory management (garbage collection).

Garbage Collection
Objects are dynamically allocated by using the new operator, dynamically allocated objects must be
manually released by use of a delete operator. Java takes a different approach; it handles deallocation
automatically this is called garbage collection. When no references to an object exist, that object is
assumed to be no longer needed, and the memory occupied by the object can be reclaimed. Garbage
collection only occurs sporadically (if at all) during the execution of your program. It will not occur
simply because one or more objects exist that are no longer used.
Applications of Java
• Some of the applications of Java is that internet users can use Java to create applet programs and run
them using a web-browser.
• The first application program written in Java was HotJava, a web browser to run applet on internet.(An
applet is a special kind of Java program that is designed to be transmitted over the internet and
automatically executed by a Java compatible web browser)
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
• Further internet users can also set up their websites containing Java applets, that could be used by
other remote users of the internet. Hence Java is popularly called as ― Language of Internet‖.
• Before the invention of Java, world wide web was limited to displaying text and still images. However,
the incorporation of Java into web pages has made web capable of supporting animations, graphics,
games, and wide range of special effects.
Structure Of Java Program

Java is an Object-oriented language. Every Java program imports packages which provides necessary
built-in classes and interfaces.
For example:
import java.util.*;
import java.io.*;

After import statement, every java program starts with the declaration of the class. A program may have
one or more classes. A class declaration starts with the keyword class, followed by the identifier or name
of the class. Giving the name of a package at the top is optional. Class declaration contains name of the
class and body of the class. The body of the class may consist of several statements and is enclosed
between the braces { }.

A sample of class declarations is as follows.

Here:
o public is access specifier. This class is accessible to any outside code. Otherwise, the class is
accessible to only same package classes.
o class is a keyword of Java language which is used to declare the class.
o The class body starts with the left brace { and ends with the right closing brace }.
o // are comments which are neglected by the compiler.
o A class body may comprise statements for declaration of variables. constants, expressions,
and methods.

Simple program in Java. Save this code as “Start.java”

public class Start


{
public static void main()
{
System.out.println(“Hello World”);
}
}
Here:
public is access specifier. This class is accessible to any outside code.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
class is a keyword.
Start is a name of the class. Any valid identifier name can be used as class name.
main( ) is the method which initiate and terminate the program. main represents the starting point
of the program.
o main is declared public - public keyword is an access modifier which represents visibility,
it means it is visible to all.
o main is declared static - static is a keyword, if we declare any method as static, there is no
need to create object to invoke the static method. The main method is executed by the
JVM, so it doesn't require to create object to invoke the main method. So it saves memory.
o void is the return type of the method; it means it doesn't return any value.
o String[] args is used for command line argument.
println( ) is method of object “out”. “out” is the object of class “System”.
println( ) prints the string “Hello World” on the screen/monitor

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 run, specifying the name of the source file on
the command line as depicted here:

javac Start.java

The Java compiler creates a file called Start.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 Start

Output: Hello World

THE JAVA ENVIRONMENT

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing java applications. It is used to provide
runtime environment. It is the implementation of JVM. It physically exists. It contains set of libraries and
other files that JVM uses at runtime. Implementation of JVMs are also actively released by other companies
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
besides Sun Micro Systems.

JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop java applications and applets. It physically exists. It contains JRE +
development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle corporation:
Standard Edition Java Platform
Enterprise Edition Java Platform
Micro/Mobile Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc) etc. to
complete the development of a Java Application.

JVM (Java Virtual Machine)


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment
in which java bytecode can be executed. JVMs are available for many hardware and software platforms (i.e.
JVM is platform dependent).The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Java character set:


• The smallest unit of Java language are its character set which is used to write Java tokens. These characters
are defined by Unicode character set that tries to create character for a large number of characters worldwide.
• The Unicode is a 16-bit character coding system and currently supports 34,000 defined characters derived
from 24 languages of worldwide.

Using blocks of code

• Java supports code blocks - which means that two or more statements are grouped into blocks of code.
• Opening and closing braces is used to achieve this.
• Each block is treated as logical unit. Whenever two or more statements must be linked blocks can be used.

Lexical issues:
A token is the smallest program element which is recognized by the compiler and Java tokens are called lexical
issues. Java programs are a collection of whitespace, identifiers, keywords, comments, separators, literals, and
operators.

Whitespace:
• Java is a free form language- means no need to follow any indentation rules.
• Whitespace is a space, tab, or newline.

Identifiers: Identifier is the name given to variables, methods, classes etc. in Java Programs.

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 (_), dollar sign($).
• 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.

Conventions for Writing Names


• Names of packages are completely in lower-case letters such as mypackage, java.lang.
• Names of classes and interfaces start with an upper-case letter.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
• Names of methods start with a lower-case character.
• Names of variables should start with a lower-case character.

Example for valid identifiers:


Var_1, count, $value etc

Example for invalid identifiers:


6name, var@value, my/name etc

Keywords: These are special words defined in Java and represent a set of instructions. Java language has 50
words as reserved keywords.
• 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:

Comments
• Comments are Line of Text which is not a part of the compiled program.
• Comments are used for documentation to explain source code.
• They are added to the source code of the program.
• Java supports three types of comments as:
1. Single-line comment: These comments are started with two front slash characters (//)
Example:
// This is Single line comment

2. Multi-line comment : These comments are enclosed with /* and */


Example:
/* It is Multi line Comments */

3. Documentation comment: This type of comment is used to produce a HTML file that documents your
program. The documentation comment begins with a /** and ends with a */. The documentation comment
is used to create documentation API. To create documentation API, you need to use javadoc tool.
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
Example:
/** It is documentation Comments */

Separators: Separators are the symbols that indicates where group of code are divided and arranged.
These include parentheses, braces, square brackets, comma, semicolon, period(.)

Literals :
Literals in Java are sequence of characters that represents constant values to be stored in variables. Java language
specifies five major types of Literals. They are:

1. Integer Literals.
2. Floating-point Literals.
3. Character Literals.
4. String Literals.
5. Boolean Literals.
Integer literals:
• Any whole number value is an integer literal.
• These are all decimal values describing a base 10 number.
• There are two other bases which can be used in integer literal, octal( base 8) where 0 is prefixed with the
value, hexadecimal (base 16) where 0X or 0x is prefixed with the integer value.
Example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;
Floating point literals:
• The default type when you write a floating-point literal is double, but you can designate it explicitly by
appending the D (or d) suffix
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
• However, the suffix F (or f) is appended to designate the data type of a floating-point literal as float.
• We can also specify a floating-point literal in scientific notation using Exponent
• for instance: the double literal 0.0314E2.
Character literals:
• char data type is a single 16-bit Unicode character.
• We can specify a character literal as a single printable character in a pair of single quote characters such
as 'a', '#', and '3'.
Boolean Literals:
• The values true and false are treated as literals in Java programming.
• When we assign a value to a boolean variable, we can only use these two values.
• Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is equivalent to false in Java.
• We have to use the values true and false to represent a Boolean value.
Example
boolean chosen = true;
String Literals:
• The set of characters in represented as String literals in Java.
• Always use "double quotes" for String literal.
Ex: “JAVA”
Escape Sequences
Escape Sequences character is preceded by a backslash (\) has a special meaning to the compiler. Escape
sequences are as follows.

Operators:
An operator is a symbol that takes one or more arguments and operates on them to produce a result.
• An operator performs an action on one or more operands.
• An operator that performs operation on one operand is called a unary operator, on two operands called
as binary operator and on 3 operands called as ternary operator(?:).
Java supports all the three types of operators, in addition to special operators like instanceof, .(dot), new, (type)
casting 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: Assume integer variable A holds 10 and variable B holds 20, then:
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Operator Description Example


+ Addition - Adds values on either side of the A + B will
operator give 30
- Subtraction – Subtracts right hand operand from left A - B will
hand operand give -10
* Multiplication - Multiplies values on either side of the A * B will
operator give 200
/ Division - Divides left hand operand by right hand B / A will
operand give 2
% Modulus - Divides left hand operand byright hand B % A will
operand and returns reminder give 0
++ Increment – Increases the value of operand by 1 B++ gives 21
-- Decrement – Decreases the value of operand by 1 B-- gives 19

public class Test


{
public static void main(String args[])
{
int a =10;
int b =20;
int c =25;
int d =25;
System.out.println("a + b = "+(a + b));
System.out.println("a - b = "+(a - b));
System.out.println("a * b = "+(a * b));
System.out.println("b / a = "+(b / a));
System.out.println("b % a = "+(b % a));
System.out.println("c % a = "+(c % a));
System.out.println("a++ = "+(a++));
System.out.println("b-- = "+(a--));
System.out.println("d++ = "+(d++));
System.out.println("++d = "+(++d));
}
}
Output:
a + b =30
a - b =-10
a * b =200
b / a =2
b % a =0
c % a =5
a++=10
b--=11
d++=25
++d =27

Relational Operators:

Relational operators are used to compare values. Assume variable A holds 10 and variable B holds 20, then:

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
Operator Description Example
== Checks if the values of two operands are equal or not, if (A == B) is not
yes then condition becomes true.
true.
!= Checks if the values of two operands are equal or not, if (A != B) is
values are not equal then condition becomes true. true.
> Checks if the value of left operand is greater than the (A > B) is not
value of right operand, if yes then condition becomes true.
true.
< Checks if the value of left operand is less than the value of (A < B) is
right operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal (A >= B) is not
to the value of right operand, if yes then condition true.
becomes true.
<= Checks if the value of left operand is less than or equal to (A <= B) is
the value of right operand, if yes then condition becomes true.
true.

public class Test


{
public static void main(String args[])
{
int a =10; int b =20;
System.out.println("a == b = "+(a == b));
System.out.println("a != b = "+(a != b));
System.out.println("a > b = "+(a > b));
System.out.println("a < b = "+(a < b));
System.out.println("b >= a = "+(b >= a));
System.out.println("b <= a = "+(b <= a));
}
}
Output:
a == b =false
a != b =true
a > b =false
a < b =true
b >= a =true
b <= a =false

Bitwise Operators:
Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation.
Assume if a = 60; and b = 13;
now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101

a&b = 0000 1100


a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13, then:

Operator Description Example

& Binary AND Operator gives a result of 1 if both bits are 1. (A & B) will give 12
which is 0000 1100
| Binary OR Operator gives a result of 1 if at least one bit is 1. (A | B) will give 61
which is 0011 1101
^ Binary XOR Operator gives a result of 0 if both bits are same. (A ^ B) will give
49 which is 0011
0001
~ Binary Ones Complement Operator is unary and has the (~A) will give -
effect of 'flipping'bits.
60which is 1100
0011
<< Binary Left Shift Operator. The left operands value is moved left A << 2 will give 240
by the number of bits specified by the right operand. which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved A >> 2 will give 15
right by the number of bits specified by the right operand. which is 1111
>>> Shift right zero fill operator. The left operands value is moved A >>>2 will give 15
right by the number of bits specified by the right operand and which is 0000 1111
shifted values are filled up with zeros.

public class Test


{
public static void main(String args[])
{
int a =60; /* 60 = 0011 1100 */
int b =13; /* 13 = 0000 1101 */
int c =0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = "+ c );
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = "+ c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = "+ c );
c =~a; /*-61 = 1100 0011 */
System.out.println("~a = "+ c );
c = a <<2; /* 240 = 1111 0000 */
System.out.println("a << 2 = "+ c );
c = a >>2; /* 215 = 1111 */
System.out.println("a >> 2 = "+ c );
c = a >>>2; /* 215 = 0000 1111 */
System.out.println("a >>> 2 = "+ c );
}
}
This would produce the following result:
a & b =12
a | b =61
a ^ b =49
~a =-61
a <<2=240
a >>15
a >>>15
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
Logical Operators:

Operator Description Example

&& Called Logical AND operator. If both the operands (A && B)


are non-zero, then the condition becomes true. is false.
|| Called Logical OR Operator. If any of the two (A || B)is
true.
operands are non-zero, then the condition becomestrue.

! Called Logical NOT Operator. Use to reverses thelogical state of !(A && B)
its operand. If a condition is true then Logical NOT operator will is true.
make false.

public class Test


{
public static void main(String args[])
{
boolean a =true;
boolean b =false;
System.out.println("a && b = "+(a&&b));
System.out.println("a || b = "+(a||b));
System.out.println("!(a && b) = "+!(a && b));
}
}
This would produce the following result:
a && b =false
a || b =true
!(a && b)=true

Assignment Operators:

Operator Description Example


= Simple assignment operator, Assigns C = A + B will assignvalue of A +
values from right side operands to leftside operand B into C
+= Add AND assignment operator, It addsright operand to C += A is equivalentto C = C + A
the left operand and assign the result to left operand
-= Subtract AND assignment operator, It subtracts right C -= A is equivalentto C = C - A
operand from the left operand and assign the result to
left operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C = C * A
operand with the left operand and assign the result to
left operand
/= Divide AND assignment operator, It divides left operand C /= A is equivalentto C = C / A
with the right operand and assign the result to left
operand
%= Modulus AND assignment operator, It takes modulus C %= A is equivalentto C = C % A
using two operands andassign the result to left
operand
<<= Left shift AND assignment operator C <<= 2 is same as C= C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C= C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C= C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C= C ^ 2
|= Bitwise inclusive OR and assignment operator C |= 2 is same as C= C | 2

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
public class Test
{
public static void main(String args[])
{
int a =10;
int b =20;
int c =0;
c = a + b;
System.out.println("c = a + b = "+ c );
c += a ;
System.out.println("c += a = "+ c );
c -= a ;
System.out.println("c -= a = "+ c );
c *= a ;
System.out.println("c *= a = "+ c );
a =10;
c =15;
c /= a ;
System.out.println("c /= a = "+ c );
a =10;
c =15;
c %= a ;
System.out.println("c %= a = "+ c );
c <<=2;
System.out.println("c <<= 2 = "+ c );
c >>=2;
System.out.println("c >>= 2 = "+ c );
c >>=2;
System.out.println("c >>= a = "+ c );
c &= a ;
System.out.println("c &= 2 = "+ c );
c ^= a ;
System.out.println("c ^= a = "+ c );
c |= a ;
System.out.println("c |= a = "+ c );
}
}
This would produce the following result:
c = a + b =30
c += a =40
c -= a =30
c *= a =300
c /= a =1
c %= a =5
c <<=2=20
c >>=2=5
c >>=2=1
c &= a =0
c ^= a =10
c |= a =10

Ternary / Conditional Operator (?:):

Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to
evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable.
The operator is written as:

variable x =(expression)? value iftrue: value iffalse

Following is the example:


Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
public class Test
{
public static void main(String args[])
{
int a , b;
a =10;
b =(a ==1)?20:30;
System.out.println("Value of b is : "+ b );
b =(a ==10)?20:30;
System.out.println("Value of b is : "+ b );
}
}
Output:
Value of b is:30
Value of b is:20

instanceof Operator:
This operator is used only for object reference variables. The operator checks whether the object is of a particular
type(class type or interface type). instanceof operator is written as:

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

If the object referred by the variable on the left side of the operator passes the check for the class/interface type on
the right side, then the result will be true. Following is the example:
String name = Java;
boolean result = name instanceof String; // This will return true since name is type of String

This operator will still return true if the object being compared is the assignment compatible with the type on the
right. Following is one more Example:
Class Vehicle
{
}
public class Car extends Vehicle
{
public static void main(String args[])
{
Vehicle ab =newCar();
boolean result = ab instanceof Car;
System.out.println(result);
}
}
Output:
True

Precedence of Java Operators:

Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated.
Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence
than the addition operator: For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here, operators with the highest precedence
appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.

Category Operator Associativity


Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A
Multiplicative */% Left to right
Additive + - Left to right
Shift >> >>> << Left to right
Relational >>= <<= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= Right to left
<<= &= ^= |=
Comma , Left to right

Arithmetic Expression Types:


Integer arithmetic expression:
-An arithmetic operation involving only integer operands is called integer arithmetic.
int + int = int
int - int = int
int * int = int
int / int = int (truncates decimal part)
int % int = int (results remainder)
Real arithmetic expression:
- An arithmetic operation involving only real operands is called real arithmetic.
real + real = real
real - real = real
real * real = real
real / real = real
real % real = not allowed
Mixed-mode arithmetic expression:
-An arithmetic operation involving one operand is real and the other operand is integer,then it is
called mixed-mode arithmetic.
real+int=real
real-int=real
real*int=real
real/int=real
real%int=not allowed

DATATYPES IN JAVA

Data types specify the different sizes and values that can be stored in the variable. There are two types of data types
in Java:
1. Primitive data types: The primitive data types include Integer, Character, Boolean, and Floating Point.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. As shown in above figure.
• The primitive types represent single values—not complex objects. Although Java is otherwise completely object-
oriented, the primitive types are not.
• They are analogous to the simple types found in most other non–object-oriented languages.
• The reason for this is efficiency. Making the primitive types into objects would have degraded performance too
much. The primitive types are defined to have an explicit range and mathematical behavior.
• Because of Java’s portability requirement, all data types have a strictly defined range. For example, an int is always
32 bits, regardless of the platform.

Integers
• Java defines four integer types: byte, short, int, and long.
• All of these are signed, positive and negative values. Java does not support unsigned, positive-only integers.
• Many other computers languages support both signed and unsigned integers.

byte
• The smallest integer type is byte.
• This is a signed 8-bit type that has a range from –128 to127.
• Variables of type byte are especially useful when you’re working with a stream of data from a network or file.
• Byte variables are declared by use of the byte keyword.
• For example, the following declares two-byte variables called b and c: byte b, c;

short
• short is a signed 16-bit type.
• It has a range from –32,768 to 32,767.
• It is probably the least-used Java type.
• Here are some examples of short variable declarations:
short s;
short t;
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

public class Demo


{
public static void main(String[] args)
{
byte b =100;
short s =123;
int v = 123543;
int calc = -9876345;
longamountVal = 1234567891;
System.out.println("byte Value = "+ b);
System.out.println("short Value = "+ s);
System.out.println("int Value = "+ v);
System.out.println("int second Value = "+ calc);
System.out.println("long Value = "+ amountVal);
}
}
Output:
byte Value = 100
short Value = 123
int Value = 123543
int Second value = -9876345
long Value = 1234567891

Floating-Point Types

• Floating-point numbers, also known as real numbers, are used when evaluating expressions that require
fractional precision.
• For example, calculations such as square root, sine and cosine, result in a value whose precision requires a
floating-point type.
• There are two kinds of floating-point types, float and double, which represent single- and double-precision
numbers, respectively.
float
• The type float specifies a single-precision value that uses 32 bits of storage.
double
• Double precision, as denoted by the double keyword, uses 64 bits to store a value.

class Area
{
public static void main(String args[])
{
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
Characters
§ In Java, the data type used to store characters is char.
§ char in Java is not the same as char in C or C++.
§ In C/C++, char is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to represent
characters.
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

o Unicode defines a fully international character set that can represent all the characters found in all human
languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew,
Katakana, Hangul, and many more. For this purpose, it requires 16 bits.
§ Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536. There are no negative values.

Example1
classCharDemo
{
public static void main(String args[])
{
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
Output: ch1 and ch2: X Y

Example2
class CharDemo2
{
public static void main(String args[])
{
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
Output:
ch1 contains X
ch1 is now Y

Boolean:
• Java has a simple type called boolean for logical values. It can have only one of two possible values. They are true
or false.
• boolean is also the type required by the conditional expressions that govern the control statements such as if and
for

class BoolTest
{
public static void main(String args[])
{
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
if(b)
System.out.println("This is executed.");
b = false;
if(b)
System.out.println("This is not executed.");
System.out.println("10 > 9 is " + (10 > 9));
}
}

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Output:
b is false
b is true
This is executed.
10 > 9 is true

Variable
A variable is an identifier that denotes a storage location used to store a data value. A variable may have different value in
the different phase of the 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. Variable is a name of memory location. All the variables
must be declared before they can be used. There are three types of variables in java: local variable, instance variable and
static variable.
To declare one identifier as a variable there are certain rules. They are:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.

Declaring Variable:
type identifier [ = value][, identifier [= value] ...] ;
Example:
int a,b,c;
float quot, div;
int d = 3, e, f = 5;
byte z = 22;
double pi = 3.14159;
char x = 'x';

1) Local Variable
• A variable defined within a block or method, or constructor is called local variable.
• These variables are created when the block in entered, or the function is called and destroyed after exiting from the
block or when the call returns from the function.
• The scope of these variables exists only within the block in which the variable is declared. i.e. we can access this
variable only within that block.
• We can’t use access specifiers for local variables.
Example:
import java.io.*;
public class StudentDetails
{
public void StudentAge()
{
int age = 0;
age = age + 5;
System.out.println("Student age is : " + age);
}
public static void main(String args[])
{
StudentDetails obj = new StudentDetails();
obj.StudentAge();
}
}

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Output:
Student age is : 5

2) Instance Variable
• Instance variables are non-static variables and are declared in a class outside any method, constructor, or block.
• As instance variables are declared in a class, these variables are created when an object of the class is created and
destroyed when the object is destroyed.
• Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier
then the default access specifier will be used.
Example:
import java.io.*;
class Marks
{
int m1;
int m2;
}
class MarksDemo
{
public static void main(String args[])
{
Marks obj1 = new Marks();
obj1.m1 = 50;
obj1.m2 = 80;
Marks obj2 = new Marks();
obj2.m1 = 80;
obj2.m2 = 60;
System.out.println("Marks for first object:");
System.out.println(obj1.m1);
System.out.println(obj1.m2);
System.out.println("Marks for second object:");
System.out.println(obj2.m1);
System.out.println(obj2.m2);
}
}
Output:
Marks for first object:
50
80
Marks for second object:
80
60
3) Static variable
• Static variables are also known as Class variables.
• These variables are declared similarly as instance variables, the difference is that static variables are declared using
the static keyword within a class outside any method constructor or block.
• Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects
we create.
• Static variables are created at start of program execution and destroyed automatically when execution ends.

Example:
import java.io.*;
class Emp
{
public static double salary;
public static String name = "Vijaya";
}
public class EmpDemo
{
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

public static void main(String args[])


{
Emp.salary = 1000;
System.out.println(Emp.name + "'s average salary:" + Emp.salary);
}
}
Output:
Vijaya’s average salary:10000.0

INSTANCE VARIABLE STATIC VARIABLE


Each object will have its own copy of instance We can only have one copy of a static variable per
variable class irrespective of how many objects we create.
Changes made in an instance variable using oneobject will In case of static changes will be reflected in other
not be reflected in other objects as each object has its objects as static variables are common to all object
own copy of instance variable of a class.
We can access instance variables through object Static Variables can be accessed directly using class
references name.
class Sample class Sample
{ {
int a; static int a;
} }

Final Keyword

Final Variable:
The value of a variable declared final cannot be changed in the program. It makes the variable a constant.
final double PI = 3.14159; // The value of PI cannot be changed in its scope
final int M = 900; // The value of M cannot be changed in its scope
final double X = 7.5643; // The value of x cannot be changed in its scope.
• As mentioned in the comments, the values of PI, M, and x cannot be changed in their respective scopes.

Final Method:
• The attribute final may be used for methods as well as for classes. These are basically connected with inheritance of
classes.
• When final keyword is used with Java method, it becomes the final method.
• A final method cannot be overridden in a sub-class.

Final Class:
• A Java class with final modifier is called final class A final class cannot be inherited. Several classes in Java are final
including String, Integer, and other wrapper classes.
• There are certain important points to be noted when using final keyword in Java
i. New value cannot be reassigned to a variable defined as final in Java.
ii. Final keyword can be applied to a member variable, local variable, method, or class.
iii. Final member variable must be initialized at the time of declaration.
iv. Final method cannot be overridden in Java
v. Final class cannot be inheritable in Java
vi. Final is different from finally keyword, which is used on Exception handling in Java

Example- 1:
public class Final
{
public static void main (String args[])
{
int n =10; // Normal variable
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

final int f = 20; // final variable


System.out.println("n = "+ n);
System.out.println("f = "+ f);
n = 50; // Now the value 50 is assigned to variable n
f = 60; // Error : f is final variable can not be changed
}
}
Output:
C:\>javac Final.java
Final.java:13: error: cannot assign a value to final variable f
f = 60; // Error : f is final variable can not be changed
^
1 error C:\>

Example-2:

public class Final


{
public static void main (String args[])
{
int n =10; // Normal variable
final int f = 20; // final variable
System.out.println("n = "+ n);
System.out.println("f = "+ f);
n = 50; // Now the value 50 is assigned to variable n
System.out.println("n = "+ n);
}
}
C:\>javac Final.java

C:\>java Final
n = 10
f = 20
n = 50

ARRAYS:
• An array is a memory space allocated that can store multiple values of same data type in contiguous locations.
• This memory space can be accessed with a common name and a specific element is accessed by using a subscript or
an index inside the brackets, along with the name of the array.(ex., marks[5], stores marks of a fifth student), each
individual value in array called as elements.
• Arrays offer a convenient means of grouping related information.
• Arrays of any type can be created and may have one or more dimensions.
ONE-DIMENSIONAL ARRAYS:
• A one-dimensional array is, essentially, a list of similar type values.
• Creating Arrays:
• declare a variable of the desired array type.
• allocate the memory that will hold the array, using new
• initializing/a ssigning valuesin to an array.

Declaring: To create an array, you first must create an array variable of the desired type.
• The general form of a one -dimensional array declaration is
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

type array_ name[ ];


• Here, type declares the base type of the array. The base type determines the data type of each element that
comprises the array. Thus, the base type for the array determines what type of data the array will hold.
Creating memory location: new is a special operator that allocates memory.
• The general form of new as it applies to one-dimensional arrays appears as follows:
Array_name = new type[size];
o Here, type specifies the type of data being allocated,
o size specifies the number of elements in the array,
o andarray_name is the array variable that is linked to the array.
Initializing:The elements in the array allocated by new will automatically be initialized to zero.
• To assign values to an array: Array_name[index]=value;
Or type Array_name[ ]={list of values};
• Example: Allocating a 12-element array of integers and links them to month_days.
month_days = new int[12];
month_days will refer to an array of 12 integers and all elements in the array will be initialized to zero.
• We can access a specific element in the array by specifying its index within square brackets. All array indexes start at zero.
• The for loops can be used to assign and access values from an array.
• To obtain the number of elements in an array, use the length property associated with all the arrays in java. I.e., use array
name followed by dot operator and the variable length.
• Example:
month_days[1] = 28;
// assigns the value 28 to the second element of month_days.
System.out.println(month_days[3]);//displays the value stored at index 3
Example:
// Demonstrate a one -dimensional array.
public class Array
{
public static void main(String args[])
{
intmarks[ ]={9,8,6,5,10};
int n=marks.length;
System.out.println(“marks of a student in a class test are:”);
for(int i=0;i<n;i++)
System.out.println(marks[i]);
}
}
Output: marks of a student in a class test are: 9 8 6 5 10
MULTIDIMENSIONAL ARRAYS
o In Java, multidimensional arrays are arrays of arrays.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

o To declare a multidimensional array variable, specify each additional index using another set of square
brackets.
o Suppose to store the marks of students in different subjects, need a 2D array conceptualized in the form of
table, with rows representing marks of each student and columns represent the subjects.
o For example, the following declares a two-dimensional array variable called marks.
int marks [][] = new int[ 5 ][6 ];
This allocates a 5 by 6 array and assigns it to marks, to store marks of 5 students in 6 subjects.
Internally this matrix is implemented as an array of arrays of int.
• Example:
// Demonstrate a two -dimensional array.
public class TwoDArray
{
public static void main(String args[])
{
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
{
twoD[i][j] = k; k++;
}
}
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Output:
01234
56789
10 11 12 13 14
15 16 17 18 19

Initializing Multidimensional Arrays:

• Enclose each dimension’s initializer within its own set of curly braces.
• The following program creates a matrix where each element contains the product of the row and column
indexes.
// Initialize a two -dimensional array. class Matrix
{
public static void main(String args[])
{
double m[][] = {{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }};
int i, j;
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

System.out.print(m[i][j] + " ");


System.out.println();
}
}
}

Output:
0.0 0.0 0.0 0.0
0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
0.0 3.0 6.0 9.0

Alternative Array Declaration Syntax :


• There is a second form that may be used to declare an array:
type[ ] var -name;
Here, the square brackets follow the type specifier, and not the name of the array variable.
• For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];

The following declarations are also equivalent:


char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][ 4];
• This alternative declaration form offers convenience when declaring several arrays at the same time.
• For example,
int[] num, num2, num3; // creates three array variables of type int.

TYPE CONVERSION AND CASTING


• If the two types are compatible, then Java will perform the conversion automatically.
• For example, it is always possible to assign an int value to a long variable.
• However, not all types are compatible, and thus, not all type conversions are implicitly allowed.
• For instance, there is no automatic conversion defined from double to byte. Fortunately, it is still possible to obtain a
conversion between incompatible types.
• To do so, you must use a cast, which performs an explicit conversion between incompatible types.

Java’s Automatic Conversions


• When one type of data is assigned to another type of variable, an automatic type conversion will take place if the
following two conditions are met:
o The two types are compatible.
o The destination type is larger than the source type.
• When these two conditions are met, a widening conversion takes place.
• For example, a smaller value can be placed in short, short in an int, int in long, and so on. Any value can be assigned to
double. Any value except a double can be assigned to a float. Any whole number can be assigned to long and int, short, byte
and char all can fit inside int.
byte b=10; //byte variable
int i=b; // implicit widening byte to int
• For widening conversions, the numeric types, including integer and floating-point types, are compatible with each other.
• However, there are no automatic conversions from the numeric types to char or boolean. Also, char and boolean are not
compatible with each other.
• Java also performs an automatic type conversion when storing a literal integer constant into variables of type byte, short,
long, or char.
Casting Incompatible Types

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

• For example, what if you want to assign an int value to a byte variable. This conversion will not be performed
automatically, because a byte is smaller than an int.
• For example, a bigger box must be placed in a small box. Then the small box must be chopped(casted) so that the bigger
box (which has now become smaller) can be placed in the small box.
• This kind of conversion is sometimes called a narrowing conversion , and termed as casting, since you are explicitly
making the value narrower so that it will fit into the target type.
• To create a conversion between two incompatible types, you must use a cast.
• A cast is simply an explicit type conversion.
• It has this general form:
(target -type) value

Here, target-type specifies the desired type to convert the specified value to.

• int a;
byte b;
// ...
b = (byte) a;
• A different type of conversion will occur when a floating -point value is assigned to an integer type: truncation. As you
know, integers do not have fractional components. Thus, when a floating -point value is assigned to an integer type, the
fractional component is lost.
• For example, if the value 1.23 is assigned to an integer, the resulting value will simply be 1. The 0.23 will have been
truncated.
• The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
public class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
System.out.println(" \nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println(" \nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println(" \nConversion of double to byte.");
b = (byte) d;
System.out.println ("d and b " + d + " " + b);
}
}

Output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Automatic Type Promotion in Expressions

• In addition to assignments, there is another place where certain type conversions may occur: in expressions.
• In an expression, the precision required of an intermediate value will sometimes exceed the range of either operand.
• For example, examine the following expression:
byte a = 40; byte b = 50; byte c = 100;
int d = a * b / c;
The result of the intermediate term a*b easily exceeds the range of either of its byte operands.
• To handle this kind of problem, Java automatically promotes each byte, short, or char operand to int when evaluating an
expression. This means that the sub expression a*b is performed using integers —not bytes. Thus, 2,000, the result of the
intermediate expression, 50 * 40, is legal even though a and b are both specified as type byte.
• As useful as the automatic promotions are, they can cause confusing compile-time errors.
• For example, this seemingly correct code causes a problem: byte b = 50; b = b * 2; // Error! Cannot assign an int to a byte!
The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte variable. However, because the
operands were automatically promoted to int when the expression was evaluated, the result has also been promoted to int.
Thus, the result of the expression is now of type int, which cannot be assigned to a byte without the use of a cast.
The Type Promotion Rules
• Java defines several type promotion rules that apply to expressions.
They are as follows:
1. All byte, short, and char values are promoted to int
2. If one operand is a long, the whole expression is promoted to long.
3. If one operand is a float, the entire expression is promoted to float.
4. If any of the operands is double, the result is double.

Example: Demonstrates how each value in the expression gets promoted to match the second argument to each binary
operator:
public class Promote
{
public static void main(String args[])
{
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}
Explanation: In the first subexpression, f * b, b is promoted to a float and the result of the subexpression is float. Next, in the
subexpression i/c, c is promoted to int, and the result is of type int. Then, in d*s, the value of s is promoted to double, and
the type of the subexpression is double. Finally, these three intermediate values, float, int, and double, are considered. The
outcome of float plus an int is a float. Then the resultant float minus the last double is promoted to double, which is the
type for the result of the expression.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Control Statements: 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 statement
b) if else statement
c) Nested-if statement

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

Syntax:

if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If not, the first
set of code after the end of the if statement(after the closing curly brace) will be executed.

Example:
public class Test
{
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

public static void main(String args[])


{
int x =10;
if( x <20)
{
System.out.print("This is if statement");
}
}
}
This would produce the following result:

This is if statement

The if...else Statement:


An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Syntax:

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

Example:

public class Test


{
public static void main(String args[])
{
int x =30;
if(x <20)
{
System.out.print("This is if statement");
}
else
{
System.out.print("This is else statement");
}
}
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

This would produce the following result:

This is else statement

The else..if Statement:


An if statement can be followed by an optional else if...else statement, which is very useful to test various conditions using
single if...else..if statement. When using if-else-if statements there are few points to keep in mind.
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.

Syntax:

if(Boolean_expression1)
{
//Executes when the Boolean expression 1 is true
}
elseif(Boolean_expression2)
{
//Executes when the Boolean expression 2 is true
}
elseif(Boolean_expression3)
{
//Executes when the Boolean expression 3 is true
}
else
{
//Executes when the none of the above condition is true.
}

Example:

public class Test


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

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

int x =30;
if( x ==10)
{
System.out.print("Value of X is 10");
}
else if( x ==20)
{
System.out.print("Value of X is 20");
}
else if( x ==30)
{
System.out.print("Value of X is 30");
}
else
{
System.out.print("This is else statement");
}
}
}
This would produce the following result:

Value of X is 30

Multi-Way Selection Statements


1. Nested if...else Statement
2. The switch Statement
Nested if...else Statement:
You can use one if or else if statement inside another if or else if statement.
Syntax:

if(Boolean_expression1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression2)
{
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Example:
public class Test
{
public static void main(String args[])
{
int x =30;
int y =10;
if( x ==30)
{
if( y ==10)
{
System.out.print("X = 30 and Y = 10");
}
}
}
This would produce the following result:
X =30 and Y =10

The switch Statement:

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the
variable being switched on is checked for each case.
Syntax:

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

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

The following rules apply to a switch statement:


• The variable used in a switch statement can only be a byte, short, int, or char.
• You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a
colon.
• The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that case will execute until a break
statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the
switch statement.
• Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until
a break is reached.
• A switch statement can have an optional default case, which must appear at the end of the switch. The default case can
be used for performing a task when none of the cases is true. No break is needed in the default case.
Example:
public class Test
{
public static void main(String args[])
{
char grade = args[0].charAt(0);
switch(grade)
{
case 'A': System.out.println("Excellent!");
break;
case 'B':
case 'C': System.out.println("Well done");
break;
case 'D': System.out.println("You passed");
case 'F': System.out.println("Better try again");
break;
default: System.out.println("Invalid grade");
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

}
System.out.println("Your grade is "+ grade);
}
}
Compile and run above program using various command line arguments. This would produce the following result:

D>java Test a
Invalid grade
Your grade is a
D> java Test A
Excellent!
Your grade is a A
D>java Test C Welldone
Your grade is a C
ITERATIVE STATEMENTS
In programming languages, loops are used to execute a set of instructions/functions repeatedly when some conditions
become true. There are three types of loops in java.

• while loop
• do-while loop
• For loop
while loop
A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
Syntax:
while(condition)
{
// body of loop
}

While loop starts with the checking of condition. If it evaluated to true, then the loop body statements are
executed otherwise first statement following the loop is executed. It is called as Entry controlled loop.
Normally the statements contain an update value for the variable being processed for the next iteration.
• When the condition becomes false, the loop terminates which marks the end of its life cycle.
Example:
// Demonstrate the while loop.
class WhileTest
{
public static void main(String args[])
{
int n = 5;
while(n > 0)
{
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

System.out.println("tick " + n);


n--;
}
}
}
Output:
tick 5
tick 4
tick 3
tick 2
tick 1

do-while loop:
do while loop checks for condition after executing the statements, and therefore it is called as ExitControlled
Loop.
Syntax:
do
{
// body of loop
} while (condition);

do while loop starts with the execution of the statement(s). There is no checking of any condition for the
first time.
After the execution of the statements, and update of the variable value, the condition is checked for
true or false value. If it is evaluated to true, next iteration of loop starts.
When the condition becomes false, the loop terminates which marks the end of its life cycle.
It is important to note that the do-while loop will execute its statements at least once before any
condition is checked, and therefore is an example of exit control loop.
Example
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=5);
}
}

Output:
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

1
2
3
4
5

for loop : for loop provides a concise way of writing the loop structure. A for statement consumes the initialization,
condition and increment/decrement in one line.
Syntax
for(initialization; condition; iteration)
{
// body
}

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already
declared variable can be used or a variable can be declared, local to loop only.
Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value.It is
also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
Statement execution: Once the condition is evaluated to true, the statements in the loop body are
executed.
Increment/ Decrement: It is used for updating the variable for next iteration.
Loop termination: When the condition becomes false, the loop terminates marking the end of its lifecycle.
Example
public class ForExample
{
public static void main(String[]
args)
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}
Output:
1
2
3
4
5

for-each Loop

The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop because we
don't need to increment value and use subscript notation. It works on elements basis not index.It returns element
one by one in the defined variable.
Syntax:
for(type itr-var : collection) statement-block

Example:
// Use a for-each style for loop.
class ForEach
{
public static void main(String args[])
{
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x : nums)
{
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55

Nested Loops
Java allows loops to be nested. That is, one loop may be inside another.
Example:
// Loops may be nested.
class Nested
{
public static void main(String args[])
{
int i, j;
for(i=0; i<10; i++)
{
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
Output:

..........
.........
........
.......
......
.....
....
...
..
.

JUMP STATEMENTS
Break Statement
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
The Java break is used to break loop or switch statement. It breaks the current flow of the program at
specified condition. In case of inner loop, it breaks only inner loop.
The break statement transfers control out of the enclosing loop (for, while, do or switch statement).
You use a break statement when you want to jump immediately to the statement following the enclosing
control structure.
You can also provide a loop with a label, and then use the label in your break statement.
The label name is optional, and is usually only used when you wish to terminate the outermost loop in a
series of nested loops.
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

Syntax:
break; // the unlabeled form
break <label>; // the labeled form

Example:
// Using break to exit a loop.
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<100; i++)
{
if(i == 10)
break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.

Example for Labelled Break

class BreakExample
{
public static void main(String args[])
{
boolean t = true;
first:
{
second:
{
third:
{
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
Prof K RADHIKA, Dept of CSE SSCE, Anekal
REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
Running this program generates the following output:
Before the break.
This is after second block.

Continue Statement
• The continue statement is used in loop control structure when you need to immediately jump to the next iteration
of the loop. It can be used with for loop or while loop.
• The Java continue statement is used to continue loop. It continues the current flow of the program and skips the
remaining code at specified condition. In case of inner loop, it continues only inner loop.
A continue statement stops the iteration of a loop (while, do or for) and causes execution to resume at the top of the
nearest enclosing loop.
You use a continue statement when you do not want to execute the remaining statements in the loop, but you do not
want to exit the loop itself.
You can also provide a loop with a label and then use the label in your continue statement.
The label name is optional, and is usually only used when you wish to return to the outermost loop in a series of nested
loops.

Syntax:
continue; // the unlabeled form
continue <label>; // the labeled form

Example:
// Demonstrate continue.
class Continue
{
public static void main(String args[])
{
for(int i=0; i<10; i++)
{
System.out.print(i + " ");
if (i%2 == 0)
continue;
System.out.println("");
}
}
}
This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline.
Output:
01
23
45
67
89

Example for labelled continue:


class ContinueLabel
{
public static void main(String args[])
{
outer: for (int i=0; i<10; i++)
{

Prof K RADHIKA, Dept of CSE SSCE, Anekal


REGULATION 2022 SCHEME OOP WITH JAVA – BCS306A

for(int j=0; j<10; j++)


{
if(j > i)
{
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
Return
The last control statement is return. The return statement is used to explicitly return from a method. That is, it causes
program control to transfer back to the caller of the method.
Syntax:
The return statement has two forms:
One that returns a value
return val;
One that doesn't return a value
return;

Example:
public class Example
{
public static void main(String[] args)
{
int res = sum(10, 20);
System.out.println(res);
}
private static int sum(int a, int b)
{
return (a + b);
}
}

Prof K RADHIKA, Dept of CSE SSCE, Anekal

You might also like