KEMBAR78
Oops With Java - PDF Unit - 1 | PDF | Java Virtual Machine | Java (Software Platform)
0% found this document useful (0 votes)
29 views61 pages

Oops With Java - PDF Unit - 1

Uploaded by

jayalakshme143
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)
29 views61 pages

Oops With Java - PDF Unit - 1

Uploaded by

jayalakshme143
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/ 61

OBJECT ORIENTED PROGRAMMING USING JAVA (B.

sc III Sem)
UNIT - 1
OOPs Concepts and Java Programming:
Introduction to Object-Oriented concepts, procedural and object-oriented
programming paradigm
Java programming:
An Overview of Java, Java Environment, Data types, Variables,
constants, scope and life time of variables, operators, type conversion and
casting, Accepting Input from the Keyboard, Reading Input with
Java.util.Scanner Class, Displaying Output with System.out.printf(), Displaying
Formatted Output with String.format(), Control Statements.
Introduction to Object-Oriented concepts :
--------------------------------------------------------------
As the name suggests, Object-Oriented Programming or OOPs refers to
languages that use objects in programming. Object-oriented programming aims
to implement real-world entities like inheritance, hiding, polymorphism, etc in
programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this
data except that function.
OOPs Concepts:
1. Class
2. Objects
3. Data Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism
1. Class :
A class is like a blueprint for an object. A class is a user-defined data
type. It consists of data members and member functions, which can be accessed
and used by creating an instance of that class. It represents the set of properties
or methods that are common to all objects of one type.

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Example:
Consider the Class of Cars. There may be many cars with different names
and brands but all of them will share some common properties like all of them
will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class,
and wheels, speed limits, mileage are their properties.
2. Object :
It is a basic unit of Object-Oriented Programming and represents the real-life
entities. An Object is an instance of a Class. When a class is defined, no
memory is allocated but when it is instantiated (i.e. an object is created)
memory is allocated. An object has an identity, state, and behavior. Each object
contains data and code to manipulate the data. Objects can interact without
having to know details of each other’s data or code, it is sufficient to know the
type of message accepted and type of response returned by the objects.
example :
-------------
“Dog” is a real-life Object, which has some characteristics like colour,
Breed, Bark, Sleep, and Eats.

3. Data Abstraction:
Data abstraction is one of the most essential and important features of object-
oriented programming. Data abstraction refers to providing only essential
information about the data to the outside world, hiding the background details
or implementation. Consider a real-life example of a man driving a car. The man
only knows that pressing the accelerators will increase the speed of the car or
applying brakes will stop the car, but he does not know about how on pressing
the accelerator the speed is increasing, he does not know about the inner
mechanism of the car or the implementation of the accelerator, brakes, etc in the
car.

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. In
Encapsulation, the variables or data of a class are hidden from any other class
and can be accessed only through any member function of their class in which
they are declared. As in encapsulation, the data in a class is hidden from other
classes, so it is also known as data-hiding.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The
capability of a class to derive properties and characteristics from another class is
called Inheritance. When we write a class, we inherit properties from other
classes. So when we create a class, we do not need to write all the properties
and functions again and again, as these can be inherited from another class that
possesses it. Inheritance allows the user to reuse the code whenever possible
and reduce its redundancy.

6. Polymorphism:
The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than
one form. For example, A person at the same time can have different
characteristics. Like a man at the same time is a father, a husband, an employee.

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

So the same person posses different behavior in different situations. This is


called polymorphism.

Procedural and object-oriented programming paradigm :

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Java programming:
An Overview of Java :
Java programming language was originally developed by
Sun Microsystems, which was initiated by James Gosling and released in 1995
as a core component of Sun Microsystems' Java platform.
The latest release of the Java Standard Edition is Java SE 23. With the
advancement of Java and its widespread popularity, multiple configurations
were built to suit various types of platforms. For example: J2EE for Enterprise
Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME,
respectively. Java is guaranteed to be Write Once, Run Anywhere.
Java is −
• Object-Oriented: In Java, everything is an object. Java can be easily
extended since it is based on the object model.
• Platform Independent: Unlike many other programming languages,
including C and C++, when Java is compiled, it is not compiled into a
platform-specific machine but rather into platform-independent byte
code. This byte code is distributed over the web and interpreted by the
virtual machine (JVM) on whichever platform it is being run on.
• Simple: Java is designed to be easy to learn. If you understand the
basic concept of OOP Java, it would be easy to master.
• Secure: With Java's secure feature, it enables the development of virus-
free, tamper-free systems. Authentication techniques are based on public-
key encryption.
Architecture-neutral: The Java compiler generates an architecture-neutral
object file format, which makes the compiled code executable on many
processors with the presence of the Java runtime system.
• Portable: Being architecture-neutral and having no implementation-
dependent aspects of the specification makes Java portable. Compiler in
Java is written in ANSI C with a clean portability boundary, which is a
POSIX subset.
• Robust: Java makes an effort to eliminate error-prone situations by
emphasizing mainly compile-time error checking and runtime checking.
Multithreaded: With Java's multithreaded feature, it is possible to write
programs that can perform many tasks simultaneously. This design
Prepared by S. Dinesh, M.C.A Lect.in Computer Science
Unit - I

