[Go to site: main page, start]

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

Java Programming Unit-I Notes

The document outlines the history and features of Java, starting from its inception in 1991 as the 'Green Project' at Sun Microsystems to its acquisition by Oracle in 2010. It describes various Java editions, object-oriented programming principles, and the architecture of the Java Virtual Machine (JVM). Additionally, it highlights Java's key features such as platform independence, security, and robustness, along with a brief overview of Java source file structure and coding conventions.

Uploaded by

vamsiakkina999
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 views51 pages

Java Programming Unit-I Notes

The document outlines the history and features of Java, starting from its inception in 1991 as the 'Green Project' at Sun Microsystems to its acquisition by Oracle in 2010. It describes various Java editions, object-oriented programming principles, and the architecture of the Java Virtual Machine (JVM). Additionally, it highlights Java's key features such as platform independence, security, and robustness, along with a brief overview of Java source file structure and coding conventions.

Uploaded by

vamsiakkina999
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

History of Java

o In 1991, a small team of engineers at Sun Microsystems led by James Gosling started
a project called “Green Project.”
o The goal was to develop software for digital devices such as televisions, VCRs, and
set-top boxes.
o The first name of the language was “Oak.”
o Later the team selected a new name Java, inspired by Java coffee, which the
developers used to drink while working.
o In 1995, Sun Microsystems officially released Java 1.0.
o The slogan was: “Write Once, Run Anywhere” (WORA).
o Java quickly became popular because programs written in Java could run on any system
using a Java Virtual Machine (JVM).
o In 2010, Oracle Corporation acquired Sun Microsystems.
o Oracle continues to maintain and develop Java.
Java Editions:

Java is available in different editions (or platforms), each designed for a specific type of
application development. The major Java editions are:

• Java SE (Java Standard Edition)

o It provides the core features of Java used for general-purpose programming.


o Used for Desktop applications, Simple standalone programs,Basic console
applications
• Java EE (Java Enterprise Edition)

o Previously called J2EE, now known as Jakarta EE after Oracle handed over to
Eclipse Foundation
o Used for building enterprise-level and large-scale web applications.
• Java ME (Java Micro Edition)
o Used to develop applications for small, resource-constrained devices.
o It is designed for Embedded systems, Mobile devices, Smart cards, Sensors /
IoT devices

• Java FX (optional, modern UI platform)

o Used for building rich graphical user interfaces (GUI) with modern features.
o JavaFX replaced the older Swing and AWT GUI technologies in modern Java
development.

Object-Oriented Programming (OOP) Principles

Object-Oriented Programming is a programming approach where everything is modeled as


objects that interact with one another. Java strongly supports OOP concepts, making programs
more modular, flexible, and [Link] are four main OOP principles:

1. Encapsulation

Encapsulation is the process of binding data (variables) and methods (functions)


together into a single unit (class) and restricting access to some components.
2. Inheritance

Inheritance allows one class to acquire the properties and behaviors of another class.

3. Polymorphism

Polymorphism means one name, many forms. A single method behaves differently
based on the object that calls it.

Types:

1. Compile-time polymorphism (Method Overloading)


2. Runtime polymorphism (Method Overriding)

4. Abstraction

Abstraction means hiding complex internal details and showing only the necessary
information to the user

What is an Object?

• An object is a software bundle of related state and behavior.


• Objects share two characteristics: they all have state and behaviour.
Examples:
1. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging
tail).
2. Bicycles also have state (current gear, current pedal cadence, current speed) and
behavior (changing gear, changing pedal cadence, applying brakes).

A software object
• Software objects consist of state and related behaviour. An object stores its state
in fields (variables in some programming languages) and exposes its behaviour
through methods (functions in some programming languages).
• Methods operate on an object's internal state and serve as the primary mechanism for
object-to-object communication.

Data encapsulation:
Hiding internal state and requiring all interaction to be performed through an object's
methods is known as data encapsulation — a fundamental principle of object-oriented
programming.

Consider a bicycle, for example:

• By attributing state (current speed, current pedal cadence, and current gear) and
providing methods for changing that state, the object remains in control of how the
outside world is allowed to use it. For example, if the bicycle only has 6 gears, a
method to change gears could reject any value that is less than 1 or greater than 6.
• Bundling code into individual software objects provides a number of benefits,
including:

1. Modularity: The source code for an object can be written and maintained
independently of the source code for other objects. Once created, an object can
be easily passed around inside the system.

2. Information-hiding: By interacting only with an object's methods, the details


of its internal implementation remain hidden from the outside world.

3. Code re-use: If an object already exists (perhaps written by another software


developer), you can use that object in your program. This allows specialists to
implement/test/debug complex, task-specific objects, which you can then trust
to run in your own code.

4. Pluggability and debugging ease: If a particular object turns out to be


problematic, you can simply remove it from your application and plug in a
different object as its replacement. This is analogous to fixing mechanical
problems in the real world. If a bolt breaks, you replace it, not the entire
machine.

What is a Class?

• A class is the blueprint from which individual objects are created.


• The following Bicycle class is one possible implementation of a bicycle:
class Bicycle {
private int cadence = 0;
private int speed = 0;
private int gear = 1;
void changeCadence(int newValue) {
cadence = newValue;
}
void changeGear(int newValue) {
gear = newValue;
}
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}

void printStates() {
[Link]("cadence:" +cadence + " speed:" + speed + " gear:" + gear);
}
}

• You may have noticed that the Bicycle class does not contain a main() method. That
is because it is not a complete application; it is just the blueprint for bicycles that might
be used in an application. The responsibility of creating and using new Bicycle objects
belongs to some other class in your application.

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

// Create two different


// Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();

// Invoke methods on
// those objects
[Link](50);
[Link](10);
[Link](2);
[Link]();

