0% found this document useful (0 votes)
27 views61 pages

Java Programming Basics Explained

course material

Uploaded by

tilahunagegnehu2
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)
27 views61 pages

Java Programming Basics Explained

course material

Uploaded by

tilahunagegnehu2
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

Chapter Two

Basics in Java Programming

Compiled By: Nigusu Y. ([Link]@[Link] )

1
Chapter Contents
▪ Identifiers
▪ Keywords

▪ Input/output

▪ Variables

▪ Data Types

▪ Operators

▪ Precedence of operators

▪ Statements and Blocks

▪ Control structure 2
Simple Java Program
Step 1 ) Copy the following code into a notepad.

Public class Welcome {


public static void main(String args[])
{
[Link]("Welcome to Java program");
}
}

Step 2 ) Save the file in the directory C:workspace , as [Link]


Step 3 ) Open the command prompt Go to Directory C:workspace
Compile the code using command, javac [Link]
Step 4) Run the code using command, java Welcome
3
Con’t
▪ Class: It is keyword which is used to declare a class
▪ Public: It is called access modifier or specifier
• It is used to define accessibility of data members (variable and member
function(methods)).
▪ Static: Used for memory management
• Can be used is variable function and block.
• Static members are belongs to class rather than object(can be called directly by the class
name).
• Static variable function and block will be in the following section.
▪ Void: there is no value to be returned by the function.
▪ Main(): The execution of any program starts from the main function.
▪ String[] args: It is command line argument that you can write anything in place of
args.
▪ [Link]: stands output object
▪ Print: is a method or function
4
Con’t
▪ When you execute the Java Virtual Machine (JVM) with the java command, the
JVM attempts to invoke the main method of the class you specify.

▪ The JVM loads the class specified by Class Name and uses that class name to
invoke method main.

▪ You can specify an optional list of Strings (separated by spaces) as command-line


arguments that the JVM will pass to your application.

▪ Why must main be declared static?


• When you execute the Java Virtual Machine (JVM) with the java command, the
JVM attempts to invoke the main method of the class you specify when no
objects of the class have been created.

▪ Declaring main as static allows the JVM to invoke main without creating an
5
instance of the class.
Java Tokens
o In Java, Tokens are the smallest elements of a program that is meaningful to the
compiler.

o They are also known as the fundamental building blocks of the program.
oTokens can be classified as follows:
▪ Keywords
▪ Identifiers
▪ Constants/Literals
▪ Operators
▪ Separators

6
Java Keywords
✓Keywords are predefined identifiers reserved by Java for a specific purpose.
✓These keywords cannot be used as names for a variable, class or method [Identifiers].

7
Java Identifiers
o Identifiers are tokens that represent names of variables, methods, classes,
packages and interfaces etc.

o Rules for Java identifiers:


• An identifier is a sequence of characters that consists of letters, digits,
underscores (_), and dollar signs ($).

• An identifier must start with a letter, an underscore (_), or a dollar sign ($).
• It cannot start with a digit.
• An identifier cannot be a reserved word.
• An identifier cannot be true, false, or null.
• An identifier can be of any length. 8
Java Literals
o Literals are tokens that do not change or are constant.
o The different types of literals in Java are:
• Integer Literals: decimal (base 10), hexadecimal (base 16), and octal (base 8).
Example: int x=5; //decimal
• Floating-Point Literals: represent decimals with fractional parts.
Example: float x=3.1415;
• Boolean Literals: have only two values, true or false (0/1).
Example: boolean test=true;
• Character Literals: represent single Unicode characters. A Unicode character is a
16-bit character set that replaces the 8-bit ASCII character set.
Example: char ch=‘A’;
• String Literals: represent multiple/sequence of characters enclosed by double
quotes.
Example: String str=“Hello World”;
9
Separators
▪ Separators are used to separate different parts of the codes.
▪ It tells the compiler about completion of a statement in the program
Example: Semicolon, comma, dot, curly brackets, parenthesis
Separator Role Descriptions

Used to group expressions or define method arguments, controlling the


() (Parentheses)
order of operations.

{} (Curly Used to define code blocks like the body of methods, loops, or
Braces) conditional statements.

Ends individual statements, marking where one instruction ends and


; (Semicolon)
another begins.

Separates items in a list, such as arguments in a method or elements in


, (Comma)
an array.

Used to access members of a class or object, such as methods and fields,


. (Dot)
and for referencing classes in imports.
10
Java Comments
▪ Java comments are notes written to a code for documentation purposes.

