You are on page 1of 47

Java Programming Using Linux

Module 1
Concepts of Object Oriented programming
In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a
paradigm that provides many concepts, such as

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of message accepted and the type of
response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.

Class
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.

Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

PGM College Kangazha 1


Java Programming Using Linux

Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to
convince the customer differently, to draw something, for example, shape, triangle, rectangle,
etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation.
For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

Benefits of OOP
 Code Organization

One of the main benefits of OOP as it relates to Java is that it gives developers the
ability to encapsulate data and behavior within classes and objects, keeping a focus
on data integrity and preventing accidental access to information.

 Code Reusability

There are several OOP mechanisms Java provides to promote code reusability. By
letting developers extend class functionality and inherit attributes and methods
from parent classes, code redundancy (or duplicate code) can be reduced, as we do
not need to recode the same functionality over and over again

 Scalability

Using OOP principles, developers create code that is highly organized and
“placed” into self-contained modules that can be developed and tested
independently from other blocks of code and classes. This modularity makes code

PGM College Kangazha 2


Java Programming Using Linux

maintenance, bug fixing, and adding features much more efficient, as any code
changes you make to a module are less likely to impact others. Additionally, using
modular code allows for easy integration of new modules, helping programmers to
scale up applications as their requirements grow.

 Collaboration

By encapsulating our code, we encourage collaboration among the software


development team, as it allows us to work on specific components independently
without having an effect on other pieces of the code base.

Features of Java
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as Java buzzwords.

A list of the most important features of the Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:

PGM College Kangazha 3


Java Programming Using Linux

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software development


and maintenance by providing some rules.

Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

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).

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:

PGM College Kangazha 4


Java Programming Using Linux

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)


which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.

Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust
The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.

High-performance
PGM College Kangazha 5
Java Programming Using Linux

Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g.,
C++). Java is an interpreted language that is why it is slower than compiled languages, e.g.,
C, C++, etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI
and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.

Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.

Java supports dynamic compilation and automatic memory management (garbage collection).

Java Runtime Environment

JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs 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.

The JVM performs the following main tasks:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

PGM College Kangazha 6


Java Programming Using Linux

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

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.

Overview of Java Language


Java is a general purpose, object oriented programming language.We can develop 2 types of JAVA
programs:

1. Standalone applications
2. Web applets

1) Standalone Application
A standalone application, also known as a desktop application is a software program
designed in such a way that to run this software program, users don’t need an internet
connection or any server access. Web-based applications need an internet connection,
servers, and any additional resources to run but standalone applications do not require any
additional resources such as an internet connection, server, etc.

2) Web Applets
PGM College Kangazha 7
Java Programming Using Linux

Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

First Java Program | Hello World Example


In this section, we will learn how to write the simple program of Java

For executing any Java program, the following software or application must be properly
installed.

o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory.
o Create the Java program
o Compile and run the Java program

To write the simple program, you need to open notepad by start menu -> All Programs ->
Accessories -> Notepad and write a simple program as we have shownbelow:

In order to compile and run the program, you need to open the command prompt by start
menu -> All Programs -> Accessories -> command prompt.

Creating Hello World Example


Let's create the hello java program:

class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}

Save the above file as Simple.java.

To compile: javac Simple.java


To execute: java Simple

Output:

Hello Java

PGM College Kangazha 8


Java Programming Using Linux

Parameters used in First Java Program


o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to
all.
o static is a keyword. If we declare any method as static, it is known as the static
method.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument.
o System.out.println() is used to print statement. Here, System is a class, out is an
object of the PrintStream class, println() is a method of the PrintStream class.

Java Tokens
In Java, the program contains classes and methods. Further, the methods contain the
expressions and statements required to perform a specific operation. These statements and
expressions are made up of tokens The tokens are the small building blocks of a Java
program that are meaningful to the Java compiler. Further, these two components contain
variables, constants, and operators.

Types of Tokens
Java token includes the following:

o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments

Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the
following keywords:

PGM College Kangazha 9


Java Programming Using Linux

01. 02. boolean 03. byte 04. break 05. class


