0% found this document useful (0 votes)
3 views76 pages

Java - UNIT I

The document provides an overview of Object Oriented Programming (OOP) concepts in Java, including basic principles such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also discusses the structure of Java programs, key features of the Java language, and the various types of tokens used in Java programming. Additionally, it highlights Java's versatility in developing applications across different platforms.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views76 pages

Java - UNIT I

The document provides an overview of Object Oriented Programming (OOP) concepts in Java, including basic principles such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also discusses the structure of Java programs, key features of the Java language, and the various types of tokens used in Java programming. Additionally, it highlights Java's versatility in developing applications across different platforms.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1

UNIT I: Object Oriented Programming:

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.

DataTypes, Variables, and Operators: Introduction, DataTypes in Java, Declaration of


Variables, DataTypes, TypeCasting, Scope of Variable, Identifier, Literal Constants,
Symbolic Constants, Formatted Output with printf() Method, Static Variables and Methods,
Attribute Final.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else
Expressions,TernaryOperator?:,SwitchStatement,IterationStatements,whileExpression,do–
whileLoop,forLoop,NestedforLoop,For–EachforLoop,BreakStatement,ContinueStatement.

What is Object Oriented Programming?


Java is called an Object Oriented Programming Language. This means in a simple way we can
say everything in Java Programming is considered an Object which contains data and functions
and this object belongs to a particular class. Here class is a type of entity and object is instance of
class.
Not only Java the majority of widely used programming languages, including Python, C++, C#,
Ruby, etc., adhere to the object-oriented paradigm.
1.1 BASIC CONCEPTS:

What are Class and Object?


 Classes are user-defined data types that act as the blueprint for individual objects,
attributes and methods.
2

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

Polymorphism is further divided into two types as follows

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

Abstraction in Java is achieved by using Abstract class and Interface.

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

1.2THE PRINCIPLES OF OOPS


1) Encapsulation
2) Inheritance
3) Polymorphism
4) Abstraction

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.

Key Features of Java


 Platform Independent: Java is famous for its Write Once, Run Anywhere (WORA)
feature. This means we can write our Java code once, and it will run on any device or
operating system without changing anything.
 Simple: Java syntax is very straightforward and very easy to learn. Java removes
complex features like pointers and multiple inheritance, which makes it a good choice for
beginners.
 Object-Oriented: Java follows the object-oriented programming. This makes code clean
and reusable.
 Secured: Java does not support pointers, it includes built-in protections to keep our
programs secure from common problems like memory leakage.
 Multithreading: Java programs can do many things at the same time using multiple
threads. This is useful for handling complex tasks like processing transactions.
 Just-In-Time (JIT) Compiler: Java uses a JIT compiler. It improves performance by
converting the bytecode into machine readable code at the time of execution.
 It is one of the most popular programming languages in the world
7

 It has a large demand in the current job market


 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast and powerful
 As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or
vice versa
It is used for:
 Mobile applications (specially Android apps)
 Desktop applications
 Web applications
 Cloud-based Applications
 Android Applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!

1.3 PROGRAM STRUCTURE IN JAVA


1. Structure of Java Program
Java is an object-oriented programming, platform-independent, and secure programming
language that makes it popular. Using the Java programming language, we can develop a wide
variety of applications. So, before diving in depth, it is necessary to understand the basic
structure of Java program in detail. In this section, we have discussed the basic structure of a
Java program.
8

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

variable-2 // hyphen is not an alphanumeric character


sum_&_difference // ampersand is not an alphanumeric character

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

Token Type Examples Description

1. Keywords class, if, while, return, Reserved words with special meaning in
public Java

2. main, System, println, Names for variables, classes, methods, etc.


Identifiers myVar

3. Literals 10, 'A', "Hello", 3.14, true Constant values used directly in the code

4. Operators +, -, *, =, ==, ++ Symbols for operations like arithmetic,


comparison

5. ;, ,, (), {}, [] Symbols that separate code elements


Separators

6. // comment, /* block Ignored by compiler; used for


Comments comment */ documentation

1.6 JAVA STATEMENTS


