0% found this document useful (0 votes)
3 views

JAVA Unit 1

The document provides detailed notes on Java programming, covering its history, types of applications, features, and object-oriented concepts. It explains the significance of Java's design principles, such as portability and security, and outlines various data types and variable classifications. Additionally, it discusses key object-oriented programming concepts like inheritance, polymorphism, encapsulation, and the structure of Java code including keywords, identifiers, and operators.

Uploaded by

bchifundo0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JAVA Unit 1

The document provides detailed notes on Java programming, covering its history, types of applications, features, and object-oriented concepts. It explains the significance of Java's design principles, such as portability and security, and outlines various data types and variable classifications. Additionally, it discusses key object-oriented programming concepts like inheritance, polymorphism, encapsulation, and the structure of Java code including keywords, identifiers, and operators.

Uploaded by

bchifundo0
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

DMI-ST.

JOHN THE BAPTIST UNIVERSITY


LILONGWE, MALAWI

Programme: Bachelor of Science in Computer Science


Semester: V
Module Code: 351CS54
Module Name: JAVA PROGRAMMING
Unit 1 Detailed Notes
School of Computer Science & Information Technology

Module Teacher: Mr. Jimu


Unit I Introduction to JAVA:
The Genesis of Java – Buzzwords - Object oriented Concepts - Lexical Issues - Data types and
variables – Arrays - Operators - Control Statements: Selection - Iteration and jump Statement.

The Genesis of Java


• Java programming language was originally developed by Sun Microsystems
• It was initiated by James Gosling and released in 1995 as core component of Sun
Microsystems’
• Java platform (Java 1.0 [J2SE]). ... Java is guaranteed to be Write Once, Run
Anywhere.
Java is − Object Oriented − In Java, everything is an Object.
• Oak
• Java, May 20, 1995, Sun World
• HotJava
• The first Java-enabled Web browser
• JDK Evolutions
• Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995.
• James Gosling is known as the father of Java.
• Before Java, its name was Oak. Since Oak was already a registered company, so James
Gosling and his team changed the Oak name to Java.
TYPES OF JAVA APPLICATIONS:
• There are mainly 4 types of applications that can be created using Java programming:
• 1) Standalone Application
• Standalone applications are also known as desktop applications or window-based
applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing are
used in Java for creating standalone applications.
• 2) Web Application
• An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are
used for creating web applications in Java.
3) Enterprise Application
• An application that is distributed in nature, such as banking applications, etc. is called
enterprise application. It has advantages of the high-level security, load balancing, and
clustering. In Java, EJB is used for creating enterprise applications.
• 4) Mobile Application
• An application which is created for mobile devices is called a mobile application.
Currently, Android and Java ME are used for creating mobile applications.
Applications of JAVA
• According to Sun, 3 billion devices run Java. There are many devices where Java is
currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics 8. Games, etc.
Buzzwords
• The Java programming language is a high-level language that can be
characterized by all of the following buzzwords:
• Simple.
• Object oriented.
• Distributed.
The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. ...
The features of Java are also known as java buzzwords.
Features of Java
• Java is simple
• Java is object-oriented
• Java is distributed
• Java is interpreted
• Java is robust
• Java is secure
• Java is architecture-neutral
• Java is portable and Platform independent
• Java’s performance
• Java is multithreaded
• Java is dynamic and High Performance