abstract

06. case 07. catch 08. char 09. continue 10. default

11. do 12. double 13. else 14. extends 15. final

16. 17. float 18. for 19. if 20. implements


finally

21. 22. instanceof 23. int 24. interface 25. long


import

26. 27. new 28. package 29. private 30. protected


native

31. 32. return 33. short 34. static 35. super


public

36. 37. synchronized 38. this 39. thro 40. throws


switch

41. 42. try 43. void 44. volatile 45. while


transient

46. assert 47. const 48. enum 49. goto 50. strictfp

Identifier: Identifiers are used to name a variable, constant, function, class, and array. It
usually defined by the user. It uses letters, underscores, or a dollar sign as the first character.
The label is also known as a special kind of identifier that is used in the goto statement.
Remember that the identifier name must be different from the reserved keywords. There are
some rules to declare identifiers are:

o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.

Some valid identifiers are:

1. PhoneNumber
2. PRICE
3. radius

PGM College Kangazha 10


Java Programming Using Linux

4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid

Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is
defined by the programmer. Once it has been defined cannot be changed. Java provides five
types of literals are as follows:

o Integer
o Floating Point
o Character
o String
o Boolean

Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"javatpoint" String

null any reference type

Operators: In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators that can be classified
according to the functionality they provide. There are eight types of operators in Java, are as
follows:

o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators

PGM College Kangazha 11


Java Programming Using Linux

o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators

Operator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !

Assignment = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Logical && , ||