In Java, a statement is a complete unit of execution, representing an instruction that the Java
compiler can execute. Statements are the building
g blocks of Java programs and dictate the flow of logic and actions performed. Most Java
statements conclude with a semicolon (;), which signals the end of the instruction to the
compiler.
Java statements can be broadly categorized into the following types:
 Declaration Statements: These statements are used to declare variables, associating a
variable name with a specific data type.
int age; // Declares an integer variable named 'age'
String name = "Alice"; // Declares and initializes a String variable
18

 Expression Statements: These statements represent an expression that produces a side


effect, meaning they modify the state of the program. Examples include assignments,
method calls, and increment/decrement operations.
x = 10; // Assignment statement
[Link]("Hello"); // Method call statement
count++; // Increment statement
 Control Flow Statements: These statements determine the order in which other
statements are executed, controlling the flow of the program.
o Conditional Statements: Execute blocks of code based on a condition.

 if, if-else, else-if ladder


 switch
 Iteration Statements (Loops): Repeatedly execute a block of code.
o for loop

o while loop

o do-while loop

 Jump Statements: Alter the normal flow of execution.


o break: Exits a loop or switch statement.

o continue: Skips the current iteration of a loop and proceeds to the next.

o return: Exits a method and optionally returns a value.

1.7 COMMAND LINE ARGUMENTS


• A Java application can accept any number of arguments from the command line.
• These arguments can be passed at the time of running the program. This enables a
programmer to check the behavior of a program for different values of inputs.
• When a Java application is invoked, the runtime system passes the command line
arguments to the application's main method through an array of strings.
• It must be noted that the number of arguments in an array. To ensure this, we can make
use of the length property of the array. This is illustrated in
Simple example of command-line argument in java
19

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

Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line. For this
purpose, we have traversed the array using for loop.
Example:
1. class A{
2. public static void main(String args[]){
3. for(int i=0;i<[Link];i++)
4. [Link](args[i]);
5. }
6. }
Compilation:
compile by > javac [Link]
run by > java A Hello 123 abc 3 @678
Output:
Hello
20

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]

Step 2: Create Scanner Class's Object


After importing the Scanner class, you need to create its object to use its methods. To create an
object of the Scanner class, invoke Scanner() constructor
Below is the statement to create an object of Scanner class:

Scanner obj = new Scanner([Link]);

Step 3: Take User Input


Scanner class provides a variety of methods which are useful to take user input of different types.
For example, if you want to input an integer value, use nextInt() method.
The following is the statement to take user input in Java –

int age = [Link]();


The above statement will wait for an integer input from the user. When user provides an integer
value, that will be assign to "age" variable
Example of User Input in Java
In the following example, we are reading two integers from the user, calculating, and printing
their addition -
21

// Importing the class


import [Link];