Features of Java
• Java is simple-java is very easy to learn, and its syntax is simple, clean and easy to
understand
• Java is object-oriented-Java is an object-oriented programming language. Everything in
Java is an object.
• Java is distributed-Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating distributed applications.
• Java is interpreted-It is executed in line-by-line statements in java programming
• Java is robust-it uses strong memory management. and There is a lack of pointers that
avoids security problems.
• Java is secure-No explicit pointer and Java Programs run inside a virtual machine
sandbox
• Java is architecture-neutral-n C programming, int data type occupies 2 bytes of memory
for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
• Java is portable -Java is portable because it facilitates you to carry the Java bytecode to
any platform. It doesn't require any implementation.
• Platform independent-Java code can be run on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run Anywhere(WORA).
• Java’s performance-
• Java is multithreaded-A thread is like a separate program, executing concurrently. We
can write Java programs that deal with many tasks at once by defining multiple threads.
• Java is dynamic -Java is a dynamic language. It supports dynamic loading of classes. It
means classes are loaded on demand.
High Performance-Java is faster than other traditional interpreted programming
languages because Java bytecode is "close" to native code.
Object oriented Concepts
• Oriented Programming is a paradigm that provides many concepts, such as inheritance,
data binding, polymorphism, etc.
• Simula is considered the first object-oriented programming language. The programming
paradigm where everything is represented as an object is known as a truly object-oriented
programming language.
• Smalltalk is considered the first truly object-oriented programming language.
• The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.
• The main aim of object-oriented programming is to implement real-world entities, for
example, object, classes, abstraction, inheritance, polymorphism, etc.
OOPs (Object-Oriented Programming System)
• Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by
providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
• Apart from these concepts, there are some other terms which are used in Object-Oriented
design:
• Coupling
• Cohesion
• Association
• Aggregation and Composition
Object
• Any entity that has state and behavior is known as an object.
• For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
• An Object can be defined as an instance of a class.
• An object contains an address and takes up some space in memory. Objects can
communicate without knowing the details of each other's data or code.
• The only necessary thing is the type of message accepted and the type of response
returned by the objects.
• Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
• Collection of objects is called class.
• It is a logical entity.
• A class can also be defined as a blueprint from which you can create an individual
object.
• Class doesn't consume any space Inheritance

When one object acquires all the properties and behaviors of a parent object, it is known
as inheritance.
• It provides code reusability.
• It is used to achieve runtime polymorphism. Polymorphism
• If one task is performed in different ways, it is known as polymorphism.
• For example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.
• In Java, we use method overloading and method overriding to achieve polymorphism.
• Another example can be to speak something; for example, a cat speaks meow, dog barks
woof, etc.
Abstraction
• Hiding internal details and showing functionality is known as abstraction.
• For example phone call, we don't know the internal processing.
• In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
• Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
• A java class is the example of encapsulation.
Java bean is the fully encapsulated class because all the data members are private here

Coupling
• Coupling refers to the knowledge or information or dependency of another class.
• It arises when classes are aware of each other. If a class has the details information of
another class, there is strong coupling.
• In Java, we use private, protected, and public modifiers to display the visibility level of a
class, method, and field.
Cohesion
• Cohesion refers to the level of a component which performs a single well-defined task.
• A single well-defined task is done by a highly cohesive method.
• The weakly cohesive method will split the task into separate parts.
• The java.io package is a highly cohesive package because it has I/O related classes and
interface.
• However, the java.util package is a weakly cohesive package because it has unrelated
classes and interfaces.
Association
• Association represents the relationship between the objects.
• Here, one object can be associated with one object or many objects.
• There can be four types of association between the objects:
• One to One
• One to Many
• Many to One, and • Many to Many
• Let's understand the relationship with real-time examples.

For example, One country can have one prime minister (one to one), and a prime minister
can have many ministers (one to many). Also, many MP's can have one prime minister
(many to one), and many ministers can have many departments (many to many).
• Association can be undirectional or bidirectional.