feature allows the developers to construct interactive applications that can


run smoothly.
• Interpreted: Java byte code is translated on the fly to native machine
instructions and is not stored anywhere. The development process is more
rapid and analytical since the linking is an incremental and light-weight
process.
• High Performance: With the use of just-in-Time compilers, Java enables
high performance.
Distributed: Java is designed for the distributed environment of the
internet.
• Dynamic: Java is considered to be more dynamic than C or C++ since it
is designed to adapt to an evolving environment. Java programs can carry
an extensive amount of run-time information that can be used to verify
and resolve accesses to objects in run-time.
Basic Java Program
--------------------------
public class Hello {
public static void main(String[] args) {
System.out.println("Hello World ");
}
}
Output
Hello world
Explanation:
• class Hello: Declares a class.
• main(String[] args): Main method (entry point).
• System.out.println(): Prints to console.

History of Java
James Gosling initiated Java language project in June 1991 for use in one of his
many set-top box projects. The language, initially called 'Oak' after an oak tree

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

that stood outside Gosling's office, also went by the name 'Green' and ended up
later being renamed as Java, from a list of random words.
Sun released the first public implementation as Java 1.0 in 1995. It
promised Write Once Run Anywhere (WORA), providing no-cost run-times on
popular platforms.
On 13 November, 2006, Sun released much of Java as free and open source
software under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free
and open-source, aside from a small portion of code to which Sun did not hold
the copyright.

Java Environment
Java Environment is the setup that allows you to write, compile, and run
Java programs. It consists of JDK, JRE, and JVM.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit
(JDK) is a software development environment that is used to develop Java
applications. 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:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro 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.
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 that are used for
developing Java applications. It is used to provide the runtime environment. It is
the implementation of JVM. It physically exists. It contains a set of libraries +
other files that the JVM uses at runtime.

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Java virtual Machine (JVM) : It is a program that interprets the intermediate


java byte code and generates the desired output.
Runtime class libraries : These are a set of core class libraries that are required
the execution of java program.
User interface toolkits : AWT and Swing are example of toolkits that support
varied input methods for the users to interact with the application program.
Deployment technologies : JRE comprises the following key deployment
technologies :
Java plug-in : Enables the execution of a java applet on the browser.
Java Web Start : Enables remote- deployment of an application.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual
machine because it doesn't physically exist. It is a specification that provides a
runtime environment in which Java bytecode can be executed. It can also run
those programs that are written in other languages and compiled to Java
bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and
JDK are platform dependent because the configuration of each OS is different
from that of others. However, Java is platform independent. There are three
notions of the JVM: specification, implementation, and instance.
The JVM performs the following main tasks:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment

Data Types :
In Java, data types define the type of data that a variable can hold.
They are categorized into two main types:
1. Primitive data types and
2. Non-primitive data types.
Prepared by S. Dinesh, M.C.A Lect.in Computer Science
Unit - I

1. Primitive Data Type:


These are the basic building blocks that store simple values directly in
memory.
Examples of primitive data types are
• char
• byte
• short
• int
• long
• float
• double
• boolean

2. Non-Primitive Data Types (Object Types):


------------------------------------------------------
These are reference types that store memory addresses of objects.
Examples of Non-primitive data types are :
• String
• Array
• Class

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

The below diagram demonstrates different types of primitive and non-primitive


data types in Java.

Primitive Data Types in Java


Primitive data store only single values and have no additional capabilities.
There are 8 primitive data types. They are depicted below in tabular format
below as follows:
1. Boolean Data Type :
The boolean data type represents a logical value that can be either true or
false. Conceptually, it represents a single bit of information, but the actual size
used by the virtual machine is implementation-dependent and typically at least
one byte (eight bits) in practice. Values of the boolean type are not implicitly or
explicitly converted to any other type using casts. However, programmers can
write conversion code if needed.

Syntax:
Datatypename variable name = value ;
boolean demo = true ;
Size : Virtual machine dependent (typically 1 byte, 8 bits)
2. byte Data Type
The byte data type is an 8-bit signed two's complement integer. The byte
data type is useful for saving memory in large arrays.
Syntax:
Datatypename variable name = value ;
byte value = 4;
Size : 1 byte (8 bits)
3. short Data Type
The short data type is a 16-bit signed two's complement integer.
Similar to byte, a short is used when memory savings matter, especially in
large arrays where space is constrained.
Syntax:

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Datatypename variable name = value ;


short s = 56;
Size : 2 bytes (16 bits)
4. int Data Type
It is a 32-bit signed two's complement integer.
Syntax:
Datatypename variable name = value ;
Int number = 25;
Size : 4 bytes ( 32 bits )
5. long Data Type
The long data type is a 64-bit signed two's complement integer. It is used when
an int is not large enough to hold a value, offering a much broader range.
Syntax:
Datatypename variable name = value ;
long value = 1345234 ;
Size : 8 bytes (64 bits)

