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

Java Programming Language Features

Java is a high-level, object-oriented programming language known for its simplicity, platform independence, and security. It features a straightforward syntax, supports core OOP concepts, and utilizes a Java Virtual Machine (JVM) to run bytecode on any platform. The document also covers Java's data types, operators, and the distinction between JDK and JRE for development and execution.

Uploaded by

vivekmeshram890
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 views24 pages

Java Programming Language Features

Java is a high-level, object-oriented programming language known for its simplicity, platform independence, and security. It features a straightforward syntax, supports core OOP concepts, and utilizes a Java Virtual Machine (JVM) to run bytecode on any platform. The document also covers Java's data types, operators, and the distinction between JDK and JRE for development and execution.

Uploaded by

vivekmeshram890
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

Unit 1

Java is a high-level, object-oriented programming language. This language is very easy to learn and widely used. It
is known for its platform independence, reliability, and security. It follows one principle, that is "Write Once, Run
Anywhere" principle. It supports various features like portability, robustness, simplicity, multithreading, and high
performance, which makes it a popular choice for beginners as well as for developers.

Features of java:
1. Simple Syntax
Java syntax is very straightforward and very easy to learn. Java removes complex features like pointers and multiple
inheritance, which makes it a good choice for beginners.
2. Object Oriented
Java is a pure object-oriented language. It supports core OOP concepts like,
 Class
 Objects
 Inheritance
 Encapsulation
 Abstraction
 Polymorphism
3. Platform Independent
Java is platform-independent because of Java Virtual Machine (JVM).
 When we write Java code, it is first compiled by the compiler and then converted into bytecode (which is
platform-independent).
 This byte code can run on any platform which has JVM installed.
4. Interpreted
Java code is not directly executed by the computer. It is first compiled into bytecode. This byte code is then
understand by the JVM. This enables Java to run on any platform without rewriting code.
5. Scalable
Java can handle both small and large-scale applications. Java provides features like multithreading and distributed
computing that allows developers to manage loads more easily.
6. Portable
When we write a Java program, the code first get converted into bytecode and this bytecode does not depend on any
operating system or any specific computer. We can simply execute this bytecode on any platform with the help of
JVM. Since JVMs are available on most devices and that's why we can run the same Java program on different
platform
7. Secured and Robust
Java is a reliable programming language because it can catch mistakes early while writing the code and also keeps
checking for errors when the program is running. It also has a feature called exception handling that helps deal with
unexpected problems smoothly.
8. Memory Management
Memory management in Java is automatically handled by the Java Virtual Machine (JVM).
 Java garbage collector reclaim memory from objects that are no longer needed.
 Memory for objects are allocated in the heap
 Method calls and local variables are stored in the stack.

Byte Code
Byte Code can be defined as an intermediate code generated by the compiler after the compilation of source
code(JAVA Program). This intermediate code makes Java a platform-independent language.
How is Byte Code generated?

Compiler converts the source code or the Java program into the Byte Code(or machine code), and secondly, the
Interpreter executes the byte code on the system. The Interpreter can also be called JVM(Java Virtual Machine). The
byte code is the common piece between the compiler(which creates it) and the Interpreter (which runs it).

Let us look at this phenomenon, step by step

 Suppose you are writing your first JAVA program.

Eg. /*package whatever //do not write package name here */


import [Link].*;
class GFG {
public static void main (String[] args) {
[Link]("GFG!");
}
}

Output

GFG!

 The above-written code is called JAVA source code.


 The compiler compiles the source code.
 Finally, Interpreter executes the compiled source code.

Java Virtual machine:


In the context of Object-Oriented Programming (OOP) in Java, the Java Virtual Machine (JVM) is the runtime
environment that executes Java bytecode, enabling Java programs to run on any platform with a JVM installed,
adhering to the "write once, run anywhere" principle.
 Mostly in other Programming Languages, compiler produce code for a particular system but Java compiler
produce Bytecode for a Java Virtual Machine.
 When we compile a Java program, then bytecode is generated. Bytecode is the source code that can be used
to run on any platform.
 Bytecode is an intermediary language between Java source and the host system.
 It is the medium which compiles Java code to bytecode which gets interpreted on a different machine and
hence it makes it Platform/Operating system independent.
How to work JVM:
 Reading Bytecode.
 Verifying bytecode.
 Linking the code with the library.
JDK:
In the context of Object-Oriented Programming (OOP) in Java, the Java Development Kit (JDK) is a crucial software
development environment that provides the tools and libraries necessary to write, compile, debug, and run Java
applications, including those that leverage OOP principles.
 The JDK includes everything required for Java development — compilers, debuggers, and other essential