Ternary (Condition) ? (Statement1) : (Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>

Separators: The separators in Java is also known as punctuators. There are nine
separators in Java, are as follows:

1. separator <= ; | , | . | ( | ) | { | } | [ | ]

o Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the
two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates
the two statements.
o Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.

PGM College Kangazha 12


Java Programming Using Linux

Comments: Comments allow us to specify information about the program inside our Java
code. Java compiler recognizes these comments as tokens but excludes it form further
processing. The Java compiler treats comments as whitespaces. Java provides the following
two types of comments:

o Line Oriented: It begins with a pair of forwarding slashes (//).


o Block-Oriented: It begins with /* and continues until it founds */.

What is constant?
Constant refers to fixed value that cannot be changed during the execution of the program.
Java does not directly support the constants. Java supports several types of constants.

Types of Constants
There are the following types if constants in Java:

1. Numeric Constants
o Integer Constants
o Real Constants
2. Non-numeric Constants
o Character Constants
o String Constants

Numeric Constants
Numeric constants are the constants that contains numerals. It may also have a leading sign
and decimal point.

Integer Constants
A constant that contains digits (0-9) and does not have decimal point is called integer
constants. By default, it is type of int. There are the following three types of integer
constants:

 Decimal Constants: It contains digits between 0 to 9. Note that must not start with 0.
For example, 898, 67, 66.
 Octal Constants: It contains digits between 0 to 7 and must begin with 0. For
example, 012, 032, 067.

PGM College Kangazha 13


Java Programming Using Linux

 Hexadecimal Constants: It contains digits between 0 to 9 and letters a to f (either in


upper or lower case). It must begin with 0X or 0x. For example, 0x23, 0x76, 0X6A,
0XFF.

 Real Constants

Numeric constants that have a decimal point are called real or floating-point constants. By
default, the real constants are of double type. We can explicitly mention the type of a
floating-point constant as a float by appending the letter f or F at the end of the constant. For
example, 45f, -0.14f, 5.6F.

The real constants can be written in the following two forms:

o Fractional Form
o Exponential Form

Fractional Form

For example, 100.34e4, -56E10, 0.233E10, -0.94e15.

Non-numeric Constants
A constant that does not contain digits is called non-numeric constants. There are the
following two types of non-numeric constants:

Character Constants
A Character constant is a single alphabet, digit or any special symbol enclosed using single
quotes. For example, 'Y', 'd', '6', '#', '&'.

The maximum length of a character constant is 1 character long. It means that we cannot put
more than one character inside single quotation marks.

String Constants
String constants consist of zero or more characters enclosed in double quotes (""). At the end
of the string, the null character i.e '\0' is automatically placed by the compiler. For
example, "hello", " " (denotes blank space), "111".

Backslash Character Constants


Java also supports backslash character constants. These are used in output methods. It is also
known as escape sequence. For Example, \n, \t, \a, etc.

PGM College Kangazha 14


Java Programming Using Linux

The following table denotes the backslash character constants used in Java.

\b Backspace
\f From feed
\n New line
\r Carriage return
\t Horizontal tab
\" Double quote
\' Single quote
\\ Backslash
\v Vertical tab
\a Alert
\? Question mark
\N Octal constant
\xN Hexadecimal constant

Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type. A variable is the name of a reserved area allocated in
memory. In other words, it is a name of the memory location. It is a combination of "vary +
able" which means its value can be changed.

There are three types of variables in java: local, instance and static.

Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable

1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

PGM College Kangazha 15


Java Programming Using Linux

A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.

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. You can
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.

Data Types in Java


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.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Value Default size

PGM College Kangazha 16


Java Programming Using Linux

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type
is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:

1. Boolean one = false

int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is
no problem about memory.

Example:

PGM College Kangazha 17


Java Programming Using Linux

1. int a = 100000, int b = -200000

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.

Example:

1. double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example:

1. char letterA = 'A'

Variable Declaration
Java programming language requires variables to operate and handle data. Java creates
several variables as per data format and data types.

There are two ways to declare a variable in Java. The first method is to assign the initial value
to the variable. The second method declares variable without initial value.

Declare a Variable with Initial Value

Datatype variable name = value;


o For example: String my_name = "Java coder";

PGM College Kangazha 18


Java Programming Using Linux

o We initialize data with a given variable and display it as an output.


o The way of declaration works on the default method of the class.

E.g.:- String student_name = "Java coder";


double numbers = 3.21;

Declare a Variable without Initial Value

1. Data_type variable_name;
o For example: String my_name;
o We do not need to initialize data with a given variable.
o Assign value in any method and display it as an output.
o The way of declaration works inside and outside of the default method.
o The variable data is displayed inside of the default method of the class.

int student_id;

Reading input from Keyboard


There are many ways to read data from the keyboard. For example:

o InputStreamReader
o Console
o Scanner
o DataInputStream etc.

InputStreamReader class
InputStreamReader class can be used to read data from keyboard. It performs two tasks:

o connects to input stream of keyboard


o converts the byte-oriented stream into character-oriented stream

BufferedReader class
BufferedReader class can be used to read data line by line by readLine() method.

PGM College Kangazha 19


Java Programming Using Linux

Example of reading data from keyboard by InputStreamReader and


BufferdReader class
In this example, we are connecting the BufferedReader stream with the InputStreamReader
stream for reading the line by line data from the keyboard.

import java.io.*;
class G5
{
public static void main (String args [])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);

System.out.println("Enter your name");


String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:Enter your name
Amit
Welcome Amit

Type Casting in Java


In Java, type casting is a method or process that converts a data type into another data type in
both ways manually and automatically. The automatic conversion is done by the compiler
and manual conversion performed by the programmer.

Syntax

type variabel1=(type) variable2;

Example:-
int m=50;
byte n= (byte)m;
long count= (long)m;

PGM College Kangazha 20


Java Programming Using Linux

Automatic conversion
It is possible to assign a value of one type to a variable of a different type without a cast. Java
does the assigned value automatically.
Example:-
byte b=75;
int a=b;

Operators in JAVA
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:

1. Arithmetic Operator
2. Relational Operator
3. Logical Operator
4. Assignment Operator
5. Increment and decrement Operator
6. Conditional Operator
7. Bitwise Operator
8. Special Operator

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

PGM College Kangazha 21


Java Programming Using Linux

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

Example for arithmetic operator

public class OperatorExample


{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}

Output:

15
5
50
2
0

Relational Operators
Java Relational Operators are a bunch of binary operators used to check for relations
between two operands, including equality, greater than, less than, etc. They return a
boolean result after the comparison and are extensively used in looping statements as well
as conditional if-else statements and so on. The general format of representing relational
operator is:

Syntax

variable1 relation_operator variable2

PGM College Kangazha 22


Java Programming Using Linux

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Example
int x = 5;

int y = 3;

System.out.println(x > y); // returns true, because 5 is higher than 3

Logical Operators
You can also test for true or false values with logical operators.

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10)

Logical operators are used to determine the logic between variables or values:

PGM College Kangazha 23


Java Programming Using Linux

public class OperatorExample


{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}

Output:

false
false

t Exercises
Assignment Operators
Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:

Example
int x = 10;

The addition assignment operator (+=) adds a value to a variable:

Example
int x = 10;

x += 5;

A list of all assignment operators:

Operator Example Same As

PGM College Kangazha 24


Java Programming Using Linux

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Increment and decrement Operators


Increment and decrement operators are unary operators. We can only apply these
operators on a single operand, hence these operators are called as unary operators.

We can apply these unary operators on all primitive types except Boolean.

PGM College Kangazha 25


Java Programming Using Linux

Increment operator (++):


The increment operator is an operator which is used to increase the value of a
variable by 1, on which it is applied.

Again these increment operators are two types:

 Pre increment (++x)


 Post increment (x++)

Pre Increment Operator:


If an Increment operator is used in front of an operand, then it is called as Pre
Increment operator.

Syntax:
++x : which increments the value by 1 of ‘x’ variable.

Example:
class PreIncrement
{

public static void main(String[] args)


{
int x = 10;
int y = ++x;
System.out.println("y value is: " + y);
}

}
Output:

y value is: 11

On the above example, pre increment operator is applied on x operand, here first
the value of x will be incremented by 1 and then the incremented value will be
assigned to the variable y .
As per example, the initial value of ‘x’ is 10. After applying pre-increment
operator on ‘x’ the value of ‘x’ is incremented by 1 (i.e., 11) and that value is
assigned to the variable ‘y’. So that the final value of ‘y’ is 11.

Post Increment Operator:

PGM College Kangazha 26


Java Programming Using Linux

If an Increment operator is used after an operand, then is called Post Increment


operator.

Syntax:

x++ : which increase the value by 1 of variable ‘x’.


Example:

class PostIncrement
{

public static void main(String[] args)


{
int x = 10;
int y = x++;
System.out.println("y value is: " + y);
}

}
Output:

y value is: 10
Post increment operator is applied on ‘x’, here the case is exact opposite of pre
increment, first the value of variable ‘x’ is assigned to the variable ‘y’ and then the
value of ‘x’ is incremented by 1 .

As per example, the initial value of ‘x’ is 10. After applying post-increment
operator the current values of ‘x’ (i.e, 10) is assigned to y, and then the value
of ‘x’ is incremented by 1. So when displaying variable ‘y’ it is showing as 10.

Decrement Operator (- -):


The Decrement operator is an operator which is used to decrease the value of the
variable by 1, on which it is applied.

Like increment operators, decrement operators are also 2 types,

 Pre decrement (- -x)


 Post decrement (x- -)

Pre Decrement Operator:


If a decrement operator is used in front of an operand, then it is called Pre
decrement operator.

PGM College Kangazha 27


Java Programming Using Linux

Syntax:
–x: which decrease the value by 1 of variable ‘x’.

Example:
class PreDecrement {
public static void main(String[] args) {
int x = 10;
int y = --x;
System.out.println("y value is: " + y);
}
}

Output:
y value is: 9

Pre decrement operator is applied on ‘x’, first, the value of ‘x’ will be decremented
by 1 and then the decremented value will be assigned to the variable ‘y’.

As per example, the initial value of ‘x’ is 10. After applying pre decrement
operator on ‘x’, the value of ‘x’ is decremented by 1 (i.e., 9) and that value is
assigned to the variable ‘y’. So, when we display the variable ‘y’ it is showing as 9.

Post Decrement Operator:


If a decrement operator is used after an operand, then it is called Post decrement
operator.

x- –: which decrease the value by 1 of variable ‘x’.


Example:

class PostDecrement {
public static void main(String[] args) {
int x = 10;
int y = x--;
System.out.println("y value is: " + y);
}
}
Output:

y value is: 10

PGM College Kangazha 28


Java Programming Using Linux

Post decrement operator is applied on ‘x’, here the case is the complete opposite of
pre decrement operator, first, the value of variable ‘x’ is assigned to the
variable ‘y’ and then the value of ‘x’ is decremented by 1.
Syntax:
As per example, the initial value of ‘x’ is 10. After applying post decrement
operator on variable ‘x’ the current values of ‘x’ (i.e, 10) is assigned to ‘y’, and
then the value of ‘x’ is decremented by 1. So when displaying the value of ‘y’ it is
showing as 10.

Conditional Operators(Ternary Operators)


The meaning of ternary is composed of three parts. The ternary operator (? :) consists of
three operands. It is used to evaluate Boolean expressions. The operator decides which value
will be assigned to the variable. It is the only conditional operator that accepts three operands.
It can be used instead of the if-else statement. It makes the code much more easy, readable,
and shorter.

Syntax:

variable = (condition) ? expression1 : expression2

The above statement states that if the condition returns true, expression1 gets executed, else
the expression2 gets executed and the final result stored in a variable.

TernaryOperatorExample.java

public class TernaryOperatorExample


{
public static void main(String args[])
{
int x, y;
x = 20;
y = (x == 1) ? 61: 90;
System.out.println("Value of y is: " + y);
y = (x == 20) ? 61: 90;
System.out.println("Value of y is: " + y);
}
}

Output

PGM College Kangazha 29


Java Programming Using Linux

Value of y is: 90
Value of y is: 61

Bitwise Operators
Bitwise operators are used to performing the manipulation of individual bits of a
number. They can be used with any integral type (char, short, int, etc.). They are
used when performing update and query operations of the Binary indexed trees. .

Types of Bitwise Operator


There are six types of the bitwise operator in Java:

o Bitwise AND
o Bitwise exclusive OR
o Bitwise inclusive OR
o Bitwise Compliment
o Bit Shift Operators

Operators Symbol Uses

Bitwise AND & op1 & op2

Bitwise exclusive OR ^ op1 ^ op2

Bitwise inclusive OR | op1 | op2

Bitwise Compliment ~ ~ op

Bitwise left shift << op1 << op2

Bitwise right shift >> op1 >> op2

Unsigned Right Shift Operator >>> op >>> number of places to shift

Special Operators
Java supports some special operators of interest such as instanceof operator and member
selection operator (.).

instanceof operator

PGM College Kangazha 30


Java Programming Using Linux

The java 'instanceof' operator is used to test whether an object is an instance of a specified
type (class or sub - class or visual interface).

'instanceof' in Java is also known as the type comparison operator because it compares the
instances with type. It returns true or false. If we apply the 'instanceof' operator with a
variable value, the value returned is false.

Example:-

person instanceof student

Is true if the object person belongs to the class student; otherwise it is false.

Dot operator
The dot operator(.) is userd to access the instance variables and methods of class objects.

Example:-

person.age // reference to the variable age

person.salary () // reference to the method salary ()

Control Statements
Branching statements
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be
used to control the flow of Java code. Such statements are called control flow statements. It is
one of the fundamental features of Java, which provides a smooth flow of program.

Branching statements are:-

o if statements
o switch statement

1) If Statement:
In Java, 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. In Java, there are four types of if-statements given below.