▪ Comment texts are not part of the program and compiler ignores executing them.

▪ Java comments add clarity and code understandability.


▪ Java supports three types of comments:
1. C++-Style/Single Line Comments – Starts with //

E.g. // This is a C++ style or single line comments

2. C-Style: Multiline comments – Starts with /* and ends with */

E.g. /* This is an example of a

C-style or multiline comments */

3. Documentation Comments: The documentation comment begins with a /** and ends
with a */.

E.g. /** This is documentation comment */. 11


Java Output Statements
o [Link](): Print the output with the same line
[Link]("Hello world ");

[Link]("This is my first java program");

o [Link](): Print the output with different/new line.


[Link]("Hello world ");

[Link]("This is my first java program");

12
Java Input Statements
o Scanner and BufferedReader class are used to accept data from user/keyboard.
o Scanner class
• Java provides various ways to read input from the keyboard, the [Link] package
• Reads input from the user and pass the input stream ([Link]) in the
constructor of Scanner class.
Scanner in = new Scanner([Link]);

13
import [Link];
public class javaIO
{
public static void main(String[] args) {
String name;
int x;
double y;
Scanner input = new Scanner( [Link] ); //obtain input from command window
[Link]("Enter Your Name: "); //prompt user to enter name
name= [Link](); // Obtain user input(line of text/string) from keyboard
[Link]("Enter x, y:"); //prompt user to enter values of x & y
x= [Link](); // Obtain user integer input from keyboard
y= [Link](); // Obtain user double input from keyboard
[Link]("Your Name is: "+name);
[Link]("The Value of x is: "+x);
[Link]("The Value of y is: "+y);
}
14
}
o BufferedReader
▪ Reads text from a character-input stream to provide efficient reading of
characters, arrays, and lines.

▪ The underlying stream reader can be any FileReaders or the


InputStreamReader.

▪ It can be used to read data line by line by readLine() method and makes the
performance fast.

▪ BufferedReader class in Java is found in the [Link] package.


BufferedReader br= new BufferedReader(new InputStreamReader( [Link]) );

15
//Accepting inputs using BufferedReader
import [Link];
import [Link];
import [Link];
public class javaIO {
public static void main( String[] args )throws IOException
{
String name;
int age;
String str;
BufferedReader br= new BufferedReader(new InputStreamReader( [Link]) );
[Link]("Please Enter Your Name:");
name=[Link]();
[Link]("Please Enter Your Age:");
str=[Link](); //to read an input data
age=[Link](str); //convert the given string int to integer
[Link]("Hello "+ name +"! Your age is: "+age);
16
} }
Data Types in java
o Data types specify the different sizes and values that can be stored in the variable.

o There are two types of data types in Java:

 Primitive data types

▪ They are the building blocks of data manipulation and cannot be further divided
into simpler data types.

▪ Example: Boolean, char, byte, short, int, long, float and double.

 Non-primitive data types: they are not predefined.

▪ They are created by the programmer.

▪ Non-primitive data types are also called 'reference variables' or 'object


references' as they reference a memory location where data is stored

▪ Example: Classes, Interfaces, Arrays, String and enum.


17
Summary of Java Primitive Data Types

Data Type Size Range


boolean 1 byte Take the values true and false only (0/1).
byte 1 byte -27 to 27 -1
short 2 bytes -215 to 215-1
int 4 bytes -231 to 231-1
long 8 bytes -263 to 263-1
float 4 bytes -231 to 231-1

double 8 bytes -263 to 263-1


char 2 bytes 256 characters (Stores single character): ‘x’
String 1 byte Sequence of characters :“Hello world”

18
Enumeration (enum) in Java
▪ Java enumerations are a special type that enables a variable to be a set of
predefined constants.

▪ Enums help in readability, maintainability, and type safety in programs by


assigning meaningful names to integer values.

▪ Mainly useful when we have a small set of possible values for an item like
directions, days of week, etc.

▪ In the Java programming, you define an enum type by using the enum keyword.
▪ The syntax to create an enum :
enum EnumName
{
CONSTANT1, CONSTANT2, CONSTANT3;
} 19
Example of enum demo in Java
public class MainClass
{
enum Colour
{
RED,
BLUE, Output
GREEN, BLUE
YELLOW
}
public static void main(String[] args)
{
Colour c = [Link];
[Link](c);
}
20
}
Variables
▪ A variable is an item of data used to store state of objects and variable has a data
type and a name.
▪ The data type indicates the type of value that the variable can hold and the variable
name must follow rules for identifiers.
▪ Declaring Variables: The variable declaration tells the compiler to allocate appropriate
memory space for the variable based on its data type.