public class AddTwoNumbers {


public static void main(String[] args) {
// Creating an object of Scanner class
Scanner sc = new Scanner([Link]);

// Reading two Integer numbers


// using nextInt() method
[Link]("Enter the first number: ");
int num1 = [Link]();

[Link]("Enter the second number: ");


int num2 = [Link]();

// Calculating the sum


int sum = num1 + num2;

// 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 {

public static void main(String[] args) {

Scanner myObj = new Scanner([Link]);

[Link]("Enter name, age and salary:");

// String input

String name = [Link]();

// Numerical input

int age = [Link]();

double salary = [Link]();

// Output input by user

[Link]("Name: " + name);

[Link]("Age: " + age);


23

[Link]("Salary: " + salary);

Output:

1.8 ESCAPE SEQUENCES IN JAVA:


 \n: Newline (moves the cursor to the next line).
 \t: Tab (inserts a horizontal tab).
 \r: Carriage Return (moves the cursor to the beginning of the current line).
 \b: Backspace (moves the cursor back one position).
 \f: Form Feed (moves the cursor to the next page or segment, often used in printing).
 \': Single Quote (inserts a single quote character).
 \": Double Quote (inserts a double quote character).
 \\: Backslash (inserts a backslash character).
1.9 PROGRAMMING STYLE
 An analysis of the programming exercises will throw some light on the look and feel of a
program. The team members should easily understand each other's code.
 For a beginner, it is better to develop a habit of writing a program in a proper style so that
there is no conflict between the current habits and the company's imposition of style rule at
a later stage.
 There are no set patterns of good style and bad style: however, if the programmer takes
care of a few requirements on the programs as discussed, the resulting style will be better
1. The program should present a clean and orderly look. In order to develop a clean
program, the programmer can adapt the following measures:
24

(a) The white spaces are neglected by the compiler.


(b) Indenting is another method often used to improve the looks and readability
(c) Use of Lambda expression and method reference of Java 8 enhances the look
(d) Include a space before and after operators
2. The program should be easy to understand. The programmer should take care of the
following aspects:
(a) If it is team work, certain conventions about naming should be preset so that a team
member can easily identify an item.
(b) The makers of Java have a set of rules which are followed in the Java library. The same
rules or an even better convention may be set.
(c) Judicial use of comments can increase understandability. Use of too many comments
makes confusion in the program.
(d) It is better to use already defined and tested library methods rather than user-defined
methods
(e) Expressions like z = x++ + - - c*++k; should be avoided.
3. Debugging should be easy. The programmer may adopt the following measures to
ensure easy debugging.
(a) The vertical alignment of a similar item enhances the ability to find errors.
(b) The code line should not be too long.
(c) The variables should be declared close to the places of their use
(d) If it is a big program, it should be divided into small segments. In Java, it is easy because
the program may comprise separate classes.
(e) The methods should not be too big.
(f) Each source code file should have one class.
(g) The braces should be vertically aligned, if possible.
4. The program should be easy to use. The following points
(a) The input into program should be easy,
(b) The output should be self-explanatory should be taken care of
(c) The names used should imply the output type such as price, weight, length, and so on.
25

(d) Confusing and long names must be avoided.


5. The program should be easy to maintain

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

DataTypes, Variables, and Operators: Introduction, DataTypes in Java, Declaration of


Variables, DataTypes, TypeCasting, Scope of Variable, Identifier, Literal Constants,
Symbolic Constants, Formatted Output with printf() Method, Static Variables and Methods,
Attribute Final.
___________________________________________________________________________
_

1.10 DATA TYPES IN JAVA


Java programming language has a rich set of data types. The data type is a category of data
stored in variables.
In java, data types are classified into two types and they are as follows.
 Primitive Data Types
 Non-primitive Data Types


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

Data Memory Default


type Meaning size Range Value

byte Whole 1 byte -128 to +127 0


numbers

short Whole 2 bytes -32768 to +32767 0


numbers

int Whole 4 bytes -2,147,483,648 to +2,147,483,647 0


numbers

long Whole 8 bytes -9,223,372,036,854,775,808 to 0L


numbers +9,223,372,036,854,775,807

float Fractional 4 bytes - 0.0f


numbers

double Fractional 8 bytes - 0.0d


numbers

char Single 2 bytes 0 to 65535 \u0000


character

boolean unsigned 1 bit 0 or 1 0


char (false)

1. boolean Data Type


The boolean data type represents a logical value that can be either true or false.
it represents a single bit of information
Syntax: boolean booleanVar;

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;

[Link]("Is Java fun? " + b1);


[Link]("Is fish tasty? " + b2);
}
}

Output
Is Java fun? true
Is fish tasty? false

1. byte Data Type

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;

[Link]("Age: " + a);


[Link]("Temperature: " + t);
}
}

Output
Age: 25
Temperature: -10

2. short Data Type


The short data type is a 16-bit signed two's complement integer. Similar to byte, a short is
used when memory savings matter, especially in large arrays where space is constrained.
28

Syntax: short shortVar;


Size : 2 bytes (16 bits)

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;

[Link]("Number of Students: " + num);


[Link]("Temperature: " + t);
}
}

Output
Number of Students: 1000
Temperature: -200

4. int Data Type


It is a 32-bit signed two's complement integer.
Syntax: int intVar;
Size : 4 bytes ( 32 bits )

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;

[Link]("Population: " + p);


[Link]("Distance: " + d);
}
}

Output
Population: 2000000
Distance: 150000000
29

5. long Data Type


The long data type is a 64-bit signed two's complement integer. It is used when an int is not
large enough to hold a value, offering a much broader range.
Syntax: long longVar;
Size : 8 bytes (64 bits)

Example: This example demonstrates how to use long data type to store large integer value.
// Demonstrating long data type