1. Simple if statement

PGM College Kangazha 31


Java Programming Using Linux

2. if-else statement
3. if-else-if ladder
4. Nested if-statement

1) Simple if statement:
It is the most basic statement among all control flow statements in Java. 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
}

Example:-

Student.java

Student.java

public class Student


{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}

Output:

x + y is greater than 20

2) if-else statement

PGM College Kangazha 32


Java Programming Using Linux

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.

Student.java

public class Student


{
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
}
else
{
System.out.println("x + y is greater than 20");
}
}
}

Output:

x + y is greater than 20

3) if-else-if ladder:

PGM College Kangazha 33


Java Programming Using Linux

The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true. We can 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.

Student.java

public class Student


{
public static void main(String[] args)
{
String city = "Delhi";
if(city == "Meerut")
{
System.out.println("city is meerut");
}
else if (city == "Noida")
{
System.out.println("city is noida");
}
else if(city == "Agra")
{

PGM College Kangazha 34


Java Programming Using Linux

System.out.println("city is agra");
}
else
{
System.out.println(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
}
}

Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");

PGM College Kangazha 35


Java Programming Using Linux

}
else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}
else {
System.out.println(address.split(",")[0]);
}
}
else {
System.out.println("You are not living in India");
}
}
}

Output:

Delhi

