JAVA PROGRAMMING
MODULE II JAVA PROGRAMMING ELEMENTS
Constants
A constant is a variable whose value cannot be changed once it has been
initialized. Java doesn't have built-in support for constants. To define a variable
as a constant, we just need to add the keyword "final" in front of the variable
declaration.
Syntax of Java Constant
final float pi = 3.14f;
The above statement declares the float variable "pi" as a constant with a
value of 3.14f. We cannot change the value of "pi" at any point in time in the
program. Later, if we try to do that by using a statement like "pi=5.25f", Java
will throw errors at compile time itself.
The final Keyword
The final keyword is a non-access modifier and is used with variables,
methods, and classes so that they cannot be changed. Methods that are defined
as final cannot be overridden, and classes that are defined as final cannot be
inherited. And, the value of final variables, as discussed above, cannot be
changed as they become constant.
Types of constants
Primary constants
● Integer constants: Whole numbers that can be positive, negative, or
zero. They can be written in decimal, octal (base-8), or hexadecimal
(base-16) formats.
o Example: 10, -5, 010 (octal for 8), 0xA (hex for 10).
● Real constants (or floating-point constants): Numbers with a fractional
part. They can be represented with a decimal point or in scientific
notation.
o Example: 3.14, -0.005, 1.23e4.
● Character constants: A single character enclosed in single quotes.
o Example: 'A', '7', '$'.
● String constants: A sequence of characters enclosed in double quotes.
o Example: "Hello", "Constants 123".
● Backslash character constants: Special escape sequences, such as \n for
a new line or \t for a tab.
Secondary constants
● Arrays: A collection of related elements of the same type, treated as a
single, unchangeable unit.
● Pointers: A variable that stores the memory address of another variable.
● Structures and unions: User-defined data types that group different
types of variables together.
Components of a Java Variable:
● Data Type: Specifies the type of data the variable can store (e.g., int for
whole numbers, String for text, boolean for true/false).
● Variable Name: A unique identifier that follows Java naming
conventions (e.g., myNumber, userName).
● Value: The actual data assigned to the variable.
Declaration and Initialization:
Variables must be declared before use, which involves specifying their
data type and name. They can also be initialized with a value at the time of
declaration or later.
// Declaration
int age;
// Initialization
age = 30;
// Declaration and Initialization
String name = "Alice";
Types of Variables in Java:
Java categorizes variables based on their scope and lifetime:
● Instance Variables (Non-static Fields):
● Declared inside a class but outside any method, constructor, or
block.
● Each object (instance) of the class gets its own copy of these
variables.
● Stored in heap memory.
● Static Variables (Class Variables):
● Declared inside a class using the static keyword.
● Shared by all instances of the class; only one copy exists per class.
● Stored in method area memory.
● Local Variables:
● Declared inside a method, constructor, or block.
● Their scope is limited to that specific block of code.
● Created when the block is entered and destroyed when the block is
exited.
● Stored in stack memory.
● Parameters (Method Parameters):
● Variables declared within the parentheses of a method signature.
● They receive values passed into the method during a call and
behave similarly to local variables within the method's scope.
public class MyClass {
// Instance variable
String instanceName;
// Static variable
static int staticCount = 0;
public void myMethod(int parameterValue) { // Parameter
// Local variable
int localVariable = 10;
[Link]("Instance Name: " + instanceName);
[Link]("Static Count: " + staticCount);
[Link]("Local Variable: " + localVariable);
[Link]("Parameter Value: " + parameterValue);
}
}
Java Data Type Categories
1. Primitive Data Type: These are the basic building blocks that store
simple values directly in memory. Examples of primitive data types
are boolean, char, byte, short, int, long, float and double.
2. Non-Primitive Data Types (Object Types): These are reference types
that store memory addresses of objects. Examples of Non-primitive data
types are String, Array, Class, Interface and Object.
Data Size
Example Description
Type (Bytes)
Used for small
byte 1 byte a = 10;
integers (-128 to 127)
Used for larger
short b =
short 2 integers (-32,768 to
200;
32,767)
int 4 int c = 5000; Default integer type
long d = Used for very large
long 8
100000L; integers
Used for decimal
float e =
float 4 numbers (single
5.75f;
precision)
Used for decimal
double f =
double 8 numbers (double
19.99;
precision)
Used for single
char 2 char g = 'A';
characters
1 (not boolean h = Used for true/false
boolean
fixed) true; values
Type Example Description
String String name = "Ari"; Sequence of characters
Collection of elements
Array int[] arr = {1,2,3};
of the same type
Class class Student { ... } Blueprint for objects
Interface interface Animal { ... } Used for abstraction
Object obj = new
Object Root of all classes
Object();
Type Casting
In Java, typecasting is the process of converting one data type to another data
type.
Types of Type Casting
There are two types of Type Casting in Java:
● Widening Type Casting
● Narrow Type Casting
1. Widening Type Casting (Implicit 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.
Note: Widening type casting is also sometimes called upcasting for primitives,
but it is not correct to call it casting down.
2. Narrow Type Casting (Explicit 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.
Types of operators
Java operators are special symbols that perform operations on variables or
values. These operators are essential in programming as they allow you to
manipulate data efficiently.
1. Arithmetic Operators
Used for mathematical calculations.
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Modulus (remainder) a%b
Example:
int a = 10, b = 3;
[Link](a + b); // 13
[Link](a % b); // 1
2. Unary Operators
Operate on a single operand.
Operator Description Example
++ Increment by 1 a++ or ++a
-- Decrement by 1 a-- or --a
+ Unary plus +a
- Unary minus -a
Example:
int a = 5;
[Link](++a); // 6 (pre-increment)
3. Assignment Operators
Used to assign values to variables.
Operator Example Meaning
= a = 10 Assign 10 to a
+= a += 5 a=a+5
-= a -= 5 a=a-5
*= a *= 5 a=a*5
/= a /= 5 a=a/5
%= a %= 5 a=a%5
4. Relational Operators
Used to compare two values.
Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
Example:
[Link](10 > 5); // true
5. Logical Operators
Used to combine multiple conditions.
Operator Description Example
&& Logical AND a > 0 && b > 0
` `
! Logical NOT !(a > 0)
Example:
int a = 5, b = 10;
[Link](a > 0 && b > 0); // true
6. Bitwise & Shift Operators
Used for bit-level operations.
Operator Description Example
& Bitwise AND a&b
` ` Bitwise OR
^ Bitwise XOR a^b
~ Bitwise NOT ~a
Operator Description Example
<< Left shift a << 2
>> Right shift a >> 2
>>> Unsigned right shift a >>> 2
7. Ternary Operator
Used as a shortcut for if-else conditions.
Syntax:
condition ? value_if_true : value_if_false;
Example:
int age = 18;
String result = (age >= 18) ? "Adult" : "Minor";
[Link](result); // Adult
8. Instanceof Operator
Used to check if an object belongs to a specific class or subclass.
Example:
String s = "Hello";
[Link](s instanceof String); // true
Expression
An expression is a combination of operators, constants and variables. An
expression may consist of one or more operands, and zero or more operators to
produce a value.
Types of Expressions:
Expressions may be of the following types:
● Constant expressions: Constant Expressions consists of only constant
values. A constant value is one that doesn't change. Examples:
5, 10 + 5 / 6.0, 'x’
● Integral expressions: Integral Expressions are those which produce
integer results after implementing all the automatic and explicit type
conversions. Examples:
x, x * y, x + int( 5.0)
where x and y are integer variables.
● Floating expressions: Float Expressions are which produce floating point
results after implementing all the automatic and explicit type
conversions. Examples:
x + y, 10.75
where x and y are floating point variables.
● Relational expressions: Relational Expressions yield results of type bool
which takes a value true or false. When arithmetic expressions are used
on either side of a relational operator, they will be evaluated first and then
the results compared. Relational expressions are also known as Boolean
expressions. Examples:
x <= y, x + y > 2
● Logical expressions: Logical Expressions combine two or more
relational expressions and produces bool type results. Examples:
x > y && x == 10, x == 10 || y == 5
● Pointer expressions: Pointer Expressions produce address
values. Examples:
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
● Bitwise expressions: Bitwise Expressions are used to manipulate data at
bit level. They are basically used for testing or shifting bits.
Examples:
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right. Shift operators are often used for
multiplication and division by powers of two.
Decision Making in Java - Conditional Statements
Decision-making in programming is similar to real-life decision-making.
We often want certain blocks of code to execute only when specific conditions
are met. In Java, this is achieved using decision-making statements that control
the flow of execution.
In Java, the following decision-making statements are available:
1. if Statement
Used to execute a block of code only if a condition is true.
if (condition) {
// code runs if condition is true
}
Example:
int age = 18;
if (age >= 18) {
[Link]("Eligible to vote");
}
2. if-else Statement
Executes one block if the condition is true, otherwise executes another block.
if (condition) {
// true block
} else {
// false block
}
Example:
int number = 5;
if (number % 2 == 0) {
[Link]("Even number");
} else {
[Link]("Odd number");
}
3. if-else-if Ladder
Used when there are multiple conditions to check sequentially.
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// block 3
}
Example:
int marks = 85;
if (marks >= 90) {
[Link]("Grade A");
} else if (marks >= 75) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}
4. Nested if Statement
When one if statement is inside another, it’s called a nested if.
if (condition1) {
if (condition2) {
// both conditions true
} else {
// only condition1 true
}
} else {
// condition1 false
}
Example:
int age = 20;
int weight = 60;
if (age > 18) {
if (weight > 50) {
[Link]("Eligible for blood donation");
}
}
5. Ternary Operator
A short form of if-else written in a single line.
variable = (condition) ? value_if_true : value_if_false;
Example:
int age = 16;
String result = (age >= 18) ? "Adult" : "Minor";
[Link](result);
6. Switch Statement
Used when you need to compare a variable with multiple possible values.
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// default block
}
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");
}
7. break Statement
The break statement is used to terminate a loop or switch immediately.
It stops the loop and jumps to the next statement after the loop.
Example 1: Break in a Loop
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // exits the loop when i = 3
}
[Link](i);
}
Output:
1
2
The loop stops when i becomes 3.
8. Labeled Loop
A labeled loop gives a name to a loop, allowing you to control which loop to
break or continue when loops are nested.
Syntax:
labelName:
for (...) {
for (...) {
if (condition)
break labelName; // exits the outer loop
}
}
Example:
outerLoop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outerLoop; // breaks the outer loop
}
[Link](i + " " + j);
}
}
Output:
11
12
13
21
When i=2 and j=2, it breaks out of both loops.
9. continue Statement
The continue statement skips the current iteration of a loop and jumps to the
next iteration.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // skips when i = 3
}
[Link](i);
}
Output:
1
2
4
5
When i is 3, the loop skips that iteration.
10. Labeled continue Statement
You can also use labels with continue to skip the current iteration of an outer
loop.
Example:
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue outer; // skips to next iteration of outer loop
}
[Link](i + " " + j);
}
}
Output:
11
21
31
Array:
In Java, an array is an important linear data structure that allows us to store
multiple values of the same type.
● Arrays in Java are objects, like all other objects in Java, arrays implicitly
inherit from the [Link] class. This allows you to invoke
methods defined in Object (such as toString(), equals() and hashCode()).
● Arrays have a built-in length property, which provides the number of
elements in the array.
Key features of Arrays
● Store Primitives and Objects: Java arrays can hold both primitive types
(like int, char, boolean, etc.) and objects (like String, Integer, etc.)
● Contiguous Memory Allocation When we use arrays of primitive types,
the elements are stored in contiguous locations. For non primitive types,
references of items are stored at contiguous locations.
● Zero-based Indexing: The first element of the array is at index 0.
● Fixed Length: After creating an array, its size is fixed; we can not
change it.
[Link]-Dimensional Array
One of the most commonly used types of arrays is the one-dimensional
array. It represents a simple list of elements where each item can be accessed
using a single index.
Creating an Array
There are two main ways:
// Method 1: Declaration and creation
int[] numbers = new int[5]; // creates array of size 5
// Method 2: Declaration, creation, and initialization
int[] marks = {90, 85, 80, 95, 100};
Accessing and Processing an Array
You can access elements using the index (0 to n−1).
for (int i = 0; i < [Link]; i++) {
[Link]("Mark " + i + ": " + marks[i]);
}
Example Output:
Mark 0: 90
Mark 1: 85
Mark 2: 80
Mark 3: 95
Mark 4: 100
Array Processing
You can perform operations like sum, average, search, or sorting.
int sum = 0;
for (int i = 0; i < [Link]; i++) {
sum += marks[i];
}
[Link]("Total = " + sum);
Output:
Total = 450
2. Multidimensional Arrays
A multidimensional array is an array of arrays (commonly 2D).
Creating a 2D Array
int[][] matrix = new int[3][3]; // 3 rows and 3 columns
Initializing a 2D Array
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing 2D Array Elements
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
Output:
123
456
789
3. Vectors in Java
A Vector is a dynamic array (it grows or shrinks automatically).
It is part of the [Link] package and is synchronized, meaning it’s thread-safe.
Syntax
import [Link];
Vector<Integer> v = new Vector<>();
Adding Elements
[Link](10);
[Link](20);
[Link](30);
Accessing Elements
[Link]([Link](1)); // prints 20
Iterating a Vector
for (int num : v) {
[Link](num);
}
4. ArrayList in Java
An ArrayList is a resizable array (similar to Vector but not synchronized).
It is part of the [Link] package and provides many built-in methods.
Syntax
import [Link];
ArrayList<String> names = new ArrayList<>();
Adding Elements
[Link]("Ari");
[Link]("John");
[Link]("Kavi");
Accessing Elements
[Link]([Link](0)); //Ari
Removing an Element
[Link]("John");
Looping through ArrayList
for (String name : names) {
[Link](name);
}
Comparison Table
Feature Array Vector ArrayList
Size Fixed Dynamic Dynamic
Type Primitive / Object Object Object
Synchronized No Yes No
Performance Fast Slower (thread-safe) Fast
Package [Link] [Link] [Link]