▪ Syntax o declare a variable is as follows.


data type VariableName; Example: int x;
▪ Initializing Variables: [At moment of variable declaration]
int x = 5; // declaring AND assigning (Initialization)
char ch = ‘A’; // initializing character
▪ Assigning values to Variables: [After variable declaration]
int x; // declaring a variable
x = 5; // assigning a value to a21
variable
Constants
▪ In Java, a variable declaration can begin with the final keyword.
▪ This means that once an initial value is specified for the variable, that value is
never allowed to change.
Example: final float pi=3.14;
final int max=100;
▪ Example: program to compute area of circle
public class Area_Circle {
public static void main(String args[])
{
final double pi=3.14;
Output
double area;
The Area of the Circle: 78.5
int rad=5;
area=pi*rad*rad; //compute area
[Link](“The Area of the Circle: ”+area);
} 22

}
Java Operators
o An operator is a symbol that operates on one or more arguments to produce a
result.

❖Assignment Operator (=)


▪ The assignment operator is used for storing a value at some memory location
(typically denoted by a variable).

int var=5; // assigning a value to a variable using =.

Operator Example Equivalent To


= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n 23
= n % 25
public class Assign
{
public static void main( String args[] )
{
int a=1;
int b=2;
int c=3;
a+=5;
b*=4;
c+=a*b;
c%=6;
[Link](“a=”+ a);
[Link](“b=”+ b);
[Link](“c=”+ c);
}
24
}
Arithmetic Operators
o Java arithmetic operators are used to perform addition, subtraction, multiplication
and division.

o Java has five basic arithmetic operators. ( +, -, *, /, %)

Operator Name Use Description

+ Addition op1 + op2 Adds op1 and op2

- Subtraction op1 - op2 Subtracts op2 from op1

* Multiplication op1 * op2 Multiplies op1 by op2

/ Division op1 / op2 Divides op1 by op2

% Remainder op1 % op2 Computes the remainder of dividing op1 by op2

25
Demonstration of arithmetic operators
public class ArithmeticOperators

public static void main(String args[]) { Output


int x=10; The value of z+y is 30
The value of z-y is 5
int y=20;
The value of x*y is 200
int z=25; The value of z/y is 0
The value of z%y is 5
[Link]( “The value of x+y is “ + (x+y));

[Link]( “The value of z-y is “ + (z-y));

[Link]( “The value of x*y is “ + (x*y));

[Link]( “The value of z/y is “ + (x/y));

[Link]( “The value of z%y is “ + (z%x));


}
26
}
Relational Operators
o Java has six relational/comparison operators that compare two numbers and
return a Boolean value.
o The relational operators are <, >, <=, >=, ==, and !=.

Operator Name Description

x<y Less than True if x is less than y, otherwise false.

x>y Greater than True if x is greater than y, otherwise false.

x <= y Less than or equal to True if x is less than or equal to y, otherwise false.

x >= y Greater than or equal to True if x is greater than or equal to y, otherwise false.

x == y Equal True if x equals y, otherwise false.

x != y Not Equal True if x is not equal to y, otherwise false.


27
Relational operators example
puplic class RelationalOperators
{
public static void main(String args[])
{
int x=10;
int y=20;
[Link]( “Demonstration of Relational Operators in Java”);
if(x<y)
[Link]( “The value of x is less than y “);
else if(x>y)
[Link]( “The value of x is greater than y “);
else
[Link]( “The value of x is equal to y”)
}
28
}
Logical Operators
o There are three logical/conditional operators for combining logical expressions.
o Logical operators evaluate to True or False.

Operator Name Example