6. float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating-point.
Use a float (instead of double) if you need to save memory in large arrays of
floating-point numbers. The size of the float data type is 4 bytes (32 bits).
Syntax:
Datatypename variable name = value ;
Float number = 2.3 ;
Size : 4 bytes (32 bits)
7. double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating-
point. For decimal values, this data type is generally the default choice. The size
of the double data type is 8 bytes or 64 bits.

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Syntax:
Datatypename variable name = value ;
double value = 123.34 ;
Size : 8 bytes (64 bits)
8. char Data Type
The char data type is a single 16-bit Unicode character with the size of 2
bytes (16 bits).
Syntax:
Datatypename variable name = value ;
char name = 'G' ;
Size : 2 bytes (16 bits)

Example: Here we are demonstrating how to use various primitive data


types.
class PrimitiveExample
{
public static void main(String args[])
{
char a = 'G';
int i = 89;
byte b = 4;
short s = 56;
double d = 4.355453532;
float f = 4.7333434f;
long l = 12121;
boolean b = true;
System.out.println("char: " + a);
System.out.println("integer: " + i);

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

System.out.println("byte: " + b);


System.out.println("short: " + s);
System.out.println("float: " + f);
System.out.println("double: " + d);
System.out.println("long: " + l);
System.out.println("boolean: " + b);
}
}

Output :
------------------
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
boolean: true

Non-Primitive Data Types :


The Non-Primitive (Reference) Data Types will contain a memory
address of variable values because the reference types won’t store the variable
value directly in memory. They are strings, objects, arrays, etc.
1. Class
A Class is a user-defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to all
objects of one type.
2. Strings

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Strings are defined as an array of characters. The difference between a


character array and a string in Java is, that the string is designed to hold a
sequence of characters in a single variable whereas, a character array is a
collection of separate char-type entities
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
This example demonstrates how to use string variables to store and display text
values.
public class StringExample {
public static void main(String[] args) {
String n = "Good Morning";
String m = "Hello, World!";
System.out.println("Name: " + n);
System.out.println("Message: " + m);
}
}

Output
Name: Good Morning
Message: Hello, World!
3. Arrays
Array is a non-primitive data type .
An array is a container object that holds a fixed number of value of a
single type.
1. One Dimensional Array
2. Two Dimensional array
Declaring and Initializing Array
1.Declaration:

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

int[] i; // Preferred
int i[]; // Also valid
2. Initialization:
i= new int[5]; // Creates an array of size 5
( Combined Declaration and Initialization)
3. Combined Declaration and Initialization:
int[] i = new int[5]; // Array with predefined values int i=10;
4. Declaration with values :
int[] x = {10, 20, 30, 40, 50};
5. Accessing Elements :
System.out.println(arr[0]); // Prints first element
arr[1] = 25; // Changes second element to 25

Variables
variables are containers that store data in memory. Understanding
variables plays a very important role as it defines how data is stored, accessed,
and manipulated.
Types of Java Variables
Now let us discuss different types of variables which are listed as follows:
• Instance Variables (non static variable)
• Class Variable (Static Variables)
• Local Variables

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Declare Java Variables


//Datatype name variable name;
Int number;

Initialize Java Variables


//datatype name variable name = value ;
Int number = 20;

1. Instance Variables :
Instance variables is also known as non-static variables and in this
variable are declared in with in class only. We can’t create out side of the class.
• Instance 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.
• Initialization of an instance variable is not mandatory. Its default value is
dependent on the data type of variable.
• Instance variables can be accessed only by creating objects.

Example :
Class InstanceExample{
Int x = 10;
Int y =30;

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Int sum = x + y;
Public static void main ( Stirng [] args )
{
InstanceExample example = new InstanceExample ( );
System.out.println (“Sum of two values is : ” + example.sum);
}
}
}
Output :
Sum of two values is : 40

2. Class Variable :
Class variable is also known as instance variable or static variable. in this
variable are declared in with in class only. We can’t create out side of the class.
• Static variables are created at the start of program execution and
destroyed automatically when execution ends.
• Initialization of a static variable is not mandatory. Its default value is
dependent on the data type of variable.
• If we access a static variable without the class name, the compiler will
automatically append the class name. But for accessing the static variable
of a different class, we must mention the class name as 2 different classes
might have a static variable with the same name.
• Static variables cannot be declared locally inside an instance method.

Example :
Class Example{
Static Int x = 50;
Static Int y =30;
Int sum = x - y;

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Public static void main ( Stirng [] args )


{

System.out.println (“Subtraction of two values is : ” + sum);


}
}
}

Output :
Subtraction of two values is : 20
3. Local Variable
A variable defined within a block or method is called a local variable. We
can’t create out side of the method.
• The Local variable is created at the time of declaration and destroyed
when the function completed its execution.
• The scope of local variables exists only within the block in which they
are declared.
• We first need to initialize a local variable before using it within its scope.

Example :
Class LocalExample{
Public static void main ( Stirng [] args )
{
Int x = 10;
Int y =30;
Int sub = x * y;
System.out.println (“Multiplication of two values is : ” + sub);
}

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

}
}

Output
Multiplication of two values is : 300

Constants
A constant in Java is a variable declared with the final keyword,
indicating that its value cannot be changed after it is assigned. Constants are
used to store values that should remain unchanged throughout the execution of a
Java program.
Constants are used for storing fixed values like mathematical constants,
configuration settings, or other unchanging data needed in various parts of the
code. Declaring a value as a constant enhances code readability, ensures data
consistency, and helps prevent accidental modifications, contributing to robust
and maintainable Java programs.
Types of Constants :

