0% found this document useful (0 votes)
5 views54 pages

Java 1st Unit

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views54 pages

Java 1st Unit

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OBJECT ORIENTED PROGRAMMING THROUGH JAVA

OBJECT ORIENTED PROGRAMMING THROUGH JAVA

Why do we need Programming language?

Computers are powerful tools capable of performing complex operations at very fast
speeds. CPU relies on binary sequences (it means —strings of 0s and 1s—) because
the CPU only understands machine language. Writing instructions in binary for even
simple tasks would be difficult and error-prone for humans. This is where programming
languages come into play, acting as a bridge between human-readable instructions and
the binary sequences understood by computers.

How CPU Works with Programming Languages?

The CPU (Central Processing Unit) is the brain of a computer. It follows a series of steps
to process instructions:

• Fetch: Get the instructions.


• Decode: Figure out what the instruction means.
• Execute: Perform the action.
The CPU understands only machine code (binary). So how does it work with
programming languages like Java, Python or C++?
The answer is compilers and interpreters. These tools convert the human-friendly
code into machine code the CPU can process.

Compilers and Interpreters: The Translators

Programming languages, like English or any natural language, need translators for a CPU
to understand them. These translators are categorized into two types:

1. Compilers
• A compiler translates the entire source code of a program into machine code
before execution.
• Once compiled, the machine code can be executed directly by the CPU without the
need for further translation.
• Examples of compiled languages include C, C++, and Go.

2. Interpreters
• An interpreter processes the code line by line, translating and executing each
instruction sequentially.
• Interpreters are more flexible but often slower compared to compilers because
the translation happens during runtime.
• Examples of interpreted languages include Python, Ruby, and JavaScript.

Introduction to Java
Java is one of the most popular languages, it was introduced in 1995 by Sun Microsystems
(now owned by Oracle Corporation). Its unique features like platform independence and
robustness have made it the preferred choice for millions of developers globally.

Here, we are going to discuss the reasons for the popularity of the Java Programming
language

1. Platform Independent

One of the key reasons for Java's popularity is platform independence. Java achieves
platform independence through its unique compilation and runtime process. Before we
talk about how Java is platform-independent let's discuss the concept of a platform. A
platform is the combination of hardware and software environment where a program
runs. For example Windows, macOS, and Linux.
How Java Works?

Java’s compilation process is different from programming languages like C/C++. When
we write a Java program, the Java compiler compiles it into an intermediate, platform-
independent code called bytecode. This bytecode can run on any platform that has
JVM(Java Virtual Machine) installed.

What is Java Virtual Machine (JVM)?

The Java Virtual machine is a software responsible for running Java bytecode on a
physical machine. Each platform (Windows, Linux, macOS) has its own implementation
of the JVM. However, the bytecode remains the same which ensures that Java programs
are truly platform-independent. As a programmer, you don’t need to worry about
installing the JVM separately, as it comes bundled with the JDK installation.

2. Popular

Java is a very popular language. Java covers over 3 billion devices worldwide and has a
community of 9 million developers and is the primary language for Android development.

3. Simple

Java syntax is very straight forward and very easy to learn. Java removes complex
features like pointers and multiple inheritance, which makes it more beginner friendly.
4. Secure

Java programming language is designed to be safe and secure.

• Built-in Safeguards: Java has features to stop harmful code from running.
• Runtime Checks: Java checks the code while it’s running to ensure nothing
dangerous happens.
• Protects Your System: This helps prevent viruses or malicious programs from
causing damage.

5. Statically Typed

In Java every variable must be explicitly declared with a type, which minimizes runtime
errors.

Similarities and Differences of Java with C/C++ and Python


Java is close to C/C++

• Java borrows much of its syntax and structure from C/C++, such as curly braces
and the use of semicolons.
• Java eliminates complexities like pointers and manual memory management.

Java is Different from Python

• Java requires explicit declarations of variables. Java is more organized and better
at avoiding error while running
• In Python you do not need to specify the type of a variable

JDK (JAVA DEVELOPMENT KIT)

Java is a versatile, platform-independent programming language that can run on any


device equipped with the Java Runtime Environment (JRE).