! Logical Negation (NOT) !(5 == 5) // gives False
&& Logical AND 5 < 6 && 6 < 6 // gives False
|| Logical OR 5 < 6 || 6 < 5 //gives True
Example:
public class LogicalOps {
public static void main(String[] args) {
int x=6;
int y=6;
int z=5;
[Link](!(x==y)); //Prints False b/c true condition reversed by negating
[Link](z < 10 && y <5); //Prints False b/c Both conditions are not true
[Link](z < 6 || x > 7); //Prints True b/c one of the condition is True
} 29

}
Logical operators Demonstration 2
import [Link]; //import statement for accepting input from keyboard
public class LogOps {
public static void main(String[] args) {
double mark;
Scanner input = new Scanner( [Link] ); //Create Scanner to obtain input from command window
[Link]( "Enter Student Mark: "); // prompt user to enter mark
mark = [Link](); // obtain user input from keyboard
if(mark<0 || mark>100) {
[Link]("Invalid Input! Mark Must be between 0 & 100");
}
else if(mark>80 && mark<=100) {
[Link]("A");
}
else if(mark>=60 && mark<80) {
[Link]("B") ;
} else {
[Link](“F");
30
} }}
Increment & Decrement Operators
o The auto increment (++) and auto decrement (--) operators provide a convenient
way of, respectively, adding and subtracting 1 from a numeric variable.

o When used in prefix form, the operator is first applied and the outcome is then
used in the expression.

o When used in the postfix form, the expression is evaluated first and then the
operator applied. Example: int k=5;

Operator Name Example

++ Auto Increment (prefix) ++k + 10; // gives 16

++ Auto Increment (postfix) k++ + 10; // gives 15

-- Auto Decrement (prefix) --k + 10; // gives 14

-- Auto Decrement (postfix) k-- + 10 ; // gives 15

31
Illustration of increment & decrement operators
public class IncDec
{
public static void main(String[] args)
{
int num;
num = 10; // assign 10 to num
[Link](num ); // prints 10
[Link](++num ); // prints 11 (Prefix)
[Link](num ); // prints11
Program Output
[Link](num++ ); // prints 11 (Postfix) 10
[Link](num ); // prints 12 11
11
}
11
} 12

32
Precedence of Java operators
o The order in which operators are evaluated in an expression is significant and is
determined by precedence rules.

33
34
Example
public class OperatorPrecedence
{
Output
public static void main(String[] args)
a+b/d = 20
{
a+b*d-e/f = 219
int a = 20, b = 10, c = 0;
int d = 20, e = 40, f = 30;
// (* = / = %) > (+ = -) precedence rules
[Link]("a+b/d = " + (a + b / d));
[Link]("a+b*d-e/f = "+ (a + b * d - e / f));

}
}
35
Java Expressions

▪ In Java, an expression is a construct that combines literals, variables,


operators, and method invocations to produce a single value.

▪ This value can be of any data type, such as a number, a string, a


boolean, or an object.

▪ Expressions are fundamental building blocks in Java programming,


forming the basis for statements and enabling the computation and
manipulation of data within a program.

▪ The followings are some common types of Java expressions:

36
▪ Arithmetic Expressions: These involve mathematical operations and produce
a numerical result.
int sum = 2 + 3; // Evaluates to 5
double product = 2.5 * 4.0; // Evaluates to 10.0

▪ Relational Expressions: These compare two values and result in a boolean


(true or false) value.
boolean isEqual = (x == y);
boolean isGreater = (age > 18);

▪ Logical Expressions: These combine boolean expressions using logical


operators (&&, ||, !) and also produce a boolean result.
boolean isEligible = (age >= 18 || age <= 32 );

37
▪ Assignment Expressions: These assign a value to a variable. The expression itself
evaluates to the assigned value.
int count = 12; // Evaluates to 12
String name = “Bob"; // Evaluates to “Bob"

▪ Method Invocation Expressions: These call a method and evaluate to the return
value of that method.
int length = [Link](); // Evaluates to the length of myString
[Link]("Hello"); // Evaluates to void (no return value)

▪ Literal Expressions: The simplest form of expression, where a literal value


directly represents itself.
int number = 100; // 100 is a literal expression
String message = "Java"; // "Java" is a literal expression

38
Java Statements & Blocks
▪ A statement is one or more line of code terminated by semicolon (;).
Example: int x=5;
[Link](“Hello World”);
▪ A block is one or more statements bounded by an opening & closing curly braces
that groups the statements as one unit.
Example: public static void main(String args[]) {
int x=5;
int y=10;
char ch=‘Z’;
[Link](“Hello ”);
[Link](“World”); //Java Block of Code
[Link](“x=”+x);
[Link](“y=”+y);
[Link](“ch=”+ch);39
}
Simple Type Conversion/Casting
o Type casting enables to convert the value of one data from one type to another type.
(int) 3.14; // converts 3.14 to an int to give 3
(double) 2; // converts 2 to a double to give 2.0
(char) 122; // converts 122 to a char whose code is 122 (z)
Example
public class TypeCasting {
public static void main(String[] args) {
float x=3.14f;
int ascii = 65;
[Link]("Demonstration of Simple Type Casting");
[Link]((int) x); //3
[Link]((long) x); //3
[Link]((double) x); //3.140000104904175
[Link]((short) x); //3
[Link]((char) ascii); //A
} }
40
Java Control Structure
o The statement is the instruction given to the computer that performs specific types
of work. They can make decisions and repetitive tasks.

o There are different forms of Java statements:


▪ Declaration statements: used for defining/creating variables.
▪ Arithmetic statements: used for arithmetic operation

▪ Control Statements: used to control the sequence of execution of different


statements of the program.

o There are three main categories of control flow statement;


• Selection or Decision Control Statement
• Repetition or Loop Control Statement
• Branching Control Statement
41
Decision Statements
o Decision statements are Java statements that allows to select and execute specific
blocks of code while skipping other sections.

❖ if statement
o The if-statement specifies that a statement (or block of code) will be executed if
and only if a certain boolean statement is true.

o Syntax: if(condition)

statements;

o The first expression is evaluated. If the outcome is true then statement is executed.
Otherwise, nothing happens.

o Example: When dividing two values, we may want to check that the denominator
is nonzero. if(y!=0)
42
div=x/y;
❖ if-else statement

o The if-else statement is used to execute a certain statement if a condition is true,


and a different statement if the condition is false.
o Syntax: if(condition)
statement1;
else
statement2;
o First expression is evaluated. If the outcome is true then statement1 is executed.
Otherwise, statement2 is executed.
Example: if(score>=50) {
[Link]("Congratulations! U Passed!”; ");
}
else {
[Link](”U Failed!”);
[Link](”U Must Take This Course Again!”);
43
}
❖ if-else-if statement
oThe statement in the else-clause of an if-else block can be another if-else
structures.
Examplemple:
oSyntax: int time = 22;
if (condition1) if (time < 10)
// block of code {
else if (condition2) [Link]("Good morning.");
//executed if the condition1 is false }

else { else if (time < 20)


{
// executed if the condition1 &2 is false
[Link]("Good Afternoon.");
}
else {
[Link]("Good evening.");

44
}
Nested if-else-if statement
▪ An if statement inside another if statement is known as nested if statements.
▪ Nested if statements are used if there is a sub condition to be tested after one
condition has been checked.

▪ The depth/number of nested if statements depends upon the number of conditions


to be checked.

▪ Syntax:
if (outerCondition) { // Code to execute if outerCondition is true
if (innerCondition1) {
} else if (innerCondition2) { // Code to execute if innerCondition1 is true
// Code to execute if innerCondition1 is false and innerCondition2 is true
} else {
// Code to execute if both innerCondition1 and innerCondition2 are false
}
} else if (anotherOuterCondition) {
// Code to execute if outerCondition is false and anotherOuterCondition is true
} else {
// Code to execute if all preceding conditions
45 are false
}
Nested if-else-if statement demonstration

public class Nested else


{ {
public static void main(String[] args) [Link]("Good score.");
{ }
int score = 85; }
boolean credit = true;
else if (score >= 50)
if (score >= 70)
{
{
[Link]("Needs improvement.");
[Link]("Passed the exam.");
}
if (score >= 90)
else
{
[Link]("Excellent score!"); {
} [Link]("Failed the exam.");
else if (credit) }
{
[Link](“Good score"); }
} }

46
switch statement
o The switch statement used to select one of many code blocks to be executed.
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed unless the default
statement is executed .

o Syntax:
switch(expression)
{
case label: // code block
break;
case label: // code block
break;
47
default: // code block }
Demonstration of switch statement
int day = 4;
switch (day)
{
case 1: [Link]("Monday");
break;
case 2: [Link]("Tuesday");
break; Output
case 3: [Link]("Wednesday"); Thursday
break;
case 4: [Link]("Thursday");
break;
case 5: [Link]("Friday");
break;
case 6: [Link]("Saturday");
break;
default:
[Link]("Sunday");
48
}
Looping Statements
▪ Looping statements are Java statements that allows to execute specific blocks
of code a number of times.

▪ Entry controlled loop: The loop in which test condition is checked in the
beginning of the loop.

✓Loop does not execute at all if the condition is false.


Example: for loop, while loop

▪ Exit controlled loop: when statements inside the loop body is executed and
then the condition is checked that loop.

✓The loop executes at least once even if the condition is false.


Example: do-while loop.
49
1) while loop statement
• The while statement is one of the looping constructs control statement that
executes a block of code while a condition is true.

• The loop will stop the execution if the testing expression evaluates to false.
• Syntax:
while(Conditions)
{ // code block to be executed
}
• Example: Adding the first 10 natural numbers(1-10)

int i=1,sum=0;
while(i<=10)
sum+=i;
50
i++;
2) do-while Loop statement
• The do-while loop is similar to the while loop, except that the test
condition is performed at the end of the loop instead of at the beginning.

• The do-while loop executes at least once without checking the


condition.

• When the loop condition becomes false, the loop is terminated and
execution continues with the statement immediately following the loop.
• Syntax:
do

//Statement too be executed

while (<loop condition>);

51
Example
public class do_while
{
public static void main(String[] args)
{
int i = 10;
do
{
[Link]("i is " + i);
i++;
}
while (i < 5);
}
}
52
3) for loop statement
✓ The for loop allows execution of the same code a number of times.
✓ Syntax: for (Initialization; Condition; Expression)
{ // code block to be executed
}
• Initialization –is executed (one time) before the execution of the code block.
• Condition -defines the condition for executing the code block.
• Expression - is executed (every time) after the code block has been executed
✓ Example: int i, sum=0; int i;
for (i = 1; i <= n; i++) for ( i = 0; i < 10; i++ )
{ {
sum += i; [Link](i)
} }
53
▪ A loop becomes infinite loop if a condition never becomes false.
▪ Removing all the expressions gives us an infinite loop.
▪This loop's condition is assumed to be always true.
• Examples infinite while loop:
while (true)

[Link]("This will print forever!");

// No condition to make the loop false

54
• Infinite for loop examples:
for (;;)
{ // No initialization, condition, or increment
[Link]("This will also print forever!");
}
• Infinite loop due to unupdated variable:
int counter = 0;

while (counter < 10)

[Link]("Counter is: " + counter);

// counter is never incremented, so counter < 10 remains true

} 55
Nested loop statement
▪ Many applications require nesting of the loop statements, allowing on loop
statement to be surrounded with in another loop statement.

▪ Nesting can be defined as the method of embedding one control structure


with in another control structure.

▪ While making control structures to be reside one with in another, the


inner and outer control structures may be of the same type or may not be
of same type.

▪ But, it is essential for us to ensure that one control structure is completely


embedded within another.

56
//Nested loop demo
public class NestedLoop
{
public static void main(String[] args)
{
int i;
int j;
for(i=5;i>=1;i--) Output
{ 55555
for(j=1;j<=i;j++) 4444
{ 333
[Link](i+ " "); 22
}
1
[Link](" ");
}
}
57
}
Branching Statements
o Branching statements allows us to redirect the flow of program execution.
o Java offers three branching statements: break, continue and return.
❖Continue statement
o The continue statement terminates the current iteration of a loop and instead causes to
jump/proceed to the next iteration of the loop.
o Example:
public class Continue {
public static void main(String[] args) {
int i, sum=0;
Output
for ( i = 1; i <= 10; i++ ) { 1
if ( i% 2== 0) { 3
5
continue; }
7
sum+=i; 9
System. [Link](i+" "); The sum is = 25
}
[Link]("the sum is = "+sum );
58
}}
❖ break statement
• Break causes immediate termination/exit from looping statements entirely.
• Example:
public class Break {
public static void main(String[] args) {
int num;
num = 10;
//loop while i is less than 6
for(int i=num; i >=1; i--) {
if(i<6){
break; // terminate loop if i <6
}
[Link](i + " ");
}
Output
[Link]("Aborted!");
10 9 8 7 6 Aborted!
}} 59
❖return statement
• The return statement is used to exit from the current method.
• The flow of control returns to the statement that follows the original
method call.
• The return statement has two forms: one that returns a value and one that
doesn't.
Syntax: return expression;
• To return a value, simply put the value (or an expression that calculates
the value after the keyword return.
For example:
return sum;
public double Sum(double x, double y) {
return sum = x+y;
}
• When a method is declared void, use the form of return that doesn't
return a value.
60
The demonstration of return statement
public class Power {
private int x; // //instance
instance variables
variables
private int y;
public Power(int a, int b) { //A constructor to Initializes instance variable
x=a;
y=b;
}
public double computePower() { //a method to access the data members
double z;
z=Math . pow (x, y);
return z;
}
public static void main(String args[]) {
Power p= new Power(2,3); //Object creation with a parameterized constructor
double result=p. computePower(); //Assign the return value of the function to the variable result
[Link]("Output :"+result);
} } 61

You might also like