Numeric Constants
1. Integer Constants

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Integer constants represent whole numbers without fractional or decimal parts.


There are three types of integer constants, such as decimal integer, octal integer
and hexadecimal integer.
Decimal Integer Constants:
Decimal integers consist of a set of digits, 0 through 9, preceded by an
optional minus sign.
Example
public class DecimalIntegerConstantExample {
public static final int age = 25;
public static void main(String[] args) {
System.out.println("Age: " + age);
}
}
Output:
Age: 25
Octal Integer Constants:
An octal integer constant consists of any combination of digits from the
set 0 through 7.
Some example of octal integer are :
037 0 0435 0551
Example
public class OctalIntegerConstantExample {
public static final int octalNumber = 012; // Octal representation
public static void main(String[] args) {
System.out.println("Octal number: " + octalNumber);
}
}
Output:
Octal number: 10
Prepared by S. Dinesh, M.C.A Lect.in Computer Science
Unit - I

Hexadecimal Integer Constants:


A sequence of digits preceded by Ox or OX is considered as hexadecimal
integer ( hex integer ). They many also include alphabets A through F or a
though f. A letter through F represents the number 10 through 15.
Following are the example of valid hex integers.
OX2 OX9F Oxbcd Ox
✓ We rarely use octal and hexadecimal numbers in program.
Example
public class HexadecimalIntegerConstantExample {
public static final int hexNumber = 0x1A; // Hexadecimal representatio
n
public static void main(String[] args) {
System.out.println("Hexadecimal number: " + hexNumber );
}
}
Output:
Hexadecimal number: 26

1. Real Constants
Real constants represent numbers with fractional parts. They include a
decimal point and can be written in scientific notation as well.
These quantities are represented by numbers containing fractional parts like
17.548. such numbers are called real ( or floating point ) constants.
Example
public class FloatingPointConstantExample {
public static final double PI = 3.14159;
public static final double scientificNotation = 2.5e3; // 2500.0
public static void main(String[] args) {
Prepared by S. Dinesh, M.C.A Lect.in Computer Science
Unit - I

System.out.println("Value of PI: " + PI);


System.out.println("Scientific notation: " + scientificNotation); }
}
Output:
Value of PI: 3.14159
Scientific notation: 2500.0

2. Non-Numeric Constants
Non-numeric constants in Java refer to constants that are not directly
associated with numeric values. These constants are used to represent non-
numeric data, such as textual information, characters, boolean values, and more.
Let's explore some common types of non-numeric constants and their
explanations.
String Constants:
String constants are used to represent sequences of characters or textual
data. They are enclosed within double quotes and can include letters, numbers,
symbols, and spaces. String constants are often used for displaying messages,
labels, prompts, and any other form of textual information.
Example
public class StringConstantExample {
public static final String name = "Welcome to our application!";
public static void main(String[] args) {
System.out.println(name);
}
}
Output:
Welcome to our application!

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Character Constants:
Character constants represent single characters and are enclosed within
single quotes. They are commonly used to represent individual characters, such
as letters, digits, and symbols.
Example
public class CharacterConstantExample {
public static final char firstLetter = 'A';
public static void main(String[] args) {
char secondLetter = 'B';
System.out.println("First letter: " + firstLetter);
System.out.println("Second letter: " + secondLetter);
}
}
Output:
First letter: A
Second letter: B

Scope and Life time of variables


In Java, the scope and lifetime of a variable determine where the variable
can be accessed and how long it exists in memory.
Here's a concise explanation:
Scope of Variables
The scope of a variable refers to the part of the program where the variable is
accessible. Java has the following types of variable scopes:
1. Class/Static Scope:
o Variables declared with the static keyword inside a class.
o Accessible by all instances of the class and without creating an
object.
o Scope: Entire class, shared across all objects.
Prepared by S. Dinesh, M.C.A Lect.in Computer Science
Unit - I

2. Instance Scope:
o Variables declared without static inside a class.
o Each object of the class has its own copy.
o Scope: Accessible within the class using an object.
3. Local Scope:
o Variables declared inside a method, constructor, or block.
o Scope: Limited to the block in which they are declared.
o Not accessible outside the block.
4. Block Scope:
o Variables declared inside loops, if statements, or other blocks.
o Scope: Limited to the block where they are defined.
Lifetime of Variables
The lifetime of a variable refers to how long the variable exists in memory:
1. Static Variables:
o Lifetime: Exists for the entire duration of the program.
o Memory is allocated when the class is loaded and deallocated when
the program ends.
2. Instance Variables:
o Lifetime: Exists as long as the object exists.
o Memory is allocated when the object is created and deallocated
when the object is garbage collected.
3. Local Variables:
o Lifetime: Exists only during the execution of the method or block.
o Memory is allocated when the method/block is invoked and
deallocated when it ends.
4. Block Variables:
o Lifetime: Exists only during the execution of the block.

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

o Memory is allocated at the start of the block and deallocated when