tools.
 Beginners often get confused between JRE and JDK.
 If you only want to run Java programs, installing JRE is enough.
 But if you want to develop Java applications, you’ll need the JDK, which includes the JRE and additional
development tools.

Data Types:
Java is a statically typed programming language, meaning variable types are known at compile time. The compiler
ensures type correctness, preventing assignments like int x = "GfG";, which would cause a compile-time error.
Data types in Java define the kind of data a variable can hold and the memory required to store it. They are broadly
divided into two categories:
 Primitive Data Types: Store simple values directly in memory.
 Non-Primitive (Reference) Data Types: Store memory references to objects.

Primitive Data Types


Primitive types are the fundamental data types that store single values. Java defines eight primitive data types,
summarized below:
1. boolean Data Type
Represents one of two logical values: true or false. Commonly used for conditional checks.
Syntax:
boolean booleanVar;
public class Geeks {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
[Link]("Is Java fun? " + isJavaFun);
[Link]("Is fish tasty? " + isFishTasty);
}
}

Output
Is Java fun? true
Is fish tasty? false

2. byte Data Type


An 8-bit signed integer used to save memory in large numeric arrays.
Syntax:
byte byteVar;
Size : 1 byte (8 bits)
public class Geeks {
public static void main(String[] args) {
byte age = 25;
byte temperature = -10;
[Link]("Age: " + age);
[Link]("Temperature: " + temperature);
}
}

Output
Age: 25
Temperature: -10

3. short Data Type


A 16-bit signed integer often used when memory is limited and values are moderate in size.
Syntax:
short shortVar;
Size : 2 bytes (16 bits)
public class Geeks {
public static void main(String[] args) {
short students = 1000;
short temp = -200;
[Link]("Students: " + students);
[Link]("Temperature: " + temp);
}
}
Output
Number of Students: 1000
Temperature: -200
4. int Data Type
A 32-bit signed integer commonly used for whole numbers.
Syntax:
int intVar;
Size : 4 bytes ( 32 bits )
public class Geeks {
public static void main(String[] args) {
int population = 2000000;
int distance = 150000000;
[Link]("Population: " + population);
[Link]("Distance: " + distance);
}
}

Output
Population: 2000000
Distance: 150000000

5. long Data Type


A 64-bit signed integer used when int is not sufficient for large values.
Syntax:
long longVar;
Size : 8 bytes (64 bits)
public class Geeks {
public static void main(String[] args) {
long worldPopulation = 7800000000L;
long lightYears = 9460730472580800L;
[Link]("World Population: " + worldPopulation);
[Link]("Light Years: " + lightYears);
}
}

Output
World Population: 7800000000
Light Year Distance: 9460730472580800

6. float Data Type


A 32-bit single-precision floating-point type used for fractional values.
Syntax:
float floatVar;
Size : 4 bytes (32 bits)
public class Geeks {
public static void main(String[] args) {
float pi = 3.14f;
float gravity = 9.81f;
[Link]("Pi: " + pi);
[Link]("Gravity: " + gravity);
}
}

Output
Value of Pi: 3.14
Gravity: 9.81

7. double Data Type


A 64-bit double-precision floating-point type and the default for decimal numbers.
Syntax:
double doubleVar;
Size : 8 bytes (64 bits). It is recommended to go through rounding off errors in java.
public class Geeks {
public static void main(String[ ] args) {
double pi = 3.141592653589793;
double avogadro = 6.02214076e23;
[Link]("Pi: " + pi);
[Link]("Avogadro's Number: " + avogadro);
}
}
Output
Value of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23

8. char Data Type


A 16-bit Unicode character used to store single symbols or letters.
Syntax:
char charVar;
Size : 2 bytes (16 bits)
Example: This example, demonstrates how to use char data type to store individual characters.
public class Geeks {
public static void main(String[] args) {
char grade = 'A';
char symbol = '$';
[Link]("Grade: " + grade);
[Link]("Symbol: " + symbol);
}
}

Output
Grade: A
Symbol: $

Non-Primitive (Reference) Data Types


Non-primitive data types store references (memory addresses) rather than actual values. They are created by users and
include types like String, Class, Object, Interface, and Array.
1. String
String represents a sequence of characters enclosed in double quotes. Unlike C/C++, Java strings are objects and are
immutable.
Syntax:
String str = "Hello";
public class Geeks {
public static void main(String[] args) {
String name = "Geek1";
String message = "Welcome to Java";
[Link]("Name: " + name);
[Link]("Message: " + message);
}
}