[Link](50);
[Link](10);
[Link](2);
[Link](40);
[Link](10);
[Link](3);
[Link]();
}
}

What is Inheritance?

• Different kinds of objects often have a certain amount in common with each other.
• Ex:
o Mountain bikes, road bikes, and tandem bikes, for example, all share the
characteristics of bicycles (current speed, current pedal cadence, current gear).
o Yet each also defines additional features that make them different: tandem
bicycles have two seats and two sets of handlebars; road bikes have drop
handlebars; some mountain bikes have an additional chain ring, giving
them a lower gear ratio.
• Object-oriented programming allows classes to inherit commonly used state and
behavior from other classes.

class MountainBike extends Bicycle {

// new fields and methods defining


// a mountain bike would go here

Features of Java Language


o Java programs are platform Independent
o JVM is platform Dependent
The Java Platform:

The Java Buzzwords:

Java is the most popular object-oriented programming language. Java has many
advanced features; a list of key features is known as Java Buzz Words. The java team
has listed the following terms as java buzz words.

• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Architecture-neutral (or) Platform Independent
• Multi-threaded
• Interpreted and High performance
• Distributed
• Dynamic
Simple

Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++. In a java programming language, many
complicated features like pointers, operator overloading, structures, unions, etc.
have been removed. One of the most useful features is the garbage collector it makes
java simpler.

Secure

Java is said to be more secure programming language because it does not have pointers
concept, java provides a feature "applet" which can be embedded into a web
application. The applet in java does not allow access to other parts of the computer,
which keeps away from harmful programs like viruses and unauthorized access.
Portable

Portability is one of the core features of java which enables the java programs to run on
any computer or operating system. For example, an applet developed using java runs
on a wide variety of CPUs, operating systems, and browsers connected to the Internet.

Object-oriented

Java is said to be a pure object-oriented programming language. In java, everything


is an object. It supports all the features of the object-oriented programming paradigm.
The primitive data types in java also implemented as objects using wrapper classes, but
still, it allows primitive data types to archive high-performance.

Robust

Java is more robust because the java code can be executed on a variety of environments,
java has a strong memory management mechanism (garbage collector), java is a
strictly typed language, it has a strong set of exception handling mechanism, and
many more.

Architecture-neutral (or) Platform Independent

Java has invented to aechieve "write once; run anywhere, any time, forever". The java
provides JVM (Java Virtual Machine) to achieve architectural-neutral or platform-
independent. The JVM allows the java program created using one operating system can
be executed on any other operating system.

Multi-threaded

Java supports multi-threading programming, which allows us to write programs that do


multiple operations simultaneously.

Interpreted and High performance


Although the bytecode has to be interpreted, it can be easily translated into native code
without impacting the performance. Java uses Just In Time (JIT) compiler, which
translates bytecode into native code very efficiently. Java run-time environment
provides this feature, without losing the benefits of platform independent code.

Distributed

Java programming language supports TCP/IP protocols which enable the java to
support the distributed environment of the Internet. Java also supports Remote Method
Invocation (RMI), this feature enables a program to invoke methods across a network.

Dynamic

Java is said to be dynamic because the java byte code may be dynamically updated on
a running system and it has a dynamic memory allocation and deallocation (objects and
garbage collector).

JVM Architecture
JVM is an abstract machine that provides a runtime environment for executing Java bytecode.
Its architecture consists of Class Loader Subsystem, Runtime Data Areas, and Execution
Engine. The Class Loader loads and verifies classes, memory areas store data during execution,
and the Execution Engine executes bytecode using interpreter and JIT compiler. JVM ensures
portability, security, and efficient memory management.
Overview of JVM Architecture
JVM architecture is broadly divided into three main subsystems:
1. Class Loader Subsystem
2. Runtime Data Areas (Memory Areas)
3. Execution Engine
Additionally, JVM interacts with Native Libraries using JNI.
Class Loader Subsystem:
The Class Loader loads .class files into memory when a program runs.
Types of Class Loaders:
1. Bootstrap Class Loader
o Loads core Java classes ([Link], [Link], etc.)
2. Extension Class Loader
o Loads classes from extension directories ([Link], [Link],
[Link])
3. Application (System) Class Loader
o Loads user-defined classes from classpath
Steps in Class Loading:
• Loading – Reads the .class file
• Linking : The dependencies of all the classes are resolved
o Verification – Ensures bytecode safety
o Preparation – Allocates memory for static variables
o Resolution – Converts symbolic references to direct references
• Initialization – Executes static initializers
Runtime Data Areas (Memory Areas):
These are the memory regions used during program execution.
a) Method Area (Shared)
• Stores class-level data:
o Class metadata
o Static variables
o Method bytecode
• Shared among all threads
b) Heap Area (Shared)
• Stores objects and instance variables
• Managed by Garbage Collector
• Largest memory area
c) Stack Area (Per Thread)
• Stores method calls, local variables and partial results for method execution
• Each thread has its own stack
• Stack Frame contains:
o Local variables
o Operand stack
o Return address
d) PC (Program Counter) Register
• Holds address of the currently executing instruction
• One PC register per thread
e) Native Method Stack
• Stores native code (written in languages like C and C++) that java
programs can interact with.
Execution Engine:
Responsible for executing bytecode.
Components:
1. Interpreter
o Executes bytecode line by line
o Slower execution
2. JIT Compiler (Just-In-Time)
o Converts frequently used bytecode into native machine code
o Improves performance
3. Garbage Collector
o Automatically removes unused objects from heap
o Prevents memory leaks
Java Native Interface (JNI):
• Enables JVM to interact with native libraries written in C/C++
• Used for platform-specific operations
Working of JVM (Flow):
1. Java source code (.java) is compiled by javac
2. Bytecode (.class) is generated
3. Class Loader loads bytecode into JVM
4. Bytecode is verified and stored in memory
5. Execution Engine executes bytecode
6. Output is produced
Java source file structure

