Java ControlStatements
Java ControlStatements
Foundations of Java:
Introduction of Java:
• Java is a high-level, class-based, object-oriented programming language that is designed to have
as few implementation dependencies as possible. Java is a versatile, powerful, and widely-used
programming language that continues to evolve.
• Its ability to run on any device with a JVM, coupled with its rich set of libraries and frameworks,
makes it a popular choice for developers across various industries. Whether you are building
enterprise-level applications, web services, mobile apps, or scientific research software, Java
provides the tools and capabilities to create efficient, reliable, and scalable solutions.
Components of Java:
1. Java Development Kit (JDK):
The JDK is a software development environment used for developing Java applications. It
includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an
archiver (jar), a documentation generator (javadoc), and other tools needed for Java development.
2. Java Runtime Environment (JRE):
The JRE provides the libraries, Java Virtual Machine (JVM), and other components required to
run applications written in Java. It does not include development tools like compilers or
debuggers.
3. Java Virtual Machine (JVM):
The JVM is a virtual machine that enables a computer to run Java programs. The JVM translates
the bytecode into machine language and executes it. The JVM is platform-specific, but the
bytecode is platform-independent.
Java Editions:
1. Java Standard Edition (Java SE):
Java SE provides the core functionality of the Java programming language. It defines everything
from the basic types and objects of the Java programming language to high-level classes used for
networking, security, database access, graphical user interface (GUI) development, and XML
parsing.
2. Java Enterprise Edition (Java EE):
Java EE builds on top of Java SE and provides an API and runtime environment for developing
and running large-scale, multi-tiered, scalable, reliable, and secure network applications.
3. Java Micro Edition (Java ME):
Java ME is a subset of the Java SE, providing a robust and flexible environment for applications
running on mobile and other embedded devices.
4. JavaFX:
JavaFX is a platform for creating rich internet applications using a lightweight user interface API.
JavaFX applications can run on various devices and platforms.
Usage of Java:
Java is used in a wide range of applications:
• Web Development: Java is used for server-side applications through technologies like Servlets,
JSP, and frameworks like Spring and Hibernate.
• Mobile Applications: Java is the primary language for Android app development.
• Enterprise Applications: Java is widely used for building large-scale enterprise applications.
1
• Embedded Systems: Java is used in a variety of embedded systems and Internet of Things (IoT)
devices.
• Scientific Applications: Java is used for developing software for scientific research and analysis
due to its robustness and security.
History of Java:
o Java continues to be a widely used and versatile programming language, powering web
applications,
o mobile apps (Android), enterprise software, cloud services, and more.
o Recent versions focus on improving performance, security, and developer productivity.
o Java is a programming language that has a rich and interesting history. overview of the key
milestones
o and events in the history of Java as follows-
Origins at Sun Microsystems (1991-1995):
o Java's story begins at Sun Microsystems, where a team of engineers, led by James Gosling and
Mike
o Sheridan, started developing a language initially called "Oak" in 1991.
o The project aimed to create a language for programming consumer electronics and embedded
systems.
Renamed to Java (1995):
o In 1995, the language was officially renamed "Java" due to trademark issues (earlier name ‘Oak’
was already trademarked). The name was inspired by coffee from a nearby café.
o The tagline "Write Once, Run Anywhere" was coined to emphasize Java's platform
independence.
Introduction of the Java Platform (1995):
o On May 23, 1995, Sun Microsystems announced the first public release of Java, which included
the Java Development Kit (JDK) 1.0.
o Java's key feature was the ability to compile source code into bytecode, which could run on any
platform with a Java Virtual Machine (JVM).
2
6. Distributed Computing :
Java supports distributed computing via RMI (Remote Method Invocation) and CORBA (Common
Object Request Broker Architecture), making it easier to develop applications that can communicate over
networks.
7. Robustness:
Java's strict type checking, exception handling, and memory management (garbage collection) contribute
to the language's robustness. It reduces the risk of runtime errors and memory leaks.
8. Security:
Java has a strong security model with features like bytecode verification, sandboxing, and security
manager, making it suitable for secure applications.
9. Multi-Threading:
Built-in support for multi-threading enables the creation of concurrent and parallel applications,
improving performance and responsiveness.
10. Rich Standard Library:
Java provides an extensive standard library (Java API) with pre-built classes and packages for various
tasks, including I/O, networking, data structures, and more.
11. Portability:
Java's platform independence ensures that Java applications can run on different devices and operating
systems without modification.
12. Community and Ecosystem:
Java has a large and active developer community, with abundant resources, libraries, frameworks (e.g.,
Spring, Hibernate), and development tools (e.g., IntelliJ IDEA, Eclipse).
13. Backward Compatibility:
Java strives to maintain backward compatibility, allowing code written for older versions to run on newer
Java versions with minimal or no changes.
14.Dynamic:
Java supports dynamic class loading and reflection, allowing for runtime introspection and modification
of classes
15. Compiler and Interpreter :
Java employs both a compiler (to convert source code into bytecode) and an interpreter (to execute the
bytecode). This dual approach enhances performance and flexibility.
16. High Performance:
Java applications can achieve high performance through features like Just-In-Time (JIT) compilation,
which translates bytecode into native machine code.
3
import java.util.Scanner;
3. Class Declaration
Every Java program must have at least one class. The class name should match the filename.
public class MyFirstProgram {
// Fields(variables/attributes/properties) and Methods go here
}
4. Main Method
The main method is the entry point of a Java program. It must be inside a class.
public class MyFirstProgram {
public static void main(String[] args) {
// Program execution starts here
}
}
5. Other Methods and Fields
You can define fields (variables) and methods (functions) inside a class. These can be static or instance
members.
Comments in Java: Comments are used to annotate the code and are ignored by the compiler.
// This is a single-line comment
/*
* This is a multi-line comment
* It spans multiple lines
*/
4
Naming Conventions in Java:
Variable Naming Conventions:
- Variable names should be meaningful and describe the purpose of the variable.
- Variable names should start with a lowercase letter and use camelCase for subsequent words.
Example: int studentAge;
String firstName;
double accountBalance;
Variables in Java:
Variables in Java are containers that hold data that can be changed during the execution of a program.
They have a type, a name, and a value. Here's an overview of variables in Java, including their types,
declaration, initialization, and scope.
Variable Types:
1. Primitive Data Types:
- byte, short, int, long, float, double, char, Boolean
5
2. Reference Data Types:
- Objects, Arrays
Variable Scope:
1. Local Variables:
- Declared inside a method or block.
- Accessible only within the method or block.
- Must be initialized before use.
Example: public void myMethod() {
int localVar = 5; // Local variable
System.out.println(localVar);
}
2. Instance Variables:
- Declared inside a class but outside any method.
- Each object of the class has its own copy.
- Initialized to default values if not explicitly initialized.
Example: public class MyClass {
int instanceVar; // Instance variable
public void myMethod() {
System.out.println(instanceVar); // Default value is 0
}
}
6
public void myMethod() {
System.out.println(staticVar); // Default value is 0
}
}
7
- Size: 1 bit
- Range: `true` or `false`
- Default Value: `false`
- Example: boolean b = true;
Note: Reference variables store the address of the object they refer to in memory, not the object itself.
8
1. Arrays: Arrays of primitive types (e.g., int[], char[]) and arrays of reference types (e.g., String[]).
2. Collections: These are part of the Java Collections Framework and include classes like ArrayList,
HashMap, HashSet, etc.
Arrays in Java:
In Java, an array is a data structure that allows you to store a fixed number of elements of the same data
type sequentially in memory. Each element in an array is accessed by an index, which starts from 0 for the
first element.
Arrays are useful when you want to work with a collection of items of the same type, such as integers,
strings, or custom objects.
1. Declaring an Array:
To declare an array in Java, you specify the data type of the elements followed by square brackets `[]`
and the name of the array variable. For example, to declare an array of integers:
Example: int[] myArray;
2. Creating an Array:
After declaring an array, you need to create it using the `new` keyword. You also need to specify the
size (the number of elements) of the array. For example, to create an array of 5 integers:
Example: int[] myArray = new int[5];
This creates an integer array called `myArray` with 5 elements, all initialized to their default value (0
for `int`).
3. Initializing an Array:
You can also initialize an array with values at the time of creation.
Example: int[] myArray = {1, 2, 3, 4, 5};
4. Accessing Array Elements:
You can access elements of an array using their index. The index starts at 0 for the first element and
goes up to `length - 1` for an array of length `length`.
Example: int thirdElement = myArray[2]; // Access the third element (index 2)
5. Array Length:
You can find the length (number of elements) of an array using the `length` property:
Example: int arrayLength = myArray.length;
6. Iterating Through an Array:
You can use loops, such as the `for` loop, to iterate through the elements of an array:
Example: for (int i = 0; i <myArray.length; i++) {
System.out.println(myArray[i]);
}
Program demonstrates the creation, initialization, and iteration through an array of integers:
public class ArrayExample {
public static void main(String[] args) {
int[] myArray = {1, 2, 3, 4, 5};
System.out.println("Elements of myArray:");
for (int i = 0; i <myArray.length; i++) {
System.out.println(myArray[i]);
}
}
}
9
This program creates an integer array, initializes it with values, and then prints each element of the array
using a `for` loop.
In Java, there are several types of arrays, each tailored to specific use cases. The most common array
types in Java include:
1. Single-Dimensional Arrays:
A single-dimensional array stores elements in a linear sequence. It is the simplest form of an array.
Example: int[] singleDimensionalArray = {1, 2, 3, 4, 5};
2. Multi-Dimensional Arrays:
Multi-dimensional arrays are arrays of arrays. They can be thought of as tables or matrices with rows
and columns.
Example: int[][] twoDimensionalArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
3. Variable-Length Arrays (Introduced in Java 5):
Variable-length arrays allow you to create arrays with a dynamic length. The size of these arrays can be
determined at runtime.
Example: int[] dynamicArray = new int[10]; // Create an array with a length of 10
4. Array of Objects:
In Java, you can create arrays of objects, allowing you to store instances of classes or custom objects.
Example: // Create an array of Person objects
Person[] people = new Person[2];
people[0] = new Person("Rama", 30);
people[1] = new Person("Sitha", 25);
// Display the details of each person in the array
for (Person person : people) {
System.out.println(person); }
5. Array of Strings:
Arrays can also store strings, which are objects in Java.
Example: String[] names = {"Rama", "Sitha", "Laxmana"};
6. Array of Primitive Data Types:
You can create arrays of primitive data types such as `int`, `double`, `char`, etc.
Example: double[] grades = {98.5, 89.0, 75.5, 87.5};
7. Jagged Arrays:
Jagged arrays are arrays of arrays where each sub-array can have a different length.
Example: int[][] jaggedArray = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
8. Arrays with User-Defined Data Types:
You can create arrays of user-defined data types or objects.
Example: class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
10
this.y = y;
}
}
Point[] points = new Point[5];
points[0] = new Point(0, 0);
points[1] = new Point(1, 1);
- A two-dimensional array in Java is an array of arrays, forming a matrix-like structure with rows and
columns.
Example: public class TwoDimensionalArrayExample {
public static void main(String[] args) {
// Declare and initialize a 2D array with 3 rows and 4 columns
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// Access and print elements of the 2D array
for (int i = 0; i <matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // Move to the next row
}
}
}
Operators in java:
Java provides a variety of operators that allow you to perform operations on variables and values. Here's
an explanation of some of the most commonly used operators in Java:
1. Arithmetic Operators:
`+` (Addition): Adds two operands.
`-` (Subtraction): Subtracts the right operand from the left operand.
`*` (Multiplication): Multiplies two operands.
`/` (Division): Divides the left operand by the right operand.
`%` (Modulus): Returns the remainder when the left operand is divided by the right operand.
2. Assignment Operators:
`=` (Assignment): Assigns the value of the right operand to the left operand.
`+=` (Addition Assignment): Adds the right operand to the left operand and assigns the result to the
left operand.
`-=` (Subtraction Assignment): Subtracts the right operand from the left operand and assigns the result
to the left operand.
`*=` (Multiplication Assignment): Multiplies the left operand by the right operand and assigns the
result to the left operand.
`/=` (Division Assignment): Divides the left operand by the right operand and assigns the result to the
left operand.
`%=` (Modulus Assignment): Calculates the modulus of the left operand with the right operand and
assigns the result to the left operand.
11
3. Increment and Decrement Operators:
`++` (Increment): Increases the value of the operand by 1.
`--` (Decrement): Decreases the value of the operand by 1.
4. Comparison Operators:
`==` (Equal to): Compares if two values are equal.
`!=` (Not equal to): Compares if two values are not equal.
`<` (Less than): Checks if the left operand is less than the right operand.
`>` (Greater than): Checks if the left operand is greater than the right operand.
`<=` (Less than or equal to): Checks if the left operand is less than or equal to the right operand.
`>=` (Greater than or equal to): Checks if the left operand is greater than or equal to the right operand.
5. Logical Operators:
`&&` (Logical AND): Returns true if both operands are true.
`||` (Logical OR): Returns true if at least one of the operands is true.
`!` (Logical NOT): Negates the value of the operand.
6. Bitwise Operators:
`&` (Bitwise AND): Performs a bitwise AND operation on the operands.
`|` (Bitwise OR): Performs a bitwise OR operation on the operands.
`^` (Bitwise XOR): Performs a bitwise XOR operation on the operands.
`~` (Bitwise Complement): Inverts the bits of the operand.
`<<` (Left Shift): Shifts the bits of the left operand to the left by a specified number of positions.
`>>` (Right Shift): Shifts the bits of the left operand to the right by a specified number of positions.
`>>>` (Unsigned Right Shift): Shifts the bits to the right, filling with zeros.
7. Conditional (Ternary) Operator:
`? :` (Conditional Operator): A shorthand way to write an `if-else` statement. It evaluates a boolean
expression and returns one of two values based on whether the expression is true or false.
8. instanceof Operator:
The `instanceof` operator is used to check if an object is an instance of a particular class or interface.
Example: Object obj = new String("Hello");
boolean isString = obj instanceof String; // true
9. Relational Operators (for Object Comparison):
The `equals()` method is used to compare objects for equality.
Example: String str1 = "Hello";
String str2 = "World";
boolean areEqual = str1.equals(str2); // false
Expressions in Java:
In Java, an expression is a combination of variables, literals, operators, and method calls that can be
evaluated to a single value. Expressions are fundamental to programming and are used to perform various
operations, calculations, and comparisons. Here are some common types of expressions in Java:
1. Arithmetic Expressions:
Arithmetic expressions involve mathematical operations such as addition, subtraction, multiplication,
division, and modulus.
Example: int result = 5 + 3 * (10 / 2) - 1;
2. Relational Expressions:
Relational expressions are used to compare values and return a boolean result. Common relational
operators include `==`, `!=`, `<`, `>`, `<=`, and `>=`.
Example: boolean isEqual = (x == y);
12
3. Logical Expressions:
Logical expressions involve logical operators like `&&` (logical AND), `||` (logical OR), and `!`
(logical NOT). They are used to make decisions and control program flow.
Example: boolean condition = (x > 5) && (y < 10);
4. Assignment Expressions:
Assignment expressions are used to assign values to variables. The assignment operator `=` is used for
this purpose.
Example: int a = 10; // assigns 10 to a
a += 5; // equivalent to a = a + 5; a is now 15
5. Conditional (Ternary) Expressions:
The conditional operator (`? :`) is used to create conditional expressions. It evaluates a boolean
condition and returns one of two values based on whether the condition is true or false.
Example: int max = (x > y) ? x : y;
6. Method Call Expressions:
Method call expressions involve calling methods on objects. The result of a method call can be used in
an expression.
Example: String fullName = getFirstName() + " " + getLastName();
7. Bitwise Expressions:
Bitwise expressions involve operations at the bit level using operators like `&`, `|`, `^`, and `~`. These
are typically used for low-level bit manipulation.
Example: int x = 5; // binary: 0101
int y = 3; // binary: 0011
int result;
result = x & y; // result is 1 (binary: 0001)
8. Type Cast Expressions:
Type cast expressions are used to convert one data type into another.
Example: double value = (double) 5 / 2;
9. String Concatenation Expressions:
String concatenation expressions are used to concatenate strings using the `+` operator.
Example: fullName = firstName + " " + lastName;
10. Type Comparision (Instanceof) Expressions:
The `instanceof` operator is used to determine if an object is an instance of a particular class or
interface.
Example: if (myObjectinstanceofMyType) {
// Do something
}
11. Array Indexing Expressions:
To access elements of an array, you use array indexing expressions.
Example: int[] numbers = {1, 2, 3, 4, 5};
int thirdNumber = numbers[2]; // Access the third element, which is 3
12. Object Member Access Expressions:
When working with objects, you can access their fields and methods using member access
expressions.
Example: Person person = new Person("Rama", 30);
String name = person.getName(); // Access the getName() of person object.
13. Lambda Expressions:
These are used to define an anonymous function that can be passed around as an object.
13
Example: Runnable r = () -> System.out.println("Hello, Lambda!");
r.run(); // prints "Hello, Lambda!"
14
System.out.println("Unknown day");
}
5. for Loop:
The `for` loop is used to iterate over a range of values. It has an initialization step, a condition to
check, and an update step.
Example: for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
6. while Loop:
The `while` loop continues to execute a block of code as long as a specified condition is true.
Example: int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
7. do-while Loop:
The `do-while` loop is similar to the `while` loop, but it guarantees that the block of code is executed at
least once.
Example: int number;
do {
number = generateRandomNumber();
} while (number < 50);
8. break,continue and return Statements:
The `break` statement is used to exit a loop prematurely, and the `continue` statement is used to skip
the current iteration and move to the next one within a loop.
Example: for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
The `return` statement is used to exit a method and return a value or control back to the caller.
Example: public int add(int a, int b) {
return a + b; // Return the sum of a and b
}
9. Exception Handling (try, catch, finally, throw, throws):
Exception handling statements allow you to handle and respond to exceptions or errors in your code.
Example: try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException ex) {
System.out.println("Division by zero error: " + ex.getMessage());
} finally {
System.out.println("This block always executes.");
15
}
16
break;
default:
dayName = "Unknown";
}
System.out.println("Day " + day + " is " + dayName);
}
}
Elements of Java-
1. Class:
A class is a blueprint or template from which objects are created. It defines a type of object according to
the attributes (fields) and behaviors (methods) that the object can have.
Example: public class Car {
// Fields (attributes)
String color;
int speed;
// Methods (behaviors)
void accelerate() {
speed += 10;
}
void brake() {
speed -= 10;
}
}
2. Object:
An object is an instance of a class. It is created using the `new` keyword and represents a specific
example of the class, with actual values for its fields.
Example: public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Creating an object of the Car class
myCar.color = "Red";
myCar.speed = 50;
myCar.accelerate(); // Using the object's methods
System.out.println("Car speed: " + myCar.speed); // Output: Car speed: 60
}
}
3. Methods:
Methods are blocks of code that perform specific tasks and are defined within a class. They define the
behaviors of the objects created from the class. Methods can take parameters, return values, and modify
the object's state. Within a class we are generally declaring the instance methods and static methods.
i) Instance Methods:
Instance methods belong to an instance of a class. They can access instance variables and other instance
methods directly. To call an instance method, you need to create an object of the class.
ii) Class (Static) Methods:
Static methods belong to the class rather than an instance of the class. They can be called without creating
an instance of the class and can access static variables and other static methods directly. Static methods
cannot access instance variables or methods directly.
17