public class longProg {


public static void main(String[] args) {
long w = 7800000000L;
long l = 9460730472580800L;

[Link]("World Population: " + w);


[Link]("Light Year Distance: " + l);
}
}

Output
World Population: 7800000000
Light Year Distance: 9460730472580800

6. float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead
of double) if you need to save memory in large arrays of floating-point numbers. The size of
the float data type is 4 bytes (32 bits).

Syntax: float floatVar;


Size : 4 bytes (32 bits)

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;

[Link]("Value of Pi: " + pi);


30

[Link]("Gravity: " + gravity);


}
}
Output
Value of Pi: 3.14
Gravity: 9.81
7. double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal
values, this data type is generally the default choice. The size of the double data type is 8
bytes or 64 bits.
Syntax: double doubleVar;
Size : 8 bytes (64 bits)

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;

[Link]("Value of Pi: " + pi);


[Link]("Avogadro's Number: " + an);
}
}

Output
Value of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23

8. char Data Type


The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
Syntax: char charVar;
Size : 2 bytes (16 bits)

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 = '$';

[Link]("Grade: " + g);


[Link]("Symbol: " + s);
}
}

Output
Grade: A
Symbol: $

Non-Primitive (Reference) Data Types


The Non-Primitive (Reference) Data Types will contain a memory address of variable
values because the reference types won’t store the variable value directly in memory. They
are strings, objects, arrays, etc.

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 ";

[Link]("Name: " + n);


[Link]("Message: " + m);
}
}
Output
Name: Welcome
Message: Java Programming
32

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.

// Demonstrating how to create a class


class Car {
String model;
int year;
Car (String model, int year) {
[Link] = model;
[Link] = year;
}
void display() {
[Link](model + + year);
}
}
public class Example {
public static void main(String[] args) {
Car myCar = new Car ("Toyota", 2020);
[Link]();
}
}
Output
Toyota 2020

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

// Constructor to initialize the Car object


Car(String model, int year) {
[Link] = model;
[Link] = year;
}
}

// Main class to demonstrate object creation


public class Geeks {
public static void main(String[] args) {
// Create an object of the Car class
Car myCar = new Car("Honda", 2021);

// Access and print the object's properties


[Link]("Car Model: " + [Link]);
[Link]("Car Year: " + [Link]);
}
}

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

// Demonstrating the working of interface


interface Animal {
void sound();
}

class Dog implements Animal {


public void sound() {
[Link]("Woof");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Dog myDog = new Dog();
34

[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++.

// Demonstrating how to create an array


public class ArrayProg {
public static void main(String[] args) {
int[] num = {1, 2, 3, 4, 5};
String[] arr = {"Geek1", "Geek2", "Geek3"};

[Link]("First Number: " + num[0]);


[Link]("Second Fruit: " + arr[1]);
}
}

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.

Key Components of Variables in Java:


A variable in Java has three components, which are listed below:
 Data Type: Defines the kind of data stored (e.g., int, String, float).
 Variable Name: A unique identifier following Java naming rules.
 Value: The actual data assigned to the variable.

Variable Declaration and Initialization


Java variables are declared by specifying the data type followed by the variable name. To
assign a value, use the assignment (=) operator followed by the value. Each declaration or
initialization statement must end with a semicolon (;).

Syntax: data type variable [ = value][, variable [ = value] ...] ;


35

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'

Scope vs Lifetime in Java:


Scope refers to the range of code where you can access a variable. We can divide the scope into:
1. Method body scope variable is accessible in method body only (local variables, parameters)
2. Class definition scope variable is accessible in the class definition (instance variables)
Lifetime refers to the amount of time a variable (or object) exists. We can divide lifetime into
categories too:
1. Method body lifetime exists on method body lifetime entry, disappears on method body exit
(local variables, parameters).
2. Class definition lifetime exists as long as the object is around (instance variables).

Program 3.10: Illustration of block scope

public class ScopeA {


static int x = 5; // Variable scope within the Class
public static void main (String args[]) {
[Link]("Class Scope variable - outside main() x = " + x);
int y = 10;

[Link]("Variable y Scope within main() y = " + y);


{ // Anonymous Block
int z = 20;
[Link]("Variable z Scope within Anonymous Block z = " + z);

}
}
}
:\>javac [Link]

E:\>java ScopeA
Class Scope variable - outside main() x = 5

Variable y Scope within main() y = 10


36

Variable z Scope within Anonymous Block z = 20

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] ();
}
}