JDK stands for Java Development Kit. It is a software development kit that provides tools
and libraries for developing Java applications.

JDK is an essential toolkit for Java developers. It includes:

• Java Virtual Machine (JVM): The JVM is the engine that runs Java programs. It
converts bytecode into machine code to execute your program. The JVM ensures
Java's "Write Once, Run Anywhere" capability.
• Java Class Libraries: These are pre-written code libraries that help simplify
complex tasks.
• Together, the JVM and class libraries form the Java Runtime Environment (JRE),
which is required to execute Java applications.

What is JRE? (Java Runtime Environment)

JRE stands for Java Runtime Environment. It is required to run the Java Program. It
provides the libraries, JVM, and other components necessary to execute Java applications.

What is JVM? (Java Virtual Machine)

JVM stands for Java Virtual Machine. JVM is called an abstract virtual machine because it
does not exist physically, but it is a kind of specification that provides a secure runtime
environment to execute the bytecode generated through the compiler, JVM invokes the
main ( ) method present in the Java program. JVM is the part of JRE.

How the JVM Works?

The JVM can execute code using two primary methods:

1. Interpreter: Translates bytecode to machine code line by line. This approach is


slower because it processes code at runtime.
2. JIT (Just-In-Time Compilation): Converts bytecode into native machine code in
bulk during execution, significantly improving performance. JIT is the most
preferred approach for its speed and efficiency.

Developer Tools in JDK

The JDK also provides essential tools for development:

• Java Compiler: Converts Java source code into bytecode.


• Java Debugger: Helps identify and fix issues in your code.
• Java Document Generator: Creates documentation from your code comments.
JDK Architecture

First Program - "Hello World"


The below-given program is the simplest program of Java, printing "Hello World" to the
screen. Let us try to understand every bit of the code step by step.

Output

Hello, World
Explanation: The "Hello World!" program consists of three primary components: the Test
class definition, the main method, and the source code comments. The following explanation
will provide you with a basic understanding of the code:

1. Class Definition

The class keyword declares a new class.

Syntax:

class Test

• Test is the name of the class (an identifier). The class name must match the file name
([Link])
• Everything inside the class is enclosed within { and }

2. Main Method

The main method is the entry point for the program

Syntax:

public static void main(String[] args)

• public: So that JVM can execute the method from anywhere.


• static: Main method is to be called without object. The modifiers public and static can
be written in either order.
• void: The main method doesn't return anything.
• main(): Name configured in the JVM.
• String[]: The main method accepts a single argument: an array of elements of type
String.

3. Printing Output

Syntax:

[Link]("Hello, World!");

This statement prints the string "Hello, World!" to the console


• System: A predefined class providing access to system resources.
• out: A static variable in the System class that represents the standard output stream
(console).
• println: A method to print the output with a line break.

4. Comments

They can either be multi-line or single-line comments.

Multi-line Comments

Start with /* and end with */. Used for multi-line explanations.

/* This is a simple Java program. Call this file "[Link]". */

Single-line Comments

Begin with // and end at the line break. Used for brief explanations.

// This is a single-line comment.

Important Points

1. Class Name and File Name:


o The name of the class (Test) must match the file name ([Link]).
o This is mandatory in Java when a public class is defined.
2. Main Class:
o A program can have only one public class with the main method.
3. Code Structure:
o All Java code resides inside a class, and the execution starts from
the main method.
TOKENS IN JAVA

In Java, Tokens are the smallest elements of a program that is meaningful to the
compiler. They are also known as the fundamental building blocks of the program.
Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants/Literals
4. Operators
5. Separators
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. Since keywords are
referred names for a compiler, they can’t be used as variable names because by doing
so, we are trying to assign a new meaning to the keyword which is not allowed.
Eg : int, float, if, else, break, continue etc

2. Identifiers
Identifiers are used as the general terminology for naming of variables, functions and
arrays. These are user-defined names consisting of an arbitrarily long sequence of
letters and digits with either a letter or the underscore (_) as a first character. Identifier
names must differ in spelling and case from any keywords. You cannot use keywords
as identifiers; they are reserved for special use. Once declared, you can use the
identifier in later program statements to refer to the associated value.

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:

final datatype variable_name;


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
• instance of operator
• Precedence and Associativity
5. Separators
Separators are used to separate different parts of the codes. It tells the compiler about
completion of a statement in the program. The most commonly and frequently used
separator in java is semicolon (;).

Types of Statements in Java


Java statements are instructions that perform actions and form the fundamental building
blocks of a Java program. They can be broadly categorized into the following types:
1. Declaration Statements:

These statements are used to declare variables, methods, or classes. They introduce new
entities into the program and specify their type and often their initial value.

Eg: int count; // Declares an integer variable named count

String name = "Java"; // Declares a String variable and initializes it

2. Expression Statements:

These statements consist of an expression followed by a semicolon. The expression is


evaluated, and its side effects are typically the primary purpose of the statement.

Eg: x++; // Increments the value of x


[Link]("Hello"); // Calls a method to print to the console

3. Control Flow Statements:

These statements govern the order in which other statements are executed, allowing for
decision-making and repetition.

• Decision-Making Statements:

• if statement: Executes a block of code if a condition is true.

• if-else statement: Executes one block if a condition is true, and another if it's false.

• if-else-if ladder: Allows for checking multiple conditions sequentially.

• switch statement: Provides a multi-way branch based on the value of an


expression.
• Looping Statements (Iteration Statements):

• for loop: Executes a block of code a specific number of times or iterates over
collections.

• while loop: Repeats a block of code as long as a condition remains true.

• do-while loop: Similar to while, but guarantees at least one execution of the loop
body.
• Jump Statements:
• break statement: Exits from a loop or a switch statement.

• continue statement: Skips the rest of the current loop iteration and proceeds to the
next.

• return statement: Exits from the current method and optionally returns a value.
4. Block Statements:

A block statement is a group of zero or more statements enclosed within curly


braces {}. Blocks are often used with control flow statements to define the scope of
execution.

Eg: if (condition) {

// Statements within the if block

Command line Arguments

Java command-line argument is an argument, i.e., passed at the time of running the
Java program. In Java, the command line arguments passed from the console can be
received in the Java program, and they can be used as input. The users can pass the
arguments during the execution, bypassing the command-line arguments inside
the main( ) method.

Why Use Command Line Arguments?


• It is used because it allows us to provide input at runtime without modifying the
whole program.
• It helps to run programs automatically by giving them the needed information
from outside.
Working of Command-Line Arguments
We need to pass the arguments as space-separated values. We can pass both strings and
primitive data types(int, double, float, char, etc) as command-line arguments. These
arguments convert into a string array and are provided to the main() function as a string array
argument.
Class Hello{

public static void main(String[ ] args){

int a=[Link](args[0);

int b=[Link](args[1]);

[Link](a+b);

}
}

Variables in Java
A variable is a name given to a memory location. It is the basic unit of storage in a program.

• The value stored in a variable can be changed during program execution.


• A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
• In Java, all the variables must be declared before use.
How to declare variables?
We can declare variables in java as follows:
• Data Type: Type of data that can be stored in this variable.
• Variable Name: Name given to the variable.
• Value: It is the initial value stored in the variable.

Examples:

//Declaring float variable


float simpleInterest;
//Declaring and Initializing integer variable
int time = 10, speed = 20;
// Declaring and Initializing character variable
char var = 'h';

Variable Naming
Java has specific rules and conventions for naming variables:

Rules
• Variable names can include letters (a-z, A-Z), numbers (0-9), underscore (_),
and dollar sign ($).
• Variable names must not begin with a number.
• Reserved keywords (e.g., else, for, while) cannot be used as variable names.

Syntax of Valid Naming:

int age; // A simple integer variable

int _name; // An integer variable starting with an underscore

double totalAmount; // A double variable for storing decimal values

String dollar$sign; // A string variable with a dollar sign in the name

Syntax of Invalid Naming:

int 123abc; // starts with a number

int a#name; // contains a disallowed character


int else; // a reserved keyword

Data Types in Java


Data types are different sizes and values that can be stored in the variable that is made as per
convenience and circumstances to cover up all test cases.

First, one is a Statically typed language where each variable and expression type is already
known at compile time. Once a variable is declared to be of a certain data type, it cannot hold
values of other data types. For example C, C++, and Java.

The other is Dynamically typed languages. These languages can receive different data types
over time. For example Ruby, Python

Java is statically typed and also a strongly typed language because, in Java, each type of
data (such as integer, character, hexadecimal, packed decimal, and so forth) is predefined as
part of the programming language and all constants or variables defined for a given program
must be described with one of the data types.
1) Primitive Data Types

Primitive data types are the basic or built-in data types provided by java to store values.
There are again classified into Non-numeric and numeric data types.

1.1 Non-Numeric Type

These data types are used for textual or logical data. There are two categories in it:

a) Boolean Type