the block ends.
Example Code
public class VariableScopeExample {
static int staticVar = 10; // Class/Static Scope

int instanceVar = 20; // Instance Scope

public void methodExample() {


int localVar = 30; // Local Scope
for (int i = 0; i < 5; i++) { // Block Scope
System.out.println("Block Variable i: " + i);
}
// System.out.println(i); // Error: i is out of scope
}
}
This structure ensures variables are used efficiently and do not interfere with
each other.

Operators
What is an Operator?
An operator is a symbol that performs operations on variables and values. Java
provides many types of operators to perform different kinds of operations.
Types of Operators in Java
1. Arithmetic Operators
2. Relational (Comparison) Operators
3. Logical Operators
4. Assignment Operators

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

5. Unary Operators
6. Bitwise Operators
7. Ternary Operator
8. Shift Operators

Arithmetic Operators in Java

Arithmetic Operators in Java are particularly used for performing arithmetic


operations on given data or variables. There are various types of operators in Java,
such as

Operators Operations

+ Addition

- Subtraction

x Multiplication

/ Division

% Modulus

Arithmetic Operators in Java Example

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

// declare variables
int a = 15, b = 5;

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

// addition operator
System.out.println("a + b = " + (a + b));

// subtraction operator
System.out.println("a - b = " + (a - b));

// multiplication operator
System.out.println("a * b = " + (a * b));

// division operator
System.out.println("a / b = " + (a / b));

// modulo operator
System.out.println("a % b = " + (a % b));

}
}
Run Code >>

Output

a + b = 20
a - b = 10
a * b = 75
a/b=3
a%b=0

Assignment Operator in Java

Assignment Operators are mainly used to assign the values to the variable that is
situated in Java programming. There are various assignment operators in Java,
such as

• += , Add and assign.


• -= , Subtract and assign.
• *= , Multiply and assign.
• /= , Divide and assign.
• %= , Modulo and assign.

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Assignment Operator in Java Example

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

// create variables
int a = 5;
int var;

// assign value using =


var = a;

System.out.println("var using =: " + var);

// assign value using =+


var += a;

System.out.println("var using +=: " + var);

// assign value using =*


var *= a;

System.out.println("var using *=: " + var);

}
}
Run Code >>

Output

var using =: 5
var using +=: 10
var using *=: 5

Relational Operators in Java

Java relational operators are assigned to check the relationships between two
particular operators. There are various relational operators in Java, such as

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Operators Description Example

== Is equal to 3 == 5 returns false

!= Not equal to 3 != 5 returns true

> Greater than 3 > 5 returns false

< Less than 3 < 5 returns true

>= Greater than or equal to 3 >= 5 returns false

<= Less than or equal to 3 <= 5 returns true

Relational Operators in Java Example

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

// create variables
int a = 7, b = 11;

// value of a and b
System.out.println("a is " + a + " and b is " + b);

// == operator
System.out.println(a == b); // false

// != operator
System.out.println(a != b); // true

// > operator
System.out.println(a > b); // false
Prepared by S. Dinesh, M.C.A Lect.in Computer Science
Unit - I

// < operator
System.out.println(a < b); // true

// >= operator
System.out.println(a >= b); // false

// <= operator
System.out.println(a <= b); // true

}
}
Run Code >>

Output

a is 7 and b is 11
false
true
false
true
false
true

Logical Operators in Java

Logical Operators in Java check whether the expression is true or false. It is


generally used for making any decisions in Java programming.

Operators Example Meaning

&& [ logical expression1 && (true) only if both of the expressions


AND ] expression2 are true

expression1 || (true) if one of the expressions in


|| [ logical OR ]
expression2 true

(true) if the expression is false and


! [ logical NOT ] !expression
vice-versa

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Logical Operators in Java Example

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

// && operator
System.out.println((6 > 3) && (8 > 6)); // true
System.out.println((6 > 3) && (8 < 6)); // false

// || operator
System.out.println((6 < 3) || (8 > 6)); // true
System.out.println((6 > 3) || (8 < 6)); // true
System.out.println((6 < 3) || (8 < 6)); // false

// ! operator
System.out.println(!(6 == 3)); // true
System.out.println(!(6 > 3)); // false

}
}
Run Code >>

Output

true
false
true
true
false
true
false

Unary Operator in Java

Unary Operators in Java are used in only one operand. There are various types of
Unary Operators in Java, such as

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Operators Description

+ Unary Plus

- Unary Minus

++ Increment operator

-- Decrement Operator

! Logical complement operator

Unary Operator in Java Example

We'll see the demonstration of the increment and decrement operator in Java in
our Java Playground.

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

// declare variables
int a = 13, b = 13;
int result1, result2;

// original value
System.out.println("Value of a: " + a);

// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);

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

// decrement operator
Prepared by S. Dinesh, M.C.A Lect.in Computer Science
Unit - I

result2 = --b;

System.out.println("After decrement: " + result2);

}
}
Run Code >>

Output

Value of a: 13
After increment: 14
Value of b: 13
After decrement: 12

Bitwise Operators in Java

Bitwise Operators in Java are used to assist the performance of the operations on
individual bits. There are various types of Bitwise Operators in Java, such as. We
will see the working of the Bitwise Operators in the Java Online Compiler.

Operators Descriptions

~ Bitwise Complement

<< Left shift

>> Right shift