Output: Employee age is : 35


37

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.

Instance Variables in Java:


The instance variable is also known as a non-static variable. It is always declared in a class but
outside the method, block, or constructor. The instance variable is created when an object of the class
is created and destroyed when the object is destroyed. Instance Variables can only be accessed by
creating the objects of the class. The initialization of the instance variable is not required, it takes the
default value as 0.

Scope of Instance Variable: Throughout the class except in static methods.


The lifetime of Instance Variable: Until the object is available in the memory.

Example to Understand Instance Variables in Java:

Example 1:
public class InstanceVariableExample {
int instanceVar; // Instance variable

public static void main(String[] args) {


InstanceVariableExample obj = new InstanceVariableExample();
[Link] = 5;
[Link]("Instance variable: " + [Link]);
}
}
Output:
Instance variable: 5

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

[Link] ("Marks for first object:");


[Link] ("First Subject :"+obj1.Marks1);
[Link] ("Second Subject :"+obj1.Marks2);
[Link] ("Third Subject :"+obj1.Marks3);
}
}

Output:
Marks for first object:
First Subject :50
Second Subject :80
Third Subject :90

Static Variables in Java:


The static variable is also known as the Class Variable. Static variables are created at the start of
program execution and destroyed automatically when execution ends. These variables are declared
similarly to instance variables, the difference is that static variables are declared using the static
keyword within a class outside any method constructor or block. Initialization of Static Variable is
not mandatory, it’s default value is 0.
To access static variables, we need not create an object of that class, we can simply access the
variable as class_name.variable_name;

Scope of Static Variable: Throughout the class.


The lifetime of Static Variable: Until the end of the program.
Example 1:
public class StaticVariableExample {
static int staticVar = 10; // Static variable

public static void main(String[] args) {


[Link]("Static variable: " + [Link]);
}
}

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

// accessing static variable without object


[Link] = 1000;
[Link] ([Link] + "'s average salary:" + [Link]);
}
}
Output: Harsh’s average salary:1000.0
SYMBOLIC CONSTANTS IN JAVA

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.

Key Keyword: final

Using the final Keyword for Constants


In Java, the final keyword is used to declare a variable as a constant. Once a final variable is
initialized, its value cannot be changed.

Syntax: [access_modifier] static final data_type CONSTANT_NAME = value;

 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

public static final dataType CONSTANT_NAME = value;


}

Example:
public class Circle {
// Symbolic constant for Pi
public static final double PI = 3.14159;

public static void main(String[] args) {


double radius = 5.0;
double area = PI * radius * radius;

[Link]("Radius: " + radius);


[Link]("Area of the circle: " + area);
}
}
Output:
Radius: 5.0
Area of the circle: 78.53975

public class MyConstants {


// A public, static, and final integer constant
public static final int MAX_USERS = 100;
// A public, static, and final double constant for PI
public static final double PI = 3.14159;
// A public, static, and final String constant for an API base URL
public static final String API_BASE_URL = "[Link]
// A private, final constant (only accessible within this class)
private final int CONFIG_VERSION = 1;
public static void main(String[] args) {
[Link]("Maximum users allowed: " + MyConstants.MAX_USERS);
[Link]("Value of PI: " + [Link]);
[Link]("API URL: " + MyConstants.API_BASE_URL);
// This would cause a compile-time error:
// MyConstants.MAX_USERS = 200; // Cannot assign a value to a final variable
}
}

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.

There are two types of Type Casting in Java:


 Widening Type Casting
 Narrow Type Casting
41

Widening Type Casting (Implicit Type Casting)


In Widening Type Casting, Java automatically converts one data type to another data type. i.e;
A lower data type is transformed into a higher one by a process known as widening type casting.
It occurs naturally. Since there is no chance of data loss, it is secure.
Widening Type casting occurs when:
 The target type must be larger than the source type.
 Both data types must be compatible with each other.
Syntax:
larger_data_type variable_name = smaller_data_type_variable;