In Java, the boolean data type is used to store true or false values. It is one of the primitive
data types in Java.

Syntax:

boolean a=true;

The default value of Boolean type is false when declared inside the class as it is treated as
instance variable.

-> Here true or false values are not strings, so no quotes required. Here true or false are
Boolean literals.

Size: 1 byte(8 bits)

Eg:

class Asc{

public static void main( String[ ] args ){

//boolean boolval=true;

[Link](“Is fish tasty? ”+boolval);

Output:

Is fish tasty? true


b) Char

-> It stores Unicode characters (‘A’, ’#’, etc)

-> It is a non-numeric datatype which is used to store a single character.

-> The default value of char is ‘\u0000’ which is a null character in Unicode. Generally it is a
space when the char value is declared inside the class.

Syntax: char a=’c’;

Size: 2 bytes (16 bits)

Range: 0 to 65,535

Hence, there are 65,535 different characters in java.

1.2 Numeric Type

These data types are used to represent numbers, either whole numbers (integers) or floating-
point(decimals).

a) Integer Type

1) byte

-> byte is an Integer type.

-> It is useful when working with small data to save memory.

-> The default value of byte is 0 when declared inside the class.

Syntax: byte a=10;

Size: 1 byte (8 bits)

Range: -128 to 127

2) short

-> short is an Integer type.

-> The default value of short is 0 when declared inside the class.

Syntax: short a=20;


Size: 2 bytes (16 bits)

Range: -32768 to 32767

3) int

-> int is an Integer type

-> The default value of int is 0 when declared inside the class.

Syntax: int a=100;

Size: 4 bytes (32 bits)

Range: -2,14,74,83,648 to 2,14,74,83,647

4) long

-> long is an integer type

-> The default value of long is 0 when declared inside the class

-> It is generally used to store large integers

-> The value must be suffixed with L

Syntax: long a=123456789L;

Size: 8 bytes (64 bits)

Range: - 92,23,37,20,36,85,47,75,808 to 92,23,37,20,36,85,47,75,807

b) Floating-point Type

1) float

-> It is a single-precision floating-point data type.

-> Used for saving memory in large arrays of decimal numbers.

-> Must be suffixed with f.

-> The default value of float is 0.0 when declared inside the class.

Syntax: float a=1.23f;

Size: 4 bytes (32 bits)


2) double

-> It is a double-precision floating-point data type.

-> It is the default type for decimals in java

-> Suitable for high-precision calculations (Scientific values)

-> The default value of double is 0.0 when declared inside the class.

Syntax: double a =2.3456;

Size: 8 bytes (64 bits)

2. Non-Primitive Data Types

Non-primitive data types are also known as reference types. Unlike primitive types which
store actual values, non-primitive types store references (addresses) to memory locations
where data is stored.

Examples of non-primitive data types include:

1. String:

A class in Java used to store a sequence of characters.

Unlike primitive types, it supports many built-in methods (e.g., length(), toUpperCase()).

2. Array:

A container object that holds multiple values of the same data type.

Syntax: int[] numbers = new int[5];

3. Class:

A blueprint for creating user-defined data types (objects).

It defines properties (fields) and behaviour (methods) of objects.

4. Object:

An instance of a class.

It allows us to use class features like variables and methods.


5. Interface:

A reference type in Java that defines a contract for classes to follow.

Used for abstraction and multiple inheritance.

Escape Sequences in Java

Escape sequences in java are special characters preceded by a backslash (\), that are used to
represent characters that are either invisible, non-printable, printable or have a special
meaning in strings and characters.