Switch Statement:
In Java, 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.

The syntax to use the switch statement is given below.

switch (expression)
{
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;

PGM College Kangazha 36


Java Programming Using Linux

Consider the following example to understand the flow of the switch statement.

Student.java

public class Student implements Cloneable {


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

Output:

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 switch permits only int,
string, and Enum type variables to be used.

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.

1. for loop
2. while loop

PGM College Kangazha 37


Java Programming Using Linux

3. do-while loop

Let's understand the loop statements one by one.

Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code. We use the for loop only
when we exactly know the number of times, we want to execute the block of code.

for(initialization, condition, increment/decrement)


{
//block of statements
}

The flow chart for the for-loop is given below.

Example:-

Calculation.java

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;
}
System.out.println("The sum of first 10 natural numbers is " + sum);

PGM College Kangazha 38


Java Programming Using Linux

}
}

Output:

The sum of first 10 natural numbers is 55

Java while loop


The while loop is also used to iterate over the number of statements multiple times. However,
if we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for 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.

while(condition)
{
//looping statements
}

The flow chart for the while loop is given in the following image.

PGM College Kangazha 39


Java Programming Using Linux

Consider the following example.

Calculation .java

public class Calculation

public static void main(String[] args) {


// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}

Output:

PGM College Kangazha 40


Java Programming Using Linux

Printing the list of first 10 even numbers

0
2
4
6
8
10

Java do-while loop


The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.

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.

PGM College Kangazha 41


Java Programming Using Linux

Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do
{
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}

Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.

Java break statement


As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However, it
breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the for loop.

BreakExample.java

PGM College Kangazha 42


Java Programming Using Linux

public class BreakExample


{
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}

Output:

0
1
2
3
4
5
6

break statement example with labeled for loop

Calculation.java

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++)
{

PGM College Kangazha 43


Java Programming Using Linux

System.out.println(k);
if(k==5)
{
break a;
}
}
}
}
}
}