public class ImplicitTC {


public static void main(String[] args) {
byte mybyte =5;
int myInt = mybyte;// Automatic casting: byte to int
double myDouble = myInt; // Automatic casting: int to double
[Link](mybyte);
[Link](myInt);
[Link](myDouble);
}
}
Output:
5
5
5.0

Here, the Java first converts the int type data into the double type. And then assign it to
the double variable.s

Narrowing Type Casting(Explicit Type Casting)


In Narrowing Type Casting, we manually convert one data type into another using the
parenthesis. i.e; the higher data types (having larger size) are converted into lower data types
42

(having smaller size). Hence there is the loss of data. This is why this type of conversion does
not happen automatically.

Syntax: smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;

// Java Program to demonstrate Narrow type casting


import [Link].*;

class ExplicitTC {
public static void main(String[] args)
{
double i = 100.245;

// Narrowing Type Casting


short j = (short)i;
int k = (int)i;

[Link]("Original Value before Casting" + i);


[Link]("After Type Casting to short " + j);
[Link]("After Type Casting to int " + k);
}
}

Output
Original Value before Casting100.245
After Type Casting to short 100
After Type Casting to int 100

Program Illustration of type casting.


class TypeCast
{
public static void main (String args[])
{

int a=4, b = 8, c = 9, d,e;


double x= 3.0, y=6.5, z,k;
d=c/a;
43

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

[Link] C:\ >java

TypeCast
k = 10.5 and e =10
d= 2 and z = 2.25

Automatic Type Promotion in Expressions


While evaluating expressions, the intermediate value may exceed the range of operands and
hence the expression value will be promoted. Some conditions for type promotion are:
1. Java automatically promotes each byte, short, or char operand to int when evaluating
an expression.
2. If one operand is long, float or double the whole expression is promoted to long, float,
or double respectively.

Example:
classGFG {

// Main driver method


publicstaticvoidmain(String args[])
{

// Declaring and initializing primitive types


byteb = 42;
charc = 'a';
shorts = 1024;
inti = 50000;
floatf = 5.67f;
doubled = .1234;
44

// The Expression
doubleresult = (f * b) + (i / c) - (d * s);

// Printing the result obtained after


// all the promotions are done
[Link]("result = "+ result);
}
}

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.

FORMATTED OUTPUT WITH printf() METHOD


The printf() method in Java, part of the PrintStream class (e.g., [Link]()), is used for
producing formatted output to the console or other output streams. It is inspired by
the printf() function in C.
Formatting Using Java Printf()
printf() uses format specifiers for formatting. There are certain data types are mentioned below:
For Number Formatting
Formatting Decimal Numbers
For Boolean Formatting
For String Formatting
For Char Formatting
For Date and Time Formatting
Common Conversion Characters:
• %s: String
• %d: Decimal integer
• %f: Floating-point number (e.g., float, double)
• %c: Character
• %b: Boolean
• %n: Line separator (platform-independent newline)

i). For Number Formatting


45

The number itself includes Integer, Long, etc. The formatting Specifier used is %d.

// Java Program to demonstrate Use of printf to Formatting Integer


import [Link].*;
class NumberFormat {
public static void main (String[] args) {
int a=10000;
[Link]("%,d%n",a);
}
}
Output
10,000

ii). For Decimal Number Formatting


Decimal Number Formatting can be done using print() and format specifier %f .

// Use of Printf() for decimal Number Formatting


import [Link].*;
class DecimalNumFormat {
public static void main(String[] args)
{
double a = 3.14159265359;
// Printing Double Value with different Formatting
[Link]("%f\n", a);
[Link]("%5.3f\n", a);
[Link]("%5.2f\n", a);
}
}
Output
3.141593
3.142
3.14
46

iii). For Boolean Formatting


Boolean Formatting can be done using printf and ( '%b' or '%B' ) depending upon the result
needed.

// Java Programs to demonstrate Use of Printf() for decimal Boolean Formatting


import [Link].*;
class BooleanFormat {
public static void main(String[] args)
{
int a = 10;
Boolean b = true, c = false;
Integer d = null;
// Fromatting Done using printf
[Link]("%b\n", a);
[Link]("%B\n", b);
[Link]("%b\n", c);
[Link]("%B\n", d);
}
}

Output
true
TRUE
false
FALSE

iv). For Char Formatting


Char Formatting is easy to understand as it need printf() and Charracter format specifier used
are '%c' and '%C'.

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