A Java source file is a text file with the extension .java. It contains Java program code written
in a well-defined structure.

Documentation Section

Package statements

Import statements

Interface statements

Class declaration statements

Main method class declaration


-main method

1. Comments
• Used to describe the program.
• Ignored by the compiler.
• Types:
o Single-line //
// This is a simple Java program
o Multi-line /* */
/*
This is a multiline comment.
It is used to write explanations
across multiple lines.
The compiler ignores this block.
*/
o Documentation /** */
Processed by the javadoc tool to create HTML documentation
/**
* This class represents a Student.
*/
class Student {
}
2. Package Statement (Optional)
• Groups related classes into a package.
• Must be the first executable statement in the file.
• Only one package statement is allowed.
package [Link];
3. Import Statements (Optional)
• Used to access predefined classes from other packages.
• Written after the package statement.
import [Link];
4. Class Declaration
• Every Java program must have at least one class.
• The file name must match the public class name.
public class Sample {
}
5. Variables (Fields)
• Used to store data.
• Can be local variables or instance variables or static variables.
int number;
static int count;
6. Methods
• Define behavior of the class.
• main() method is the entry point of the program.
public static void main(String[] args) {
[Link]("Welcome");
}
7. Statements
• Instructions executed by the program.
• Written inside methods.
int a = 10;
[Link](a);
Important Rules to Remember
• Only one public class is allowed in a source file.
• File name must match the public class name.
• Order should be:
1. Package
2. Import
3. Class
• Java is case-sensitive.
• Program execution starts from main().
A First Simple Program:

A Second Short Program:


Using Blocks of Code:

Java Tokens
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
Whitespace: In Java, whitespace is a space, tab, or newline
Identifiers:
Identifiers are used to name things, such as classes, variables, and methods. An
identifier may be any descriptive sequence of uppercase and lowercase letters,
numbers, or the underscore and dollar-sign characters.

Valid Identifiers:

Literals:
A constant value in Java is created by using a literal representation of it.

Comments:
As mentioned, there are three types of comments defined by Java. You have already seen
two: single-line and multiline. The third type is called a documentation comment. This
type
of comment is used to produce an HTML file that documents your program. The
documentation comment begins with a /** and ends with a */.
Separators:
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon.
Java Keywords:
• Keywords in Java are reserved words that have a predefined meaning to the compiler.
• They cannot be used as identifiers (class names, variable names, method names).

Java Is a Strongly Typed Language:


Java is called a strongly typed language because every variable, expression, and object
has a clearly defined data type, and type rules are strictly enforced by the compiler.
Key Characteristics of Strong Typing in Java
a) Every Variable Has a Type
• Each variable must be declared with a data type before use.
• The type determines:
o What values the variable can store
o What operations can be performed on it
Example:
int count = 10;
String name = "Java";
b) Every Expression Has a Type
• Expressions in Java evaluate to a specific type.
• The resulting type depends on the operands and operators used.
Example:
int a = 10;
double b = 5.5;
double result = a + b; // result is double
c) Strict Type Definitions
• Java strictly defines what each type represents.
• Types cannot be mixed arbitrarily.
Example (Invalid):
int x = "Hello"; // Compile-time error
d) Type Checking at Compile Time
• Java performs compile-time type checking.
• All assignments and method parameter passing are checked for type compatibility.
• Errors must be fixed before successful compilation.
Example:
void show(int n) { }

show(10); // Valid
show("Ten"); // Compile-time error
e) No Automatic Type Coercion for Conflicting Types
• Java does not automatically convert incompatible types.
• Explicit type casting is required when conversion is necessary.
Example:
int x = (int) 10.5; // Explicit casting required
Without casting:
int x = 10.5; // Compile-time error
Data Types

• Java defines eight primitive types of data: byte, short, int, long, char, float, double,
and boolean.
• The primitive types are also commonly referred to as simple types.
• These eight primitive types can be put in four groups

Integers:
• Java defines four integer types: byte, short, int, and long. All of these are
signed, positive and negative values.
• Java does not support unsigned, positive-only integers
• The width and ranges of these integer types vary widely, as shown in this table:
byte:
• Smallest integer type
• This is a signed 8-bit type that has a range from –128 to 127.
• Useful for file handling, network data, or raw binary data
• Byte variables are declared by use of the byte keyword
byte b, c;
Short:
• short is a signed 16-bit type.
• It has a range from –32,768 to 32,767.
• short variables are declared by use of the short keyword
short s;
short t;
int:
• The int data type is the most commonly used integer type in Java.
• It is a signed 32-bit type that has a range from –2,147,483,648 to
2,147,483,647.
• variables of type int are commonly employed to control loops and to
index arrays.
• When byte and short variables are used in expressions, Java
automatically promotes them to int before performing the operation.
• int variables are declared by use of the int keyword
int i, j;
long:
• long is a signed 64-bit type and is useful for those occasions where an
int type is not large enough to hold the desired value.
• The range of a long is quite large ( –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 )
• This makes it useful when big, whole numbers are needed.
• long variables are declared by use of the long keyword
long i, j;
Floating-Point Types:
• Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision.
• There are two kinds of floating-point types, float and double, which
represent
single- and double-precision numbers, respectively.
• Their width and ranges are
float:
• The type float specifies a single-precision value that uses 32 bits of
storage
• Variables of type float are useful when you need a fractional
component, but don’t require a large degree of precision.
• float can be useful when representing rupees, dollars and cents.
• some example float variable declarations:
float hightemp, lowtemp;
double:
• Double precision, as denoted by the double keyword, uses 64 bits to
store a value
• When you need to maintain accuracy over many iterative calculations,
or are manipulating large-valued numbers, double is the best choice.
• some example double variable declarations:
double hightemp, lowtemp;
Characters:
• In Java, characters are stored using the char data type.
• Java char is different from C/C++ char; C/C++ uses 8 bits, while Java
uses 16 bits.
• Java uses Unicode, a universal character set that supports all human
languages.
• Unicode includes characters from Latin, Greek, Arabic, Cyrillic,
Hebrew, Japanese, Korean, and more.
• The range of char is 0 to 65,536.
• char is an unsigned type, so it cannot store negative values.
• ASCII characters range from 0 to 127 and are part of Unicode.
• Java uses Unicode to ensure internationalization and global
portability, even though it is less memory-efficient for some
languages.
• Although char is designed to hold Unicode characters, it can also be used as an
integer type on which you can perform arithmetic operations