Output:

0
1
2
3
4
5

Java continue statement


Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.

Consider the following example to understand the functioning of the continue statement in
Java.

public class ContinueExample


{
public static void main(String[] args)
{
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++)
{
if(j == 4) {
continue;
}
System.out.println(j);
}

PGM College Kangazha 44


Java Programming Using Linux

}
}
}

Output:

0
1
2
3
5
1
2
3
5
2
3
5

Labeled loops
A label is a valid variable name that denotes the name of the loop to where the control of
execution should jump. To label a loop, place the label before the loop with a colon at the
end. Therefore, a loop with the label is called a labeled loop.

Example:-

Loop1: for (…………..)

…………………..

…………………….

……………….

A block statement can be labelled as shown below:

Block1: {

……….

…………

Block2: {

……….

PGM College Kangazha 45


Java Programming Using Linux

……….

……..

……

Example:

Example of labeled for-loop.

LabeledForLoop.java

public class LabeledForLoop


{
public static void main(String args[])
{
int i, j;
//outer loop
outer: //label
for(i=1;i<=5;i++)
{
System.out.println();
//inner loop
inner: //label
for(j=1;j<=10;j++)
{
System.out.print(j + " ");
if(j==9)
break inner;
}
}
}
}

Output:

123456789
123456789

PGM College Kangazha 46


Java Programming Using Linux

123456789
123456789
123456789

PGM College Kangazha 47

You might also like