They help format output or represent characters that are hard to type directly, such as
newline, tab, or double quotes.
Comments
Comments are lines in a java program that are ignored by the compiler. They are used to:

-> Explain code for better readability

-> Describe the logic or purpose of code blocks

-> Adds documentation for methods or classes


Types of Comments:

1) Single line Comments:


-> Used for short notes or explanation on a single line.

-> Starts with //

Eg: //This is a single line comment

2) Multi-line Comments:

->Starts with /* and ends with */

-> Used for long explanations generally used for the multiple lines of comments.

Eg: /* this is

a multi line
comment*/
3) Documentation comments

-> Special form of multi-line comment

-> Starts with /** and ends with */

-> Used to generate external documentation (JavaDoc)

-> Placed above classes, methods, fields

-> It describes the purpose and behaviour of methods and classes

Programming Style in java

Programming style refers to a set of guidelines and conventions that make your Java code:

-> Easy to read

-> Easy to understand

-> Easy to maintain

-> Consistent across teams

Type Casting:

Type casting in Java is the process of converting a variable from one data type to another. This
is crucial when performing operations involving different data types or when converting
between primitive data types and their corresponding wrapper classes.

Types of Type Casting:

1) Implicit Type Casting

2) Explicit Type Casting

1) Implicit Type Casting (Widening Type Casting):

A lower data type is transformed into a higher one by a process known as widening type
casting. Implicit type casting and casting down are some names for it. 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.
2) Explicit Type Casting (Narrowing Type Casting):

The process of downsizing a bigger data type into a smaller one is known as narrowing type
casting. Casting up or explicit type casting are other names for it. It doesn't just happen by
itself. If we don't explicitly do that, a compile-time error will occur. Narrowing type casting
is unsafe because data loss might happen due to the lower data type's smaller range of
permitted values. A cast operator assists in the process of explicit casting.
Scope of a Variable in Java:

The scope of a variable in Java defines the region of the program where that variable can be
accessed and its lifetime in memory. Java has three primary types of variable scope:

1) Local Variables:

• Scope: Declared within a method, constructor, or any block of code


(e.g., if block, for loop).

• Accessibility: Only accessible within the block where they are declared and
any nested blocks.

• Lifetime: Created when the block is entered and destroyed when the block is
exited.

• Initialization: Must be explicitly initialized before use.


2) Instance Variables (Non-Static Fields):

• Scope: Declared within a class but outside any method, constructor, or block.

• Accessibility: Accessible by all methods, constructors, and blocks within the


same class.

• Lifetime: Created when an object of the class is instantiated and destroyed


when the object is garbage collected.

• Initialization: Automatically initialized to default values if not explicitly


assigned (e.g., 0 for numeric types, null for objects, false for boolean).
3) Class Variables (Static Fields):
• Scope: Declared within a class using the static keyword.

• Accessibility: Accessible by all methods, constructors, and blocks within the


same class, and can be accessed directly using the class name
(e.g., [Link] )

• Lifetime: Created when the class is loaded into memory by the JVM and
persists for the entire duration of the program's execution.

• Initialization: Automatically initialized to default values if not explicitly


assigned, similar to instance variables.
Literal Constants:
In Java, a Literal constant is value of boolean, numeric, character, or string data. Any constant
value that can be assigned to the variable is called a literal.
Eg: int x=101;
boolean y=true;
Types of Literals in Java
Java supports the following types of literals:
• Integral Literals
• Floating-Point Literals
• Char Literals
• String Literals
• Boolean Literals
Symbolic Constants
-> In Java, a symbolic constant is a variable whose value cannot be changed after it is
assigned and which is referred to by a symbolic name, instead of a hard-coded literal.
-> These are created using the final keyword and are typically written in uppercase
letters by convention.
Eg: final double PI=3.14;
Formatted Output with printf( ) method:
• Formatted output means displaying output in a structured and readable way using
placeholders, alignment, precision, and formatting rules.
• In Java, the [Link]( ) method is used for this purpose, similar to C's
printf( ).
Syntax:
[Link](“format string”,arguments);
o Format string: contains format specifiers like %d, %f, %s
o Arguments: values that replace the specifiers

Static methods:

➢ The keyword static means "belonging to the class, not to any specific object".
➢ When a variable or method is marked static. It can be accessed without creating any object.
➢ Only one copy exists in the memory for the entire class.
Precedence and Associativity of operators:

In Java, precedence and associativity determine the order in which operators are evaluated
in expressions.

Precedence:

Precedence defines which operator is evaluated first when two different operators appear
in an expression.

Associativity:

Associativity defines the direction (left-to-right or right-to-left) in which an expression is


evaluated when two operators of the same precedence appear together.

Arithmetic operators:

Arithmetic operators in Java are used to perform basic mathematical operations such as
addition, subtraction, multiplication, division, and modulo (remainder). These operators
work with primitive numeric types like int, float, double, long, etc.

Eg: +, -, *, /, %
Assignment Operators

Assignment operators in Java are used to assign values to variables. The most basic one is =,
but Java provides many compound assignment operators that combine arithmetic or bitwise
operations with assignment.

Eg: +=, -=, *=, /=, %=, =

In Java, arithmetic operations on smaller data types like byte, short, or char are promoted to
int during evaluation. This is called automatic type promotion in expressions.

Output:
Increment and decrement operators

In Java, the increment (++) and decrement (--) operators are unary operators used to increase
or decrease a variable’s value by 1.

These operators help simplify code, especially in looping, counter logic, and array indexing.

Prefix:

++a or --a
Here variable is updated before its value is used

Postfix:

a++ or a--

Here variable is updated after its value is used.

Ternary Operator:

The Ternary Operator is a shorthand way of writing simple if-else conditions in a single line.
It is called "ternary" because it works with three operands.

Syntax:

condition? Expression_if_true : expression_if_false;


Where,

condition → a boolean expression (true or false)

If the condition is true, the first expression (expression_if_true) is evaluated.

If the condition is false, the second expression (expression_if_false) is evaluated.


Output:

20

Relational Operators:

Relational operators in Java are used to compare two values or expressions. They return a
boolean result (true or false) based on the comparison.

They are called "relational" because they test the relationship between two operands — like
greater than, equal to, etc.

Eg: ==

!=

>=

<=
Output:

Boolean Logical Operators:

Boolean logical operators in Java are used to perform logical operations on boolean expressions
(true or false). These operators are mostly used in decision-making statements (if, while, etc.)
and in expressions that evaluate conditions.

1. && (Logical AND)

Returns true only if both operands are true else it returns false.

Syntax: expr1 && expr2


Output:

Both conditions are true.

2. || (Logical OR)

Returns true if at least one operand is true and returns false if both operands are false.

Syntax: expr1 || expr2

Output:

At least one condition is true


3) ! (Logical NOT)

Reverses the value of a boolean expression.

If expr is true, result is false, and vice versa.

Syntax:- !expr

Output:

false

Bitwise Operators:

Bitwise operators work on individual bits. It works with integer types (byte, short, int, long).
When a bitwise operation is performed, each bit of the particular number is treated as an
individual based on the operation.

1. Bitwise AND (&)


This operator is a binary operator, denoted by '&.' It returns bit by bit AND of input values,
i.e., if both bits are 1, it gives 1, else it shows 0.

2. Bitwise OR (|)
This operator is a binary operator, denoted by '|'. It returns bit by bit OR of input values, i.e.,
if either of the bits is 1, it gives 1, else it shows 0.

3. Bitwise XOR (^)


This operator is a binary operator, denoted by '^.' It returns bit by bit XOR of input values,
i.e., if corresponding bits are different, it gives 1, else it shows 0.
4. Bitwise Complement (~) :
This operator is a unary operator, denoted by '~.' It returns the one's complement
representation of the input value, i.e., with all bits inverted, which means it makes every 0 to
1, and every 1 to 0.

5. Bitwise left shift operator


The left shift operator shifts all bits towards the left by a certain number of specified bits. It is
denoted by <<.
Eg: 10 << 2
10 = 00000000 00000000 00000000 00001010

10 << 2 = 00000000 00000000 00000000 00101000 => 40


6. Bitwise right shift operators

The signed right shift operator shifts all bits towards the right by a certain number of specified
bits. It is denoted by >>.