boolean:
• Java provides a primitive data type boolean to represent logical values.
• A boolean variable can have only two values: true or false.
• Boolean values are mainly used in decision-making and control statements.
• Returned by relational operators such as <, >, <=, >=, ==, !=
boolean b = false;
b = (10 > 9); // true
if(b) { }

Literals
• Literals are fixed constant values assigned directly to variables in a Java program.
• They represent constant data and do not change during program execution.
• Different type of Literals are
o Integer Literals
o Floating Point Literals
o Boolean Literals
o Character Literals
o String Literals
Integer Literals:
• Integer literals represent whole number constants in a Java program.
• Common examples: 1, 2, 42 (decimal / base-10 numbers).
Number Systems Used in Integer Literals
1. Decimal (Base 10)
• Default number system.
• Digits: 0–9
• Leading zero is not allowed.
• Example:
int a = 42;
2. Octal (Base 8)
• Digits: 0–7
• Indicated by a leading zero (0).
• Example:
int x = 012; // decimal 10 ( 1*81 + 2*80 = 8+2 =10)
• Invalid example:
int y = 09; // error (9 is not allowed in octal)
3. Hexadecimal (Base 16)
• Digits: 0–9 and A–F / a–f
• Indicated by 0x or 0X.
• Commonly used because it matches 8, 16, 32, 64-bit word sizes.
• Example:
int h = 0x1A; // decimal 26 (1*161 + 10*160 = 16+10 =26)
Type of Integer Literals
• By default, integer literals are of type int (32-bit).
• Range: –2,147,483,648 to 2,147,483,647.
Assigning Integer Literals to Other Types
• An integer literal can be assigned to:
o byte or short → only if value is within range
byte b=16;
o long → always allowed
long l=256;
Long Literals
• Must end with L or l.
• Example:
long n = 9223372036854775807L;
Binary Literals (JDK 7 onwards)
• Binary (base 2) literals are prefixed with 0b or 0B.
• Useful for bit manipulations.
• Example:
int x = 0b1010; // decimal 10 (1*23+0*22 + 1*21 + 0*20 = 8+0+2+0
=10)
Underscores in Integer Literals (JDK 7 onwards)
• Underscores (_) improve readability.
• Ignored by the compiler.
• Can appear between digits only.
• Examples:
int a = 1_23_456;
int b = 123___456___789;
int c = 0b1101_0101_0001_1010;
Floating-Point Literals:
• Floating-point literals represent decimal numbers with a fractional part.
• Used when values require precision beyond integers.
Forms of Floating-Point Literals
1. Standard Notation
• Consists of:
o Whole number part
o Decimal point
o Fractional part
• Examples:
2.0
3.14159
0.6667
2. Scientific Notation
• Written as a decimal number multiplied by a power of 10.
• Uses E or e followed by an exponent.
• Exponent can be positive or negative.
Examples:
6.022E23 (6.022 * 1023)
314159E-05 (314159 * 10-5)
2e+100 (2 * 10100)
Default Type of Floating-Point Literals
• Floating-point literals are double by default.
• double uses 64 bits of memory.
Specifying float and double Literals
• To specify a float literal, append F or f.
• Appending D or d explicitly specifies a double (optional).
Examples:
float f = 3.14f;
double d = 3.14;
Hexadecimal Floating-Point Literals
• Rarely used.
• Use 0x prefix and P or p instead of E.
• P specifies a power of 2 (binary exponent).
Example:
double x = 0x12.2P2; // value is 72.5
(12.2)16 * 22= ( (1*161 + 2*160) . ( 2 * 16-1 ) ) * 4 = (18 + 0.125) * 4 = 18.125 * 4 =
72.5
Underscores in Floating-Point Literals (JDK 7+)
• Improve readability of large numbers.
• Ignored by the compiler.
• Allowed between digits only.
• Can be used in fractional part as well.
Examples:
double num1 = 9_423_497_862.0;
double num2 = 9_423_497.1_0_9; // fractional part is .109
Boolean Literals:
• Boolean literals represent logical constant values in Java.
• There are only two boolean literals:
o true
o false
Key Characteristics
• Boolean literals do not have any numeric representation.
• true is not equal to 1 and false is not equal to 0.
• Java does not allow implicit conversion between boolean and numeric types.
Usage of Boolean Literals
• Can be assigned only to variables of type boolean.
• Can be used in logical and conditional expressions.
• Commonly used with:
o Relational operators (<, >, ==, etc.)
o Logical operators (&&, ||, !)
o Control statements (if, while, for)
Example:
boolean flag = true;
if(flag) {
[Link]("Condition is true");
}
Invalid Usage
int x = true; // Compile-time error
Character Literals:
• Character literals represent single characters in Java.
• Java characters are based on the Unicode character set.
• Each character is a 16-bit value and internally represented as an integer.
• Character values can participate in arithmetic operations like addition and
subtraction.
Representation of Character Literals
• A character literal is written inside single quotes (' ').
• Any visible ASCII character can be written directly.
Examples:
'a'
'z'
'@'
Escape Sequences in Character Literals
• Used for characters that cannot be typed directly.
• Common escape sequences include:

Octal Character Literals


• Written using a backslash followed by three octal digits.
• Represent character values in base 8.
Example:
'\141' // represents 'a' ( 1*82 + 4*81 + 1*80 = 64+32+1 = 97 (ASCII Value of ‘a’)
Hexadecimal (Unicode) Character Literals
• Written using \u followed by exactly four hexadecimal digits.
• Used to represent Unicode characters directly.
Examples:
'\u0061' // 'a' (ISO-Latin-1) ( 6*161 + 1*160 = 96 + 1 = 97)
'\ua432' // Japanese Katakana character
String Literals:
• String literals represent a sequence of characters in Java.
• They are written by enclosing characters within double quotes (" ").
• In Java, strings are objects of the String class, not primitive data types.
Examples of String Literals
"Hello World"
"two\nlines"
"\"This is in quotes\""
Variables
• A variable is the basic unit of storage in a Java program.
• It is used to store data values during program execution.
• Each variable is defined by:
o Identifier (name) : identifier is the variable name
o Data type : The type specifies what kind of data the variable can store
o Optional initializer (value) : Initialization assigns an initial value to a
variable
• Every variable has a scope (visibility) and a lifetime.
Declaring a Variable
• In Java, variables must be declared before use.
• General syntax:
type identifier [= value][, identifier [= value]];
Examples of Variable Declarations
int a, b, c; // declares three int variables
int d = 3, e, f = 5; // declares and initializes d and f
byte z = 22; // initializes byte variable
double pi = 3.14159; // initializes double variable
char x = 'x'; // initializes char variable
Dynamic Initialization
• Dynamic initialization means initializing a variable using an expression
evaluated at runtime, not just a constant value.
double a = 3.0, b = 4.0;
double c = [Link](a * a + b * b);
Scope and Lifetime of Variables
Scope of a Variable
• A scope defines the visibility (accessibility) of a variable in a program.
• In Java, a scope is created using curly braces { }, which form a block.
• Every block introduces a new scope.
Types of Scope in Java
• The three main scopes are:
o Class scope
o Method scope
o block-level scopes
Class scope:
• Any variable, method, or block declared inside a class but outside all methods belongs
to the class scope.
• Class scope includes instance variables, static variables, methods, constructors, static
blocks, and instance initialization blocks, all of which are declared inside a class but
outside any method.
• Class scope means the region inside a class where class-level members can be
accessed by other members of the same class, depending on access specifiers.
Ex:
class Student {
int rollNo; // instance variable (class scope)
static String college; // static variable (class scope)
void display() { // method (class scope)
int j=10; //doesn’t come under class scope
[Link](rollNo);
[Link](college);
}
}
• Method Scope
• Begins with the opening { of a method.
• Includes:
o Local variables
o Method parameters
• Variables declared in a method are accessible only within that method.
Ex:
int add(int a, int b) // parameters ‘a’, ‘b’ comes under method scope
{
int c; //local varible ‘c’ comes under method scope
c=a+b;
}

Block (Local) Scope


• A block is any code enclosed within { } (e.g., if, for, while).
• Variables declared inside a block are visible only within that block.
• Block scope supports encapsulation and data protection.
Ex: int n=10;
for(int i=0;i<n;i++) //local varible ‘i’ comes under block scope
{
int j=20; //local varible ‘j’ comes under block scope
}
Nested Scopes
• Scopes can be nested inside other scopes.
• Outer scope variables are accessible inside inner scopes.
• Inner scope variables are NOT accessible outside the inner block.

Declaration Rules
• Variables must be declared before they are used.
• A variable declared at the end of a block is practically useless.
• Using a variable before declaration causes a compile-time error.

Lifetime of a Variable
• Variables are created when their scope is entered.
• Variables are destroyed when their scope is exited.
• A variable does not retain its value once it goes out of scope.
Reinitialization of Variables
• Variables declared inside a block with an initializer are reinitialized every time the
block is entered.
• This is common in loops.

Important Rule: No Redeclaration


• A variable cannot be redeclared in an inner scope if it already exists in an outer
scope.
• Redeclaring a variable with the same name causes a compile-time error.

Selection statements
Selection statements in Java are used to make decisions in a program and execute different
blocks of code based on conditions. They allow the program to choose one path among multiple
possible paths.
Types of Selection Statements in Java:
Java provides three main types of selection statements:
1. if Statement
Syntax:
if (condition) {
// code to execute if condition is true
}
Example:
int age = 20;
if (age >= 18) {
[Link]("Eligible to vote");
}
2. if-else Statement
Syntax:
if (condition) {
// executed when condition is true
} else {
// executed when condition is false
}
Example:
int num = 5;
if (num % 2 == 0) {
[Link]("Even number");
} else {
[Link]("Odd number");
}
3. else-if Ladder
Used when there are multiple conditions to check.
Syntax:
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else if (condition3) {
// block 3
} else {
// default block
}
Example:
int marks = 72;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else if (marks >= 60) {
[Link]("Grade C");
} else {
[Link]("Grade D");
}
4. Nested if Statement
if statements inside another if.
Example:
int a = 10;
int b = 20;
if (a > 0) {
if (b > 0) {
[Link]("Both numbers are positive");
}
}
5. switch Statement
Used when one value needs to be tested against multiple cases.
Works with int, char, String, enum etc.
Syntax:
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// default statements
}
Example:
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid day");
}
Iteration Statements
Iteration statements in Java are used to repeat a block of code multiple times. They allow
programs to perform looping, which is essential for tasks like counting, traversing arrays,
repeating operations, etc.
These are also called looping statements or control flow loops.

Types of Iteration Statements in Java


