OOp With Java-module1 Notes (1)
OOp With Java-module1 Notes (1)
BCS306A
JAVA
MODULE 1
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:
INTRODUCTION
• The Primitive Types (Integers, Floating-Point
TO Types, Characters, Booleans),
OBJECT • Variables,
• Type Conversion and Casting,
ORIENTED • Automatic Type Promotion in Expressions,
CONCEPTS • 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).
Dis-Advantage of POPS:
➢ Since every function has complete access to the global variables, the new programmer can
corrupt the data accidentally by creating function. Similarly, if new data is to be added, all the
function needed to be modified to access the data.
➢ POP doesn‟t support object programming features like – abstraction, Encapsulation,
Inheritance etc..,
Advantages
Class:
➢ A Class is a collection of objects (Members and member functions).
➢ Keyword is class.
➢ Class can contain fields, methods, constructors, and certain properties.
➢ Class acts like a blueprint.
➢ When defining class, it should starts with keyword class followed by name of the class;
and the class body, enclosed by a pair of curly braces.
Syntax: Example:
public class First
class <class_name> {
{ public static void main(String args[ ] )
// class Body {
System.out.println(“Hello”);
}
}
Object:
➢ Object is an instance of the class.
➢ Object is used to access members (variables) and member functions (methods).
Example :
public class First
{
public void display( ) //method
{
System.out.println(“EPCET”);
}
public static void main(String args[ ] )
{
First obj = new First( ) ; //create object
obj . display( ) ; //access display method using object obj
}
}
Output:
EPCET
For example, when you login to your face book account, you enter your user_id and password and
press login, what happens when you press login; how the input data sent to server, how it gets
verified is all abstracted away from you.
public class First
Example: {
public static void main(String args[ ] )
{
System.out.println(“My name is Ram”);
}
}
In the above example we are printing the message “My name is Ram” using println function but we
are not bothered about how println is working internally to display that message.
The Three OOP Principles:
1) Data Encapsulation
2) Inheritance
3) Polymorphism
Data Encapsulation:
➢ Wrapping (combining) of data and functions into a single unit (class) is known as data
encapsulation.
➢ Data is not accessible to the outside world, only those functions which are wrapped in the
class can access it.
➢ We can also call Information hiding.
➢ Java supports the properties of encapsulation and data hiding through the creation of
user-defined types, called classes.
Example: //I shown here only for private; similarly we can write for public and protected also.
class First
{
private int a=10;
} Output:
class Second extends First
{ a has private access in First
public static void main(String args[ ] ) System.out.println( obj.a ) ;
{
Second obj = new Second( );
System.out.println( obj.a ) ; 1 error
}
}
Example: Below example shows Second class can access values of a and b from Class One
class One
{
int a=10,b=20;
}
class Second extends One
{
public static void main(String[ ] args)
{
Second obj=new Second( );
System.out.println(obj.a + obj.b);
}
Output:
30
Polymorphism:
➢ Polymorphism means "many forms", and it occurs when we have many classes that are
related toeach other by inheritance.
➢ Polymorphism uses those methods to perform different tasks. This allows us to perform
a singleaction in different ways.
➢ Example: Method overloading (same method name but different action ) and method
overriding(same method name override in child class with different action)
Page 7
2024
//Method Overloading
class One
{
public void sum(int a,int b)
{
System.out.println(a+b);
} Output:
Introduction to JAVA:
JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995, later
acquired by Oracle Corporation.
History:
The history of Java is very interesting. Java was originally designed for interactive television,
but it was too advanced technology for the digital cable television industry at the time.
❖ James Gosling and his team Mike Sheridan, and Patrick Naughton initiated the Java
languageproject in June 1991. The small team of sun engineers called Green Team.
❖ Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
❖ After that, it was called Oak and was developed as a part of the Green project.
❖ In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Page 8
2024
❖ Java is an island in Indonesia where the first coffee was produced (called Java coffee).
Java name was chosen by James Gosling while having acup of coffee nearby his office.
Initially developed by James Gosling at Sun Microsystems and released in 1995.
JAVA Buzzwords:
Simple:
❖ Java was designed to be easy for the professional programmer to learn and use effectively.
❖ If you already understand the basic concepts of object-oriented programming, learning Java
will be even easier. Because Java inherits the C/C++ syntax.
Secure:
❖ Java is best known for its security. With Java, we can develop virus-free systems.
Java issecured because:
❖ No explicit pointer
❖ Java Programs run inside a virtual machine sandbox
❖ Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)
which isused to load Java classes into the Java Virtual Machine dynamically.
❖ Security Manager: It determines what resources a class can access such as
reading andwriting to the local disk.
Portable:
❖ Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn'trequire any implementation.
Object-Oriented:
❖ Java is an 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
incorporate both data and behavior.
Page 9
2024
❖ Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
❖ Object
❖ Class
❖ Inheritance
❖ Polymorphism
❖ Abstraction
❖ Encapsulation
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.
❖ Java provides a software-based platform.
❖ Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode.
This bytecode is a platform-independent code because it can be run on multiple platforms,
i.e., Write Once and Run Anywhere.
Robust:
The English mining of Robust is strong. Java is robust because:
❖ It uses strong memory management.
❖ There is a lack of pointers that avoids security problems.
❖ Java provides automatic garbage collection which runs on the Java Virtual Machine to
get ridof objects which are not being used by a Java application anymore.
❖ There are exception handling and the type checking mechanism in Java.
Multithreaded:
Java was designed to meet the real-world requirement of creating interactive, networked
programs. To accomplish this, Java supports multithreaded programming, which allows you to
write programs that domany things simultaneously.
Architectural Neutral/Machine Independent:
Page 10
2024
bytesof memory for 64-bit architecture. However, it occupies 4 bytes of memory for both
32 and 64- bit architectures in Java.
Distributed:
❖ Java is designed for the distributed environment of the Internet because it handles
TCP/IP protocols.
❖ In fact, accessing a resource using a URL is not much different from accessing a file. Java
also supports Remote Method Invocation (RMI).This feature enables a program to invoke
methods across a network.
Dynamic:
❖ Java is a dynamic language. It supports the 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).
Compiler
Byte-Code
.class file
Page 12
2024
Working:
1. First we will write the java code with .java extension using any editor Eclipse
IDE(Integrated DevelopmentEnvironment)
2. Then, compiler will convert the source file to Byte code with .class extension.
3. The Byte code then converts to Machine code by using Java Virtual Machine (JVM).
4. We can run this bytecode on any other platform as well. But the bytecode is a non-
runnable code thatrequires or relies on an interpreter. This is where JVM plays an
important part.
The main difference between the machine code and the bytecode is that the machine code is a set of
instructions in machine language or binary which can be directly executed by the CPU.
While the bytecode is a non-runnable code generated by compiling a source code that relies on
an interpreter to get executed
Page 13
2024
1. Install JDK , Set the JDK path in the system environmental variable location.
2. Write program using Notepad editor and save file name as class name with .java
extension (First.java)(Pretend we saving our java file in desktop)
3. Open command prompt , change the directory where the java file present.
C:\> cd desktop
4. Compile the java file using command –
C:\desktop> javac First .java
5. If any errors present compiler will show and programmer should clear those bugs.
6. Run the java file to see output using command
C:desktop> java First
JVM:
• A Java virtual machine (JVM) is an abstract computing machine that enables a computer
to run a Java program.
• A JVM implementation is a computer program that meets the requirements of the JVM
specification.
• An instance of a JVM is an implementation running in a process that executes a computer
program compiled into Java bytecode.
• A specification where working of Java Virtual Machine is specified.
• But the implementation provider is independent to choose the algorithm.
• Its implementation has been provided by sun and other companies. Its implementation is
known as JRE.
• JVMs are available for many hardware and software platforms that is JVM is platform
independent.
• The JVM performs following operation:
a. Loads code
b. Verifies code
c. Executes code
d. Provides runtime environment
Page 14
2024
Working:
➢ Save file name as First.java (should be same as class name)
➢ In the above program , first line shows the comment
➢ Single line comment starts with the symbol / /
➢ Multi line comment starts with /* and ends with */
➢ Next we used import statement to import an entire package or sometimes import certain
classes and interfaces inside the package. The import statement is written before the class
definition and after the package statement (if there is any). Also, the import statement is
optional.
import java.io.*;
import java.util.Scanner ;
➢ Class definition starts with keyword class followed by name
class First {
➢ The next line of code is shown here:
public static void main(String args[ ] ) {
➢ This line begins the main( ) method at which the program will begin executing.
➢ The public keyword is an access specifier, which allows the programmer to control
the visibility of class members.
➢ The keyword static allows main( ) to be called without having to create object
(instance of the class).
➢ The keyword void simply tells the compiler that main( ) does not return a value.
➢ In main( ), there is only one parameter, String args[ ] declares a parameter named
args, which is an array of instances of the class String. (Arrays are collections of
similar objects.) Objects of type String store character strings. In this case, args
receives any command-line arguments present when the program is executed.
➢ The last character on the line is the{. This signals the start of main( )‟s body.
Note: Our program may contain more than one class also but only one class contains main
method to get things started.
➢ The next line of code is shown here. Notice that it occurs inside main( ).
System.out.println("Welcome to EPCET ");
➢ This line outputs the string “Welcome to EPCET” followed by a new line on the screen.
Output is actually accomplished by the built-in println( ) method. In this case, println( )
Page 15
2024
displays the string which is passed to it. As you will see, println( ) can be used to display
other types of information, too. The line begins with
➢ System.out. Systemis a predefined class that provides access to the system, and
out is the output stream that is connected to the console.
➢ The first } in the program ends main( ), and the last } ends the First class definition.
Lexical issues:
Java programs are a collection of white space identifiers, comments, literals, operators, separators,
and keywords.
1) Whitespace:
Java is a free-form language. This means that you do not need to follow any special indentation rules.
Ex: The program could have been written all on one line or in any other strange way you felt like
typing it, as long as there was at least one whitespace character between each token.
Page 16
2024
In java, whitespace is a space, tab, or new line.
2) Identifiers:
Identifiers are used for class names, method names, and variable names. An identifier may be any
descriptive sequence of uppercase and lowercase letters, numbers or the underscore and dollar sign
characters.
3) Literals:
Left to right, the first literal specifies an integer, the next is a floating-point value, the third is a
character constant, and the last is a string. A literal can be used anywhere a value of its type is
allowed.
4) Comments:
1. Single line comments begin with the token // and end with a carriage return.
For example: //this is the single-line syntax.
Page 17
2024
2. Multi-Line comments begin with the token /* and end with the token */
For example: /* this is multiline syntax*/
3. Documentation comments used to produce an HTML file that documents your program.
The documentation comment begins with a /** and ends with a*/
5) Separators :
Separators help us defining the structure of a program.
In Java, There are few characters used as separators.
The most commonly used separator in java is a semicolon(;).
Used to define a block of code, for classes, methods and local scopes
{} Braces
Used to contain the value of automatically initialised array
[] Brackets declares array types and also used when dereferencing array values
Java Keywords:
Java has a set of keywords that are reserved words that cannot be used as variables, methods,
Dept of Page 18
CSE,EPCET
2024
classes, or any other identifiers:
Keyword Description
abstract A non-access modifier. Used for classes and methods: An abstract class cannot be used to
create objects (to access it, it must be inherited from another class). An abstract method
can only be used in an abstract class, and it does not have a body. The body is provided by
the subclass (inherited from)
boolean A data type that can only store true and false values
byte A data type that can store whole numbers from -128 and 127
Dept of Page 19
CSE,EPCET
2024
double A data type that can store whole numbers from 1.7e−308 to 1.7e+308
extends Extends a class (indicates that a class is inherited from another class)
final A non-access modifier used for classes, attributes and methods, which makes them non-
changeable (impossible to inherit or override)
finally Used with exceptions, a block of code that will be executed no matter if there is an
exception or not
float A data type that can store whole numbers from 3.4e−038 to 3.4e+038
int A data type that can store whole numbers from -2147483648 to 2147483647
Dept of Page 20
CSE,EPCET
2024
interface Used to declare a special type of class that only contains abstract methods
long A data type that can store whole numbers from -9223372036854775808 to
9223372036854775808
private An access modifier used for attributes, methods and constructors, making them only
accessible within the declared class
protected An access modifier used for attributes, methods and constructors, making them accessible
in the same package and subclasses
public An access modifier used for classes, attributes, methods and constructors, making them
accessible by any other class
return Finished the execution of a method, and can be used to return a value from a method
short A data type that can store whole numbers from -32768 to 32767
static A non-access modifier used for methods and attributes. Static methods/attributes can be
accessed without creating an object of a class
Dept of Page 21
CSE,EPCET
2024
this Refers to the current object in a method or constructor
Note: true, false, and null are not keywords, but they are literals and reserved words that cannot be used as
identifiers.
Dept of Page 22
CSE,EPCET
2024
A. 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.
• The Java run-time environment is free to use whatever size it wants, as long as
the types behave as you declared them.
➢ Byte –
• The smallest integer type is byte.
It is an (1 byte)8-bit signed integer. Its value-range lies between -128 to 127 (-28 to 28-1).
• Its minimum value is -128 and maximum value is 127. Its default value is 0.
• This is useful when you‟re working with binary data.
• It saves space because a byte is 4 times smaller than an integer. It can also be used in
place of "int" data type.
Example: byte a = 10,b= -20 ;
➢ Short-
• The short data type is a (2 bytes)16-bit signed integer. Its value-range lies between -
32,768 to 32,767 (-216 to 216-1). Its default value is 0.
• The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.
Example: short s=10000 , r=-5000;
➢ Int-
• The most commonly used integer type is int.
• The short data type is a (4 bytes)32-bit signed integer.
• Commonly used in control loops and to index the array.
Example: int a=10, i=0;
➢ Long
• The long data type is a 64-bit(8 bytes) integer. Its value-range liesbetween -264 to
264-1.
• Its default value is 0. The long data type is used when you need a range of values
morethan those provided by int.
Example: long a=100000L
Dept of Page 23
CSE,EPCET
2024
B. Floating-point numbers
• Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision.
• There are two kinds of floating-point types, float and double, which represent
single- and double-precision numbers, respectively.
Float
• float is a keyword.
• Size is 4 bytes (32 bits) and its value range lies between -232 to 232-1
Example: float a=10.6;
Double
• The double data type is a 64-bit floating point. Its value range is unlimited.
• The double data type is generally used for decimal values just like float.
Example: double a=10.6;
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);
}
}
Dept of Page 24
CSE,EPCET
2024
C. Characters
➢ char
• The char data type is used to store characters.
• The char data type is a single 16-bit Unicode (ASCII) character.
• The range of a char is 0 to 65,536. There are no negative chars.
• ASCII(American Standard Code for Information Interchange), a set of digital codes
representing letters, numerals, and other symbols, widely used as a standard format in
the transfer of text between computers.
• Example: char a=‟K‟; //K
char a=‟75‟; //75
char a=75; //K
Note: in the 3rd example above, 75 is not inside pair of single quotes so we will get answer as
ASCII code of that
class CharDemo {
public static void main(String args[]) { 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
D. Boolean
• Java has a primitive type, called boolean, for logical values. It can have only one of
two possible values, true or false.
• This is the type returned by all relational operators, as in the case of a < b.
• 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;
Dept of Page 25
CSE,EPCET
2024
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));
}
}
Output:
b is false
b is true
This is executed.
10 > 9 is true
Dept of Page 26
CSE,EPCET
2024
• But Java performs an automatic type conversion when storing a literal integer constant into variables of
type byte, short, long or char.
• Example :
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
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
Dept of Page 27
CSE,EPCET
2024
byte b;
B=(byte) a;
class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
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 10
• A different type of conversion will occur when a floating-point value is assigned to an
integer type called truncation.
Arrays:
Qp).How are arrays defined and used in Java? Explain with example.
• Definition: An array is a group of like-typed variables that are referred by a common
name.
• Arrays of any type can be created and may have one or more dimensions. A specific
element in an array is accessed by its index.
One dimensional array:
• It is a list of like typed variables.
• The general form of 1D array is:
type var_name[ ];
• The type declares the data type of the array i.e., it determines what type of data the array
will hold.
• The declaration establishes the fact that there is an array variable, but no array exits. The
value of the array is set to null i.e., an array with no value.
• To link the array name with an actual, physical array of integers, new keyword is used.
new is a special operator that allocates memory.
Dept of Page 28
CSE,EPCET
2024
• syntax to allocate memory for array:
array_var=new type[size];
The size specifies the number of elements in the array. The elements in the array allocated by
new will automatically be initialized to zero.
• Once the memory is allocated for an array, the specific elements in the array be accessed
by specifying its index within the square brackets.
• Example:
class array
{
public static void main(string args[])
{
int digits[ ];
int digits[ ]=new int[10];
for(int i=0;i<10;i++)
digits[i]=i;
System.out.println(“the digits are:”);
for(int i=0;i<10;i++)
System.out.println(i);
}
}
• It is possible to combine the declaration of the array variable with the allocation of the
array itself. There is no need to use new.
• Example:
class array
{
public static void main(string args[])
{
int digits[ ]={0,1,2,3,4,5,6,7,8,9};
System.out.println(“the digits are:”);
for(int i=0;i<10;i++)
System.out.println(i);
}
}
Multidimensional array:
• Multidimensional arrays are actually arrays of arrays. To declare a multidimensional
array variable, specify each additional index using another set of square brackets.
Dept of Page 29
CSE,EPCET
2024
• syntax:
type array_name=new type[row_size][col_size];
example: int a[ ][ ]=new a[2][2];
• Internally this matrix is implemented as an array of arrays of the specified type.
• When you allocate memory for multidimensional array, you need to only specify the
memory of the first (row) dimension. You can allocate the remaining dimensions separately.
• Example: 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();
}
}
}
Dept of Page 30
CSE,EPCET
2024
• This alternative declaration form offers convenience when declaring several arrays at the
same time.
• Example: int[ ] a, num1, num2;// create three arrays
• The alternative declaration form is also useful when specifying an array as a return type
for a method.
Variable:
❖ Variable is a name given to memory location to store data while java program executed.
❖ It is a combination of "vary + able" which means its value can be changed.
Types of Variables
➢ local variable
➢ instance variable
➢ static variable
Local Variable
➢ A variable declared inside the body of the method is called local variable.
➢ You can use this variable only within that method and the other methods in the class
aren't evenaware that the variable exists.
➢ A local variable cannot be defined with "static" keyword.
Instance Variable
➢ A variable declared inside the class but outside the body of the method, is called an
instancevariable. It is not declared as static.
➢ To access instance variable we need to create object of the class.
Static variable
➢ A variable that is declared as static is called a static variable. It cannot be local.
➢ To access static variable no need to create object of the class.
➢ You can create a single copy of the static variable and share it among all the
instances of theclass.
➢ Memory allocation for static variables happens only once when the class is loaded in the
memory.
Example: public class A
{
int data=50; //instance variable
static int m=100; //static variable
void demo( )
{
int n=90; //local variable
}
public static void main(String args[])
{
int b=20; //instance variable
}}
Dept of Page 31
CSE,EPCET
In the above example ,
➢ variable „data‟ is a instance variable because to access „data‟ variable we should create
object ofthe class.
➢ variable „m‟ is declared as static that means, we can access „m‟ anywhere without creating
object.
➢ variable „n‟ is a local variable that means variable „n‟ is visible(valid) only inside method
demo( )and we can‟t access in other methods.
Where,
❖ println( ) is used to display along with newline . We can also use just print( ) but without
newline.
❖ out is an instance of PrintStream type, which is a public and static member field of the System
class.
Read (Input):
❖ To Read value of a variable at compile time we will
use ,Example: int a =10,b=20;
❖ To Read value of a variable at Run time (from the keyboard ) we will use
Scanner classScanner:
➢ Scanner class in Java is found in the java.util package. Java provides various ways to
read
input from the keyboard, the java.util.Scanner class is one of them.
➢ The Java Scanner class provides nextXXX( ) methods to return the type of value such
as nextInt( ), nextByte( ), nextShort( ), next( ), nextLine( ), nextDouble( ), nextFloat(
), nextBoolean( ), etc.
➢ To get a single character from the scanner, you can call next( ).charAt(0) method
which returns a single character.
Example:
Scanner sc = new Scanner(System.in);
System.out.println(“Enter a name” );
String a = sc.next( ) ; //Read a String
System.out.println(“Enter value of n” );
int a = sc.nextInt( ) ; //Read an interger value
Page 32
System.out.println(“Enter percentage” );
float a = sc.nextFloat( ) ; //Read an floating point number
Operators:
❖ Arithmetic Operators
❖ Relational Operators
❖ Logical Operators
❖ Increment/Decrement Operators
❖ Assignment Operators
❖ Conditional Operators
❖ Bitwise Operators
Arithmetic Operators:
Operator used to perform arithmetic operations.
int a=10,b=5;
System.out.println(a+b); Output:
System.out.println(a-b); 15
System.out.println(a*b); 5
System.out.println(a/b); 50
System.out.println(a%b); 2
System.out.println(a+=1); 0
System.out.println(a-=1); 11
9
Page 33
Increment/Decrement operators:
These operators are used to increment /decrement a value of the variable by one.
Example:
Relational operators:
➢ operators used to find relationship between two operands are called relational operator.
➢ Relational operator result is either true or false
Operator Symbol Priority Example Result Associativity
Less than < 1 10 > 20 0 L-R
Greater than > 1 10 < 20 1 L-R
Lesser or Equal <= 1 10 <= 20 1 L-R
Greater orEqual >= 1 10 >= 20 0 L-R
Equal == 2 10 == 10 1 L-R
Not Equal != 2 10 != 10 0 L-R
Page 34
Logical operators:
➢ Operator used to combine 2 or more relational expressions are called logical operators.
➢ Logical operators are used in comparisons and results the boolean value either true or false.
Operator Description Example
&& This operator returns true if and only if boolean a=true,
(AND) both b=false;a && b //
operands are true otherwise, returns false. returns false
|| (OR) This operator returns true if and only if boolean a=true,
any b=false;a || b // returns
one of the operand is true otherwise, true
returnsfalse.
^ (XOR) This operator returns false if and only if boolean a=true,
bothoperands are either true or false b=true;a || b // returns
otherwise, false
returns true.
! (NOT) As this is unary operator it will returns boolean a=true;
true if !a //returns false
the operand is false and vise versa.
Assignment operators:
❖ Operator used to assign some values to the variables.
❖ This operator is used to assign some value present in the RHS side to LHS variable.
❖ Types:
➢ Simple Assignment: Assigning RHS value to LHS variable.
Example : C=a+b;
➢ Multiple Assignment: if more than one variable having same value then we
will prefermultiple assignment operator.
Example: C=D=a+b;
➢ Compound Assignemnt: if LHS variable name and RHS first operand name is
same thenwe will prefer compound assignemnt(+=, -=,*=,/=).
Example: a=a+b; can be rewrite as a += b;
C=C-b; can be rewrite as C -= b;
Conditional operator:
❖ It is also called ternary(three-way) operator.
❖ Symbol ? and :
➢ Syntax: (expression1)?expression2:expression3
expression3 is answer.
Page 35
Ex :(4>5)?4:5
Page 36
❖ Bit wise operators are used to manipulate the bits.
❖ When compared to logical operators, Bit-wise operators are not used for comparisons
rather these operators are used to manipulate the bits.
c→ 0100=4
Bitwise OR | This operator returns result true if and only if int a=5,b=6,c;
any one operand is true. c=a|b;
// 5→0101
6→0110
c→ 0111=7
Bitwise XOR ^ This operator returns result false if and only if int a=5,b=6,c;
either both operands are true or both operands c=a^b;
are false. // 5→0101
6→0110
c→ 0011=3
Bitwise ~ As this is unary operator, if operand is true then int a=6,c;
NOT result will be false and vise versa. c=~a;
// 6→0110
~6→ 1001=9
Left shift << Shift the user specified number of bits towards int a=6,c ;
left. c=a<<1;
// 6→ 0110
Shift 1 bit towards left side.
Output:1100=12
Right shift >> Shift the user specified number of bits towards int a=6,c ;
right. c=a>>1;
// 6→ 0110
Shift 1 bit towards right side.
Output:0011=3
Operator precedence :
The operator precedence represents how two expressions are bind together.
While solving an expression two things must be kept in mind the first is a precedence and the second
is associativity.
Precedence:
• Precedence is the priority for grouping different types of operators with their operands. It is
meaningful only if an expression has more than one operator with higher or lower precedence.
Page 37
• The operators having higher precedence are evaluated first.
• If we want to evaluate lower precedence operators first, we must group operands by using
parentheses and then evaluate.
Associativity:
We must follow associativity if an expression has more than two operators of the same precedence. In
such a case, an expression can be solved either left-to-right or right-to-left, accordingly.
Page 38
9 < Relational less than Left to right
<= Relational less than or equal
> Relational greater than
>= Relational greater than or equal
instance of Type comparison (objects only)
Control statements:
➢ Conditional statements
o Conditional Branch statements – if ,if-else,nested if , else-if ladder,switch.
o Conditional iterative(looping) statements – for , while, do-while.
➢ Unconditional statements
➢ break, continue
Page 39
statement.
Syntax: if expression is true then it will execute set of statements
if( expression )
{ statements; }
Example:
int a=5,b=3;if(a>b)
System.out.println(“a is Big:” +a); //output: a is Big:5
if else:
class First
{
public static void main( String s[ ] )
{
int n = 13;
if (n%2= = 0)
{
System.out.println(“even number”);
}
else
{
System.out.println (“odd number”);
}
}
}
Page 40
2023
else if ladder:
❖ This is a Multiway selection statement.
❖ That is more than one condition we can check at a time.
Nested if Statement:
“An if or if –else statements present within another if or if-else statement is called nested if
statement”.
Syntax: Example: to check largest of 3 numbers
if(a>b)
{
if(condition1) if(a>c)
{ {
if(condition 2) System.out.println (“a is big”);
{ }
Statements; }
} else if(b>c)
} {
System.out.println (“b is big”);
}
else
{
System.out.println (“c is big”);
}
Dept of Page 41
CSE,EPCET
2023
• nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming.
• When you nest if, the main thing to remember is that an else statement always refers to the
nearest if statement that is within the same block as the else and that is not already
associated with an else.
Switch statement:
❖ switch statement switch statement is used to make selection between many alternatives.
❖ Instead of else-if statement we are using switch to reduce program complexity.
Syntax: switch( choice)
{
case 1: statements;
break;
case 2: statements;
break;
…………………..
………………….
default : System.out.println(“give error message”);
}
➢ The switch statement works like this: The value of the expression is compared with each of
the literals values in the case statements.
➢ If a match is found, the code sequence following that case statement is executed.
➢ If none of the constants matches the value of the expression, then the default statement is
executed. However the default statement is optional. If no case matches and no default is
present, then no further action is taken.
➢ The break statement is used inside the switch to terminate sequence.
Dept of Page 42
CSE,EPCET
2023
Looping statements:
➢ while loop
➢ for loop
➢ do-while loop
Dept of Page 43
CSE,EPCET
2023
while loop:
➢ A set of statements may have to be repeatedly executed till the condition is true once the
condition becomesfalse control comes out of the loop.
➢ It is pre-test loop or top testing looping and hence condition testing occurs at the top.
Syntax:
initialization;
while(condition)
Statements;
increment / decrement ;
Example:
for loop:
❖ A set of statements may have to be repeatedly executed for specified number of time
or till thecondition satisfied.
❖ Once specified number of times loop executed, control comes out of the loop.
❖ This method is also top testing loop i.e condition is test at the top and body of the loop
executedonly if the condition is true.
Dept of Page 44
CSE,EPCET
2023
Qp)List and explain different versions of for loop. Write a java program to
search a for- each loop.
a. The traditional form of for loop:
Syntax: for(initialisation;condition;iteration)
{
//body
}
• The for loop operates as follows:
When the loop first starts, the initialization portion of the loop is executed. This expression sets
the value for the loop control variable, which acts as a counter that controls the loop. This is
executed only once.
Condition is evaluated. This must be a Boolean expression. It usually tests the loop control variable
against the target value. If this expression is true, then the body of the loop is executed. If it is
false, the loop terminates.
The iteration portion of the loop is executed. It is usually an expression that increments or
decrements the control variable.
The loop then iterates, first evaluating the condition and then executing the body of the loop, with
each pass. This process is repeated until the conditional expression is false.
• Example:
class ForDemo
{
Public static void main(String args[ ])
{
for(int i=1;i<=10;i++)
System.out.println(i);
}
}
Dept of Page 45
CSE,EPCET
2023
• To allow two or more variables to control a for loop, Java permits to include
multiple statements in both the initialization and iteration portions of the for.
• Each statement is separated from the next by a coma.
• EXAMPLE:
class Coma
{
public static void main(string args[])
{
int a,b;
for(a=1,b=4;a<b;a++,b--)
{
System.out.println(“a=”+a);
System.out.println(“b=”+b);
}
}
}
output:
a=1
b=4
a=2
b=3
c. Infinite loop:
• In this variation of for you can intentionally create an infinite loop.
• This is done by leaving all the three parts of the for empty.
• General form
for( ; ; )
{
//body
}
This loop will run forever because there is no condition under which it can terminate.
Although there are some programs, such as operating system, command processors, that require an
infinite loop, most ―infinite loops‖ are really just loops with some special termination requirements.
d. Similar to the while loop:
• This version of for loop is similar to the execution of the while loop. This is because
it has no initialization and iterative portion. The for statement has only the
conditional part, just as in a while loop.
Dept of Page 46
CSE,EPCET
2023
• General form:
for( ;conditionalexpn; ){
//body
}
• Example:
class loops
{
public static void main(string args[])
{
int i=1;
for(;i<=5;)
{
System.out.println(―i=‖+i);
i++;
}
}
}
output:
1
2
3
4
5
Dept of Page 47
CSE,EPCET
2023
public class Temp
{
public static void main(String[] args)
{
int a[]= {1,2,3,4,5,6};
for(int i:a)
System.out.println(i);
}
}
output
1
2
3
4
5
6
Examples:
• Example: linear search for the key element in the list using for-each
class LinearSearch
{
public static void main(string args[])
{
int nums[]={1,2,3,4};
int key=3;
for(int x:nums)
{
If(x==key)
System.out.println(“key element found in the list”); Exit(0);
}
System.out.println(“key element not found in the list”);
}
}
Dept of Page 48
CSE,EPCET
2023
//Java Program to print squares of a natural numbers.
package jk;
import java.util.Scanner;
public class Square
{
public static void main(String[] args) Output:
{
Enter the value of n
int n,sum,i;
System.out.println("enter the value of n"); 4
Scanner sc=new Scanner(System.in); Sum=30
n=sc.nextInt();
sum=0;
for(i=1;i<=n;i++)
{
sum=sum+i*i;
}
System.out.println("sum="+sum);
}
}
do while loop:
❖ do while loop is similar to while loop but condition is test at bottom.
❖ This loop is called post-testing or bottom- testing loop.
❖ As bottom testing loop , all the statements within body are executed at least
once .Syntax:
do
Statements;
}while(condition);
int n, sum,i;
System.out.println("enter the value of n");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
sum=0;
i=1;
do
while(i<=n) ;
ept of
System.out.println("sum="+sum);
DCSE,EPCET Page 48
2023
Qp) Discuss the break and continue statement. Write a java program to
compute reverse of a number and check whether it is palindrome or not.
• The three jump statements: break, continue and return.
• These statements transfer control to another part of your program.
a. BREAK
The break statements have three uses.
It terminates a statements sequence in a switch statement.
It can be use to exit a loop.
It can be used as a ―civilized form of goto.
Dept of Page 49
CSE,EPCET
2023
• General form: break label;
Where label is the name of label that identifies a block of code. When this form of block is executed,
control is transferred to the named block.
• Example:
Program to check whether a number is palindrome using labelled break.
import java.util.*;
class Palindrome
{
public static void main(string args[])
{
int num,digit=0,rev=0;
Scanner obj=new Scanner(System.in);
System.out.println(“Enter the number”):
num=obj.nextInt();
int num1=num;
back: digit =num%10;
num=num/10;
rev=rev*10+digit;
if(num>0)
break back;
System.out.println(“the reverse of the number is: “+rev);
if(num1==rev)
System.out.println(“Number is palindrome”);
else
System.out.println(“number is not palindrome”);
}
}
b. CONTINUE:
• A continue statement causes the immediate code to be bypassed.
• Example:
class continue{
public static void main(string args[])
{
for(i=1;i<=5;i++)
{
if (i= = 3) continue;
System.out.print (“\t”+i);
}
}
}
Dept of Page 50
CSE,EPCET
2023
Output:
1245
Return:
• Return is the control statement used to exit from a method, with or without a value.
• The return statement immediately terminates the method in which it is executed.
• It causes program control to transfer back to the caller of the method.
Note: the void keyword to specify that a method should not have a return value:
class return{
public static void main(string args[])
{
boolean t=true;
System.out.println(“before the return”);
If(t)
return;//return to caller
Local Variable Type Inference is one of the most evident change to language available from Java 10
onwards.
It allows to define a variable using var and without specifying the type of it.
The compiler infers the type of the variable using the value provided. This type inference is restricted
to local variables.
Now compiler infers the type of name variable as String by inspecting the value provided.
Page 51
2023
Program shows the use of Local Variable Type Inference
import java.util.List;
Julie
Robert
Chris
Joseph
Julie
Robert
Chris
Joseph
Page 52