When we shift any number to the right, the least significant bits (rightmost) are discarded and
the most significant position (leftmost) is filled with the sign bit. (i.e. 0 for positive and 1 for
negative)

8. Bitwise Unsigned right shift Operator

Java also provides an unsigned right shift. It is denoted by >>>.


Here, the vacant leftmost position is filled with 0 instead of the sign bit.
In Unsigned right shift operator, the negative values also return large positive values.
Output:

1073741821

Control Statements:

A programming language uses control statements to control the flow of execution of a


program. They help in making decisions, repeat operations, and manages the code execution
based on certain conditions.

If-statement:

The if statement is the simple decision-making statement. If a certain condition is true then
a block of statements is executed otherwise not.

Syntax:
if(condition) {
// Statements to execute if
// condition is true
}
Flow Chart:

Eg:

2. If-else statement

If a certain condition is true then a block of statements is executed otherwise the else block
of statements will be executed.
Syntax:
if(condition){
// Executes this block if
// condition is true
}else{
// Executes this block if
// condition is false
}
Flow chart:
3. nested-if Statement
A nested if is an if statement that is the target of another if or else. Nested if statements mean
an if statement inside an if statement.
Syntax:
if (condition1) {
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
If-else-if ladder:

In Java, the if-else-if ladder is used to execute one block of code from multiple conditional
options. It checks conditions in sequence from top to bottom and executes the first true
condition. Once a condition is true, the rest are skipped.

Syntax:

if (condition1) {

// code to be executed if condition1 is true

} else if (condition2) {

// code to be executed if condition2 is true

} else {

// code to be executed if all conditions are false

}
Switch statement:

The switch statement in Java is a multi-way branch statement. It allows you to execute
one block of code among many alternatives based on the value of a single expression.

It's a cleaner alternative to multiple if-else-if statements when comparing the same
variable against many values.

Syntax
switch(expression) {

case x:

// code block

break;

case y:

// code block

break;

default:

// code block

• The switch expression is evaluated once.


• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed.
• The break and default keywords are optional
Looping statements:

Loops in programming allow a set of instructions to run multiple times based on a condition.
In Java, there are three types of loops:

• for loop

• while loop

• do-while loop
1) for loop

The for statement includes the initialization, condition, and increment/decrement in one line.

Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Flow chart:

• Initialization condition: Here, we initialize the variable in use. It marks the


start of a for loop. An already declared variable can be used or a variable can be
declared, local to loop only.
• Testing Condition: It is used for testing the exit condition for a loop. It must
return a boolean value. It is also an Entry Control Loop as the condition is checked
prior to the execution of the loop statements.
• Statement execution: Once the condition is evaluated to true, the statements in
the loop body are executed.
• Increment/ Decrement: It is used for updating the variable for next iteration.
• Loop termination: When the condition becomes false, the loop terminates
marking the end of its life cycle.
Enhanced for loop (for each)
This loop is used to iterate over arrays or collections.
Syntax:
for (dataType variable : arrayOrCollection) {
// code to be executed
}
While loop:

In Java, a while loop is a control flow statement that allows code to be executed repeatedly
based on a boolean condition.

• It is called an entry-controlled loop because the condition is checked before each


iteration.
• If the condition is initially false, the loop body is never executed.

Syntax:

while (condition) {

// loop body: statements to execute repeatedly

}
Flow Chart:
do-while loop:

In Java, a do-while loop is a control flow statement that executes a block of code at least
once, and then repeats it as long as the condition evaluates to true.
This makes it different from a while loop, which checks the condition before executing the
code.

Syntax:

do {

// Loop body: statements to execute

} while (condition);

• The do block runs first.


• After running once, the condition is checked.
• If true, the loop repeats; if false, the loop stops.

Flow Chart:
Break Statement:

The Break Statement in Java is a control flow statement used to terminate loops and switch
cases. As soon as the break statement is encountered from within a loop, the loop iterations
stop there, and control returns from the loop immediately to the first statement after the loop.

Syntax:

break;

Flow chart:
Continue:

The continue statement in Java is a control flow statement used within loops (for, while, and
do-while) to skip the current iteration and proceed to the next iteration of the loop.

Syntax:

Continue;

Flow Chart:

You might also like