Java provides three primary loop statements:
1. while Loop
Used when the number of iterations is not known in advance.
Syntax:
while (condition) {
// statements
}
Example:
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
• Loop runs as long as condition is true.
2. do-while Loop
Same as while, but it executes the loop body at least once (because condition
is checked after executing the block).
Syntax:
do {
// statements
} while (condition);
Example:
int i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
• Guarantees one execution even if condition is false.
3. for Loop
• Used when the number of iterations is known or fixed.
• Very common for counting loops.
Syntax:
for (initialization; condition; increment/decrement) {
// statements
}
Example:
for (int i = 1; i <= 5; i++) {
[Link](i);
}
Enhanced for Loop (for-each loop)
Used to iterate over arrays and collections easily.
Syntax:
for (datatype var : arrayName) {
// statements
}
Example:
int[] nums = {10, 20, 30, 40};
for (int value : nums) {
[Link](value);
}
o No index required, easy and clean syntax.

Loop Control Statements


These are used inside loops to control execution flow:
break:
• Stops the loop completely.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
[Link](i);
}
Output:
1
2
continue:
• Skips current iteration and moves to next iteration.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
[Link](i);
}
Output:
1
2
4
5

Operators
• Java provides a rich set of operators to perform operations on variables and values.
Java operators are mainly classified into:
1. Arithmetic Operators
2. Bitwise Operators
3. Relational Operators
4. Logical Operators
5. Assignment Operator
6. Ternary Operator
These operators act on operands and produce a result .
Arithmetic Operators:
• Arithmetic operators are used for mathematical calculations, similar to
algebra.
List of Arithmetic Operators

• Operands must be of numeric type.


• Arithmetic operators cannot be applied to boolean values.
Modulus Operator Example
// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
[Link]("x mod 10 = " + x % 10);
[Link]("y mod 10 = " + y % 10);
}
}
Output:
x mod 10 = 2
y mod 10 = 2.25

Assignment with Arithmetic Operators


a = a + 4;
a += 4;

a = a % 2;
a %= 2;

Increment and Decrement Operators

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

Increment Operator (++)


• It increases the value of a variable by 1.
• Types of Increment
a) Pre-increment (++variable)
• The value is incremented first
• Then it is used in the expression
Example:
int a = 5;
int b = ++a;
[Link](a); // 6
[Link](b); // 6

b) Post-increment (variable++)
• The current value is used first
• Then the variable is incremented
Example:
int a = 5;
int b = a++;
[Link](a); // 6
[Link](b); // 5

Decrement Operator (--)


• It decreases the value of a variable by 1.
• Types of Decrement
a) Pre-decrement (--variable)
• Value is decremented first
•Then used in the expression
Example:
int a = 5;
int b = --a;
[Link](a); // 4
[Link](b); // 4

b) Post-decrement (variable--)
• Value is used first
• Then decremented
Example:
int a = 5;
int b = a--;
[Link](a); // 4
[Link](b); // 5
• Increment and decrement operators Works only with variables, not constants
5++; // Error

Bitwise Operators:
• Bitwise operators work on individual bits of integer types (byte, short, int, long, char).
• All of the integer types (except char) are signed integers. This means that they can
represent negative values as well as positive ones.
• Java represents negative numbers using two’s complement encoding. In this method,
all the bits of a number are first inverted (0 becomes 1 and 1 becomes 0), and then 1 is
added to the resulting value.
• Example : -5 ( 11111011 )
5 = 00000101
Invert all the bits (One’s Complement):
00000101
11111010
Add 1 to the inverted bits (Two’s Complement):
11111010
+ 1
------------
11111011
• To decode a negative number, first invert all of the bits, then add 1.
• The high-order bit determines the sign of an integer ( 1 - negative number, 0 – positive
number)
• List of Bitwise Operators

The Bitwise Logical Operators:


• The bitwise logical operators are &, |, ^, and ~.

The Bitwise NOT:


• Also called the bitwise complement, the unary NOT operator, ~, inverts all of the
bits of its operand.
• For example, the number 42, which has the following bit pattern:
00101010
becomes
11010101

after the NOT operator is applied.


The Bitwise AND:
The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced
in all other cases. Here is an example:
The Bitwise XOR
The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result
is 1. Otherwise, the result is zero.

Left Shift Operator (<<) :


The left shift operator (<<) shifts all bits of a number to the left by a specified
number of positions.
General Form
value << num
• value → the number whose bits are to be shifted
• num → number of bit positions to shift left
Working of Left Shift Operator
When a value is left shifted:
• Bits are moved left by num positions
• High-order bits that move beyond the limit are discarded
• Zeros (0) are filled on the right side
Important Points
• Each left shift is equivalent to multiplying the value by 2
• Left shift by n positions ≈ multiplication by 2ⁿ
Example 1: Simple Left Shift
int a = 5;
int result = a << 1;
[Link](result); // 10
Step-by-step Explanation
Binary representation of 5 (8-bit for understanding):
5 = 00000101
Left shift by 1 (<< 1):
00000101 << 1 → 00001010
Binary to decimal:
00001010 = 10
Output
10
So, 5 << 1 = 10
(Equivalent to 5 × 21)
Example 2: Left Shift by 2 Positions
int a = 5;
[Link](a << 2); // 20
Binary operation:
00000101 << 2 → 00010100
Decimal value:
20
So, 5 << 2 = 20
(Equivalent to 5 × 2²)

Example Program Demonstrating Left Shift on byte