Aggregation
• Aggregation is a way to achieve Association.
• Aggregation represents the relationship where one object contains other objects as a part
of its state.
• It represents the weak relationship between objects.
• It is also termed as a has-a relationship in Java. Like, inheritance represents the isa
relationship. It is another way to reuse objects.
Composition
• The composition is also a way to achieve Association.
• The composition represents the relationship where one object contains other objects as a
part of its state.
• There is a strong relationship between the containing object and the dependent object.
• It is the state where containing objects do not have an independent existence.
• If you delete the parent object, all the child objects will be deleted automatically. Lexical
Issues
The Java compiler recognizes five kinds of tokens: identifiers, keywords, literals, operators,
and miscellaneous separators. Comments and white space such as blanks, tabs, line feeds,
and are not tokens, but they often are used to separate tokens
Java keywords
• Java keywords are also known as reserved words.
• Keywords are particular words which acts as a key to a code. These are predefined words
by Java so it cannot be used as a variable or object name.
• A keyword is a reserved word in Java language. Keywords are used to perform a specific
task in the computer program. For example, to define variables, do repetitive tasks or
perform logical operations.
• Java is rich in keywords.such as abstract continue for new switch assert default goto
package synchronized boolean do if private this break double implements protected
throw byte else import public throws case enum instanceof return transient catch
extends int short try char final interface static var class finally long strictfp void
const float native super volatile while Java identifiers
• Identifiers are names for variables, methods, classes, or parameters. Identifiers can have
alphanumerical characters, underscores and dollar signs ($). It is an error to begin a
variable name with a number. White space in names is not permitted.
• Identifiers are case sensitive. This means that Name, name, or NAME refer to three
different variables. Identifiers also cannot match language keywords.
• String name23; int _col; short car_age; These are valid Java identifiers. Java literals

• A literal is a textual representation of a particular value of a type. Literal types include
boolean, integer, floating point, string, null, or character. Technically, a literal will be
assigned a value at compile time, while a variable will be assigned at runtime.
int age = 29; String nationality = "Hungarian";
Java operators
• An operator is a symbol used to perform an action on some value. Operators are used in
expressions to describe operations involving one or more operands.
• + - * / % ^ & | ! ~ = += -= *= /= %= ^= ++ -- == != < > &= >>= <<= >= <= || && >> <<
?: This is a partial list of Java operators.
Java separators.
• A separator is a sequence of one or more characters used to specify the boundary
between separate, independent regions in plain text or other data stream.
• [ ] ( ) { } , ; . " String language = "Java"; The double quotes are used to mark the
beginning and the end of a string. The semicolon ; character is used to end each Java
statement.
Data types and variables
Data Types in Java
• Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:
• Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
• Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
• Java Primitive Data Types
• In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.
There are 8 types of primitive data types:
• boolean data type
• byte data type
• char data type
• short data type
• int data type
• long data type
• float data type
• double data type
Data Type Default Value Default size

boolean false 1 bit


char '\u0000' 2 byte

byte 0 1 byte
short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

• Boolean Data Type


• Example: Boolean one = false
• Byte Data Type
• Example: byte a = 10, byte b = -20
• Short Data Type
• Example: short s = 10000, short r = -5000
• int Data Type
• Example: int a = 100000, int b = -200000
• Long Data Type
• Example: long a = 100000L, long b = -200000L
• Float Data Type
• Example: float f1 = 234.5f
• Double Data Type
• Example: double d1 = 12.3
• Char Data Type
• Example: char letterA = 'A'
Java variables
• A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
• Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
• Variable is name of reserved area allocated in memory. In other words, it is a name of
memory location. It is a combination of "vary + able" that means its value can be changed.
• int data=50;//Here data is variable • Types of Variables
• There are three types of variables in Java:
• local variable
• instance variable
• static variable
• 1) Local Variable
• A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that
the variable exists.

• A local variable cannot be defined with "static" keyword.


• 2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.
• It is called instance variable because its value is instance specific and is not shared among
instances.
• 3) Static variable
• A variable which is declared as static is called static variable. It cannot be local. You can
create a single copy of static variable and share among all the instances of the class.
Memory allocation for static variable happens only once when the class is loaded in the
memory.
Example to understand the types of variables in java • class A{
• int data=50;//instance variable
• static int m=100;//static variable
• void method()
• {
• int n=90;//local variable
• }
• }//end of class
Java Variable Example: Add Two Numbers
• class Simple{
• public static void main(String[] args){
• int a=10;
• int b=10;
• int c=a+b;
• System.out.println(c);
• }} • Output: • 20
Arrays
• An array is a collection of similar type of elements which has contiguous memory
location.
• Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.
• Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
• In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store
primitive values or objects in an array in Java. Like C/C++, we can also create single
dimentional or multidimentional arrays in Java.
• Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.