v). For String Formatting


String Formatting requires the knowledge of Strings and format specifier used '%s' and '%S'.

// Java Program to implement Printf() for String Formatting


import [Link].*;
class StringFormat {
public static void main(String[] args)
{
String str = "javaprogramming";
// Formatting from lowercase to Uppercase
[Link]("%s \n", str);
[Link]("%S \n", str);

str = "JAVA";
// Vice-versa not possible
[Link]("%S \n", str);
[Link]("%s \n", str);
}
}

Output
48

javaprogramming
JAVAPROGRAMMING
JAVA
JAVA

vi). For Date and Time Formatting


Formatting of Date and Time is not as easy as the data-type used above. It uses more than simple
format specifier knowledge can be observed in the example mentioned below.

// Java Program to demonstrate use of printf() for formatting Date-time


import [Link].*;
import [Link].*;

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

// Another Method to print the time Followed by am/pm , time in milliseconds


// nanoseconds and time-zone offset
[Link]("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n", 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 Operator in Java

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

! Logical complement operator

Unary Operator in Java Example

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

[Link]("Value of b: " + b);

// decrement operator
result2 = --b;

[Link]("After decrement: " + result2);

}
}

Output

Value of a: 13
After increment: 14
Value of b: 13
After decrement: 12

Java Arithmetic Operators


Arithmetic Operators in Java are particularly used for performing arithmetic operations on given
data or variables. There are various types of operators in Java, such as

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

Relational Operators in Java

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

== Is equal to 3 == 5 returns false

!= Not equal to 3 != 5 returns true

> Greater than 3 > 5 returns false


52

Operators Description Example

< Less than 3 < 5 returns true

>= Greater than or equal to 3 >= 5 returns false

<= Less than or equal to 3 <= 5 returns true

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

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.

Operators Example Meaning

&& [ logical AND ] expression1 && expression2 (true) only if both of the expressions are true

|| [ logical OR ] expression1 || expression2 (true) if one of the expressions in true

! [ logical NOT ] !expression (true) if the expression is false and vice-versa

Logical Operators in Java Example

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

Java Ternary Operator


Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in
Java programming. It is the only conditional operator which takes three operands.
Java Ternary Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. [Link](min);
7. } }
Output:
2

Bitwise Operators in Java

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

<< Left shift

>> Right shift

>>> Unsigned Right shift

& Bitwise AND


55

Operators Descriptions

^ Bitwise exclusive OR

Bitwise AND (&)


It is a binary operator denoted by the symbol &. It returns 1 if and only if both bits are 1, else
returns 0.

[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

Let's use the bitwise complement operator in a Java program.


[Link]
1. public class BitwiseComplimentExample
2. {
3. public static void main(String[] args)
4. {
5. int x = 2;
6. // bitwise compliment
7. // ~0010= 1101 = -3
8. [Link]("~x = " + (~x));
9. }
10. }
Output
~x = -3
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.
Java Left Shift Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. [Link](10<<2);//10*2^2=10*4=40
4. [Link](10<<3);//10*2^3=10*8=80
5. [Link](20<<2);//20*2^2=20*4=80
6. [Link](15<<4);//15*2^4=15*16=240
7. }}
Output:
40
80
80
240
58

Java Right Shift Operator


The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.
Java Right Shift Operator Example
1. public OperatorExample{
2. public static void main(String args[]){
3. [Link](10>>2);//10/2^2=10/4=2
4. [Link](20>>2);//20/2^2=20/4=5
5. [Link](20>>3);//20/2^3=20/8=2
6. }}
Output:
2
5
2

Bit Shift Operators


Shift operator is used in shifting the bits either right or left. We can use shift operators if we
divide or multiply any number by 2. The general format to shift the bit is as follows:
1. variable << or >> number of places to shift;
For example, if a=10
1. a>>2; //shifts two bits
2. a>>4; //shifts 4 bits
Java provides the following types of shift operators:
o Signed Right Shift Operator or Bitwise Right Shift Operator
o Unsigned Right Shift Operator
o Signed Left Shift Operator or Bitwise Left Shift Operator
Note: Java does not support the unsigned left shift operator (<<<).

Unsigned Right Shift Operator (>>>)


