OOP Through Java Unit - 1
OOP Through Java Unit - 1
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.
Disadvantage of Conventional Programming:
• Traditional programming languages such as COBOL, FORTRAN, C etc. are commonly
known as procedure-oriented languages and also called as Conventional Languages.
• The program written in these languages consists of a sequence of instructions that tells the
compiler or interpreter to perform a given task.
• When a program code is large, it becomes inconvenient to manage and debug. To
overcome this problem, it is divided into smaller functions the carryout some specific task.
• Each function can call another function during the execution.
• As the functions are executing, they may access same data, and modify the data which in
turn effects the entire task.
• Most of the functions are allowed to access the global data.
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 functions Data is shared among the objects
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.
[Link]. C Java
1 C is Procedure Oriented Programming Java is an Object Oriented Programming
language language.
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 [Link].*;” for the same
input and output oprations. purpose.
8 In C all variables are declared at the starting In Java all variables are declared
of the scope. anywhere in the scope.
[Link] the time of first use.
9 C is a function-driven language. Java is an object-driven language
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.
S. No C++ Java
1 C++ was developed by Bjarne Stroustrup in Java was developed by James Gosling in
1979. 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 write
programs without using a class or object. 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): [Link] for input
and [Link] 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 and
overloading. 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 “.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.
Example 2:
class Account {
private double account_balance;
……..
…….
}
Inheritance:
➢ It is a process of using the properties and methods 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 properties and methods 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
➢ Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
e.g.: mouseClick()
Close button -> Window gets closed
Max button -> window gets maximised
Min button -> window gets minimized
Abstraction:
It is a process of Hiding internal details and showing functionality is known as abstraction.
They are divided into two types:
For example: Phone call, we don't know the internal processing.
Message Passing:
An object-oriented program contains a set of objects that communicate with one another. The
process of object-oriented programming contains the basic steps:
1. Creating classes
2. Creating objects
3. Establishing communication among objects
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:
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.
Features (Buzzwords) of Java:
Java has become a popular language because of the following features:
1. Simple: Java is one of the simple languages as it does not have complex features like
pointers, operator overloading, multiple inheritances, 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.
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 [Link].
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
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.
Java Platforms / Editions:
There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as [Link],
[Link], [Link], [Link], [Link], [Link] etc. It includes core topics like OOPs, String,
Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing,
Reflection, Collection, etc.
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 specifier 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:
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[]) {
[Link]("Welcome to Java Class");
}
}
From the above example, we have the following Java identifiers:
1. SampleProgram (Class name)
2. main (User defined method)
3. String (Predefined class name)
4. args (String variables)
5. System (Predefined class name)
6. out (Instance name)
7. println (Predefined method name)
Valid identifiers:
➢ TestVariable
➢ testvariable
➢ a
➢ i
➢ Test_Variable
➢ _testvariable
➢ $testvariable
➢ sum_of_array
➢ TESTVARIABLE
➢ TEST123
➢ Javatest123
Invalid identifiers:
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.: [Link], [Link], [Link] 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 ()
4. Variable names also follow the same above method rule
e.g.: sum, count, totalCount
5. Constants should be written using all capital letters
e.g.: PI, COUNT
6. Keywords are reserved words and are written in small letters.
e.g.: int, short, float, public, void
Variables:
➢ 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:
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.
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
2. Non-Primitive Data Types
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 [-2 7 to 2 7 -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
➢ 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 (-2 15 to 2 15 -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 (-2 31 to 2 31 -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: -2 to 2 63 -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=[Link]() ; ►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.
E. Floating Point Data types:
float double
If we want to 5 to 6 decimal places of If we want to 14 to 15 decimal places
accuracy then we should go for float. of accuracy then we should go for
double.
Size: Size:
4 bytes 8 bytes
Range: Range:
-3.4e38 to 3.4e38 -1.7e308 to1.7e308.
Literals in Java:
Literal: Any constant value which can be assigned to the variable is called literal/constant.
Example:
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
[Link] 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';
[Link](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
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.
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
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
[Link]("a + b = " + (a + b));
[Link]("a - b = " + (a - b)); b%a=0
[Link]("a * b = " + (a * b)); c%a=5
[Link]("b / a = " + (b / a));
[Link]("b % a = " + (b % a));
[Link]("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
Checks if the value of left operand is less than the value (A < B) is
< (less than)
of right operand, if yes then condition becomes true. true.
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
[Link]("a == b = " + (a == b));
[Link]("a != b = " + (a != b));
[Link]("a > b = " + (a > b));
[Link]("a < b = " + (a < b));
[Link]("b >= a = " + (b >= a));
[Link]("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
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 & b; /* 12 = 0000 1100 */
[Link]("a & b = " + c ); Output
c = a >> 2; /* 15 = 1111 */
[Link]("a >> 2 = " + c );
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
= 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;
[Link]("c = a + b = " + c);
c += a;
[Link]("c += a = " + c);
c -= a; Output
[Link]("c -= a = " + c);
c = a + b = 30
c *= a; c += a = 40
[Link]("c *= a = " + c); c -= a = 30
c *= a = 300
a = 10; c /= a = 1
c = 15; c %= a = 5
c /= a;
[Link]("c /= a = " + c);
a = 10;
c = 15;
c %= a;
[Link]("c %= a = " + c);
}
}
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.
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:
c = (a>b)? a : b;
Output:
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();
[Link](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:
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) {
[Link](3 + 5 * 5);
[Link]((3 + 5) * 5);
}
}
Output:
28
40
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.
Primitive type conversion and casting:
Difference Between Type Casting and Type Conversion
2 Type conversion is only used with It can be used both compatible data type
compatible data types, and hence it does and incompatible data type.
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 smaller
greater than the source data type. than the source data.
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
❖ 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) {
[Link]("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)
[Link]("The number is positive.");
else
[Link]("The number is not positive.");
}
}
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){
[Link]("fail");
}
else if(marks>=50 && marks<60){
[Link]("D grade");
}
else if(marks>=60 && marks<70){
[Link]("C grade");
}
else if(marks>=70 && marks<80){
[Link]("B grade");
}
else if(marks>=80 && marks<90){
[Link]("A grade");
}else if(marks>=90 && marks<100){
[Link]("A+ grade");
}else{
[Link]("Invalid!");
}
}
}
Output:
C grade
❖ 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
❖ 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.
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
[Link] Output:
//Java Program to demonstrate the example of for loop 1
public class ForExample { 2
3
public static void main(String[] args) {
4
//Code of Java for loop 5
for(int i=1;i<=10;i++){ 6
7
[Link](i);
8
} 9
} 10
}
//Java Program to demonstrate the example of While loop
[Link]
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
[Link](i);
i++;
}
}
}
//Java Program to demonstrate the example of Do-While loop
[Link]
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
[Link](i);
i++;
}while(i<=10);
}
}
Infinite Loop:
[Link] 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(;;){
[Link]("infinitive loop");
}
}
}
//Java program to demonstrate the use of infinite While loop
[Link]
public class WhileExample2 {
public static void main(String[] args) {
// setting the infinite while loop by passing true to the condition
while(true){
[Link]("infinitive loop");
}
}
}
//Java program to demonstrate the use of infinite Do-While loop
[Link]
public class DoWhileExample2 {
public static void main(String[] args) {
do{
[Link]("infinitive loop");
}while(true);
}
}
Nested for Loop
If we have a for loop inside another loop, it is known as nested for loop. The inner loop executes
completely whenever outer loop executes.
Example: [Link]
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
[Link]("* ");
}
[Link]();//new line
}
}
}
Output:
*
**
***
****
*****
Example: [Link]
//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){
[Link](i);
}
}
}
Output:
12
23
44
56
78
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;
[Link](i);
}
Output:
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: [Link]
Output:
1
2
4
5
❖ labelled break and continue statements
❖ The java programming language does not support goto statement, alternatively, the
break and continue statements can be used with label.
❖ The labelled break statement terminates the block with specified label.
❖ The labelled continue statement takes the execution control to the beginning of a loop
with specified label.
Example: [Link]
//A Java program to demonstrate the use of labelled for loop using break 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){
break aa;
}
[Link](i+" "+j);
}
}
}
}
Output:
11
12
13
21
Example: [Link]
//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;
}
[Link](i+" "+j);
}
}
}
}
Output:
11
12
13
21
31
32
33