Output
Name: Geek1
Message: Welcome to Java
Note: String cannot be modified after creation. Use StringBuilder for heavy string manipulation.

2. Class
A class is a user-defined blueprint that defines variables and methods. It represents a type of object and forms the
foundation of Object-Oriented Programming.
class Car {
String model; public class Geeks {
int year; public static void main(String[] args) {
Car myCar = new Car("Toyota", 2020);
Car(String model, int year) { [Link]();
[Link] = model; }
[Link] = year; }
}
Output
void display() { Toyota 2020
[Link](model + " " + year);
}
}
3. Object
An Object is an instance of a class representing real-world entities. It has state (data), behavior (methods), and identity
(unique reference).
class Car { public static void main(String[] args) {
String model; Car myCar = new Car("Honda", 2021);
int year; [Link]("Model: " + [Link]);
[Link]("Year: " + [Link]);
Car(String model, int year) { }
[Link] = model; }
[Link] = year;
} Output
} Car Model: Honda
Car Year: 2021
public class Geeks {

4. Interface
An interface defines a contract of abstract methods that implementing classes must define. It provides a way to achieve
abstraction and multiple inheritance in Java.
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
[Link]("Woof");
}
}

public class Geeks {


public static void main(String[] args) {
Animal dog = new Dog();
[Link]();
}
}

Output
Woof

5. Array
An array stores multiple elements of the same type in a single structure. Java arrays are objects, dynamically allocated,
and indexed from 0.
public class Geeks {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Geek1", "Geek2", "Geek3"};
[Link]("First number: " + numbers[0]);
[Link]("Second name: " + names[1]);
}
}

Output
First Number: 1
Second Fruit: Geek2

Operator:
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
Arithmetic Operators are used to perform simple arithmetic operations on primitive and non-primitive data types.

Example:
public class GFG{
public static void main(String[] args) {
int a = 10, b = 3;
// Addition
int sum = a + b;

// Subtraction
int diff = a - b;

// Multiplication
int mul = a * b;

// Division
int div = a / b;

// Modulus
int mod = a % b; // Modulus

[Link]("Sum: " + sum);


[Link]("Difference: " + diff);
[Link]("Multiplication: " + mul);
[Link]("Division: " + div);
[Link]("Modulus: " + mod);
}
}

Output
Sum: 13
Difference: 7
Multiplication: 30
Division: 3
Modulus: 1

2. Unary Operators
Unary Operators need only one operand. They are used to increment, decrement, or negate a value.
import [Link].*;

// Driver Class
class Geeks{

public static void main(String[] args){

// Integer declared
int a = 10;
int b = 10;

// Using unary operators


[Link]("Postincrement : " + (a++));
[Link]("Preincrement : " + (++a));

[Link]("Postdecrement : " + (b--));


[Link]("Predecrement : " + (--b));
}
}
Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8

3. Assignment Operator
The assignment operator assigns a value from the right-hand side to a variable on the left. Since it has right-to-left
associativity, the right-hand value must be declared or constant.
public class GFG{
public static void main(String[] args){

int n = 10;

// n = n + 5
n += 5;
[Link]("After += : " + n);

// n = n * 2
n *= 2;
[Link]("After *= : " + n);

// n = n - 5
n -= 5;
[Link]("After -= : " + n);

// n = n / 2
n /= 2;
[Link]("After /= : " + n);

// n = n % 3
n %= 3;
[Link]("After %= : " + n);
}
}

Output
After += : 15
After *= : 30
After -= : 25
After /= : 12
After %= : 0

4. Relational Operators
Relational Operators are used to check for relations like equality, greater than, and less than. They return boolean
results after the comparison and are extensively used in looping statements as well as conditional if-else statements.
import [Link].*;

class Geeks{

public static void main(String[] args){


// Comparison operators
int a = 10;
int b = 3;
int c = 5;

[Link]("a > b: " + (a > b));


[Link]("a < b: " + (a < b));
[Link]("a >= b: " + (a >= b));
[Link]("a <= b: " + (a <= b));
[Link]("a == c: " + (a == c));
[Link]("a != c: " + (a != c));
}
}

Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true

5. Logical Operators
Logical Operators are used to perform "logical AND" and "logical OR" operations, similar to AND gate and OR gate
in digital electronics. They have a short-circuiting effect, meaning the second condition is not evaluated if the first is
false.
import [Link].*;