Random access: We can get any data located at an index position.


Disadvantages
• Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.

There are four types of array.


Single Dimensional Array (1D Array)
2D Array
3DArray
Multidimensional Array
Single Dimensional Array in Java • Syntax to Declare an Array in Java
• dataType[] arr; (or)
• dataType []arr; (or)
• dataType arr[];
• Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Example of Java Array simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.
• //Java Program to illustrate how to declare, instantiate, initialize
• //and traverse the Java array.
• class Testarray{
• public static void main(String args[]){
• int a[]=new int[5];//declaration and instantiation
• a[0]=10;//initialization
• a[1]=20; • a[2]=70;
• a[3]=40;
• a[4]=50;
• //traversing array
• for(int i=0;i<a.length;i++)//length is the property of array •
System.out.println(a[i]);
}} Output:

• 10 20 70 40 50
Declaration, Instantiation and Initialization of Java Array
• We can declare, instantiate and initialize the java array together by:
• int a[]={33,3,4,5};//declaration, instantiation and initialization
//Java Program to illustrate the use of declaration, instantiation and initialization of Jav
a array in a single line • class Testarray1{
• public static void main(String args[]){
• int a[]={33,3,4,5};//declaration, instantiation and initialization
• //printing array
• for(int i=0;i<a.length;i++)//length is the property of array
• System.out.println(a[i]);
• }} • Output:
• 33 3 4 5
Java operators
• Operators are used to perform operations on variables and values.
• In the example below, we use the + operator to add together two values:
• Example
• int x = 100 + 50;
• Although the + operator is often used to add together two values, like in the example
above, it can also be used to add together a variable and a value, or a variable and another
variable:
Types of operators
• Java divides the operators into the following groups:

• Arithmetic operators

• Assignment operators

• Comparison operators

• Logical operators

• Bitwise operators
• Java divides the operators into the following groups:

• Arithmetic operators

• Assignment operators

• Comparison operators

• Logical operators

• Bitwise operators
Arithmetic operators
Arithmetic operators are used to perform common mathematical operations

Operator Name Description

+ Addition Adds together two values

- Subtraction Subtracts one value from another

* Multiplication Multiplies two values

/ Division Divides one value by another

% Modulus Returns the division remainder

++ Increment Increases the value of a variable by 1

-- Decrement Decreases the value of a variable by 1


Java Assignment operators


• Assignment operators are used to assign values to variables.
• In the example below, we use the assignment operator (=) to assign the value 10 to a
variable called x:

• Example

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3


<<= x <<= 3 x = x << 3

• int x = 10;

Java comparison operators


Comparison operators are used to compare two values:

Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


Java logical operators
Logical operators are used to determine the logic between variables or values

Operator Name Description Example

&& Logical and Returns true if both x < 5 && x <


statements are true 10

|| Logical or x < 5 || x < 4


Returns true if one of the
statements is true

! Logical not Reverse the result, returns !(x < 5 && x <
false if the result is true 10)
Java Bitwise operators
Bitwise operators are used to perform binary logic with the bits of an integer or long integer

Operator Description Example Same as Result Decimal

& AND - Sets each bit to 1 if both bits are 1 1 0101 & 0001 1
5&
0001

| 1 0101 5
OR - Sets each bit to 1 if any of the two bits 5 | 0101 |
is 1 0001

~
NOT - Inverts all the bits ~5 ~0101 1010 10

^ XOR - Sets each bit to 1 if only one of the 1 0101 ^ 0100 4


