Java - UNIT I
Java - UNIT I
Basic concepts, Principles, Program Structure in Java: Introduction, Writing Simple Java
Programs, Elements or Tokens in Java Programs, Java Statements, Command Line
Arguments, User Input to Programs, Escape Sequences Comments, Programming Style.
Objects are instances of a class created with specifically defined data. Objects can
correspond to real-world objects or abstract entities.
For Example, let’s say a Car is a type of Class whereas its instances such as a Tesla, Toyota, Ford
etc serve as an Object of Class Car.
As we said that Class contains Attributes(state) and Methods (Behaviour), we can consider the
following as Class Car attributes and Methods.
Attributes can be the Price, Speed, Color, Weight etc., of the car.
Methods can be changeGear(), slowSpeed(), brake() etc.,
When coming to the Object, let's Say the Object is Mini cooper.
So here Mini cooper is an instance of a Class Type Car and it has defined specific attributes and
Methods.
Inheritance
The concept of inheritance in Java refers to the transfer of properties from one class to another,
such as the relationship between a Mom and daughter.
Inheritance in Java is a process of acquiring all the behaviours of a parent object to child object.
3
In the above figure, we can see say inheritance as daughter class inheriting the variables and
methods of the mom parent class. Here Mom is called Base class or Parent Class and Daughter is
called Derived Class or Child Class.
Here, Inheritance is further classified into 4 types as follows
Polymorphism
4
Polymorphism, where “poly” stands for numerous and “morph” for form, refers to taking on
several forms. It refers to an object’s, function’s, or variable’s capacity to assume several forms.
It is the ability of a class to offer various implementations of a method depending on the kind of
object that is passed to the method. To put it simply, polymorphism in Java allows us to perform
the same action in many different ways.
Abstraction
Data abstraction is the process of withholding some information from the user and only
displaying what is absolutely necessary. Abstract classes or interfaces can be used to
accomplish abstraction.
Simply said, abstraction “displays” only the necessary features of objects while “hiding” the
unnecessary specifics.
5
ENCAPSULATION
In Java, encapsulation refers to the process of binding or combining data (variables) and
the code that affects them (methods) into a single unit.
(or)
It is a process of binding or wrapping the data members (states/properties /variables) and
member functions (behaviors /actions)together representing as a single unit is known as
Encapsulation.
6
What is Java?
Java is a popular high-level, object-oriented programming language that was originally
developed by Sun Microsystems and released in 1995. Currently, Java is owned by
Oracle, and more than 3 billion devices run Java.
Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions
of UNIX.
Today Java is being used to develop numerous types of software applications, including
desktop apps, mobile apps, web apps, games, and much more.
Java is a general-purpose programming language intended to let programmers Write
Once, Run Anywhere (WORA). This means that compiled Java code can run on all
platforms that support Java without the need to recompile.
Let's see which elements are included in the structure of a Java program. A typical structure of
a Java program contains the following elements:
Documentation Section
Package Declaration
Import Statements
Interface Section
Class Definition
Class Variables and Variables
Main Method Class
Methods and Behaviors
Documentation Section
The documentation section is an important section but optional for a Java program. 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. The comments may be single-line,
multi-line, and documentation comments.
9
Single-line Comment: It starts with a pair of forwarding slash (//). For example:
1. //First Java Program
Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols. For example:
1. /*It is an example of
2. multiline comment*/
Documentation Comment: It starts with the delimiter (/**) and ends with */. For
example:
1. /**It is an example of documentation comment*/
Package Declaration
The package declaration is optional. It is placed just after the documentation section. In this
section, we declare the package name in which the class is placed. Note that 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. For all these classes package belongs to a single
parent directory. We use the keyword package to declare the package name. For example:
1. package javatpoint; //where javatpoint is the package name
2. package [Link]; //where com is the root directory and javatpoint is the subdirect
ory
Import Statements
The package contains the many predefined classes and interfaces. If we want to use any class of
a particular package, we need to import that class. The import statement represents the class
stored in the other package. We use the import keyword to import the class. It is written before
the class declaration and after the package statement. We use the 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:
1. import [Link]; //it imports the Scanner class only
2. import [Link].*; //it imports all the class of the [Link] package
Interface Section
It is an optional section. We can create an interface in this section if required. We use
the 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
10
instantiated. We can use interface in classes by using the implements keyword. An interface can
also be used with other interfaces by using the extends keyword. For example:
1. interface car
2. {
3. void start();
4. void stop();
5. }
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.
We use 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:
1. class Student //class definition
2. {
3. }
Class Variables and Constants
In this section, we define variables and constants that are to be used later in the program. In a
Java program, the variables and constants are defined just after the class definition. The variables
and constants store values of the parameters. It is used during the execution of the program. We
can also decide and define the scope of variables by using the modifiers. It defines the life of the
variables. For example:
1. class Student //class definition
2. {
3. String sname; //variable
4. int id;
5. double percentage;
6. }
Main Method Class
11
In this section, we define the main() method. It is essential for all Java programs. Because the
execution of all Java programs starts from the main() method. In other words, it is an entry point
of the class. It must be inside the class. Inside the main method, we create objects and call the
methods. We use the following statement to define the main() method:
1. public static void main(String args[])
2. {
3. }
For example:
1. public class Student //class definition
2. {
3. public static void main(String args[])
4. {
5. //statements
6. }
7. }
You can read more about the Java main() method here.
Methods and behavior
In this section, we define the functionality of the program by using the methods. The methods are
the set of instructions that we want to perform. These instructions execute at runtime and
perform the specified task. For example:
1. public class Demo //class definition
2. {
3. public static void main(String args[])
4. {
5. void display()
6. {
7. [Link]("Welcome to Java Program");
8. }
9. //statements
12
10. }
11. }
1.5 ELEMENTS OR TOKENS IN JAVA PROGRAMS
In Java, tokens are the smallest individual units of a program that are meaningful to the
compiler. They are the fundamental building blocks of any Java code.
There are five main types of tokens in Java:
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators (or Punctuators)
1. Keyword
Keywords are pre-defined or reserved words in a programming language. Each keyword
is meant to perform a specific function in a program.
The keywords represent groups of instructions for the compiler.
These are special tokens that have a predefined meaning and their use is restricted.
keywords cannot be used as names of variables, methods, classes, or packages.
These are written in the lower case.
Java language supports the following keywords:
abstract assert boolean
break byte case
catch char class
const continue default
do double else
enum exports extends
final finally float
for goto if
implements import instanceof
int interface long
module native new
open opens package
private protected provides
public requires return
short static strictfp
super switch synchronized
this throw throws
13
to transient transitive
try uses void
volatile while with
2. Identifiers
Identifier is the name of variables, methods, classes etc.
Rules for framing Names or Identifiers.
It should be a single word which contains alphabets a to z or A to Z, digits 0 to 9,
underscore (_).
It should not contain white spaces and special symbols.
It should not be a keyword of Java.
It should not be Boolean literal, that is, true or false.
It should not be null literal.
It should not start with a digit but it can start with an underscore.
It can comprise one or more unicode characters which are characters as well as digits.
Conventions for Writing Names
Names of packages are completely in lower-case letters such as mypackage, [Link].
Names of classes and interfaces start with an upper-case letter.
Names of methods start with a lower-case character.
Names of variables should start with a lower-case character.
Examples of valid identifiers:
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
asha123
Examples of invalid identifiers:
My Variable // contains a space
123asha // Begins with a digit
a+c // plus sign is not an alphanumeric character
14
3. Constants/Literals
Constants are also like normal variables. But the only difference is, their values cannot be
modified by the program once they are defined. Constants refer to fixed values. They are also
called as literals. Constants may belong to any of the data type.
Syntax : data_type variable_name;
Types of Literals:
I. Integer literals
i. Sequences of digits.
ii. The whole numbers are described by different number systems such as decimal
numbers, hexadecimal numbers, octal numbers, and binary numbers.
iii. Each number has a different set of digits.
Decimal Integer Literals
i. These are sequences of decimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.
ii. Examples of such literals are 6, 453, 34789, etc.
Hex Integral Literals
i. These are sequences of hexadecimal digits which are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A,
B, C, D, E, and F.
ii. The values 10 to 15 are represented by A, B, C, D, E, and F or a, b, c, d, e, and f.
iii. The numbers are preceded by 0x or 0X. Examples are 0x56ab o0X6AF2, etc.
Octal Integer Literals
i. These are sequences of octal digits which are 0, 1, 2, 3, 4, 5, 6, and 7.
ii. These numbers are preceded by 0. Examples of literals are 07122, 04, 043526.
Binary Literal
i. These are sequences of binary digits.
ii. Binary numbers have only two digits—0 and 1 and a base 2.
iii. Examples of such literals are 0b0111001, 0b101, 0b1000, etc.
II. Floating point literal
i. These are floating decimal point numbers or fractional decimal numbers with base
10. Examples are 3.14159, 567.78, etc.
III. Boolean literal
i. These are Boolean values.
ii. There are only two values—true or false.
IV. Character literal
i. These are the values in characters.
15
ii. Characters are represented in single quotes such as ‘A’, ‘H’, ‘k’, and so on.
V. String literal
i. These are strings of characters in double quotes.
ii. Examples are “Delhi”, “John”, “AA”, etc. vi.
VI. Null literal
i. There is only one value of Null Literal, that is, null.
5. Separators
Separators are used to separate different parts of the codes. It tells the compiler about completion
of a statement in the [Link] include parentheses (), curly braces {}, square
brackets [], semicolons ;, and commas ,.
Int variable; //here the semicolon (;) ends the declaration of the variable
4. Operators
Java provides many types of operators which can be used according to the need. They are
classified based on the functionality they provide. Some of the types are-
Arithmetic Operators
Unary Operators
Assignment Operator
Relational Operators
Logical Operators
Ternary Operator
Bitwise Operators
Shift Operators
Operators: Operators are mostly represented by symbols such as + , -, *, etc
Types of Operators:
ArithmeticOperators:
Operator Description
+ Addition or Unaryplus
- Subtraction or Unaryminus
* Multiplication
/ Division
16
% Modulus
Increment/Decrement Operators:
Operator Description
++ Increment by one
-- Decrement by one
AssignmentOperators:
Operator Description
+= Add and assign to
-= Subtract and assign to
*= Multiply and assign to
/= Divide and assign to
%= Modulus and assign to
RelationalOperators:
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
LogicalOperators:
Operator Description
&& Greater than
|| Greater than or equal to
! Less than
ConditionalOperators:
Operator Description
?: Used to construct Conditional expression
BitwiseOperators:
Operator Description
& Bitwise AND
17
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise compliment
>> Shift Right
<< Shift Left
>>> Shift right with Zero fill
1. Keywords class, if, while, return, Reserved words with special meaning in
public Java
3. Literals 10, 'A', "Hello", 3.14, true Constant values used directly in the code
o while loop
o do-while loop
o continue: Skips the current iteration of a loop and proceeds to the next.
In this example, we are receiving only one argument and printing it. To run this java program,
you must pass at least one argument from the command prompt.
Example:
class CommandLineExample{
public static void main(String args[]){
[Link]("Your first argument is: "+args[0]);
}
}
Compilation:
compile by > javac [Link]
run by > java CommandLineExample Asha
Output:
Your first argument is: Asha
123
abc
3
@678
1.8 USER INPUT TO PROGRAMS
To take input from the user in Java, the Scanner class is used.
The Scanner class a built-in class of [Link].
Java Scanner class provides many built-in methods to take different types of user inputs from
the users.
The following are the steps to use Scanner class for the user input in Java
Step 1: Import Scanner Class
Fist you need to import the Scanner class to use its methods. To import the Scanner class, use the
following import statement −
import [Link]
// Printing the su
[Link]("The sum of the two numbers is: " + sum);
}
}
Output
Enter the first number: 10
Enter the second number: 20
The sum of the two numbers is: 30
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read
other types, look at the table below:
22
In the example below, we use different methods to read data of various types:
Example
import [Link];
class Main {
// String input
// Numerical input
Output:
(a) The program should be easily modifiable to ensure simplicity in fixing errors.
(b) The comments can help in modification of the program, fixing errors.
6. The program should be fail-safe. The failure of a program should not be catastrophic.
Primitive Data Types
The primitive data types are built-in data types and they specify the type of value stored in a
variable and the memory size. The primitive data types do not have any additional methods.
In java, primitive data types includes byte, short, int, long, float, double, char, and boolean.
The following table provides more description of each primitive data type.
26
Example: This example, demonstrating how to use boolean data type to display true/false
values.
// Demonstrating boolean data type
public class booleanProgram {
public static void main(String[] args) {
27
boolean b1 = true;
boolean b2 = false;
Output
Is Java fun? true
Is fish tasty? false
The byte data type is an 8-bit signed two's complement integer. The byte data type is useful
for saving memory in large arrays.
Syntax: byte byteVar;
Size : 1 byte (8 bits)
Example: This example, demonstrating how to use byte data type to display small integer
values.
// Demonstrating byte data type
public class byteProg{
public static void main(String[] args) {
byte a = 25;
byte t = -10;
Output
Age: 25
Temperature: -10
Example: This example, demonstrates how to use short data type to store moderately small
integer value.
// Demonstrating short data types
public class shortProg {
public static void main(String[] args) {
short num = 1000;
short t = -200;
Output
Number of Students: 1000
Temperature: -200
Example: This example demonstrates how to use int data type to display larger integer
values.
// Demonstrating int data types
public class intProg {
public static void main(String[] args) {
int p = 2000000;
int d = 150000000;
Output
Population: 2000000
Distance: 150000000
29
Example: This example demonstrates how to use long data type to store large integer value.
// Demonstrating long data type
Output
World Population: 7800000000
Light Year Distance: 9460730472580800
Example: This example demonstrates how to use float data type to store decimal value.
// Demonstrating float data type
public class floatProg {
public static void main(String[] args) {
float pi = 3.14f;
float gravity = 9.81f;
Example: This example demonstrates how to use double data type to store precise decimal
value.
// Demonstrating double data type
public class doubleProg {
public static void main(String[] args) {
double pi = 3.141592653589793;
double an = 6.02214076e23;
Output
Value of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23
Example: This example, demonstrates how to use char data type to store individual
characters.
// Demonstrating char data type
public class Geeks{
public static void main(String[] args) {
char g = 'A';
31
char s = '$';
Output
Grade: A
Symbol: $
1. Strings
Strings are defined as an array of characters. The difference between a character array and a
string in Java is, that the string is designed to hold a sequence of characters in a single
variable whereas, a character array is a collection of separate char-type entities.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example: This example demonstrates how to use string variables to store and display text
values.
public class StringProg {
public static void main(String[] args) {
String n = "Welcome";
String m = "Java Programming ";
2. Class
A Class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type.
3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life entities.
An object consists of :
State: It is represented by the attributes of an object. It also reflects the properties of an
object.
Behavior: It is represented by the methods of an object. It also reflects the response of an
object to other objects.
Identity: It gives a unique name to an object and enables one object to interact with other
objects.
Example: This example demonstrates how to create the object of a class.
// Define the Car class
class Car {
String model;
int year;
33
Output
Car Model: Honda
Car Year: 2021
4. Interface
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).
[Link]();
}
}
5. Array
An Array is a group of like-typed variables that are referred to by a common name. Arrays in
Java work differently than they do in C/C++.
Output
First Number: 1
Second Fruit: Geek2
JAVA VARIABLES
In Java, variables are fundamental elements used to store data that can be
manipulated throughout a program. A variable is essentially a container that holds data that can
be changed during the execution of a program. Java supports various types of variables, each
designed for specific data types and use cases.
where, data_type is the type of data to be stored in this variable, and variable_name is the name
given to the variable.
Example
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'
}
}
}
:\>javac [Link]
E:\>java ScopeA
Class Scope variable - outside main() x = 5
Types of Variables
Basically, there are three types of variables in java :
1. Local Variables: Declared inside a method or block and can only be accessed within that
method or block.
2. Instance Variables: Declared inside a class but outside of any method. They are
associated with an instance of the class.
3. Static Variables: Declared as static and are shared among all instances of a class.
Local Variables are declared inside the method of the class. The scope of the local variable is limited
to the method, which means you cannot change the value of the local variable outside the method and
you cannot even access it outside the method. The initialization of the local variable is mandatory.
Scope of Local Variable: Within the block in which it is declared.
The lifetime of Local Variable: Until the control leaves the block in which it is declared.
Example 1:
public class LocalVariableExample {
public static void main(String[] args) {
int number = 10; // Local variable
[Link]("Local variable: " + number);
}
}
Output:
Local variable: 10
Example 2:
import [Link].*;
public class LocalVariableExample
{
public void EmployeeAge ()
{
// local variable age
int age = 30;
age = age + 5;
[Link] ("Employee age is : " + age);
}
public static void main (String args[])
{
LocalVariableExample obj = new LocalVariableExample ();
[Link] ();
}
}
In the above code, age is the Local Variable to the method EmployeeAge(). If we declare age outside
the method, it will give a compilation error.
Example 1:
public class InstanceVariableExample {
int instanceVar; // Instance variable
Example 2:
class Marks {
// These variables are instance variables.
// These variables are in a class
// and are not inside any function
int Marks1;
int Marks2;
int Marks3;
}
class Main {
public static void main (String args[])
{
//Object
Marks obj1 = new Marks ();
obj1.Marks1 = 50;
obj1.Marks2 = 80;
obj1.Marks3 = 90;
// displaying marks for object
38
Output:
Marks for first object:
First Subject :50
Second Subject :80
Third Subject :90
Output:
Static variable: 10
Example 2:
class Employee
{
// static variable salary
public static double salary;
public static String name = "Harsh";
}
public class StaticVariableExample
{
public static void main (String[]args)
{
39
In Java, a symbolic constant is a name given to a fixed, unchangeable value. Once defined, this
name can be used throughout your program instead of the literal value. This offers several
benefits:
1. Readability: Makes your code more understandable. Instead of "magic numbers" like
3.14159, you use meaningful names like PI.
2. Maintainability: If the constant's value needs to change, you only modify it in one place
(its definition), rather than searching and replacing it everywhere it's used.
3. Error Reduction: Reduces the likelihood of typos when repeatedly typing a value.
4. In Java, symbolic constants are typically defined using the final keyword.
The final keyword is crucial for declaring a symbolic constant. When applied to a variable, it
ensures that the variable's value can only be assigned once.
Typically written in uppercase letters with words separated by underscores.
Often declared as public static final when used in classes or interfaces.
static: Makes the constant belong to the class itself, rather than individual instances (objects)
of the class. This means you don't need to create an object to access the constant; you can
access it directly using the class name (e.g., ClassName.CONSTANT_NAME).
public: Makes the constant accessible from anywhere (within the same package or from
other packages).
Naming Convention:
By convention, symbolic constants in Java are named using uppercase letters with underscores to
separate words (e.g., MAX_USERS, PI, BASE_URL). This makes them easily distinguishable
from regular variables.
Syntax:
final dataType CONSTANT_NAME = value;
inside a class:
public class MyClass {
40
Example:
public class Circle {
// Symbolic constant for Pi
public static final double PI = 3.14159;
TYPECASTING IN JAVA
In Java , The process of converting the value of one data type (int, float, double, etc.) to another
data type is known as typecasting.
Here, the Java first converts the int type data into the double type. And then assign it to
the double variable.s
(having smaller size). Hence there is the loss of data. This is why this type of conversion does
not happen automatically.
class ExplicitTC {
public static void main(String[] args)
{
double i = 100.245;
Output
Original Value before Casting100.245
After Type Casting to short 100
After Type Casting to int 100
k=a+y;
e=a+(int)y;
z=(double)c/a;
[Link]("k = " + k +" and e =" +e); [Link]("d=
"+ d + " and z = "+ z);
}
}
Output
C:\ >javac
TypeCast
k = 10.5 and e =10
d= 2 and z = 2.25
Example:
classGFG {
// The Expression
doubleresult = (f * b) + (i / c) - (d * s);
Output
result = 626.7784146484375
In the first subexpression, f * b, b is promoted to a float and the result of the subexpression is
float. Next, in the subexpression i/c, c is promoted to int, and the result is of type int. Then, in
d*s, the value of s is promoted to double, and the type of the subexpression is double. Finally,
these three intermediate values, float, int, and double, are considered. The outcome of float plus
an int is a float. Then the resultant float minus the last double is promoted to double, which is the
type for the result of the expression.
The number itself includes Integer, Long, etc. The formatting Specifier used is %d.
Output
true
TRUE
false
FALSE
import [Link].*;
class CharFormat{
public static void main(String[] args)
{
47
char c = 'g';
// Formatting Done
[Link]("%c\n", c);
// Converting into Uppercase
[Link]("%C\n", c);
}
}
Output
g
G
str = "JAVA";
// Vice-versa not possible
[Link]("%S \n", str);
[Link]("%s \n", str);
}
}
Output
48
javaprogramming
JAVAPROGRAMMING
JAVA
JAVA
class DateTimeFormat{
public static void main(String[] args)
{
Date time = new Date();
[Link]("Current Time: %tT\n", time);
// Another Method with all of them Hour, minutes and seconds seperated
[Link]("Hours: %tH Minutes: %tM Seconds: %tS\n", time,time, time);
Output
Current Time: 11:32:36
Hours: 11 Minutes: 32 Seconds: 36
11:32:36 am 198 198000000 +0000
49
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:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Unary Operators in Java are used in only one operand. There are various types of Unary
Operators in Java, such as
Operators Description
+ Unary Plus
- Unary Minus
++ Increment operator
-- Decrement Operator
classMain
{
publicstaticvoidmain(String[] args)
{
// declare variables
50
inta=13, b = 13;
int result1, result2;
// original value
[Link]("Value of a: " + a);
// increment operator
result1 = ++a;
[Link]("After increment: " + result1);
// decrement operator
result2 = --b;
}
}
Output
Value of a: 13
After increment: 14
Value of b: 13
After decrement: 12
classMain
{
publicstaticvoidmain(String[] args)
{
// declare variables
inta=15, b = 5;
51
// addition operator
[Link]("a + b = " + (a + b));
// subtraction operator
[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));
}
}
Output
a + b = 20
a - b = 10
a×b=75
a ÷b=3
a%b=7
Java relational operators are assigned to check the relationships between two particular
operators. There are various relational operators in Java, such as
Operators Description Example
classMain
{
publicstaticvoidmain(String[] args)
{
// create variables
inta=7, b = 11;
// value of a and b
[Link]("a is " + a + " and b is " + b);
// == operator
[Link](a == b); // false
// != operator
[Link](a != b); // true
// > operator
[Link](a > b); // false
// < operator
[Link](a < b); // true
// >= operator
[Link](a >= b); // false
// <= operator
[Link](a <= b); // true
}
}
Output
a is 7 and b is 11
falsetrue
53
false
true
false
true
Logical Operators in Java are used for checking whether the expression is true or false. It is
generally used for making any decisions in Java programming. Not only that but Jump
statements in Java are also used for checking whether the expression is true or false. It is
generally used for making any decisions in Java programming.
&& [ logical AND ] expression1 && expression2 (true) only if both of the expressions are true
classMain
{
publicstaticvoidmain(String[] args)
{
// && operator
[Link]((6>3) && (8>6)); // true
[Link]((6>3) && (8<6)); // false
// || operator
[Link]((6<3) || (8>6)); // true
[Link]((6>3) || (8<6)); // true
[Link]((6<3) || (8<6)); // false
// ! operator
[Link](!(6 == 3)); // true
[Link](!(6>3)); // false
}
}
54
Output
(6>3) && (8>6) returns true because both(6>3) and (8>6) are true.
(6>3) && (8>6) returns false because the expression(8<6) is false
(6<3) || (8>6) returns true because the expression(8>6) is true
(6>3) || (8<6) returns true because the expression(6>3) is true
(6<3) || (8<6) returns false because both(6<3) and (8<6) are false
! (6 == 3) returns true because 6 == 3 isfalse
! (6>3) returns false because 6>3 is true
Bitwise Operators in Java are used to assist the performance of the operations on individual bits.
There are various types of Bitwise Operators in Java, such as
Operators Descriptions
~ Bitwise Complement
Operators Descriptions
^ Bitwise exclusive OR
[Link]
1. public class BitwiseAndExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 9, y = 8;
6. // bitwise and
7. // 1001 & 1000 = 1000 = 8
8. [Link]("x & y = " + (x & y));
9. }
10. }
Output
x& y = 8
Bitwise exclusive OR (^)
It is a binary operator denoted by the symbol ^ (pronounced as caret). It returns 0 if both bits are
the same, else returns 1.
[Link]
1. public class BitwiseXorExample
56
2. {
3. public static void main(String[] args)
4. {
5. int x = 9, y = 8;
6. // bitwise XOR
7. // 1001 ^ 1000 = 0001 = 1
8. [Link]("x ^ y = " + (x ^ y));
9. }
10. }
Output
x^y=1
Bitwise inclusive OR (|)
It is a binary operator denoted by the symbol | (pronounced as a pipe). It returns 1 if either of the
bit is 1, else returns 0.
[Link]
1. public class BitwiseInclusiveOrExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 9, y = 8;
6. // bitwise inclusive OR
7. // 1001 | 1000 = 1001 = 9
8. [Link]("x | y = " + (x | y));
9. }
10. }
Output
x|y=9
Bitwise Complement (~)
It is a unary operator denoted by the symbol ~ (pronounced as the tilde). It returns the inverse or
complement of the bit. It makes every 0 a 1 and every 1 a 0.
57
Therefore, before shifting the bits the decimal value of a is 240, and after shifting the bits the
decimal value of a is 60.
[Link]
1. public class UnsignedRightShiftOperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x = 20;
6. [Link]("x>>>2 = " + (x >>>2));
7. }
8. } Output
x>>>2 = 5
Decision-Making statements:
As the name suggests, 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, i.e., If statement and 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
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.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java code.
[Link]
[Link]
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. [Link]("x + y is greater than 20");
7. }
8. }
9. }
Output:
x + y is greater than 20
61
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:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Consider the following example.
[Link]
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. [Link]("x + y is less than 10");
7. } else {
8. [Link]("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
Example 2:
import [Link];
public class EvenOddCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter the number");
int number=[Link]();
if (number % 2 == 0)
62
9. [Link]("city is agra");
10. }else {
11. [Link](city);
12. }
13. }
14. }
Output:
Delhi
Example 2:
import [Link];
public class Student {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int m1,m2,m3;
[Link]("Enter the 3 subject marks:");
[Link]("Enter the 1st subject marks:");
m1=[Link]();
[Link]("Enter the 2nd subject marks:");
m2=[Link]();
[Link]("Enter the 3rd subject marks:");
m3=[Link]();
double totalMarks;
totalMarks=m1+m2+m3;
[Link]("Total Marks: "+totalMarks);
double perc = (totalMarks / 300) * 100;
String grade;
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Example 1:
1. public class Test {
2. public static void main(String args[]) {
3. int x = 30;
4. int y = 10;
5. if( x == 30 ) {
6. if( y == 10 ) {
7. [Link]("X = 30 and Y = 10");
8. }
9. }
10. }
11. }
Example 2:
import [Link];
public class Student {
static String grade;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int m1,m2,m3;
[Link]("Enter the 3 subject marks:");
[Link]("Enter the 1st subject marks:");
m1=[Link]();
[Link]("Enter the 2nd subject marks:");
m2=[Link]();
[Link]("Enter the 3rd subject marks:");
m3=[Link]();
double totalMarks;
totalMarks=m1+m2+m3;
[Link]("Total Marks: "+totalMarks);
double perc = (totalMarks / 300) * 100;
if(m1>=40&&m2>=40&&m3>=40)
{
if (perc >= 90)
grade = "A+";
else if ((perc >= 80) && (perc < 90))
grade = "A";
66
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.
Example 2:
import [Link];
class Switch_Case {
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
[Link]("Enter Letter :");
char ch=[Link]().charAt(0);
switch (ch)
{
case 'A': [Link]("Letter A");
break;
case 'B': [Link]("Letter B");
break;
default: [Link]("Default case: NO Letter Matched!");
}
}
}
Output:
Enter Letter :
A
Letter A
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
3. do-while loop
4. for-each 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.
1. for(initialization, condition, increment/decrement) {
69
2. //block of statements
3. }
The flow chart for the for-loop is given below.
[Link]
public class Calculation {
public static void main(String[] args) {
int sum = 0, j;
for( j = 1; j<=10; j++) {
sum = sum + j;
}
[Link](""The sum of first " +j+ " natural numbers is " + sum);
}
}
Output:
The sum of first 10 natural numbers is 55
Java for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In the
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(dataType item : array) {
….
}
Here,
[Link]
public class Calculation {
public static void main(String[] args) {
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
Example 2:
// print array elements
class Main {
public static void main(String[] args) {
// create an array
int[] numbers = {3, 9, 5, -5};
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.
1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.
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.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.
[Link]
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. do {
7. [Link](i);
8. i = i + 2;
9. }while(i<=10);
10. }
73
11. }
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Nested for-loop
To place a loop inside another loop is called a nested loop.
A nested for loop in Java involves placing one for loop inside another. Nested loops are useful
when working with tables, matrices, multi-dimensional data structures or or when a specific
action needs to be repeated multiple times within each iteration of an outer loop.
Example: Multiplication Table
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
[Link](i * j + " ");
}
[Link]();
}
}
}
Output:
1 2 3 4 5 6 7 8 9 10
2 1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12
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.
74