It shifts a zero at the leftmost position and fills 0. It is denoted by the symbol >>>. Note that the
leftmost position after >> depends on the sign bit. It does not preserve the sign bit.
Example: If a=11110000 and b=2, find a>>>b?
a >>> b = 11110000 >>> 2 = 00111100
The left operand value is moved right by the number of bits specified by the right operand and
the shifted bits are filled up with zeros. Excess bits shifted off to the right are discarded.
59

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

Control Statements: Introduction, if Expression, Nested if Expressions, if–else


Expressions,TernaryOperator?:,SwitchStatement,IterationStatements,whileExpression,do–
whileLoop,forLoop,NestedforLoop,For–EachforLoop,BreakStatement,ContinueStatement.

Java Control Statements | Control Flow in Java


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.
Java provides three types of control flow statements.
1. Decision Making statements
o if statements
o switch statement
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
60

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

[Link](number + " is an even number.");


else
[Link](number + " is an odd number.");
}
}
Output:

Enter the number


23
23 is an odd number.
3) if-else-if ladder:
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.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Consider the following example.
[Link]
1. public class Student {
2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. [Link]("city is meerut");
6. }else if (city == "Noida") {
7. [Link]("city is noida");
8. }else if(city == "Agra") {
63

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;

if (perc >= 90)


grade = "A+";
else if ((perc >= 80) && (perc < 90))
grade = "A";
else if ((perc >= 70) && (perc < 80))
grade = "B";
64

else if ((perc >= 60) && (perc < 70))


grade = "C";
else if ((perc >= 50) && (perc < 60))
grade = "D";
else if ((perc >= 40) && (perc < 50))
grade = "E";
else
grade = "F";

[Link]("The percentage of the student is: " + perc);


[Link]("The grade of the student is: " + grade);
}
}
Output:: Enter the 3 subject marks:
Enter the 1st subject marks:
67
Enter the 2nd subject marks:
78
Enter the 3rd subject marks:
87
Total Marks: 232.0
The percentage of the student is: 77.33333333333333
The grade of the student is: B
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.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
65

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

else if ((perc >= 70) && (perc < 80))


grade = "B";
else if ((perc >= 60) && (perc < 70))
grade = "C";
else if ((perc >= 50) && (perc < 60))
grade = "D";
else if ((perc >= 40) && (perc < 50))
grade = "E";
}
else {
grade = "F";
}
[Link]("The percentage of the student is: " + perc);
[Link]("The grade of the student is: " + grade);
}
}
Output:
Enter the 3 subject marks:
Enter the 1st subject marks:
90
Enter the 2nd subject marks:
35
Enter the 3rd subject marks:
69
Total Marks: 194.0
The percentage of the student is: 64.66666666666666
The grade of the student is: F
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.
Points to be noted about switch statement:
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression.
It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o 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.
67

The syntax to use the switch statement is given below.


1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Consider the following example to understand the flow of the switch statement.
[Link]
1. public class Student implements Cloneable {
2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. [Link]("number is 0");
7. break;
8. case 1:
9. [Link]("number is 1");
10. break;
11. default:
12. [Link](num);
13. }
14. }
15. }
Output:
2
68

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,

 array - an array or a collection


 item - each item of array/collection is assigned to this variable
 dataType - the data type of the array/collection
70

[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};

// for each loop


for (int n1: numbers) {
[Link](n1);
}
}
}
Output:
3
9
5
-5
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.
71

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.

Consider the following example.


Calculation .java
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. while(i<=10) {
7. [Link](i);
8. i = i + 2;
9. }
10. }
11. }
Output:
Printing the list of first 10 even numbers
72

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

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
[Link]
1. public class BreakExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. [Link](i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
[Link]
1. public class Calculation {
2. public static void main(String[] args) {
3. a:
4. for(int i = 0; i<= 10; i++) {
5. b:
6. for(int j = 0; j<=15;j++) {
7. c:
75

8. for (int k = 0; k<=20; k++) {


9. [Link](k);
10. if(k==5) {
11. break a; }
12. }
13. }
14. }
15. }
16. }
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) {
for (int j = 1; j<=5; j++) {
if(j == 3) {
continue;
}
[Link](j);
}
}
}
Output:
1
2
3
5
76

You might also like