5^
two bits is 1 0001
<< Zero-fill left shift - Shift left by pushing 9 << 1 1001 << 1 0010 2
zeroes in from the right and letting the
leftmost bits fall off

>> Signed right shift - Shift right by pushing 9 >> 1 1001 >> 1 1100 12
copies of the leftmost bit in from the left
and letting the rightmost bits fall off

>>> Zero-fill right shift - Shift right by pushing 9 >>> 1 1001 >>> 1 0100 4
zeroes in from the left and letting the
rightmost bits fall off

Control statements:
• Selection
• Iteration and • jump Statement.
Selection
Java Conditions and If Statements





Java supports the usual logical conditions from mathematics:
Less than: a < b
Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• Equal to a == b
• Not Equal to: a != b
Conditional statements
• Java has the following conditional statements:
• Use if to specify a block of code to be executed, if a specified condition is true(if
statement)
• Use else to specify a block of code to be executed, if the same condition is false(if–else
statement)
• Use else if to specify a new condition to test, if the first condition is false(if–elseif
statement)
• Use switch to specify many alternative blocks of code to be executed(switch statement)

If statement
• Use the if statement to specify a block of Java code to be executed if a condition is true.
• Syntax
• if (condition)
• { // block of code to be executed if the condition is true }
• Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
• Example
• int x = 20;
• int y = 18;
• if (x > y)
• { System.out.println("x is greater than y");
• }
The else statement
• Use the else statement to specify a block of code to be executed if the condition is false.
• Syntax
• if (condition)
• { // block of code to be executed if the condition is true } • else
• { // block of code to be executed if the condition is false }
• Example
• int time = 20;
• if (time < 18)





• { System.out.println("Good day."); }
• else
• { System.out.println("Good evening."); }
• // Outputs "Good evening."
The elseif statement
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1)
{ // block of code to be executed if condition1 is true }
else if (condition2)
• { // block of code to be executed if the condition1 is false and condition2 is true } •
else
• { // block of code to be executed if the condition1 is false and condition2 is false }

Example
• int time = 22;
• if (time < 10)
• { System.out.println("Good morning."); }
• else if (time < 20)
• { System.out.println("Good day."); }
• else
• { System.out.println("Good evening."); }
• // Outputs "Good evening."
Short Hand If...Else (Ternary Operator)
• There is also a short-hand if else, which is known as the ternary operator because it
consists of three operands.
• It can be used to replace multiple lines of code with a single line.
• It is often used to replace simple if else statements:
Syntax
• variable = (condition) ? expressionTrue : expressionFalse;

• //program
• int time = 20;
• if (time < 18)
• { System.out.println("Good day."); }
• Else
• { System.out.println("Good evening."); }






• You can simply write:
• Example
• int time = 20;
• String result = (time < 18) ? "Good day." : "Good evening."; System.out.println(result);

Java switch statement


• Use the switch statement to select one of many code blocks to be executed. Syntax
• switch(expression)
• {
• case x: // code block break;
• case y: // code block break;
• default: // code block
}
This is how it works:
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.
The break and default keywords are optional, Example
• int day = 4;
• switch (day)
• {
• case 1:
• System.out.println("Monday");
• break;
• case 2:
• System.out.println("Tuesday");
• break;
• case 3:
• System.out.println("Wednesday");
• break; • case 4:
• System.out.println("Thursday");
• break;
• case 5:
• System.out.println("Friday");
• break;
• case 6:
• System.out.println("Saturday");






• break; • case 7:
• System.out.println("Sunday");
• break; }
• // Outputs "Thursday" (day 4) The break Keyword
• When Java reaches a break keyword, it breaks out of the switch block.
• This will stop the execution of more code and case testing inside the block.
• When a match is found, and the job is done, it's time for a break. There is no need for
more testing.
• A break can save a lot of execution time because it "ignores" the execution of all the rest
of the code in the switch block.
The default Keyword
• The default keyword specifies some code to run if there is no case match: Loops
• Loops can execute a block of code as long as a specified condition is reached.
• Loops are handy because they save time, reduce errors, and they make code more
readable.
Java While Loop
The while loop loops through a block of code as long as a specified condition is true:
Syntax while
(condition) { //
code block to be
executed }
int i = 0; while
(i < 5)
• { System.out.println(i);
• i++; }
The Do/While Loop
• The do/while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true.
• Syntax
• Do
• {
• // code block to be executed
• } while (condition);
• The example below uses a do/while loop.
• The loop will always be executed at least once, even if the condition is false, because the
code block is executed before the condition is tested:






• Example
• int i = 0; do
• { System.out.println(i);
• i++;
• } while (i < 5); Java for loop
• When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
• Syntax
• for (statement 1; statement 2; statement 3) { // code block to be executed } •
Statement 1 is executed (one time) before the execution of the code block.
• Statement 2 defines the condition for executing the code block.
• Statement 3 is executed (every time) after the code block has been executed.
• The example below will print the numbers 0 to 4:
• Example
• for (int i = 0; i < 5; i++)
• { System.out.println(i);
• }
• Statement 1 sets a variable before the loop starts (int i = 0).
• Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
• Statement 3 increases a value (i++) each time the code block in the loop has been
executed.

Java break
It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
This example jumps out of the loop when i is equal to 4:






for (int i = 0; i < 10; i++)


{
• if (i == 4)
• { break; }
• System.out.println(i); }
Continue statement
• The continue statement breaks one iteration (in the loop), if a specified condition occurs,
and continues with the next iteration in the loop.
• This example skips the value of 4:
• Example
• for (int i = 0; i < 10; i++)
• { if (i == 4)
• { continue; }
• System.out.println(i); }
Use break and continue in while loops:
• Break Example
• int i = 0;
• while (i < 10)
• { System.out.println(i);
• i++;
• if (i == 4)
• { break; } }
• Continue Example
• int i = 0;
• while (i < 10)
• { if (i == 4)
• { i++; continue; }
• System.out.println(i); i++;
• }
jumping statements
• The jumping statements are the control statements which transfer the program
execution control to a specific statements.
• Java has three types of jumping statements they are break, continue, and return.
• These statements transfer execution control to another part of the program.
• Jump statements cause an unconditional jump to another statement elsewhere in the
code.
• They are used primarily to interrupt switch statements and loops.
The jump statements are the,
• the continue statement,




• the break statement
• goto statement and •
the return statement.
Goto statements java does not support goto, it is reserved as a keyword just in case they
wanted to add it to a later version.
Unlike C/C++, Java does not have goto statement, but java supports label.
The only place where a label is useful in Java is right before nested loop statements

The labeled break statement


• To use the break statement with a label.
• The break statement is used when we want to transfer the flow of control from an inner
loop to an outer loop, but when we want the flow of control to exit the outer loop then
we use a labeled break statement.
• A labeled break statement is somehow similar to the goto statement.
Example
• package myclass1;
• class Myclass1
• {
• public static void main (String args[])
• {
• boolean a=true;
• m:
• { • n:
• { • o:
• {
• System.out.println("Before break");
• if(a)
• break n;
• System.out.println("This will not execute");
• }
• }
• System.out.println("After break");
• }
• }
• }
The return statement
• The return statement is the last jump statement.
• The return statement is used to end the execution of a specific method and then return a
value.
• When we use a return statement in our program then it sends the program control to the
method caller.


• The data type of the returned value should always be equal to the data type of the
method's declared return value.

• Syntax
• if(condition)
• {
• return;
• }
package myclass1; class
Myclass1
• {
• public static void main(String[] args)
• {
• yahoo(true);
• System.out.println("hi");
• }
• public static void yahoo(boolean a)
• {
• System.out.println("1");
• if (a)
• {
• return;
• }
• System.out.println("2");
• System.out.println("3");
• }
• }

You might also like