>>> Unsigned Right shift

& Bitwise AND

^ Bitwise exclusive OR

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Bitwise Operators in Java Example

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

String str = "ScholarHat";


boolean result;

// checks if str is an instance of


// the String class
result = str instanceof String;

System.out.println("Is str an object of String? " + result);


}
}
Run Code >>

Output

Is str an object of String? true

Comparison Operators in Java

To compare two values (or variables), comparison operators are used. This is
crucial to programming since it facilitates decision-making and the search for
solutions. A comparison's return value is either true or false. These are referred to
as "Boolean values."

Operators Operations

== Equal to

!= Not equal

> Greater than

< Less than

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Operators Operations

>= Greater than or equal to

<= Less than or equal to

Example

public class ComparisonOperatorsExample {


public static void main(String[] args) {
int num1 = 10;
int num2 = 20;

// Equal to (==) operator


boolean isEqual = (num1 == num2);
System.out.println("num1 is equal to num2: " + isEqual);

// Not equal to (!=) operator


boolean isNotEqual = (num1 != num2);
System.out.println("num1 is not equal to num2: " + isNotEqual);

// Greater than (>) operator


boolean isGreaterThan = (num1 > num2);
System.out.println("num1 is greater than num2: " + isGreaterThan);

// Less than (<) operator


boolean isLessThan = (num1 < num2);
System.out.println("num1 is less than num2: " + isLessThan);

// Greater than or equal to (>=) operator


boolean isGreaterThanOrEqual = (num1 >= num2);
System.out.println("num1 is greater than or equal to num2: " +
isGreaterThanOrEqual);

// Less than or equal to (<=) operator


boolean isLessThanOrEqual = (num1 <= num2);
System.out.println("num1 is less than or equal to num2: " + isLessThanOrEqual);
}
}

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Run Code >>

Output

num1 is equal to num2: false


num1 is not equal to num2: true
num1 is greater than num2: false
num1 is less than num2: true
num1 is greater than or equal to num2: false
num1 is less than or equal to num2: true

Ternary Operators in Java

The only conditional operator that accepts three operands is the ternary operator
in Java. Java programmers frequently use it as a one-line alternative to the if-
then-else expression. The ternary operator can be used in place of if-else
statements, and it can even be used to create switch statements with nested ternary
operators. The conditional operator uses less space and aids in writing if-else
statements as quickly as possible even if it adheres to the same algorithm as an
if-else statement

Example

public class TernaryOperatorExample {


public static void main(String[] args) {
int num1 = 10;
int num2 = 20;

// Using the ternary operator to find the maximum of two numbers


int max = (num1 > num2) ? num1 : num2;

System.out.println("The maximum number is: " + max);


}
}

Run Code >>

Output

The maximum number is: 20

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Type conversion and Type casting


Type casting
In java, type casting is a typically converting one data type into another
data type in both ways manually and automatically.
The automatic conversion is done by the compiler and manual conversion
performed by the programmer.
Types of Type Casting
There are two types of type casting :
1. Widening type casting
2. Narrowing type casting
1. Widening type casting
It is used to converting a lower data type into higher data type.
✓ It is also known as implicit conversion or promotion or automated.
✓ It is done automatically.
✓ It is safe because there is no chance to lose data.
For Example, in java, the numeric data types are compatible with each other but
no automatic conversion is supported from numeric type to char or boolean.
Also, char and boolean are not compatible with each other.

Example :
// Java Program to Illustrate Automatic Type Conversion

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

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

{
int i = 100; // Automatic type conversion
long l = i; // Integer to long type
float f = l; // long to float type
System.out.println("Int value " + i);
System.out.println("Long value " + l);
System.out.println("Float value " + f);
}
}

Output

Int value 100


Long value 100
Float value 100.0
Narrowing
It is used to converting a higher data type into lower data type. we
perform explicit type casting or narrowing.
• This is useful for incompatible data types where automatic conversion
cannot be done.
• Here, the target type specifies the desired type to convert the specified
value to.

Example :
// Java program to Illustrate Explicit Type Conversion
public class NarrowingExample{
public static void main(String[] args)

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

{
// Double datatype
double d = 100.04;

// Explicit type casting by forcefully getting


// data from long datatype to integer type
long l = (long)d;

// Explicit type casting


int i = (int)l;

// Print statements
System.out.println("Double value " + d);
System.out.println("Long value " + l);
System.out.println("Int value " + i);
}
}
Output :
Double value 100.04
Long value 100
Int value 100
Type conversion :
In type conversion, a data type is automatically converted into another
data type by a compiler at the compiler time. In type conversion, the destination
data type cannot be smaller than the source data type, that's why it is also called
widening conversion. One more important thing is that it can only be applied to
compatible data types.

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Type Conversion example -


int x=30;
float y;
y=x; // y==30.000000.
Let's see the difference between Type casting and Type conversion which
are given below:

S.NO TYPE CASTING TYPE CONVERSION

In type casting, a data type is


Whereas in type conversion, a data
converted into another data type
1. type is converted into another data
by a programmer using casting
type by a compiler.
operator.

Type casting can be applied


Whereas type conversion can only
to compatible data types as
2. be applied to compatible
well as incompatible data
datatypes.
types.