// Left shifting a byte value.
class ByteShift {
public static void main(String args[]) {
byte a = 64; // 01000000
int i;
byte b;
i = a << 2; // promoted to int, then shifted
b = (byte)(a << 2); // cast back to byte
[Link]("Original value of a: " + a);
[Link]("i and b: " + i + " " + b);
}
}
Output
Original value of a: 64
i and b: 256 0
Explanation of the Output
Step-1: Binary Representation
64 =00000000 00000000 00000000 01000000
Step-2: Left Shift by 2
01000000 << 2 = 00000000 00000000 00000001 00000000
Step-3: Results
• i = 256 → correct int result
• b = 0 → lower 8 bits kept, higher bits discarded
Right Shift Operator ( >> ):
The right shift operator ( >> ) shifts all bits of a number to the right by a specified
number of positions.
General Form
value >> num
• value → the number whose bits are to be shifted
• num → number of bit positions to shift right
Working of Right Shift Operator
When a value is right shifted:
• Bits are moved right by num positions
• Low-order bits that move beyond the limit are discarded
• The left side is filled as follows:
o 0 for positive numbers
o 1 for negative numbers (to preserve the sign bit)
Important Points
• Each right shift is equivalent to dividing the value by 2
• Right shift by n positions ≈ division by 2ⁿ
• The sign of the number is preserved (this is why it is called signed right
shift)
Examples:
int a = 16; // Binary: 00000000 00000000 00000000 00010000 (16)
int b = a >> 2; // Result: 00000000 00000000 00000000 00000100 (4)
16 >> 2 = 4

When you are shifting right, the top (leftmost) bits exposed by the right shift are filled
in with the previous contents of the top bit. This is called sign extension and serves to
preserve the sign of negative numbers when you shift them right.
11111111 11111111 11111111 11111000 -8
>>1
11111111 11111111 11111111 11111100 -4
Unsigned Right Shift Operator ( >>> ):
The unsigned right shift operator (>>>) shifts all bits of a number to the right by a
specified number of positions without preserving the sign bit.
General Form
value >>> num
• value → the number whose bits are to be shifted
• num → number of bit positions to shift right
Working of Unsigned Right Shift Operator
When a value is unsigned right shifted:
• Bits are moved right by num positions
• Low-order bits that move beyond the limit are discarded
• Zeros (0) are always filled on the left side, regardless of whether the
number is positive or negative
Important Points
• The unsigned right shift does not preserve the sign
• It treats the number as an unsigned binary value
• It is useful when working with raw binary data, bit masks, and low-level
operations
• Available only for int and long data types in Java
Example with Positive Number
int a = 8; // Binary: 00000000 00000000 00000000 00001000
a = a >>> 2; // Binary: 00000000 00000000 00000000 00000010
Result: 2
Example with Negative Number
int a = -1; // Binary: 11111111 11111111 11111111 11111111
a = a >>> 24; // Binary: 00000000 00000000 00000000 11111111
Result: 255
Relational Operators:
• Relational operators are used to compare two operands and determine the relationship
between them.
• They are mainly used to check equality and ordering.
• The result of any relational operation is always a Boolean value: true or false.
• Relational operators are most commonly used in the expressions that control the if
statement and the various loop statements.
• Only numeric types can be compared using the ordering operators.

Boolean Logical Operators:


• Boolean logical operators are used to combine or manipulate boolean values (true
or false).
• They are mainly used in decision-making statements such as if, while, and for.
Logical AND (&)
• Returns true only if both conditions are true
Logical OR (|)
• Returns true if any one condition is true
Logical XOR (^)
• Returns true if only one condition is true
Logical NOT (!)
• Inverts the boolean value
Short-Circuit Logical AND (&&)
• The Short-Circuit logical AND operator (&&) returns true only if both operands are
true.
• If the first operand is false, the second operand is not evaluated.
int x = 5;
if (x > 10 && x++ > 4) {
[Link]("Inside if");
}
[Link](x); // x=5

Short-Circuit Logical OR (||)


• The Short-Circuit logical OR operator (||) returns true if any one operand is true.
• If the first operand is true, the second operand is not evaluated.
int y = 10;
if (y < 20 || y++ > 15) {
[Link]("Condition satisfied");
}
[Link](y);
Equality (==) and Inequality (!=) Operators:
• The operators == and != are called equality operators.
• They are used to compare two operands and determine whether they are equal or not
equal.
• The result of these operators is always a boolean value: true or false.

Ternary Operator (? :) :
• Java provides a special ternary (three-operand) operator, also called the conditional
operator, which is used as a compact alternative to certain if–else statements.
• This operator is represented by ? :
Syntax:
expression1 ? expression2 : expression3
• Here, expression1 can be any expression that evaluates to a boolean value. If
expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated.
The result of the ? operation is that of the expression evaluated. Both expression2 and
expression3 are required to return the same (or compatible) type, which can’t be void.

Operator Precedence and associativity


• operator precedence determines the order in which operators are evaluated in an
expression when multiple operators are present.
• associativity defines the direction in which operators of the same precedence are
evaluated when they appear together in an expression.

• Operators in the same row are equal in precedence.


• In binary operations, the order of evaluation is left to right (except for assignment,
which evaluates right to left).
• [ ], ( ), and . can also act like operators, they have the highest precedence.
• Parentheses raise the precedence of the operations that are inside them.
Ex:
int x = 5 + 3 * 2; // 11
int x = (5 + 3) * 2; // 16
int x = 10 - 5 - 2; // 3 , left to right associative ((10-5)-2)
Type Conversion and Casting
• In Java, it is very common to assign a value of one data type to a variable of another
data type.
• Java supports two kinds of type conversions:
1. Automatic (Implicit) Type Conversion
2. Explicit Type Conversion (Casting)
Automatic Type Conversion (Widening Conversion)
• Java automatically converts one data type into another only when it is safe to do so.
• Automatic type conversion occurs only if both conditions are satisfied:
1. The source and destination types are compatible
2. The destination type is larger than the source type
This is also called widening conversion, because data moves from a smaller type to a
larger type.
Examples
int i = 100;
long l = i; // int → long (automatic)
float f = i; // int → float (automatic)
double d = f; // float → double (automatic)
Widening Conversion Order
byte → short → int → long → float → double
char → int → long → float → double
• Numeric types are compatible with each other
• No automatic conversion:
o Numeric → boolean
o boolean → any type
o numeric → char (except constants within range)
o char ↔ boolean
Automatic Conversion of Integer Literals
• Java allows integer constants to be assigned to byte, short, or char if the value is within
range.
byte b = 10; // allowed
char c = 65; // allowed (ASCII 'A')
But:
byte b = 130; // compile-time error (out of range)