class Geeks {

// Main Function
public static void main (String[] args) {

// Logical operators
boolean x = true;
boolean y = false;

[Link]("x && y: " + (x && y));


[Link]("x || y: " + (x || y));
[Link]("!x: " + (!x));
}
}

Output
x && y: false
x || y: true
!x: false

6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has three operands and hence the name Ternary.
The general format is,
public class Geeks{

public static void main(String[] args){

int a = 20, b = 10, c = 30, result;

// result holds max of three


// numbers
result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
[Link]("Max of three numbers = "+ result);
}
}

Output
Max of three numbers = 30

7. Bitwise Operators
These operators perform operations at the bit level.
 Bitwise Operators manipulate individual bits using AND, OR, XOR, and NOT.
 Shift Operators move bits to the left or right, effectively multiplying or dividing by powers of two.

import [Link].*;

class Geeks
{
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;

[Link]("d & e : " + (d & e));


[Link]("d | e : " + (d | e));
[Link]("d ^ e : " + (d ^ e));
[Link]("~d : " + (~d));
[Link]("d << 2 : " + (d << 2));
[Link]("e >> 1 : " + (e >> 1));
[Link]("e >>> 1 : " + (e >>> 1));
}
}

Output
d&e:8
d | e : 14
d^e:6
~d : -11
d << 2 : 40
e >> 1 : 6
e >>> 1 : 6
8. instanceof Operator
The instanceof operator is used for type checking. It can be used to test if an object is an instance of a class, a subclass,
or an interface. The general format,
public class GFG{

public static void main(String[] args){

String str = "Hello";


[Link](str instanceof String);

Object obj = new Integer(10);


[Link](obj instanceof Integer);
[Link](obj instanceof String);
}
}

Output
true
true
false

Control Statement
Control statements in Java are the instructions that controls or manages the flow of execution of a program
based on specific conditions or loops.
 Control Statements are used to:
o Make decisions: Control program flow based on conditions (e.g., if, switch).
o Loop through blocks of code: Repeat code execution multiple times (e.g., for, while).
o Jump to a different part of the code: Change the natural flow of execution (e.g., break, continue).
Types of Control Statements:
Control Statements in Java are divided in 3 main categories:
1. Decision-Making Statements or Conditional Statements
o These statements allow the program to make decisions and execute a block of code based on a
condition.
o Examples are: if, if-else, if-else if ladder, switch.
2. Iteration or Looping Statements
o These statements allow the execution of a block of code multiple times until a condition is satisfied.
o Examples are: for, while, do-while.
3. Jump Statements
o These statements are used to alter the flow of control by jumping to a specific part of the program.
o Examples are: break, continue, return.

Decision Making Statement:


1) if Statement :

 The if statement in Java evaluates a boolean condition.


 If the condition is true, the block of code inside the if statement is executed.
Syntax:
if(condition)
{
// this block will be executed if the condition is true
}
 Program:
public class IfExample
{
public static void main(String[] args)
{
int number = 10;

// Check if the number is positive


if (number > 0)
{
[Link]("The number is positive.");
}
}
}
Output:
The number is positive.

2) if-else Statement in Java


 The if-else statement in Java evaluates a boolean condition.
 If the condition is true, the block of code inside the if is executed; otherwise, the code inside the else block
runs.
 Syntax:
if(condition)
{
// this block will be executed if the condition is true
}
else

{
// this block will be executed if condition is false
}
 Program:
public class IfElseExample
{
public static void main(String[] args)
{
int number = -5;

// Check if the number is positive or negative


if (number > 0)
{
[Link]("The number is positive.");
}
else
{
[Link]("The number is negative.");
}
}
}
Output:The number is negative.
3) if-else if Ladder Statement in Java

o The if-else if ladder in Java evaluates multiple boolean conditions in sequence.


o If any of the condition is true, the block of code associated with that condition is executed; if none
of the conditions are true, the optional else block runs.
Syntax:
if (condition1)
{
// Code to execute if condition1 is true
}
else if (condition2)
{
// Code to execute if condition2 is true
}
// ---- more else-if blocks as needed ----
else
{
// Code to execute if none of the above conditions are true
}