In type casting, casting operator


Whereas in type conversion, there
3. is needed in order to cast a data
is no need for a casting operator.
type to another data type.

In type casting, the destination


data type may be smaller than Whereas in type conversion, the
4. the source data type, when destination data type can't be
converting the data type to smaller than source data type.
another data type.

Type casting takes place during


Whereas type conversion is done
5. the program design by
at the compile time.
programmer.

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

S.NO TYPE CASTING TYPE CONVERSION

Type casting is also called Whereas type conversion is also


narrowing conversion because in called widening conversion
6. this, the destination data type because in this, the destination
may be smaller than the source data type can not be smaller than
data type. the source data type.

Whereas type conversion is less


Type casting is often used in
used in coding and competitive
7. coding and competitive
programming as it might cause
programming works.
incorrect answer.

Type casting is more efficient Whereas type conversion is less


8.
and reliable. efficient and less reliable.

Write a program to read an input with Java.util.Scanner class

import java.util.Scanner; // Import the Scanner class


public class UserInputExample {
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);

// Prompt the user for input


System.out.print("Enter your name: ");
String name = scanner.nextLine(); // Read a line of text

// Display the input back to the user


Prepared by S. Dinesh, M.C.A Lect.in Computer Science
Unit - I

System.out.print("Hey %s , How are You? \n” , name);

// Using print statement


System.out.print("Enter your age: ");
int age = scanner.nextInt(); // Read an integer

System.out.print("Enter your height : ");


double height = scanner.nextDouble(); // Read a double

System.out.print("Enter your weight: ");


int weight = scanner.nextInt(); // Read an integer

System.out.println("Thankyou for the information… ");

// Close the scanner


scanner.close();
}
}
Output
Enter your name: Dinesh
Hey Dinesh , How are you ?
I’m very good
Enter your age: 20
Enter your height : 6
Enter your weight: 55
Thankyou for the information…

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Displaying Output with System.out.printf( )


In Java, System.out.printf() is used to display formatted output. It allows
you to format strings, numbers, and other data types in a structured way. Here's
a quick guide with examples:
Syntax
Copy codeSystem.out.printf(String format, Object... args);
• format: A string containing text and format specifiers (e.g., %d, %s, etc.).
• args: The values to be formatted and inserted into the placeholders.
Common Format Specifiers
Specifier Description

%d Integer (decimal)

%f Floating-point number

%s String

%c Character

%n Newline (platform-independent)

Examples
1. Formatting Strings
System.out.printf("Hello, %s!%n", "World");
// Output: Hello, World!

2. Formatting Numbers
System.out.printf("Integer: %d, Float: %.2f%n", 42, 3.14159);
// Output: Integer: 42, Float: 3.14
3. Aligning Text
System.out.printf("Left: %-10s Right: %10s%n", "Java", "Code");
// Output: Left: Java Right: Code

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

4. Padding Numbers
System.out.printf("Padded: %05d%n", 42);
// Output: Padded: 00042
5. Displaying Percentages
System.out.printf("Success Rate: %.2f%%%n", 99.99);
// Output: Success Rate: 99.99%

Displaying Formatted Output with String.formate( )


In Java, the String.format() method is a powerful tool for creating
formatted strings. It allows you to format text, numbers, and other data types in
a structured way. Here's a concise explanation and example of how to use it:
Syntax
Copy codeString.format(String format, Object... args)
• format: A format string that specifies how the output should be
formatted.
• args: The arguments to be formatted and inserted into the format string.
Common Format Specifiers
• %d - Integer
• %f - Floating-point number
• %s - String
• %n - Newline
• %t - Date/Time
Example 1: Formatting Numbers
Copy codepublic class Main {
public static void main(String[] args) {
int number = 42;
double price = 1234.56789;

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

String formattedString = String.format("Number: %d, Price: %.2f",


number, price);
System.out.println(formattedString);
}
}
Output:
Copy codeNumber: 42, Price: 1234.57

Example 2: Aligning Text


Copy codepublic class Main {
public static void main(String[] args) {
String name = "Alice";
int age = 25;

String formattedString = String.format("Name: %-10s Age: %5d", name,


age);
System.out.println(formattedString);
}
}
Output:
Copy codeName: Alice Age: 25
• %-10s: Left-align the string in a 10-character width.
• %5d: Right-align the integer in a 5-character width.

Example 3: Formatting Date/Time


Copy codeimport java.util.Date;
public class Main {
public static void main(String[] args) {

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Date date = new Date();

String formattedDate = String.format("Current Date: %tD, Time: %tT",


date, date);
System.out.println(formattedDate);
}
}
Output:
Copy codeCurrent Date: 08/09/25, Time: 14:30:45
Key Notes
• String.format() does not print directly; it returns the formatted string.
• For direct output, you can use System.out.printf() which works similarly.
This method is versatile and helps in creating clean, readable, and well-
structured output.