Explicit Type Conversion (Casting / Narrowing Conversion)


• When automatic conversion is not possible, Java requires explicit casting.
• Casting is an explicit conversion from one data type to another incompatible or
smaller type.
Syntax
(target-type) value

Example
int a = 130;
byte b = (byte) a;
This is called a narrowing conversion, because data moves from a larger type to a
smaller type.
Effects of Casting
a) Integer to Byte (Modulo Reduction)
When an integer value exceeds the range of the target type, Java performs
modulo reduction.
Byte range: -128 to 127 (256 values)
int i = 257;
byte b = (byte) i;
Calculation:
257 % 256 = 1
Result:
b=1
b) Floating-Point to Integer (Truncation)
When a floating-point value is cast to an integer:
• Fractional part is discarded

• No rounding takes place


double d = 123.99;
int i = (int) d;
Result:
i = 123

c) Floating-Point to Byte
Two things happen:
1. Fractional part is truncated
2. Value is reduced modulo the byte range
double d = 323.142;
byte b = (byte) d;
Steps:
323 → 323 % 256 = 67
Result:
b = 67
Automatic Type Promotion in Expressions:
• Type promotion also occurs during expression evaluation, as intermediate results may
exceed the range of smaller data types.
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
Here:
• a * b = 2000 → exceeds byte range
• Java promotes byte operands to int automatically
Compile-Time Error Due to Promotion
byte b = 50;
b = b * 2; // Compile-time error
Reason
• b * 2 → operands promoted to int
• Result is int
• Cannot assign int to byte without casting

Correct Code
b = (byte)(b * 2); // correct statement

Command Line Arguments


• Command line arguments are the values passed to a Java program at the time of
execution from the command prompt (command line).
• These arguments are received by the main() method.
Syntax of main() Method
public static void main(String[] args)
• args is an array of String
• Each command line argument is stored as one element in this array
• Arguments are separated by spaces
Simple Example
Program
class CommandLineDemo {
public static void main(String[] args) {
[Link]("First Argument: " + args[0]);
[Link]("Second Argument: " + args[1]);
}
}
Compilation
javac [Link]
Execution
java CommandLineDemo Hello Java
Output
First Argument: Hello
Second Argument: Java

Accessing Number of Arguments


[Link]("Number of arguments: " + [Link]);

Example: Adding Two Numbers


class AddNumbers {
public static void main(String[] args) {
int a = [Link](args[0]);
int b = [Link](args[1]);
int sum = a + b;
[Link]("Sum = " + sum);
}
}
Execution
java AddNumbers 10 20
Output
Sum = 30

Arrays
• An array in Java is a collection of elements of the same data type stored in
contiguous memory locations.
• It allows you to store multiple values in a single variable instead of declaring many
separate variables.
Why Do We Use Arrays?
• To store a fixed number of elements.
• Easy to access elements using indexing.
• Useful for loops and data processing.
Types of Arrays
1. One-dimensional array (1D)
2. Two-dimensional array (2D / Matrix)
3. Multi-dimensional array
1. One-Dimensional Array
Declaration :
type var-name[ ];
int[] arr; // preferred style
// or
int arr[];
Memory Allocation:
array-var = new type [size];
arr = new int[5]; // size = 5
▪ Declaration and Memory Allocation can be done in single statement also
int arr[] = new int[5];
[Link]([Link]);
Initialization
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
Declaration + Initialization
int[] arr = {10, 20, 30, 40, 50};
Array Indexing
• Index starts from 0
• Last index = size – 1
Example Program: 1D Array
class ArrayExample {
public static void main(String[] args) {
int[] num = {2, 4, 6, 8, 10};
[Link]("Array elements:");
for (int i = 0; i < [Link]; i++) {
[Link](num[i]);
}
}
}
2. Two-Dimensional Array (2D Array)
A 2D array looks like a table or matrix.
Declaration
int[][] matrix;
Allocation
matrix = new int[4][5]; // 4 rows, 5 columns
▪ Declaration and Memory Allocation can be done in single statement also
int matrix[][] = new int[4][5];
Initialization
int[][] matrix = {
{1, 2, 3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20}
};

Program: 2D Array Printing


class MatrixExample {
public static void main(String[] args) {
int[][] m = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < m[i].length; j++) {
[Link](m[i][j] + " ");
}
[Link]();
}
}
}
Ragged Array:
A ragged array in Java is a two-dimensional array in which each row can have a different
number of columns.

for(int i=0;i<[Link];i++)
{
for(int j=0;j<twoD[i];j++)
{
twoD[i][j]=[Link]();
}
}
Array Properties in Java
Property Explanation
length stores array size
fixed size size cannot be changed once created
same data type all elements must be of one type
indexed elements accessed by index
Common Array Errors
Error Reason
ArrayIndexOutOfBoundsException accessing invalid index
NullPointerException using an uninitialized array
Useful Programs for Practice
1. Sum of Array Elements
int sum = 0;
int arr={10,20,30,40};
for(int x : arr) {
sum += x;
}
2. Find Largest Element
int arr={30,20,40,10};
int max = arr[0];
for(int x : arr) {
if(x > max) max = x;
}
3. Linear Search
for(int i = 0; i < [Link]; i++) {
if(arr[i] == key) {
[Link]("Found at index " + i);
}
}

You might also like