Java Unit 1
Java Unit 1
UNIT I: Introduction to OOP, procedural programming language and object oriented language,
principles of OOP, applications of OOP, history of java, java features, JVM, program structure.
Variables, primitive data types, identifiers, literals, operators, expressions, precedence rules and
associativity, primitive type conversion and casting, flow of control.
Introduction to OOP:
The major motivating factor in the invention of object-oriented approach is to remove
drawbacks of procedural oriented approach.
OOP treats data as critical element in the program development and does not allow it
freely to flow around the system or application or program.
OOP combines the data and methods(functions) into a single unit this process is called
encapsulation.
The organisation of data and Methods(functions) in object-oriented programming is
shown in the following diagram.
OOP allows divide a problem into a no of entities called as objects and then build data
and Methods(functions) around these objects.
The data of an object can be accessed only by the method(function) associated with that
object.
In OOP, method(function) of one object can access the method(function) of other objects.
1
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Disadvantages:
1. Large programs are divided into smaller programs known as functions. These functions can
call one another. Hence security is not provided.
2. No importance is given to security of data and importance is given to doing things.
3. Data move openly around the system from function to function.
4. Most functions accesses global data, what happens to the data is not known.
4 In POP large program is divided into In OOP entire program is divided into
functions. objects.
5 Global data is shared among the Data is shared among the objects
functions in the program. through the methods.
6 Instead of focusing on data, POP focuses OOP mainly focuses on data security
on method or procedure. instead of focusing on method or
procedure.
7 POP does not support access modifiers. OOP supports access modifiers.
S.No. C Java
1 C is Procedure Oriented Programming Java is an Object-Oriented Programming
language language.
3
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
5 In C In Java
6 In C format specifiers are required to read In Java format specifiers are optional or
and print the data. not required to print or read the data.
7 C uses “#include <stdio.h>” header file for Java uses “import java.io.*;” for the
input and output oprations. same purpose.
8 In C all variables are declared at the In Java all variables are declared
starting of the scope. anywhere in the scope.
11 In C, malloc() and calloc() Functions are In Java, new is used for Memory
used for Memory Allocation and free() Allocation and Deallocation is done by
function for memory Deallocating. the JVM.
17 C does not support Exception handling and Java supports Exception handling and
Event handling. Event handling.
4
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
S. No C++ Java
1 C++ was developed by Bjarne Stroustrup Java was developed by James Gosling
in 1979. in 1995.
2 C++ is not a purely object oriented Java is purely an object oriented
language, since it is possible to write C++ language, since it is not possible to
programs without using a class or object. write java programs without using
atleast one class.
3 It is platform dependent. It is platform independent.
4 Uses compiler only Uses compiler and interpreter
5 C++ uses cin for input and cout for an Java uses the (System
output operation. class): System.in for input
and System.out for output.
6 It doesn‟t support documentation It supports documentation comments
comments for source code. (e.g., /**.. */) for source code.
7 C++ supports goto keyword. Java doesn‟t support goto Keyword
8 C++ supports Structures and Unions. Java doesn‟t support Structures and
Unions.
9 It has 63 keywords It has 50 keywords
10 Supports Multiple inheritance in C++. Doesn‟t support multiple inheritance in
java, but we can achieve this by
interfaces.
11 There are constructors and destructors in Only constructors are available in Java.
C++.
12 It supports call by value and call by It supports call by value only
reference
13 It supports both method and operator It supports only method overloading
overloading. and doesn‟t allow operator overloading.
14 It has Virtual Keyword It doesn‟t have Virtual Keyword.
15 It supports manual object management Automatic object management with
using new and delete. garbage collection.
16 Execution can be done by OS. Execution can be done by JVM.
17 C++ doesn't support >>> operator. Java supports >>> operator.
18 The extension of C++ program is “.cpp”. The extension of Java program is
5
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
“.java”
Basic Concepts (Key Concepts) / principles / features of Object-Oriented Programming:
Object-Oriented Programming is a methodology or paradigm to design a program using
classes and objects.
It simplifies the software development and maintenance by providing some concepts like:
Class
Object
Encapsulation & Data hiding
Inheritance
Polymorphism
Abstraction
Message Passing
Class:
Class is an abstract data type (user defined data type) / non-primitive data type that contains
attributes and methods that operate on data. It starts with the keyword class.
(or)
Class is a blueprint or template for creating an object.
(or)
An object is an entity that exists physically in the real world which requires some memory will
be called as an object.
Note: The recommended modifier for data members is private. The main advantage of data
hiding is security
Example 2:
class Account {
private double account_balance;
……..
…….
}
Inheritance:
7
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
It is a process of using the properties of one class inside other class is known as inheritance.
The main aim of Inheritance is Reusability of the data and methods i.e. data and methods
declared in one class can be accessed by other class.
In Inheritance, two classes are involved (super class/base class/parent class and sub
class/derived class/child class).
The class which gives the properties is called as super class / base class / parent class.
The class which takes the properties and methods is called as sub-class/derived class /child
class.
Base Class
Derived Class
Reusability: Using the already existing code is called as reusability. This is mostly used in
inheritance. The already existing code is inherited to the new class. It saves a lot of time and
effort. It also reduces the size of the program.
Polymorphism:
The word polymorphism is derived from two latin words poly(many) and morph (forms).
Polymorphism means the ability to take many forms. Polymorphism allows to take different
implementations for same name.
Poly -> many
Morph -> forms
ism -> behaviours
There are two types of polymorphism, Compile time polymorphism and Run time
polymorphism.
In Compile time polymorphism binding is done at compile time and in runtime polymorphism
binding is done at runtime.
e.g.: Method Overloading and Method Overriding
Method Overloading:
Method overloading is used for compile time polymorphism.
Same method name having different implementations with different number and type of
arguments.
Method Overriding:
Method overriding is used for runtime polymorphism
8
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
This communication is done with the help of methods (i.e., passing objects to methods)
Objects communicate with one another by sending and receiving information much the same
way as people pass messages to one another.
Message passing involves specifying the name of object, the name of the method (message) and
the information to be sent.
Example:
Advantages of OOP:
9
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Object oriented technology provides many advantages to the programmer and the user. This
technology solves many problems related to software development, provides improved quality
and low-cost software.
Applications of OOP:
History of java:
1. Java is an Object-Oriented Programming language, High level, Case Sensitive and
General purpose programming language.
2. JAVA was developed by James Gosling and his team at Sun Microsystems Inc in the
year 1991, later acquired by Oracle Corporation.
3. James Gosling is known as the father of Java.
4. Before Java, it was called Oak and was developed as a part of the Green project. Since
Oak was already a registered company, so James Gosling and his team changed the name
from Oak to Java In 1995.
5. Java is an island in Indonesia where the first coffee was produced (called Java coffee).
Java name was chosen by James Gosling while having a cup of coffee nearby his office.
6. Java is just a name, not an acronym.
1. Simple: Java is one of the simple languages as it does not have complex features like
pointers, operator overloading, multiple inheritances, and explicit memory allocation.
2. Object-Oriented: Java Supports OOP features like Class, Object, Encapsulation and
Data hiding, Abstraction, Inheritance, Polymorphism, Message Communication/ Message
Passing.
3. Portable: Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
4. Platform independent: 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 (WORA).
5. Secured: Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
No explicit pointer
The main features of java that make it robust are garbage collection, Exception Handling,
and memory allocation.
11
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
In C programming, int data type occupies 2 bytes of memory for 16-bit architecture and 4
bytes of memory for 32 and 64-bit architecture. However, it occupies 4 bytes of memory
for both 32 and 64-bit architectures in Java.
8. Compiled and Interpreted: Unlike other languages Java uses a system with both a
compiler and an interpreter for program execution. First, the compiler converts the
program code to bytecode which in turn is converted to machine code on any machine,
using the interpreter. The machine code thus generated can be executed irrespective of
the system on which it is being executed.
9. High Performance: Java architecture is defined in such a way that it reduces overhead
during the runtime and at some time java uses Just In Time (JIT) compiler where the
compiler compiles code on-demand basics where it only compiles those methods that are
called making applications to execute faster.
11. Distributed: We can create distributed applications using the java programming
language. Remote Method Invocation and Enterprise Java Beans are used for creating
distributed applications in java. The java programs can be easily distributed on one or
more systems that are connected to each other through an internet connection.
12. Dynamic: Java being completely object-oriented gives us the flexibility to add classes,
new methods to existing classes and even creating new classes through sub-classes. Java
even supports functions written in other languages such as C, C++ which are referred to
as native methods.
Applications of Java:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as irctc.co.in.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
12
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
8. Games, etc.
Java Versions:
Many java versions have been released till now. The current stable release of Java is Java SE 10.
Note: Since Java SE 8 release, the Oracle corporation follows a pattern in which every even
version is release in March month and an odd version released in September month.
14
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
1)
Class Loader
The class loader is a subsystem used for loading class files. It performs three major functions -
Loading, Linking, and Initialization.
2) Method Area
In the method area, all class level information like class name, immediate parent class name,
methods and variables information etc. are stored, including static variables. There is only one
method area per JVM, and it is a shared resource.
3) Heap
Information of all objects is stored in the heap area. There is also one Heap Area per JVM. It is
also a shared resource.
4) JVM language Stacks
Java language Stacks store local variables, and it‟s partial results. Each thread has its own JVM
stack, created simultaneously as the thread is created. A new frame is created whenever a method
is invoked, and it is deleted when method invocation process is complete.
5) PC Registers
PC register store the address of the Java virtual machine instruction which is currently executing.
6) Native Method Stacks
It contains all the native methods used in the application.
7) Execution Engine
15
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
It contains:
Interpreter: It interprets the bytecode line by line and then executes. The disadvantage here is
that when one method is called multiple times, every time interpretation is required.
Just-In-Time (JIT) compiler: It is used to increase the efficiency of an interpreter. It compiles
the entire bytecode and changes it to native code so whenever the interpreter sees repeated
method calls, JIT provides direct native code for that part so re-interpretation is not required,
thus efficiency is improved.
8) Native Method interface
It is an interface that interacts with the Native Method Libraries and provides the native
libraries (C, C++) required for the execution. It enables JVM to call C/C++ libraries and to be
called by C/C++ libraries which may be specific to hardware.
9) Native Method Libraries
Native Libraries is a collection of the Native Libraries (C, C++) which are needed by the
Execution Engine.
It is a class including a group of method declaration. It is used when multiple inheritances are
implementing.
Class definition
Classes are defining to make the objects of real-world problem. The number of classes used
depends on complexity of the program
Main method class:
It is the starting point and essential part of java programming while executing. It creates object of
various classes and established a communication between them.
Simple Java Program
public class Demo {
public static void main (String args[]) {
System.out.println("Welcome to Java Class");
}
}
Let us discuss the program line by line and understand the unique features that constitute a Java
program.
Class Declaration
The first line class Demo, class is a keyword used to declare the class. As we know Java is a
truly object-oriented language so everything must be placed inside a class. Demo is the identifier
in java that defines the name of the class.
Opening brace
Every class definition in java begins with an opening brace “{” and ends with a matching closing
brace “}”.
The Main Line:
public static void main (String args[])
Every Java program must include the main() method. Java applets does not use main() method.
This line contains a number of keywords public, static and void.
Public:
The keyword is an access modifier which represents visibility; it means it is accessible to all
other classes. This is similar to C++ public modifier.
Static:
Statics a keyword, if we declare any method as static, it is treated as static method. The static
method invoked without creating instance of a class. The main method is executed by the JVM,
so it doesn't require creating an object to call the main method. So, it saves memory.
void:
18
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
void means nothing. It is the return type. main method use void as it does not return any value.
String args[]:
main method accept some data from user as command line argument in form of String and this
can be achieved by String args[] array.
Identifiers in Java:
Identifiers in Java are symbolic names used for identification. They can be a class name, variable
name, method name, package name, constant name, and more.
Rules for Identifiers in Java
If the identifiers are not properly declared, we may get a compile-time error. Following are some
rules and conventions for declaring identifiers:
A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore
(_) or a dollar sign ($).
For example, @sample is not a valid identifier because it contains a special character
which is @.
There should not be any space in an identifier.
Example:
public class SampleProgram{
public static void main (String args[]) {
System.out.println("Welcome to Java Class");
}
}
Naming Conventions
Naming conventions specify the rules to be followed by a Java programmer while writing the
names of packages, classes, methods etc.
1. Package names are written in small letters.
e.g.: java.io, java.lang, java.awt etc
2. Each word of class name and interface name starts with a capital
e.g.: Sample, AddTwoNumbers
3. Method names start with small letters then each word start with a capital
e.g.: sum (), sumTwoNumbers (), minValue ()
20
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
A variable is a name given to a memory location that is used to store the value.
The value stored in a variable can be changed during program execution.
In Java, all the variables must be declared before use.
Variable Declaration:
Variable initialization:
}
}
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside any method,
constructor, or block.
As instance variables are declared in a class, these variables are created when an object of
the class is created and destroyed when the object is destroyed.
Use access specifier for instance variables. If we do not specify any access specifier, then
the default access specifier will be used.
Initialization of Instance Variable is not mandatory. Its default value is 0
Instance Variable can be accessed only by creating objects.
Example:
class Add{
int a=10, b=20; // Instance variables
public static void main(String[] args){
// Instance or object creation
Add ob = new Add();
3. Static Variables
Static variables are also known as Class variables.
These variables are declared similarly as instance variables. The difference is that static
variables are declared using the static keyword within a class outside any method
constructor or block.
Static variables are created at the start of program execution and destroyed automatically
when execution ends.
Initialization of Static Variable is not Mandatory. Its default value is 0
we can access the static variable like the Instance variable (through an object).
we can access the static variable with class name.
we can access the static variable without class name.
22
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Example:
class Add{
static int a=10, b=20; // static variables
public static void main(String[] args){
}
}
Instance Variables:
Instance Variables are declared without static keyword.
They are specific to object i.e., for every object, separate memory will be allocated for
each instance Variable.
They can be accessed only by using the Object.
Static Variables:
Static Variables are declared with static keyword.
They are also called as “Class Variables”.
They are not specific to any object.
The memory for static Variables will be allocated whenever the class is loaded in to the
memory i.e., memory will be allocated only once which will be shared by all the objects of
the class.
Data types in Java:
The type of value stored in a variable is called as datatype.
Ex: int a = 20;
char ch= „A‟;
Data types can be classified into two types in java
1. Primitive Data Types
23
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Note:
Except Boolean and char all remaining data types are considered as signed data types because we
can represent both “+ve” and”-ve” numbers.
1. Primitive Data Types:
There are 8 primitive data types supported by Java.
Primitive data types are predefined by the language and named by a key word.
A. byte:
Size: 1 Byte (8 bits)
Max-value: +127
Min-value: -128
Range: -128 to 127 [-27 to 27 -1]
Example:
byte b=10; ►✔
byte b2=130; ►C.E: possible loss of precision
byte b=10.5 ►C.E: possible loss of precision
byte b=true; ►C.E: incompatible types
byte b="REC"; ►C.E: incompatible types
24
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
byte data type is best suitable if we are handling data in terms of streams either from the
file or from the network.
B. short:
Size: 2 Bytes
Range: -32768 to 32767 (-215 to 215 -1)
Example:
short s=130; ►✔
short s=32768; ►C.E: possible loss of precision
short s=true; ►C.E: incompatible types
The most rarely used data type in java is short.
Short data type is best suitable for 16-bit processors like 8086 but these processors are
completely outdated and hence the corresponding short data type is also outdated data
type.
C. Int:
Size: 4 bytes
Range: -2147483648 to 2147483647 (-231 to 231 -1)
Example:
int i=130; ►✔
int i=10.5; ►C.E: possible loss of precision
int i=true; ►C.E: incompatible types
This is most commonly used data type in java.
D. long:
Size: 8 bytes
Range: -263 to 263 -1
Example:
long l= 13l;
To hold the no. Of characters present in a big file int may not enough hence the
return type of length() method is long.
long l=f.length() ; ►f is a file
Whenever int is not enough to hold big values then we should go for long data type.
Note:
All the above data types (byte, short, int and long) can be used to represent whole numbers. If we
want to represent real numbers then we should go for floating point data types.
25
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
for 2 bytes.
Summary of java primitive data types:
Literals in Java:
Literal: Any constant value which can be assigned to the variable is called literal/constant.
Example:
1. Integral Literals
Integral literals are specified in four different ways, as follows:
27
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Octal:
It has base eight and allows digits from 0 to 7. While assigning an octal literal in the Java code, a
number must have a prefix 0.
Hexadecimal:
It has base 16. Hexadecimal allows digits from 0 to 9, and characters from A to F. Even though
Java is case sensitive, and it also provides an exception for using either uppercase or lowercase
characters in the code for hexadecimal literals.
For example:
int x = 0X123Fadd;
int x = 0xFACE;
int x = 0xFace;
Binary:
It can be specified in binary literals, that is 0 and 1 with a prefix 0b or 0B.
For example: int x = 0b1011;
Note:
There is no direct way to specify byte and short literals explicitly. But whenever we are
assigning integral literal to the byte variables and its value within the range of byte compiler
automatically treats as byte literal. Similarly short literal also.
1. byte b=10; ►valid
2. byte b=130; ►Invalid ►C.E: possible loss of precision
3. short s=32767; ►valid
4. short s=32768; ►Invalid ►C.E: possible loss of precision
3.Char literals:
➤ A char literal can be represented as single character within single quotes.
Example:
1. char ch='a'; ►valid
2. char ch=a; ►Invalid ►C.E: cannot find symbol a
3. char ch="a"; ►Invalid ►C.E: incompatible types
4. char ch='ab'; ►Invalid ►C.E: unclosed character literal
➤ We can specify a char literal as integral literal which represents Unicode of that character. We
can specify that integral literal either in decimal or octal or hexadecimal form but allowed values
range is 0 to 65535.
Example:
1. char ch=97; ►valid
2. char ch=0xFace; ►valid
3. char ch=65536; ►Invalid ►C.E: possible loss of precision
➤ We can represent a char literal by Unicode representation which is nothing but „\uxxxx‟.
Example:
1. char ch1='\u0061';
System.out.println(ch1);
►Output: a
2. char ch2=\u0062; ►Invalid ►C.E: cannot find symbol
3. char ch3='\iface'; ►Invalid ►C.E: illegal escape character
➤ Every escape character in java acts as a char literal.
Example:
1. char ch='\n'; ►valid
2. char ch='\l'; ►Invalid ►C.E: illegal escape character
4. String literals:
➤ Any sequence of characters with in double quotes is treated as String literal.
Example:
String s="Raghu"; ►Valid
29
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
5. Boolean literals:
➤ The only allowed values for the boolean type are true (or) false where case is important.
Example:
1. boolean b=true; ►valid
2. boolean b=0; ►Invalid ►C.E: incompatible types
3. boolean b=True; ►Invalid ►C.E: cannot find symbol True
4. b="true"; ►Invalid ►C.E: incompatible types
6. Null Literals
➤ Null literal in Java representing a null value.
➤ Null often describe the uninitialized state in the program.
Operators in Java:
Operator in Java is a symbol that is used to perform operations on variables / operands /
constants.
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:
1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Unary Operators
7. Conditional Operator
8. Misc Operators
1. Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
The following table lists the arithmetic operators and Assume integer variable A holds 10 and
variable B holds 20, then
30
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Example Output
public class Test { a + b = 30
public static void main(String args[]) {
a - b = -10
int a = 10;
int b = 20; a * b = 200
int c = 25; b/a=2
System.out.println("a + b = " + (a + b));
System.out.println("a - b = " + (a - b)); b%a=0
System.out.println("a * b = " + (a * b)); c%a=5
System.out.println("b / a = " + (b / a));
System.out.println("b % a = " + (b % a));
System.out.println("c % a = " + (c % a));
}
}
2. Relational Operators
Relational operators are used to check the relationship between two operands.
The following table lists the Relational operators and Assume integer variable A holds 10 and
variable B holds 20, then
31
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Example Output
public class Test { a == b = false
a != b = true
public static void main(String args[]) { a > b = false
int a = 10; a < b = true
int b = 20; b >= a = true
b <= a = false
System.out.println("a == b = " + (a == b));
System.out.println("a != b = " + (a != b));
System.out.println("a > b = " + (a > b));
System.out.println("a < b = " + (a < b));
System.out.println("b >= a = " + (b >= a));
System.out.println("b <= a = " + (b <= a));
}
}
3. Bitwise Operators
Bitwise operators in Java are used to perform operations on individual bits.
The following table lists the bitwise operators and Assume integer variable A holds 60 and
variable B holds 13 then
32
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
33
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Example:
public class Test {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
34
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
4. Logical Operators:
Logical operators are used to check whether an expression is true or false. They are used in
decision making.
The following table lists the logical operators and Assume Boolean variables A holds true and
variable B holds false, then
Example: Output
public class Test {
a && b = false
public static void main(String args[]) {
a || b = true
boolean a = true;
!(a && b) = true
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b));
System.out.println(“! (a && b) = " +! (a && b));
}
}
35
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
5. Assignment Operators:
Assignment operators are used in Java to assign values to variables.
Following are the assignment operators supported by Java language.
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
Example:
public class Test {
c = a + b;
System.out.println("c = a + b = " + c);
c += a;
System.out.println("c += a = " + c);
c -= a; Output
System.out.println("c -= a = " + c);
c = a + b = 30
c *= a; c += a = 40
System.out.println("c *= a = " + c); c -= a = 30
c *= a = 300
a = 10; c /= a = 1
c = 15; c %= a = 5
c /= a;
System.out.println("c /= a = " + c);
a = 10;
c = 15;
c %= a;
System.out.println("c %= a = " + c);
}
}
36
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
6. Unary Operators
In Java, the unary operator is an operator that can be used only with an operand. It is used to
represent the positive or negative value, increment/decrement the value by 1,
and complement a Boolean value.
The following table describes the short description of the unary operators.
37
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
7. Conditional Operator:
The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making. In this operator, first, we verify a condition, then we
perform one operation out of the two operations based on the condition result. If the condition is
TRUE the first option is performed, if the condition is FALSE the second option is performed.
Syntax:
Example:
public class ConditionalOperator {
c = (a>b)? a : b;
Output:
38
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
c = 20
8. Misc Operators
Instanceof operator:
The java instanceof operator is used to test whether the object is an instanceof the specified
type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
Example:
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);
}
}
Output:
true
Expressions in Java:
An expression is a collection of operators and operands that represents a specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic
operations, logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can be a
direct value or variable or address of memory location.
Following are some of the examples for expressions in Java:
39
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Operator precedence determines which operator is performed first in an expression with more
than one operator with different precedence.
Example:
public class Precedence {
public static void main(String[] args) {
System.out.println(3 + 5 * 5);
System.out.println((3 + 5) * 5);
}
}
Output:
28
40
40
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Associativity:
Operators Associativity is used when two operators of same precedence appear in an expression.
Associativity can be either Left to Right or Right to Left.
For example: „*‟ and „/‟ have same precedence and their associativity is Left to Right
public class Precedence {
Output:
10
In the above expression, the operators / and * both belong to the same group in the operator
precedence table. So, we have to check the associativity rules for evaluating the above
expression. Associativity rule for / and * group is left-to-right i.e, evaluate the expression from
left to right. So, 10/5 is evaluated to 2 and then 2*5 is evaluated to 10.
41
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
2 Type conversion is only used with It can be used both compatible data type
compatible data types, and hence it and incompatible data type.
does not require any casting operator.
5 When converting one data type to When casting one data type to another,
another, the destination type should be the destination data type must be
greater than the source data type. smaller than the source data.
42
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
The control statements are used to control the order of execution according to our requirements.
Java provides several control statements, and they are classified as follows.
Types of Control Statements
In java, the control statements are classified as follows.
Selection Control Statements (Decision Making Statements)
Iterative Control Statements (Looping Statements)
Jump Statements
Selection Control Statements
In java, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be executed based
on a condition. Java provides the following selection statements.
if statement
if-else statement
if-else-if ladder statement
nested if statement
switch statement
43
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
if statement
The if statement checks, the given condition then decides the execution of a block of statements.
If the condition is True, then the block of statements is executed and if it is False, then the block
of statements is ignored.
Syntax:
if(condition){
//code to be executed
}
Example:
class IfStatement {
public static void main(String[] args) {
int number = 10;
if (number < 0) {
System.out.println("The number is negative.");
}
Output:
Statement outside if block
if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
class Main {
public static void main(String[] args) {
int number = 10;
if (number > 0)
System.out.println("The number is positive.");
else
System.out.println("The number is not positive.");
}
}
44
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Output:
The number is positive
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example:
public class IfElseIfExample {
public static void main(String[] args) {
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60){
System.out.println("D grade");
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
}
else if(marks>=80 && marks<90){
System.out.println("A grade");
}else if(marks>=90 && marks<100){
System.out.println("A+ grade");
}else{
System.out.println("Invalid!");
}
}
}
Output:
C grade
45
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
nested if statement
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:
Output:
You are eligible to donate blood
46
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Switch Statement
The switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement.
Points to Remember
Output:
20
1. Initialization: It is the initial condition which is executed once when the loop starts. Here,
we can initialize the variable, or we can use an already initialized variable. It is an optional
condition.
2. Condition: It is the second condition which is executed each time to test the condition of the
loop. It continues execution until the condition is false. It must return boolean value either
true or false. It is an optional condition.
3. Increment/Decrement: It increments or decrements the variable value. It is an optional
condition.
4. Statement: The statement of the loop is executed each time until the second condition is
false.
48
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
for-each loop
The Java for-each statement was introduced since Java 5.0 version.
It provides an approach to traverse through an array or collection in Java.
The for-each statement also known as enhanced for statement.
The for-each statement executes the block of statements for each element of the given array or
collection.
Syntax:
For
While
initialization
while (condition){
//code to be executed
Increment / decrement statement
}
Do-While
initialization
do{
//code to be executed / loop body
//update statement
}while (condition);
For-each Loop
49
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Examples:
ForExample.java Output:
//Java Program to demonstrate the example of for loop 1
public class ForExample { 2
public static void main(String[] args) { 3
4
//Code of Java for loop 5
for(int i=1;i<=10;i++){ 6
7
System.out.println(i);
8
} 9
} 10
}
//Java Program to demonstrate the example of While loop
WhileExample.java
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
//Java Program to demonstrate the example of Do-While loop
DoWhileExample.java
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
50
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Infinite Loop:
ForExample.java o/p
//Java program to demonstrate the use of infinite for loop Infinite Loop
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println("infinitive loop");
}
}
}
//Java program to demonstrate the use of infinite While loop
WhileExample.java
public class WhileExample2 {
public static void main(String[] args) {
// setting the infinite while loop by passing true to the condition
while(true){
System.out.println("infinitive loop");
}
}
}
//Java program to demonstrate the use of infinite Do-While loop
DoWhileExample2.java
public class DoWhileExample2 {
public static void main(String[] args) {
do{
System.out.println("infinitive loop");
}while(true);
}
}
51
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Example: PyramidExample.java
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
Output:
*
**
***
****
*****
Example: ForEachExample.java
//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output:
12
23
44
56
78
52
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Jump Statements
The java programming language supports jump statements that used to transfer execution control
from one line to another line. The java programming language provides the following jump
statements.
break statement
continue statement
labelled break and continue statements
break statement
The break statement in java is used to terminate a switch or looping statement. That means the
break statement is used to come out of a switch statement and a looping statement like while, do-
while, for, and for-each.
Example:
public class JavaBreakStatement {
for(int i : list) {
if(i == 30)
break;
System.out.println(i);
}
Output:
53
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
10
20
Continue Statement
The Java continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition. In case of an inner loop, it
continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-
while loop.
Example: ContinueExample.java
Output:
1
2
4
5
54
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Output:
11
12
13
21
55
RAGHU ENGINEERING COLLEGE (A) OOP Through Java
Example: LabeledForExample.java
//A Java program to demonstrate the use of labelled for loop using continue statement.
public class LabeledForExample {
public static void main(String[] args) {
//Using Label for outer and for loop
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
continue aa;
}
System.out.println(i+" "+j);
}
}
}
}
Output:
11
12
13
21
31
32
33
56