Control Statements
Control statements in Java are the instructions that controls or manages
the flow of execution of a program based on specific conditions or loops.
Control Statements are used to:
o Make decisions: Control program flow based on conditions
(e.g., if, switch).
o Loop through blocks of code: Repeat code execution multiple
times (e.g., for, while).
o Jump to a different part of the code: Change the natural flow of
execution (e.g., break, continue).
Types of Control Statements in Java
1. Decision-making statements
2. Looping (Iteration) statements
3. Branching (Jump) statements

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Decision-making statements
Decision making statements allow you to make a decision, based upon
the result of a condition.
Types of Decision-Making Statements
• if
• if - else
• if-else-if ladder
1. if statement
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed or
not i.e. if a certain condition is true then a block of statements is executed
otherwise not.

Syntax
----------
if(condition) {
// Statements to execute if
// condition is true
}
Example :
class IfExample {
public static void main(String[] args) {

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

int x = 10;
int y = 12;
int sum = x+y;
if(sum > 20) {
System.out.println("sum is greater than 20");
}
}
}

Output
sum is greater than 20

2. Java if-else Statement


The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won't. But what if we want to do
something else if the condition is false? Here, comes the "else" statement. We
can use the else statement with the if statement to execute a block of code when
the condition is false.
Syntax

if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Example

public class Main {


public static void main(String[] args) {

int num = 20;


if(num < 10) {
System.out.println("num is less than 10");
} else {
System.out.println("num is greater than 20");
}
}
}

Output :
x + y is greater than 20

if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple
else-if statements. In other words, we can say that it is the chain of if-else
statements that create a decision tree where the program may enter in the block
Prepared by S. Dinesh, M.C.A Lect.in Computer Science
Unit - I

of code where the condition is true. We can also define an else statement at the
end of the chain.
Syntax :
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

Example
class Example {
public static void main(String args[])
{
int i = 20;
if (i == 10)

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

System.out.println("i is equal to 10");


else if (i == 15)
System.out.println("i is equal to 15");
else if (i == 20)
System.out.println("i is equal to 20");
else
System.out.println("i is not present");
}
}
Output
i is equal to 20

nested-if Statement
In nested if-statements, the if statement can contain a if or if-
else statement inside another if or else-if statement.
Syntax :
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Example

class ConditionExample {
public static void main(String args[])
{
int i = 10;
if (i == 10 || i < 15) {
if (i < 15)
if (i < 12)
System.out.println( "i is smaller than 12 too");
}
else {

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

System.out.println("i is greater than 15");


}
}
}

Output
i is greater than 15
i is smaller than 12 too
Java Switch Case
The switch statement is a multiway branch statement. It provides an easy
way to dispatch execution to different parts of code based on the value of the
expression.
Syntax:
witch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// more cases...
default:
// code to be executed if no cases match
}

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Example :
class SwitchExample {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Output :
2
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly
while some condition evaluates to true. However, loop statements are used to
execute the set of instructions in a repeated order. The execution of the set of
instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly.
1. for loop
2. while loop
3. do-while loop
Let's understand the loop statements one by one.
For Loop
In Java, for loop is similar to C and C++. It enables us to initialize the
loop variable, check the condition, and increment/decrement in a single line of
code. We use the for loop only when we exactly know the number of times, we
want to execute the block of code.
Syntax :
for(initialization, condition, increment/decrement) {
//block of statements
}

Example

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

public class ForExample {


public static void main(String[] args) {
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is :" + sum);
}
}
Output :
The sum of first 10 natural numbers is : 55
while loop
In Java, a while loop is used to repeatedly execute a block of code as long
as a specified condition evaluates to true. It is particularly useful when the
number of iterations is not known beforehand.
Syntax
while(condition){
//looping statements
}

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Example :
Public WhileExample {
public static void main(String[] args) {
int i = 1;
System.out.println("Printing the list of first 10 even numbers");
while(i<=5) {
System.out.println(“Well come to the world”);
i ++;
}
}
}
Output
Well come to the world
Well come to the world
Well come to the world
Well come to the world
Well come to the world
do-while loop
The do-while loop checks the condition at the end of the loop after
executing the loop statements. When the number of iteration is not known and
we have to execute the loop at least once, we can use do-while loop.
Syntax :
do
{
//statements
} while (condition);

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Example :
Class DoExample {
public static void main(String[] args) {
int i = 0;
System.out.println("Printing the list of first 10 even numbers ");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output :
Printing the list of first 10 even numbers
0
2
4
6

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

8
10
Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the
other part of the program. There are two types of jump statements in Java, i.e.,
break and continue.
Java break statement
As the name suggests, the break statement is used to break the current
flow of the program and transfer the control to the next statement outside a loop
or switch statement. However, it breaks only the inner loop in the case of the
nested loop.
The break statement cannot be used independently in the Java program, i.e., it
can only be written inside the loop or switch statement.

Example :

public class BreakExample {


public static void main(String[] args) {
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==4) {
break;
}
}
}
}

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Output :
0
1
2
3
4
Java continue statement
Unlike break statement, the continue statement doesn't break the loop, whereas,
it skips the specific part of the loop and jumps to the next iteration of the loop
immediately.
Example :
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue; // Skip the iteration when i equals 5
}
System.out.print(i + " ");
}
}
}
Output :
0
1
2
3
4
5

Prepared by S. Dinesh, M.C.A Lect.in Computer Science


Unit - I

Prepared by S. Dinesh, M.C.A Lect.in Computer Science

You might also like