Program:
public class IfElseIfLadderExample
{
public static void main(String[] args)
{
int marks = 75;

// Determine the grade based on marks


if (marks >= 90)
{
[Link]("Grade: A");
}
else if (marks >= 75)
{
[Link]("Grade: B");
}
else if (marks >= 50)
{
[Link]("Grade: C");
}
else
{
[Link]("Grade: F");
}
}
}
Output:
Grade: B
4) Switch Statement in Java
o The switch statement in Java runs one block of code based on matching a condition.
o It checks multiple cases for a value and runs the matching case.
o If no case matches, the optional default block runs.
Syntax:
switch (expression)
{
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// ---- more cases as needed ----
default:
// Code to execute if no case matches (optional)
break;
}

 Program:

public class SwitchExample


{
public static void main(String[] args)
{
int day = 3;

// Determine the day of the week


switch (day)
{
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day");
}
}
}
Output:

Wednesday

Iteration or Looping Statement:


1) For Loop in Java
 The for loop is used to repeat a block of code a specific number of times.
 The for loop is useful when the number of iterations is known beforehand (i.e. we know exactly how
many times we need to repeat a task), like when working with arrays or running a piece of code a specific
number of times.
Syntax:
for (initialization; condition; increment/decrement)
{
// statements (code to execute)
}
 Below is syntax explanation:
o Initialization: Variable is initialized before the loop starts. This part runs only once at the
beginning.
o Condition: Checks the condition before each iteration. If the condition is true, the loop continues
to execute the for block statements.
o Increment/Decrement: Updates the loop variable, helping the loop move toward finishing.
o Statements: Statements which are executed when the for loop condition is true.
 Program:
public class ForLoopExample
{
public static void main(String[] args)
{
// Print numbers from 1 to 5 using a for loop
for (int i = 1; i <= 5; i++)
{
[Link]("Number: " + i);
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
2) While Loop in Java
 The while loop is used to repeat a block of code as long as a specific condition is true.
 The while loop is useful when we don’t know how many times we need to repeat the task, and the loop will
continue as long as the condition holds true.
Syntax:
while (condition)
{
// statements (code to execute)
}
 Below is syntax explanation:
o Condition: Checks the condition before each iteration. If the condition is true, the loop continues to
execute the while block statements.
o Statements: The statements inside the loop are executed repeatedly as long as the condition
remains true.
 NOTE :
o If the condition is false, the loop will not run even once.
o If the condition is always true, then the loop will run infinite times.
 Program:
o Task : Print all the even numbers between 1 and 17
o Solution : Since we don't know the exact number of even numbers within this range, we should
avoid using a for loop and instead use a while loop.
public class WhileLoopExample
{
public static void main(String[] args)
{
int no = 2; // Start from the smallest even number

while (no <= 17)


{
[Link]("Even Number: " + no);

no = no + 2; // Skip directly to the next even number


}
}
}

Output:
Even Number: 2
Even Number: 4
Even Number: 6
Even Number: 8
Even Number: 10
Even Number: 12
Even Number: 14
Even Number: 16
3) do-while Loop in Java

 The do-while loop is used to repeat a block of code at least once and then repeatedly as long as the condition
is true.
 The do-while loop is useful when we want the code to run at least once, even if the condition
is false initially.
 Syntax:
do
{
// statements (code to execute)
} while (condition);

 Below is syntax explanation:


o Statements: The block of code that will be executed at least once, regardless of the condition.
o Condition: After executing the statements, the condition is checked. If it evaluates to true, the loop
continues to execute the statements. If it's false, the loop terminates.
 NOTE :
o The do-while loop guarantees that the code inside the loop will run at least once.
o The loop then checks the condition after the code execution, and if true, it continues to run. If false,
it exits.
 Program:
o Task : The user will provide an input, and we need to check whether it is a positive or negative
number.
o Solution : Since the user will always provide input, we need to check the number. We have
to ensure that the code for taking input is always executed first, so we have to use do-while loop.
import [Link];

public class DoWhileExample


{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
int number;

// Prompting user for a positive number


do
{
[Link]("Enter a positive number: ");
number = [Link]();
} while (number <= 0);

[Link]("You entered a valid positive number: " + number);


}
}
Output:
Enter a positive number: -20
Enter a positive number: 0
Enter a positive number: 5
You entered a valid positive number: 5
4) for-each Loop (Enhanced For Loop) in Java
 The for-each loop (also called Enhanced For Loop) in Java is used to iterate over elements in an array or
collection without needing an index variable.
 It's commonly used when we don’t need to know the index of the element and simply want to process each
element in the collection.
 Syntax:
for (dataType variable : collection)
{
// statements (code to execute)
}

 Below is syntax explanation:


o dataType: Specifies the type of the elements in the collection (e.g. int, String).
o variable: Represents each element in the collection during each iteration.
o collection: The array or collection (i.e. List, Set etc.) we want to iterate over.
 NOTE : The for-each loop (enhanced for loop) in Java is primarily used with arrays and collections, but it
can also be used with any other Iterable objects also.

 Program:
public class EnhancedForLoopExample
{
public static void main(String[] args)
{
String[] fruits = {"Apple", "Banana", "Cherry"};

// Using Enhanced For Loop (For-each loop)


for (String fruit : fruits)
{
[Link](fruit);
}
}
}
Output:
Apple
Banana
Cherry

Jump Statement:
1) Break Statement in Java
 The break statement is used to exit a loop or a switch statement before it has completed its normal
execution.
o Loops: The break statement can be used to terminate loops (for, while, do-while) prematurely when
a specific condition is met.
o Switch Statements: It is commonly used in switch statements to exit a particular case and prevent
the execution of subsequent cases.
 How it works:
o The break statement stops the loop or case execution and moves the control to the first statement
outside the loop or switch block.
 Syntax:
break;
 Program 1 (Using break in a loop):
public class BreakExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
[Link]("Loop stopped at: " + i);
break; // Exit the loop when i equals 5
}
[Link]("Number: " + i);
}
}
}

Output:

Number: 1

Number: 2

Number: 3

Number: 4
Loop stopped at: 5

 Program 2 (Using break in a switch statement):


public class BreakSwitchExample
{
public static void main(String[] args)
{
int day = 3;

switch (day)
{
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thrusday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day");
}
}
}
Output:
Wednesday

2) continue Statements in Java


 The continue statement is used to skip the current iteration of a loop and move to the next iteration
without completing the remaining code in the loop for that iteration.
 It is useful when we want to skip specific conditions and proceed with the rest of the loop.
 How it works:
o In Loops:
 When the continue statement is encountered, the loop immediately jumps to the next
iteration.
 In a for loop, the increment/decrement step is executed next.
 In a while or do-while loop, the condition is checked again.
 Syntax:
continue;
 Program 1 (Using continue in a Loop):
public class ContinueExample
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; i++)
{
if (i == 3)
{
[Link]("Skipping number: " + i);
continue; // Skip the rest of the code in this iteration
}
[Link]("Number: " + i);
}
}
}
Output:
Number: 1
Number: 2
Skipping number: 3
Number: 4
Number: 5
 Program 2 (Using continue in a while loop):
public class ContinueWhileExample }
{ [Link]("Number: " +
public static void main(String[] args) number);
{ number++;
int number = 1; }
}
while (number <= 5) }
{
if (number == 3) Output:
{ Number: 1
[Link]("Skipping number: Number: 2
" + number); Skipping number: 3
number++; // Increment the number to Number: 4
avoid an infinite loop Number: 5
continue; // Skip the rest of the code in
this iteration

3) Return Statements in Java


 The return statement is used to exit from a method and optionally send a value back to the method's
caller.
 It is essential for returning a result from a method or terminating the execution of a method before it reaches
its end.
 Syntax:
return value; // For methods with return types, to send a value back.
return; // For void methods, to exit the method.
 Program 1 (Using return in a method):
public class ReturnExample
{
public static void main(String[] args)
{
[Link]("Result: " + addNumbers(5, 3)); // Calling method
}

public static int addNumbers(int a, int b)


{
int sum = a + b;
return sum; // Return the sum to the caller
}
}
Output:
Result: 8
 Program 2 (Using return in a void method):
public class ReturnVoidExample
{
public static void main(String[] args)
{
checkAge(16); // Testing with an age less than 18
// checkAge(20); // Testing with an age greater than or equal to 18
[Link]("Voting Ended.");
}

public static void checkAge(int age)


{
if (age < 18)
{
return; // Exits the method early if age is less than 18
}
[Link]("You can vote");
}
}

Output:
Voting Ended.

Difference Between If and if_ _ _else statement


Attribute If If Else
Condition Executes code if condition is true Executes code if condition is true, otherwise executes alternative
code
Number of Conditions Only one condition can be checked Multiple conditions can be checked using else if statements
Execution Code inside if block is executed if condition is Code inside if block is executed if condition is true, otherwise
true, otherwise skipped code inside else block is executed
Alternative Execution N/A Provides an alternative code block to execute if condition is false
Code Complexity Simplest form of conditional statement Allows for more complex conditional logic with multiple
conditions
Usage Used when only one condition needs to be Used when multiple conditions need to be checked and
checked alternative code needs to be executed

You might also like