Java OOP Concepts and Basics Guide
Java OOP Concepts and Basics Guide
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 1
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Why OOPs
• Used to breaking down large problems into sub-problems and solving them in separate units of
code
• Modularity for easier troubleshooting
• 2. Reuse of code through inheritance
• 3. Flexibility through polymorphism
• 4. Effective problem solving
Class
A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.
• Collection of objects is called class. It is a logical entity.
• A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 2
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Figure: Student
Figure: Person
Abstraction
• The abstraction is hiding the internal implementation and highlight the set of features offered.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 3
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Example: ATM
• Internal implementation – how each features work
• Features – Deposit, Withdraw, Balance enquiry
• Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details.
• The properties and behaviors of an object differentiate it from other objects of similar
type and also help in classifying/grouping the objects.
• Consider a real-life example of a man driving a car.
• The man only knows that pressing the accelerators will increase the speed of a car or
applying brakes will stop the car, but he does not know about how on pressing the
accelerator the speed is actually increasing, he does not know about the inner
mechanism of the car or the implementation of the accelerator, brakes, etc in the car.
This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
Figure: Abstraction
Encapsulation
• The process of binding of data and method together as a single unit
• The process of grouping of data members and corresponding methods into single unit
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 4
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Data members →string name, int age, int rollno, int marks
Methods→read(), write()
Example 1:
class student
{
string name;
int age;
int rollno;
int marks;
}
read()
{
}
write()
{
}
Any component following data hiding and abstraction is called encapsulation
Example 2:
Class account
{
private double balance;
{
}
public double getbalance()
{
return balance;
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 5
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
}
public void setbalance(double amount)
{
[Link] = [Link] + amount;
}
NOTE:
• End user doesnot know the functionality, but the end user can perform withdraw and
deposit
• Through getbalance() and setbalance(), the data must be provided
• Both are interface for outside person, hiding data behind methods
Advantages
• Security
• Enhancement
• Maintainability
• Modularity
Disadvantages
• Increase the length of the code
• Slow down the execution
• Validation must be required- lengthy process
Example: For transferring funds→ user name + Password + card no + OTP
This programming paradigm emphasizes on the use of This programming paradigm is based on object
functions where each function performs a specific oriented concept. Classes are used where
task. instance of objects are created
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 6
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
No data hiding is possible. Hence, Security is not Provides data hiding. Hence, secured programs
possible. are possible.
3. Characteristics of Java
a. Platform Independent
• Java is compiled, it is not compiled into platform specific machine, rather into platform-
independent byte code.
• This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.
b. Simple
Java is designed to be easy to learn.
c. Secure
• Java enables to develop virus-free, tamper-free systems.
• Authentication techniques are based on public-key encryption.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 7
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
d. Architecture-neutral
• Java compiler generates an architecture-neutral object file format, which makes the compiled
code executable on many processors, with the presence of Java runtime system.
e. Portable
Being architecture-neutral and having no implementation dependent aspects of the specification makes
Java portable.
The compiler in Java is written in ANSI C with a clean portability boundary
f. Robust
• Java makes an effort to eliminate error-prone situations by emphasizing mainly on compile time
error checking and runtime checking.
g. Multithreaded
• Possible to write programs that can perform many tasks simultaneously.
• This design feature allows the developers to construct interactive applications that can run
smoothly.
h. Interpreted
• Java byte code is translated on the fly to native machine instructions and is not stored anywhere.
• The development process is more rapid and analytical since the linking is an incremental and
light-weight process.
i. High Performance
• With the use of Just-In-Time compilers, Java enables high performance.
j. Distributed
• Java is designed for the distributed environment of the internet.
k. Dynamic
• Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving
environment.
• Java programs can carry an extensive amount of run-time information that can be used to verify
and resolve accesses to objects at run-time.
JAVA Environment –JVM and JDK
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 8
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
be executed. It can also run those programs which are written in other languages and compiled to Java
bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform
dependent because the configuration of each OS is different from each other. However, Java is platform
independent. There are three notions of the JVM: specification, implementation, and instance.
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to
provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set
of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro Systems.
JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically exists.
It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
o Standard Edition Java Platform
o Enterprise Edition Java Platform
o Micro Edition Java Platform
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 9
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc.
to complete the development of a Java Application.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 10
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Documentation Section
• The documentation section is an important section but optional for a Java program.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 11
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
• It includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program.
• It improves the readability of the program. Whatever we write in the documentation section, the
Java compiler ignores the statements during the execution of the program.
• To write the statements in the documentation section, we use comments.
Package Declaration
• The package declaration is optional. It is placed just after the documentation section.
• There can be only one package statement in a Java program.
• It must be defined before any class and interface declaration.
• It is necessary because a Java class can be placed in different packages and directories based on
the module they are used.
• Classes package belongs to a single parent directory.
Import Statements
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 12
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
• import statement in two ways, either import a specific class or import all classes of a particular
package.
• In a Java program, we can use multiple import statements. For example:
import [Link]; //it imports the Scanner class only
import [Link].*; //it imports all the class of the [Link] package
Interface Section
• It is an optional section.
• An interface in this section if required.
• interface keyword to create an interface.
• An interface is a slightly different from the class.
• It contains only constants and method declarations.
• Another difference is that it cannot be instantiated.
• interface in classes by using the implements keyword.
• An interface can also be used with other interfaces by using the extends keyword. For example
interface car
{
void start();
void stop();
}
Class Definition
• In this section, we define the class.
• It is vital part of a Java program.
• Without the class, we cannot create any Java program.
• A Java program may conation more than one class definition.
• The class keyword to define the class.
• The class is a blueprint of a Java program.
• It contains information about user-defined methods, variables, and constants.
• Every Java program has at least one class that contains the main() method. For example:
class Student //class definition
{
}
Class Variables and Constants
• Define variables and constants that are to be used later in the program.
• Java program, the variables and constants are defined just after the class definition.
• The variables and constants store values of the parameters.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 13
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
For example:
public class Student //class definition
{
public static void main(String args[])
{
//statements
}
}
Methods and behavior
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 14
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
[Link]("Welcome to javatpoint");
}
//statements
}
}
[Link]
/*Program name: Palindrome*/
//Author's name: Mathew
/*Palindrome is number or string that will remains the same
When we write that in reverse order. Some example of
palindrome is 393, 010, madam, etc.*/
//imports the Scanner class of the [Link] package
import [Link];
//class definition
public class CheckPalindromeNumber
{
//main method
public static void main(String args[])
{
//variables to be used in program
int r, s=0, temp;
int x; //It is the number variable to be checked for palindrome
Scanner sc=new Scanner([Link]);
[Link]("Enter the number to check: ");
//reading a number from the user
x=[Link]();
//logic to check if the number id palindrome or not
temp=x;
while(x>0)
{
r=x%10; //finds remainder
s=(s*10)+r;
x=x/10;
}
if(temp==s)
[Link]("The given number is palindrome.");
else
[Link]("The given number is not palindrome.");
}
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 15
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
}
OUTPUT
Constructors in Java
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 16
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of obje
creation.
//Java Program to create and call a default constructor
class Bike1{
//creating a default constructor
Bike1()
{
[Link]("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
Q)
What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object like 0, null, etc., depending
on the type.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 17
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
The parameterized constructor is used to provide different values to distinct objects. However, you can
provide the same values also.
In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.
/Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 18
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
id = i;
name = n;
}
//method to display the values
void display(){[Link](id+" "+name);}
7. Method in Java
A method is a way to perform some task. Similarly, the method in Java is a collection of instructions
that performs a specific task.
Method in Java
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 19
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Method Declaration
• The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments.
• It has six components that are known as method header
Method Signature
• Every method has a method signature. It is a part of the method declaration. It includes
the method name and parameter list.
Return Type:
Method Name:
Parameter List:
• It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
• It contains the data type and variable name.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 20
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Method Body:
Naming a Method
• While defining a method, remember that the method name must be a verb and start with
a lowercase letter.
• If the method name has more than two words, the first name must be a verb followed by
adjective or noun.
• In the multi-word method name, the first letter of each word must be in uppercase except the
first word.
• For example:
1. Predefined Method
• Predefined methods are the method that is already defined in the Java class libraries is known
as predefined methods.
• It is also known as the standard library method or built-in method.
• Directly use these methods just by calling them in the program at any point.
• Pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
• When we call any of the predefined methods in our program, a series of codes related to the
corresponding method runs in the background that is already stored in the library.
• Each and every predefined method is defined inside a class. Such as
o print() method is defined in the [Link] class. It prints the statement that
we write inside the method. For example, print("Java"), it prints Java on the console.
[Link]
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 21
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Output:
The maximum number is: 9
2. User-defined Method
• User defined method that checks the number is even or odd. First,define the method.
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
}
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 22
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
[Link]
import [Link];
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
//reading value from user
int num=[Link]();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
}
}
Output 1:
Enter the number: 12
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 23
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
12 is even
Output 2:
Enter the number: 99
99 is odd
9. Static members
• Static members are those which belongs to the class and you can access these members without
instantiating the class.
• The static keyword can be used with methods, fields, classes (inner/nested), and blocks.
Static Methods
• Create a static method by using the keyword static.
• Static methods can access only static fields, methods.
• To access static methods there is no need to instantiate the class, you can do it just using the
class name as −
Example
public class MyClass {
public static void sample(){
[Link]("Hello");
}
public static void main(String args[]){
[Link]();
}
}
Output : Hello
Static Fields
• Create a static field by using the keyword static.
• The static fields have the same value in all the instances of the class.
• These are created and initialized when the class is loaded for the first time.
• Just like static methods you can access static fields using the class name (without instantiation).
Example
public class MyClass {
public static int data = 20;
public static void main(String args[]){
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 24
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
[Link]([Link]);
}
Java Arrays with Answers
27
}
Output: 20
Static Blocks
• These are a block of codes with a static keyword.
• These are used to initialize the static members.
• JVM executes static blocks before the main method at the time of class loading.
Example
public class MyClass {
static{
[Link]("Hello this is a static block");
}
public static void main(String args[]){
[Link]("This is main method");
}
}
Output
Hello this is a static block
This is main method
Data types specify the different sizes and values that can be stored in the variable. There are two types
of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 25
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 26
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
2. Byte type
• The byte data type can have values from -128 to 127 (8-bit signed two's complement integer).
• If it's certain that the value of a variable will be within -128 to 127, then it is used instead of int
to save memory.
• Default value: 0
Example 2: Java byte data type
class Main {
public static void main(String[] args) {
byte range;
range = 124;
[Link](range); // prints 124
}
}
3. Short type
• The short data type in Java can have values from -32768 to 32767 (16-bit signed two's
complement integer).
• The value of a variable will be within -32768 and 32767, then it is used instead of other integer
data types (int, long).
• Default value: 0
Example 3: Java short data type
class Main {
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 27
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
short temperature;
temperature = -200;
[Link](temperature); // prints -200
}
}
4. Int type
• The int data type can have values from -231 to 231-1 (32-bit signed two's complement integer).
• If you are using Java 8 or later, you can use an unsigned 32-bit integer. This will have a
minimum value of 0 and a maximum value of 232-1. Default value: 0
Example 4: Java int data type
class Main {
public static void main(String[] args) {
5. Long type
• The long data type can have values from -263 to 263-1 (64-bit signed two's complement
integer).
• If you are using Java 8 or later, you can use an unsigned 64-bit integer with a minimum value
of 0 and a maximum value of 264-1.
• Default value: 0
Example 5: Java long data type
class LongExample {
public static void main(String[] args) {
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 28
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
}
}
Note: The use of L at the end of -42332200000. This represents that it's an integer of the long type.
6. Double type
• The double data type is a double-precision 64-bit floating-point.
• It should never be used for precise values such as currency.
• Default value: 0.0 (0.0d)
Example 6: Java double data type
class Main {
public static void main(String[] args) {
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 29
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
• The minimum value of the char data type is '\u0000' (0) and the maximum value of the is '\uffff'.
• Default value: '\u0000'
• Example 8: Java char data type
class Main {
public static void main(String[] args) {
char letter = '\u0051';
[Link](letter); // prints Q
}
2. String: A string represents a sequence of characters like India, ABC123, etc. The simplest way to
create a string object is by storing sequence of characters into string type variable like this:
Here, string type variable str contains “Universe”. A string is also a class. For more details: String in
Java.
3. Array: An array in java is an object which is used to store multiple variables of the same type. These
variables can be primitive or non-primitive data types.
The example of declaring an array variable of primitive data type int is as follows:
int [ ] scores;
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 30
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
11. Variable
Types of Variables
• local variable
• instance variable
• static variable
1) Local Variable
• A variable declared inside the body of the method is called local variable.
• Use this variable only within that method and the other methods in the class aren't even aware
that the variable exists.
• A local variable cannot be defined with "static" keyword.
2) Instance Variable
• A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 31
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
• It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
• A variable that is declared as static is called a static variable.
• It cannot be local.
• Create a single copy of the static variable and share it among all the instances of the class.
• Memory allocation for static variables happens only once when the class is loaded in the
memory.
Example to understand the types of variables in java
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
} }//end of class
Java Variable Example: Add Two Numbers
public class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
[Link](c);
} }
Output:
20
Java Variable Example: Widening
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 32
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
• Arithmetic Operator
• Assignment Operator
• Relational Operator
• Logical Operator
• Unary Operator
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 33
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
• Bitwise Operator
• Ternary Operator
1) Java Arithmetic Operators
• Arithmetic operators are used to perform arithmetic operations on variables and data.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)
Example : Arithmetic Operators
class Main {
public static void main(String[] args) {
// declare variables Output
int a = 12, b = 5;
a + b = 17
// addition operator a-b=7
[Link]("a + b = " + (a + b)); a * b = 60
// subtraction operator a/b=2
a%b=2
[Link]("a - b = " + (a - b));
// multiplication operator
[Link]("a * b = " + (a * b));
// division operator
[Link]("a / b = " + (a / b));
// modulo operator
[Link]("a % b = " + (a % b));
}}
2. Java Assignment Operators
• Assignment operators are used in Java to assign values to variables.
For example,
int age;
age = 5;
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 34
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Here, = is the assignment operator. It assigns the value on its right to the variable on its left. That is, 5
is assigned to the variable age.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 35
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 36
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 37
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Working of Program
(5 > 3) && (8 > 5) returns true because both (5 > 3) and (8 > 5) are true.
(5 > 3) && (8 < 5) returns false because the expression (8 < 5) is false.
(5 < 3) || (8 > 5) returns true because the expression (8 > 5) is true.
(5 > 3) && (8 > 5) returns true because the expression (5 > 3) is true.
(5 > 3) && (8 > 5) returns false because both (5 < 3) and (8 < 5) are false.
!(5 == 3) returns true because 5 == 3 is false.
!(5 > 3) returns false because 5 > 3 is true.
int num = 5;
// increase num by 1
++num;
The value of num gets increased to 6 from its initial value of 5.
Example 5: Increment and Decrement Operators
class Main {
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 38
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Value of a: 12
After increment: 13
Value of b: 12
After decrement: 11
• In the above program, we have used the ++ and -- operator as prefixes (++a, --b). We can also
use these operators as postfix (a++, b++).
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 39
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Operator Description
~ Bitwise Complement
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
& Bitwise AND
^ Bitwise exclusive OR
These operators are not generally used in Java. To learn more, visit Java Bitwise and Bit Shift
Operators.
Other operators
• Besides these operators, there are other additional operators in Java.
• Java instanceof Operator
• The instanceof operator checks whether an object is an instanceof a particular class. For
example,
class Main {
public static void main(String[] args) {
String str = "Programiz";
boolean result;
// checks if str is an instance of
// the String class
result = str instanceof String;
[Link]("Is str an object of String? " + result);
}
}
Output
• Is str an object of String? true
• Here, str is an instance of the String class. Hence, the instanceof operator returns true.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 40
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
class Java {
public static void main(String[] args) {
int februaryDays = 29;
String result;
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
[Link](result);
}
}
Output
• Leap year
• In the above example, we have used the ternary operator to check if the year is a leap year or
not. To learn more, visit the Java ternary operator.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 41
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
1. Decision-Making statements:
• Decision-making statements decide which statement to execute and when.
• Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided.
• There are two types of decision-making statements in Java
• If statement
• Switch statement.
a) If Statement
• The "if" statement is used to evaluate a condition.
• The control of the program is diverted depending upon the specific condition.
• The condition of the If statement gives a Boolean value, either true or false.
• There are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
• It evaluates a Boolean expression and enables the program to enter a block of code if the
expression evaluates to true.
Syntax of if statement is given below.
if(condition)
{
statement 1; //executes when condition is true
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 42
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
}
Consider the following example in which we have used the if statement in the java code.
[Link]
[Link]
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
[Link]("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
2) if-else statement
• The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block.
• The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Consider the following example.
[Link]
public class Student {
public static void main(String[] args) {
int x = 10;
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 43
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
int y = 12;
if(x+y < 10) {
[Link]("x + y is less than 10");
} else {
[Link]("x + y is greater than 20");
} } }
Output:
x + y is greater than 20
3) if-else-if ladder:
• The if-else-if statement contains the if-statement followed by multiple else-if statements.
• The chain of if-else statements that create a decision tree where the program may enter in the
block of code where the condition is true.
• Also,define an else statement at the end of the chain.
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Consider the following example.
[Link]
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
[Link]("city is meerut");
}else if (city == "Noida") {
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 44
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
[Link]("city is noida");
}else if(city == "Agra") {
[Link]("city is agra");
}else {
[Link](city);
} } }
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.
Syntax of Nested if-statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
[Link]
public class Student {
public static void main(String[] args) {
String address = "Delhi, India";
if([Link]("India")) {
if([Link]("Meerut")) {
[Link]("Your city is Meerut");
}else if([Link]("Noida")) {
[Link]("Your city is Noida");
}else {
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 45
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
[Link]([Link](",")[0]);
}
}else {
[Link]("You are not living in India");
} } }
Output:
Delhi
b)Switch Statement:
• Switch statements are similar to if-else-if statements.
• The switch statement contains multiple blocks of code called cases and a single case is
executed based on the variable which is being switched.
• The switch statement is easier to use instead of if-else-if statements. It also enhances the
readability of the program.
Points to be noted about switch statement:
• The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
• Cases cannot be duplicate
• Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
• Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
• While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
switch (expression){
case value1:
statement1;
break;
.
.
.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 46
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
[Link]
public class Student implements Cloneable {
public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
[Link]("number is 0");
break;
case 1:
[Link]("number is 1");
break;
default:
[Link](num);
}
}
}
Output:
2
Example:
Java Program to Make a Simple Calculator Using switch...case
CODE:
import [Link];
class Main {
public static void main(String[] args) {
char operator;
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 47
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 48
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
default:
[Link]("Invalid operator!");
break;
} }}
• While using switch statements, we must notice that the case expression will be of the same
type as the variable.
• It will also be a constant value.
• The switch permits only int, string, and Enum type variables to be used.
b) Loop Statements
• To execute the block of code repeatedly while some condition evaluates to true.
• Loop statements are used to execute the set of instructions in a repeated order.
• The execution of the set of instructions depends upon a particular condition.
• Three types of loops that execute similarly. However, there are differences in their syntax and
condition checking time.
1. for loop
2. while loop
3. do-while loop
1. for loop
• To check the condition, and increment/decrement in a single line of code.
• Use for loop only when we exactly know the number of times, we want to execute the block
of code.
for(initialization, condition, increment/decrement) {
//block of statements
}
The flow chart for the for-loop is given below.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 49
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Consider the following example to understand the proper functioning of the for loop in java.
[Link]
public class Calculattion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
[Link]("The sum of first 10 natural numbers is " + sum);
}
}
Output:
The sum of first 10 natural numbers is 55
• Java provides an enhanced for loop to traverse the data structures like array or collection.
• for-each loop, we don't need to update the loop variable.
• The syntax to use the for-each loop in java is given below.
for(data_type var : array_name/collection_name){
//statements
}
Consider the following example to understand the functioning of the for-each loop in Java.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 50
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
[Link]
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
[Link]("Printing the content of the array names:\n");
for(String name:names) {
[Link](name);
}
}
}
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
2. While loop
• The while loop is also used to iterate over the number of statements multiple times.
• If we don't know the number of iterations in advance, it is recommended to use a while loop.
• The initialization and increment/decrement doesn't take place inside the loop statement in
while loop.
• It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
The syntax of the while loop is given below.
1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 51
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
3. do-while loop
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 52
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
• The do-while loop checks the condition at the end of the loop after executing the loop
statements.
• When the number of iteration is not known and we have to execute the loop at least once, we
can use do-while loop.
• It is also known as the exit-controlled loop since the condition is not checked in advance.
• The syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Consider the following example to understand the functioning of the do-while loop in Java.
[Link]
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
[Link]("Printing the list of first 10 even numbers \n");
do {
[Link](i);
i = i + 2;
}while(i<=10);
}
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 53
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
[Link] Statements
• Jump statements are used to transfer the control of the program to the specific statements.
• Jump statements transfer the execution control to the other part of the program.
[Link] break statement
• The break statement is used to break the current flow of the program and transfer the control
to the next statement outside a loop or switch statement.
• It breaks only the inner loop in the case of the nested loop.
• The break statement cannot be used independently in the Java program, it can only be written
inside the loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for loop.
[Link]
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
[Link](i);
if(i==6) {
break;
} } }}
Output:
0
1
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 54
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
2
3
4
5
6
Break statement example with labeled for loop
[Link]
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
[Link](k);
if(k==5) {
break a;
} }} } }}
Output:
0
1
2
3
4
5
2. Continue statement
• Continue statement doesn't break the loop, whereas, it skips the specific part of the loop and
jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
public class ContinueExample {
public static void main(String[] args) {
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 55
U21CSG04 –
[UNIT I – OBJECT ORIENTED PROGRAMMING AND JAVA
Java Programming BASICS]
Prepared By: Dr. R. H. Aswathy, AP(Sl. G.) / CSE Department, KPRIET, Coimbatore. Page 56