2
Outline
A simpleJava Program
Java Program Development Environment
Primitive Data Types
Variables
Constants
Assignments
Initializations
Operators
Strings
Control Flow
Arrays
Methods
3.
3
2.1 Building Blocksof Java Program
The building blocks of a Java program are the essential components that form the
structure of any Java application.
Here are the primary building blocks:
1. Class
A class is a blueprint for creating objects in Java.
It contains methods and variables that define the behavior and state of objects.
Example:
public class MyClass {
// class body
}
4.
4
2.1 Building Blocksof Java Program-----
2. Main Method
The main method is the entry point for any standalone Java application.
When you run the program, the Java Virtual Machine (JVM) looks for the main
method to begin execution.
public static void main(String[] args) {
// code
}
3. Variables
Variables are used to store data that can be used throughout the program.
They have a specific data type, such as int, double, String, etc.
5.
5
2.1 Building Blocksof Java Program-----
Example:
int number = 5;
String message = "Hello, World!";
4. Methods
Methods define the behavior of a class.
They can perform operations, return values, or modify the state of objects.
Example:
public void displayMessage() {
System.out.println("Hello, Java!");
}
6.
6
2.1 Building Blocksof Java Program-----
5. Objects
An object is an instance of a class.
It encapsulates the state and behavior defined by the class
Example:
MyClass myObject = new MyClass();
6. Statements
Statements are individual instructions that perform a specific task.
These include assignments, method calls, loops, conditionals, etc.
Example:
int x = 10;
x = x + 5;
7.
7
2.1 Building Blocksof Java Program-----
7. Control Flow Statements
Control flow statements are used to control the flow of
execution based on conditions or loops, like
if, else, switch, for, while, etc.
Example:
if (x > 5) {
System.out.println("x is greater than 5");
}
else {
System.out.println("x is less than 5");
}
8.
8
2.1 Building Blocksof Java Program-----
8. Comments
Comments are nonexecutable lines that explain code, which helps developers und
erstand the program.
Single-line comment: // This is a single-line comment
Multi-line comment:
/*
This is a
multi-line comment
*/
9.
9
2.1 Building Blocksof Java Program-----
9. Import Statements
Import statements are used to bring in classes and libraries that are needed in the
program.
Example:
import java.util.Scanner;
10. Packages
A package is a namespace used to organize classes and interfaces in a structured
manner.
Example:
package com.mycompany;
10.
2.2 Example ofJava Program
//This is a simple Java program. Call this
class Welcome {
// Your program begins with a call to main() method
public static void main(String args[]) {
System.out.println(“Welcome to Java Programming");
}//End of main ()
}//End of class
1. Define a class
class Welcome {
This line uses the keyword class to declare that a new class is being defined.
10
11.
11
2.2 Example ofJava Program-----
Welcome is an identifier that is the name of the class.
The entire class definition, including all of its members, will be between the
opening curly brace ({) and the closing curly brace (}).
2) Main Method
public static void main(String args[]) {
This line begins the main( ) method.
This is the line at which the program will begin execution.
All Java applications begin execution by calling main( ) method.
This is just like C/C++.
12.
12
2.2 Example ofJava Program-----
2.1) The public keyword
is an access modifier allows the programmer to control the visibility of class members.
When a class member is preceded by public, then that member may be accessed by
code outside the class in which it is declared.
In Java, main( ) must be declared as public, since it must be called by code outside of
its class when the program is started to execute.
2.2) The keyword static
Allows main( ) to be called without having to instantiate(create object) a particular
instance of the class.
13.
13
2.2 Example ofJava Program-----
This is necessary since main( ) is called by the Java interpreter before any objects are
made.
2.3) The keyword void simply tells the compiler that main( ) does not return a value.
2.4) main( )
is the method called when a Java application begins.
Keep in mind that Java is case-sensitive. Thus, Main is different from main.
The Java compiler will compile classes that do not contain a main( ) method.
But the Java interpreter has no way to run these classes.
So, if you had typed Main instead of main, the compiler would still compile your program.
However, the Java interpreter would report an error because it would be unable to find the
main( ) method.
14.
14
2.2 Example ofJava Program-----
2.5 String args []
Java main method accepts a single argument of type String array. This is also called
as java command line arguments
String args[], which is actually an array of java.lang.String type, and it's name is args
here.
It's not necessary to name it args always, you can name it strArray or whatever you like,
but most programmer prefer to name it args, because that's what everyone else do.
When we run a Java program from command prompt, we can pass some input to our
Java program.
Those inputs are stored in this String args array.
15.
15
2.2 Example ofJava Program-----
2.6) The last character on the line is the {.
This signals the start of main( )'s body of Java Program.
All Java code that comprises a method will occur between the opening curly[ { ] brace and
its closing[ } ] curly brace.
One other point in Java Program main( ) is simply a starting place for the interpreter.
A complex program will have dozens of classes, only one of which will need to have a
main( ) method to get things started.
3) Body of the main() Method
System.out.println(“Welcome to Java Programming");
This line allows to outputs the string “Welcome to Java Programming" followed by a new
line on the screen.
16.
16
2.2 Example ofJava Program-----
3.1 The keyword System
System is a predefined class that provides access to the system. System class contains
several useful class fields (variables) and methods and it cannot be instantiated
System class provides different facilities such as:
Standard input, standard output, and error output streams;
Access to externally defined properties and environment variables;
Loading files and libraries;
Provides utility method for quickly copying a portion of an array
3.2 out Keyword
out is "standard" output stream that is connected to the console.
17.
17
2.2 Example ofJava Program-----
This stream is already open and ready to accept output data.
3.3 println( ) method
The method println prints the text on the screen with a new line.
Output in Java is actually accomplished by the built-in println( ) method
This println() method displays the string on the console which is passed to it when the
method is called.
println( ) statement ends with a semicolon. All statements in Java end with a semicolon.
The reason that the other lines in the program do not end in a semicolon is that they are not,
technically, statements.
4. Two Ending [ } }] curly Braces
The first } in the program ends main( ) method
18.
2.3 Java ProgramDevelopment Environment
Java programs normally go through five phases:
Edit (Creating a Program)
Compile
Load
Verify
Execute
We discuss these phases in the context of the JDK 7.1 from SunMicrosystems (currently
owned by Oracle), Inc.,
You can download the most up-to-date JDK and its documentation from:
java.sun.com/javase/8.1/download.jsp. 18
21
Java Data Types
1.Simple Data Types
Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
1) Integers
This includes byte, short, int, and long, which are for whole-valued signed numbers only.
2) Floating-point numbers:
This includes float and double, which represent numbers with fractional precision.
3) Characters
This includes char, represents symbols in a character set, like letters and numbers.
4) Boolean
is a special data type used for representing true/false values.
22.
22
Java Data Typescontinued
1. Integers
Java defines four integer types: byte, short, int, and long.
All of these are signed positive and negative values.
Java does not support unsigned, positive-only integers.
But C/C++, support both signed and unsigned integers.
The width of an integer type should not be thought of as the amount of storage it
consumes, but rather as the behavior it defines for variables and expressions of that
type.
The Java run-time environment is free to use whatever size it wants, as long as the
types behave as you declared them.
23.
23
Java Data Typescontinued
In fact, at least one implementation stores bytes and shorts as 32-bit (rather than
8- and 16-bit) values to improve performance, because that is the word size of
most computers currently in use.
The width and ranges of these integer types vary widely, as shown in this table:
24.
24
Java Data Typescontinued
A. byte
is the smallest integer type.
is a signed 8-bit type that has a range from –128 to 127.
Variables of type byte are especially useful, when you're working with:
a stream of data from a network or file.
raw binary data that may not be directly compatible with Java's other built-
in types.
Byte variables are declared by use of the byte keyword.
For example, the following declares two byte variables called b and c:
byte b, c;
25.
25
Java Data Typescontinued
B. short
is a signed 16-bit type. It has a range from –32,768 to 32,767.
It is probably the least-used Java type, since it is defined as having its high byte first
(called big-endian format).
Here are some examples of short variable declarations:
short s;
short t;
Note :-"Endianness" describes how multi byte data types, such as short, int, and
long, are stored in memory.
26.
26
Java Data Typescontinued
If it takes 2 bytes to represent a short, then which one comes first, the most
significant or the least significant?
To say that a machine is big-endian, means that the most significant byte is first,
followed by the least significant one.
Machines such as the SPARC and PowerPC are big-endian, while the Intel x86
series is little-endian.
C. int
is the most commonly used integer type.
is a signed 32-bit type that has a range from –2,147,483,648 to 2,147,483,647.
is the most versatile and efficient type.
27.
27
Java Data Typescontinued
int type is mainly used to create a number for counting or indexing arrays or doing
integer math and to control loops.
It may seem that using short or byte will save space, but there is no guarantee that
Java won't promote those types to int internally anyway.
Remember, type determines behavior, not size.
The only exception is arrays, where byte is guaranteed to use only one byte per
array element, short will use two bytes, and int will use four.
D. long
is a signed 64-bit type or 8 byte.
is useful for those occasions where an int type is not large enough to hold the desired
value.
28.
28
Java Data Typescontinued
The range of a long is quite large.
This makes it useful when big, whole numbers are needed.
2. Floating Point
are also known as real numbers,
are used when evaluating expressions that require fractional precision.
For example, calculations such as square root, or transcendental such as sine and
cosine, result in a value whose precision requires a floating-point type.
Java implements the standard (IEEE–754) set of floating-point types and operators.
There are two kinds of floating-point types, float and double, which represent single-
and double-precision numbers, respectively.
29.
29
Java Data Typescontinued
Their width and ranges are shown here:
A. Float
specifies a single-precision value that uses 32 bits of storage.
Single precision is faster on some processors and takes half as much space as
double precision, but will become imprecise when the values are either very large or
very small.
30.
30
Java Data Typescontinued
useful when you need fractional component, but don't require large degree of precision.
For example, float can be useful when representing dollars and cents.
Here are some example float variable declarations:
float hightemp, lowtemp;
B. double
Uses 64 bits to store a value.
double precision is faster than single precision on some modern processors that have been
optimized for high-speed mathematical calculations.
All transcendental math functions, such as sin( ), cos( ), and sqrt( ), return double values.
It best data type when you need to maintain:
Accuracy over many iterative calculations, or
Manipulating large-valued numbers
31.
31
Activity
1. Write separateJava program to demonstrate short, byte, int and long
respectively.
2. Use float data type and write separate Java program to calculate area
of triangle and a program to exchange dollars to Ethiopian birr
respectively. Use 1 dollar is exchanged by 56.65 birr currently.
3. Use double data type and write separate Java Program to calculate
area of a circle and a program to calculate the square root of any
double number.
32.
32
Java Data Typescontinued
3. char
is used to store characters
However, C/C++ programmers beware: char in Java is not the same as char in C or C++.
In C/C++, char is an integer type that is 8 bits wide. This is not the case in Java.
Instead, Java uses Unicode to represent characters.
Unicode defines a fully international character set that can represent all of the characters
found in all human languages.
It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic,
Hebrew, Katakana, Hangul, and many more.
For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type.
The range of a char is 0 to 65,536. There are no negative chars.
33.
33
Java Data Typescontinued
The standard set of characters known as ASCII still ranges from 0 to 127 as always,
and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255.
Since Java is designed to allow applets to be written for worldwide use, it makes
sense that it would use Unicode to represent characters.
Of course, the use of Unicode is somewhat inefficient for languages such as English,
German, Spanish, or French, whose characters can easily be contained within 8
bits.
But such is the price that must be paid for global portability.
Example: Write Java program that demonstrates char variables
// Demonstrate char data type.
class CharDemo {
34.
34
Java Data Typescontinued
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // ASCII and Unicode code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
corresponds to the letter X.
The ASCII character set occupies the first 127 values in the Unicode character set.
This program displays the following
output:
ch1 and ch2: X Y
35.
35
Java Data Typescontinued
Though chars are not integers, in many cases you can operate on them as if they were
integers.
This allows to add two characters together, or to increment the value of a character variable.
For example, consider the following program:
// char variables behave like integers.
class CharDemo2 {
public static void main(String args[]) {
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
The output generated by this program is
ch1 contains X
ch1 is now Y
In the program, ch1 is first given the value
X. Next, ch1 is incremented.
This results in ch1 containing Y, the next
character in the ASCII (and Unicode)
sequence.
36.
36
Java Data Typescontinued
public static void main(String args[]) {
char ch1, ch2;
ch1 = 88; // ASCII and Unicode code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
corresponds to the letter X.
The ASCII character set occupies the first 127 values in the Unicode character set.
This program displays the following
output:
ch1 and ch2: X Y
37.
37
Java Data Typescontinued
4. boolean
Java has a simple type, called boolean, for logical values.
It can have only one of two possible values, true or false. This is the type returned by all
relational operators, such as a < b.
boolean is also the type required by the conditional expressions that govern the control
statements such as if and for.
Here is a program that demonstrates the boolean type:
class BoolTest {
public static void main(String args[]) {
//Declaration boolean data type
boolean b;
38.
38
Java Data Typescontinued
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) {
System.out.println("This is executed.");
}
b = false;
if(b){
System.out.println("This is not executed.");
}
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
39.
39
Java Data Typescontinued
System.out.println("5> 9 is " + (5 > 9));
}
}
There are three interesting things to notice about this program.
First, as you can see, when a boolean value is output by println( ), "true" or "false" is
displayed.
Second, the value of a boolean variable is sufficient, by itself, to control the if statement.
There is no need to write an if statement like this: if(b = = true) ...
Third, the outcome of a relational operator, such as <, is a boolean value.
This is why the expression 10 > 9 displays the value "true."
Further, the extra set of parentheses around 10 > 9 is necessary because the + operator has a
40.
40
Integer Literals
Floating-Point Literals
Boolean Literals
Character Literals
String Literals
R
E
A
D
I
N
G
A
S
S
I
G
N
M
E
N
T
41.
Reading Input fromthe Console
Reading input from the console enables the program to accept input from the user.
In the following java program, the radius is fixed in the source code.
To use a different radius, you have to modify the source code and recompile it.
Obviously, this is not convenient, so instead you can use the Scanner class for console
input.
Java uses System.out to refer to the standard output device and System.in to the
standard input device.
By default, the output device is the display monitor and the input device is the keyboard.
To perform console output, you simply use the println method to display a primitive
value or a string to the console.
41
42.
42
Reading Input fromthe Console contnued
Console input is not directly supported in Java, but you can use the Scanner class to
create an object to read input from System.in, as follows:
Scanner input = new Scanner(System.in);
Example :Write java program to read input from the console and to display area of a
circle as an output. Suppose the program is used to calculate area of a circle:
import java.util.Scanner; //Scanner is a java.util package
public class NumScanner {
public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);
// Prompt the user to enter the value of radius
43.
43
Reading Input fromthe Console contnued
System.out.print("Enter any number for radius:");
//Declaration of variables()
double radius;
//Call nextDouble() to read a double value from the keyboard
radius= input.nextDouble();
//Declaration of variables
double area;
// Compute area of a circle
area = (radius*radius)* 3.14159;
System.out.println("Area of a circle="+ area);
}
44.
44
Reading Input fromthe Console contnued
The syntax new Scanner(System.in) creates an object of the Scanner type.
The syntax Scanner input declares that input is a variable whose type is Scanner.
The whole line
Scanner input=new Scanner(System.in) creates a Scanner object and assigns its
reference to the variable input.
The line System.out.print("Enter any number for radius:"); displays the string
"Enter a number for radius: " to the console.
This is known as a prompt, because it directs the user to enter an input.
An object may invoke its methods.
To invoke a method on an object is to ask the object to perform a task.
45.
45
Reading Input fromthe Console contnued
You can invoke the nextDouble() method to read a double value as follows:
double radius = input.nextDouble();
This statement reads a number from the keyboard and assigns the number to
radius.
Scanner class is in the java.util package.
It is imported and placed before class definition.
There are two types of import statements: specific import and wildcard import.
The specific import specifies a single class in the import statement.
For example, the following statement imports Scanner class from the package
java.util.
import java.util.Scanner;
46.
46
Reading Input fromthe Console contnued
The wildcard import imports all the classes in a package by using the asterisk as the
wildcard.
For example, the following statement imports all the classes from the package java.util.
import java.uitl.*;
The information for the classes in an imported package is not read in at compile time or
runtime unless the class is used in the program.
The import statement simply tells the compiler where to locate the classes.
There is no performance difference between a specific import and a wildcard import
declaration.
Example 2:Write Java program to read multiple input of three numbers and display their
average:
47.
47
Reading Input fromthe Console contnued
// Import Scanner class from the java.util package
import java.util.Scanner;
public class ComputeAverage {
public static void main(String[] args) {
// Create a Scanner object
Scanner input = new Scanner(System.in);
//Prompt the user to enter the values of three numbers
System.out.print("Enter three numbers: ");
//Read the values of three Numbers and assign the values to its separate variables
double number1 = input.nextDouble();
double number2 = input.nextDouble();
48.
48
Reading Input fromthe Console contnued
double number3 = input.nextDouble();
// Compute average of three numbers
double average;
average=(number1 + number2 + number3) / 3;
// Display the results
System.out.println("Average of three Numbers=" + average);
}
}
49.
49
Methods for ScannerObjects
You know how to use the nextDouble() method in the Scanner class to read a double
value from the keyboard
The following are methods for scanner object to read a number of the byte, short, int,
long, and float and double type.
50.
50
Activity
1. Write JavaProgram to read a number of the byte, short, int, long, and float type by
calling methods useful for each data types respectively:
2. Use Scanner class and if------else if statement and write Java program to accept
marks as an input from the user and output letter Grade. Use the following input
output information for this question:
Input Output
(marks>90) and(marks<=100)------------------------A
(marks>=80) and(marks<=90)------------------------B
(marks>=50) and(marks<80)--------------------------C
(marks>=40) and(marks<50)--------------------------D
(marks>=20) and(marks<40)--------------------------F
else--------------------------------------------------------I
51.
51
Variables
In Java, variablesare containers that hold data values.
Each variable has a data type, a name, and may have an initial value.
Java is a strongly-typed language, meaning you must declare a variable
with a specific type before using it.
In addition, all variables have a scope, which defines their visibility,
and a lifetime.
52.
52
Variable Declaration inJava
Syntax
<data_type> <variable_name> = <value>;
Explanation
1. data_type
Specifies the type of data the variable will hold (e.g., int, double, String, etc.).
2.variable_name
The identifier or name assigned to the variable. Follows Java naming conventions.
3. = (assignment operator)
Assigns a value to the variable.
4.value
The initial value of the variable (optional for instance/
53.
53
Examples
// Primitive datatypes
int age = 25;
double pi = 3.14;
char grade = 'A';
boolean isActive = true;
// Reference data types
String name = "Alice";
int[] numbers = {1, 2, 3, 4, 5};
// Declaration without initialization
int score; // Allowed, but must be initialized before use
score = 100; // Now assigned a value
// Constant declaration
final double GRAVITY = 9.81; // 'final' makes it immutable
54.
54
Multiple Variable Declaration
Youcan declare multiple variables of the same type in one line:
int a = 10, b = 20, c = 30;
Variable Naming Rules
Must start with a letter, _, or $.
Cannot start with a digit.
No special characters allowed (except _ and $).
Java keywords (like class, int, etc.) cannot be used as variable names.
Follow camelCase for variable names (e.g., studentScore).
55.
55
Types of Variablesin Java
Java has three main types of variables:
1.Local Variables
2.Instance Variables (Non-static)
3.Static Variables (Class Variables)
56.
56
Types of Variablesin Java----
1. Local Variables
Declared inside methods, constructors, or blocks.
Only accessible within the method or block where they are declared.
Must be initialized before use.
Example:
public class Example {
void display() {
int x = 10; // Local variable
System.out.println("Value of x: " + x);
}
}
57.
57
Types of Variablesin Java----
2. Instance Variables
Declared inside a class but outside of any method or constructor.
Each object of the class has its own copy of the variable.
Default values are assigned (e.g., 0 for integers, null for objects).
Example:
class Person {
String name; // Instance variable
int age; // Instance variable
}
58.
58
Types of Variablesin Java----
3. Static Variables
Declared with the static keyword inside a class.
Shared among all objects of the class (only one copy in memory).
Can be accessed directly using the class name.
Example:
class Counter {
static int count = 0; // Static variable
Counter() {
count++;
}
void displayCount() {
System.out.println("Count: " + count);
}
}
59.
59
Lifetime of Variables
Thelifetime of a variable refers to how long the variable exists in memory.
Lifetime Rules
1. Local Variables:
Exist only while the method or block runs.
2. Instance Variables:
Exist as long as the object exists.
3. Static Variables:
Exist for the program's entire runtime.
60.
60
Example Combining Scopeand Lifetime
class VariableDemo {
static int staticVar=50; //Static variable (Class-level)
int instanceVar = 30;// Instance variable (Object-level)
void M1() {
int localVar = 10; // Local variable (Method-level)
System.out.println("Local Variable: " + localVar);
System.out.println("Instance Variable: " + instanceVar);
System.out.println("Static Variable: " + staticVar);
}//End of M1()
public static void main(String[] args) {
VariableDemo obj = new VariableDemo();
obj.M1();
}//End of main ()
}//End of class
61.
61
String in Java
In Java, a String is an object that represents a sequence of characters.
Strings are widely used in Java programming and are part of the java.lang
package.
They are immutable, meaning their values cannot be changed once created.
Creating a String
You can create a string in two main ways:
1.Using String Literal
String str1 = "Hello, World!";
2. Using the new keyword
String str2 = new String("Hello, World!");
63
String Example
//Simple JavaString Progra
//Define a class
class StringExample {
//main method ()
public static void main(String[] args) {
//Creating Strings
String str1="Hello";
String name="John";
64.
64
String Example----
String str2=greeting+ ", "+name+"!";
System.out.println("Greeting: "+str2);
//String Length
System.out.println("Length of Greeting:"+str2.length());
//Upper and Lower Case
System.out.println("Uppercase:"+str2.toUpperCase());
System.out.println("Lowercase:"+str2.toLowerCase());
//Character at a specific position
66
Arrays in Java
An array in Java is a data structure that stores multiple elements of the same
data type in a contiguous block of memory.
Arrays are useful when you need to manage and manipulate collections of data
efficiently.
Key Features of Java Arrays
1.Fixed Size: The size of an array is defined when it is created and cannot be changed.
2.Index-Based: Array elements are accessed using zero-based indexing (first element
at index 0).
3.Homogeneous Elements: All elements in the array must be of the same data type.
4.Stored in Continuous Memory Locations: Provides fast access to elements.
67.
67
1. Single orOne-dimensional Array
A single-dimensional array is the most basic form of an array,
storing elements in a linear structure.
Syntax:
/ /Declaration
dataType[] arrayName; // Preferred syntax
dataType arrayName[]; // Valid but less common (legacy C-style)
// Initialization
arrayName = new dataType[size];
// Declaration and Initialization in one step
dataType[] arrayName = new dataType[size];
// Declaration with Initial Values
dataType[] arrayName = {value1, value2, value3, ...};
68.
68
Example
//Write Java Programto demonstrate one-dimensional array
//Define a class
class SingleDimArray {
//main method()
public static void main(String[] args) {
//Declaration of array size of 4 with some initial value
int[] numbers={10, 20, 30, 40};
//for ---loop
for (int num=0;num<4;num++) {
System.out.print(numbers[num]+" ");
} //End of for---loop
} //End of main ()
}//End of class
69.
69
Accessing Elements of1D Arrays
In Java, elements in a one-dimensional array are accessed using their
index.
Array indexing in Java starts at 0 and goes up to array.length - 1.
Syntax for Accessing Elements
arrayName[index];
arrayName → Name of the array.
index → Position of the element you want to access (starts from 0).
70.
70
Example: Accessing Elementsin an Array
//Write Java program to demonstrate accessing elements in the array
class ArrayAccessExample {
public static void main(String[] args) {
// Declaration and Initialization
int[] numbers = {10, 20, 30, 40, 50};
// Accessing individual elements
System.out.println("First element: " + numbers[0]); // Output: 10
System.out.println("First element: " + numbers[1]); // Output: 20
System.out.println("Third element: " + numbers[2]); // Output: 30
System.out.println("First element: " + numbers[3]); // Output: 40
System.out.println("Last element: " + numbers[numbers.length - 1]); // Output: 50
}
}
71.
71
Traversing a One-DimensionalArray
To access all elements in an array, you can use:
1. for Loop (Index-Based)
Best suited when you need the index or want to modify the array.
//Define a class
class ForLoopExample {
//Main method
public static void main(String[] args){
72.
72
Traversing a One-DimensionalArray
//Declaration of Arrays with 4 elements
int numbers[]={5,10,15,20}; //int[]numbers={5,10,15,20};
for(int i=0;i<numbers.length;i++) {
System.out.println("Element at index"+i+":"+numbers[i]);
}//End of for loop()
}//End of main ()
}//End of class
73.
73
Traversing a One-DimensionalArray---
2. Enhanced for Loop (For-Each Loop)
Best for reading values but cannot modify the array directly.
The enhanced for loop (also called the for-each loop) is a simpler and
more readable way to iterate over arrays and other collections in Java.
Syntax of the Enhanced for Loop
for (dataType variableName : arrayName) {
// Code to process the variable
}
dataType: The type of elements in the array (e.g., int, String, etc.).
variableName: A variable that temporarily holds each element of the array during the
iteration.
arrayName: The array (or collection) to iterate over.
74.
74
Traversing a One-DimensionalArray---
Example: Write Java Program to demonstrate accessing arrays through enhanced for---loop
//Define a class
class ForEachExample {
public static void main(String[] args){
//Declare Arrays with 5 elements
int[]numbers={1,2,3,4,5};
//For ---loop
for (int num : numbers) {
System.out.print(num+" ");
}//End of for loop
}//End of main ()
}//End of class
75.
75
Traversing a One-DimensionalArray---
3. Using Arrays.toString() (Quick Display)
This method is ideal for debugging or quick display of array contents.
//import Array class from java.util package
import java.util.Arrays;
//Define a class
class ToStringExample{
//Main method
public static void main(String[] args){
//Declare int type array of 4 elements
int[] numbers={10,20,30,40};
76.
76
Traversing a One-DimensionalArray---
// Output by calling toString(array name):
//Output as follows [10, 20, 30, 40]
System.out.print(Arrays.toString(numbers)+" ");
}//End of main ()
}//End of class
77.
77
2. Multidimensional Array
An array of arrays, where elements are stored in a matrix-like structure.
Each element is accessed using multiple indices.
The most common type is a 2D array, often used to represent matrices or grids.
Syntax for Multidimensional Arrays
// Declaration
dataType[][] arrayName; // Preferred
dataType arrayName[][]; // Valid but less common
// Initialization
arrayName = new dataType[rows][columns];
78.
78
2. Multidimensional Array-----
//Declaration and Initialization in one step
dataType[][] arrayName = new dataType[3][3]; // 3x3 matrix
// Array with predefined values
int[][] matrix ={
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
79.
79
Example of a2D Array (Matrix)
//Define a class
class MatrixExample {
//Main method
public static void main(String[] args) {
// Declaration 2D arrays of (3 by 3) and Initialization
int[][] matrix={{1,2,3},{4,5,6},{7,8,9}};
// Accessing elements
System.out.println("Element at row 2, column 3:"+matrix[1][2]); // Output: 6
80.
80
Example of a2D Array (Matrix)-----
// Traversing the 2D Array
System.out.println("Matrix Elements:");
for (int i=0;i<matrix.length; i++) {
for (int j=0;j<matrix.length; j++){
System.out.print(matrix[i][j] + " ");
}//End of inner for() loop
System.out.println();
}//End of outer for() loop
}//End of main ()
}//End of class
81.
81
3. Example ofa 3D Array (3D Matrix)
Syntax: dataType[][][] arrayName = new dataType[depth][rows][columns];
class ThreeDArray {
//main method ()
public static void main(String[] args) {
//3D Array Declaration and Initialization
int[][][] cube={
{{1,2},{3,4}},
{{5,6},{7,8}},
{{9,10},{11,12}}
};
82.
82
3. Example ofa 3D Array (3D Matrix)----
// Accessing elements
System.out.println("Element at [2][1][1]:"+cube[2][1][1]); // Output: 12
// Traversing the 3D Array
System.out.println("3D Array Elements:");
for (int i=0;i<cube.length; i++){
for (int j=0;j<cube[i].length; j++) {
for (int k=0;k<cube[i][j].length; k++) {
System.out.print(cube[i][j][k] + " ");
}//End of the third loop()
System.out.println();
}//End of inner for loop
83.
83
3. Example ofa 3D Array (3D Matrix)----
System.out.println();
}//End of outer for() loop
}//End of main ()
}//End of class()
84.
84
3. Jagged Array(Irregular Array)
A jagged array is a special type of multidimensional array
where each row can have a
different number of columns.
It is useful when dealing with irregular data structures.
// Declaration
dataType[][] arrayName = new dataType[rows][];
// Initialization
arrayName[0] = new dataType[size1];
arrayName[1] = new dataType[size2];
arrayName[2] = new dataType[size3];
85.
85
3. Jagged Array(Irregular Array) Example
class JaggedArrayExample {
public static void main(String[] args) {
//Declaration and Initialization
int[][] jagged = new int[3][];
jagged[0] = new int[]{1, 2}; // Row 1 with 2 elements
jagged[1] = new int[]{3, 4, 5};// Row 2 with 3 elements
jagged[2] = new int[]{6}; // Row 3 with 1 element
// Displaying the Jagged Array
for (int i=0;i<jagged.length; i++) {
for (int j=0;j<jagged[i].length;j++) {
86.
86
3. Jagged Array(Irregular Array) Example---
System.out.print(jagged[i][j] + " ");
}//End of inner() for loop
System.out.println();
}//End of outer for() loop
}//End of main ()
}//End of class
87.
87
4. Array ofObjects
Java allows arrays to store objects, which is helpful for managing collections of custom data
types.
1. Write java program to demonstrate arrays to store objects that helps for managing collections
of custom data types.
//Define a class
class Student {
//Declaration of instance variable of a class
String name;
int age;
//Define Constructor
Student(String name, int age){
88.
88
4. Array ofObjects----
this.age=age;
}//End of constructor
}//End of class
//Define another class
class ObjectArray{
//main method
public static void main(String[] args){
//Declare and create object array
Student[] students={
new Student("Alice", 20),
new Student("Bob", 22)
89.
89
4. Array ofObjects----
for (Student s :students){
System.out.println(s.name + " - " + s.age);
}//End of for loop
}//End of main ()
}//End of class
90.
90
Using Scanner: One-dimensionalArray
Write Java program to demonstrate one-dimensional array using Scanner
based on the following additional information
1. Read the array length as scan.nextInt() and store it in the variable
arrayLength and declare anArray int[arrayLength].
2. To store elements in to the array for i=0 to i<arrayLength of an array read
the element using scan.nextInt() and store the element at the index
anArray[i].
3. Display the elements of an array for loop iterates from i=0 to
i<arrayLength of an array print the array element anArray[i].
91.
91
Using Scanner: One-dimensionalArray-------
/* Java program to demonstrate 1D array using scanner */
//Import Scanner class from java.util package
import java.util.Scanner;
//Define a class
class OneDimensionalArrayScanner {
public static void main(String args[]){
//Create Scanner Object
Scanner scan=new Scanner(System.in);
//Users prompt to input the length of the array
System.out.println("Input the length of the Array: ");
92.
92
Using Scanner: One-dimensionalArray-------
//Declare int type variable named arrayLength
int arryLength;
//Call nextInt() to read int values and stores in arrayLength
arryLength=scan.nextInt();
//Declare and allocates memory for the length of the array you inputted
int []anArray=new int[arryLength];
//Users input the contents of the array
System.out.println("Input the Contents of the Array:");
//For loop to count the contents of the array inputted by the user
for(int i=0;i<arryLength;i++){
93.
93
Using Scanner: One-dimensionalArray-------
//Call nextInt() and stores the contents on the array variable
anArray[i]=scan.nextInt();
}//End of for loop
// Printing the contents of One Dimensional Array
System.out.println("Displaying the Contents of 1D Array:");
for(int i=0;i<arryLength;i++){
System.out.print(anArray[i]+" ");
}//End of for loop
System.out.println();
}//End of main ()
}//End of class
94.
94
Using String: One-dimensionalArray
1. We declared one-dimensional string array with three elements strings.
2. To print strings from the string array. for i=0 to i<strArray of the string print string
which is at the index strArray[i].
/* Java program to demonstrate 1D array using String method and the program determine
the length of the string array */
class OneDimensionalArrayString {
public static void main(String args[]){
//Declaring and Initializing the String Array
String[] strArray={"Alive is Awesome","Be in Present","Be Yourself"};
System.out.println("The length of String Array is: "+strArray.length);
95.
95
Using String: One-dimensionalArray
//Printing the One Dimensional String Array
System.out.println("Displaying 1D String array elements:");
//for------loop to count the string of the array
for(int i=0;i<strArray.length;i++){
System.out.println(strArray[i]+ " ");
}//End of for-----loop
}//End of main ()
}//End of class
96.
96
2D Arrays usingScanner
1. Read the row length, column length of an array using sc.nextInt() method of Scanner
class.
2. Declare the array with the dimension row, column.
3. for i=0 to i<row for j=0 to j<column sc.nextInt() reads the entered number and insert the
element at a[i][j].
Example:
/*Java program to demonstrate two dimensional array using Scanner. The program accepts
values of elements of array from the user */
//import scanner class from the java util package
import java.util.Scanner;
//Define a class
97.
97
2D Arrays usingScanner
public class TwoDArrayExample {
//Main method ()
public static void main(String args[]){
//Declare 2D array of 3 by 3
int a[][]=new int[3][3];
//Create objects of scanner class
Scanner sc=new Scanner(System.in);
//Declare index variable named r and c
int r,c;
//User input 3 by 3 elements or 9 elements
98.
98
2D Arrays usingScanner
//Outer for loop to count rows
for(r=0; r<3; r++){
//Inner for loop to count columns
for(c=0; c<3; c++){
//Call nextInt() to read integer values
a[r][c]=sc.nextInt();
}//End of inner for loop
}//End of outer for loop
System.out.println("Values of the Array is as follows:");
// this loop is for row
99.
99
2D Arrays usingScanner
for(r=0; r<3; r++){
//this loop will print 3 numbers in each row
for(c=0; c<3; c++){
System.out.print(a[r][c]+" "+" ");
}//End of inner for loop
// break the line after printing the numbers in a row
System.out.println();
}//End of outer for loop
}//End of main ()
}//End of class
100.
100
2D Arrays usingString
/*Java program to demonstrate 2D arrays using String*/
class TwoDimensionalString {
public static void main(String[] args){
//Declare string array of size 3 by 2 with initial value
String[][] str=new String[][]{{"one","two"},{"three","four"},{"five","six"}};
System.out.println("2D string array elements are:");
//Outer for loop to count rows
for(int i = 0; i < 3; i++){
//Inner for loop to count columns
for (int j = 0; j < 2; j++){
101.
101
2D Arrays usingString------
//Output the string arrays
System.out.println("str["+i+"]["+j+"]:"+str[i][j]);
}//End of inner for loop
} //End of outer for loop
}//End of main ()
}//End of class
103
Operators in Java
In Java, operators are special symbols that perform specific operations on variables and
values.
They are essential for performing arithmetic, comparisons, logic, and other tasks.
Java provides several types of operators:
1. Arithmetic Operators
Used for basic mathematical operations.
104.
104
Example
//Define a class
classArithmeticExample{
//main method
public static void main(String[] args){
//Declaration of variables with some initial value
int a=10,b=5;
//Output
System.out.println("Addition:"+(a+b)); //15
System.out.println("Subtraction:"+(a-b));//5
System.out.println("Multiplication:"+(a*b));//50
System.out.println("Division:"+(a/b));//2
System.out.println("Modulus:"+(a% b));//0
}//End of main ()
}//End of class
112
Example
//Define a class
classAssignmentExample {
public static void main(String[] args) {
int a=10;
a+=5; // Same as a = a + 5;
System.out.println("a += 5 : " + a); // 15
a *=2; // Same as a = a * 2;
System.out.println("a *= 2 : " + a); // 30
}
}
113.
113
6. Unary Operators
Operate on a single operand.
Used to increment, decrement, or change signs.
114.
114
Example
//Define a class
classUnaryExample {
public static void main(String[] args) {
int a=5;
System.out.println("a++ : " + (a++)); // 5 (Post-increment)
System.out.println("++a : " + (++a)); // 7 (Pre-increment)
System.out.println("a-- : " + (a--)); // 7 (Post-decrement)
System.out.println("--a : " + (--a)); // 5 (Pre-decrement)
}
}
115.
115
7. Ternary Operator
A shorthand for if-else conditions.
Syntax:
condition ? trueResult : falseResult;
Example:
int result = (a > b) ? a : b;
116.
116
8. Special Operators
Used to test whether an object is an instance of a particular class or subclass.
Useful in inheritance and type-checking.
new — Used to create new objects.
this — Refers to the current object instance.
super — Refers to the immediate parent class object.
class Animal {}
class Dog extends Animal {
}
public class InstanceofExample {
public static void main(String[] args) {
Dog dog = new Dog();
118
9. Increment (++)and Decrement (--) Operators in Java
In Java, the increment (++) and decrement (--) operators are unary
operators that increase or decrease a variable’s value by 1.
1. Increment Operator (++)
The increment operator is used to increase the value of a variable by 1.
Syntax
Pre-increment: ++variable (Increments the value before using it)
Post-increment: variable++ (Increments the value after using it)
119.
119
Examples of Incrementoperator
public class IncrementExample {
public static void main(String[] args) {
int a = 5;
// Pre-increment
int preResult = ++a; // a = 6, preResult = 6
System.out.println("Pre-increment result: " + preResult);
System.out.println("Value of a after pre-increment: " + a);
// Post-increment
int postResult = a++; // postResult = 6, a = 7
System.out.println("Post-increment result: " + postResult);
System.out.println("Value of a after post-increment: " + a);
}
}
120.
120
2. Decrement Operator(--)
The decrement operator is used to decrease the value of a variable by 1.
Syntax
Pre-decrement: --variable (Decrements the value before using it)
Post-decrement: variable-- (Decrements the value after using it)
Example: Decrement Operator
public class DecrementExample {
public static void main(String[] args) {
int b = 5;
// Pre-decrement
int preResult = --b; // b = 4, preResult = 4
System.out.println("Pre-decrement result: " + preResult);
System.out.println("Value of b after pre-decrement: " + b);
121.
121
2. Decrement Operator(--)
The decrement operator is used to decrease the value of a variable by 1.
Syntax
Pre-decrement: --variable (Decrements the value before using it)
Post-decrement: variable-- (Decrements the value after using it)
Example: Decrement Operator
public class DecrementExample {
public static void main(String[] args) {
int b = 5;
// Pre-decrement
int preResult = --b; // b = 4, preResult = 4
System.out.println("Pre-decrement result: " + preResult);
System.out.println("Value of b after pre-decrement: " + b);
122.
122
2. Decrement Operator(--)
// Post-decrement
int postResult = b--; // postResult = 4, b = 3
System.out.println("Post-decrement result: " + postResult);
System.out.println("Value of b after post-decrement: " + b);
}
}
124
Control Structures
Normally, statementsin a program are executed one after the other in the order in
which they are written.
This process is called sequential execution.
Various Java statements, enable the programmer to specify that the next statement to
execute is not necessarily the next one in sequence.
This is called transfer of control.
A programming language uses control statements to cause the flow of execution to
advance and branch based on changes to the state of a program.
Java's program control statements can be put into the following categories: Sequence
Structure, Selection Structure and Repetition Structure.
125.
125
1. Java SequenceStructure
Executes Java statements one after the other in the order in which they are
written—that is, in sequence.
The following diagram illustrates a typical sequence structure in which two
calculations are performed in order.
126.
126
Example 1
class SequenceExample{
public static void main(String args[]) {
float num1, num2, num3;
num1=20;
num2=30;
num2=num2*10;
System.out.println("Num1 is "+ " "+num1 + " " +"and"+ " "+ "Num2 is"+ " "+num2);
num3=num1*num2;
System.out.println("Num 3 is"+" "+num3);
}
}
127.
127
Example 2
import javax.swing.JOptionPane;
classSequenceExample2 {
public static void main( String args[] ) {
String firstNumber, secondNumber;
int number1, number2, sum;
firstNumber=JOptionPane.showInputDialog("Enter the first Number");
secondNumber=JOptionPane.showInputDialog("Enterthesecond umber");
//========Convertthestringtwo Integer==========
number1=Integer.parseInt(firstNumber);
number2=Integer.parseInt(secondNumber);
sum = number1 + number2; // add numbers
JOptionPane.showMessageDialog(null,"The sum is "+ sum, "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE);
}
}
128.
128
Activity
1.Suppose that themonthly interest rate that the bank provides for the customer is
6%. Initial deposit of the customer is 4400, and interest is calculated at the end of
each month. Write Java program to calculate Interest Rate and Ending Balance of
the customers in the bank at the end of each month.
2. Write Java program for the following mathematical expression
A. s= – B) x=
C) z= + m*n D) F=(9/5 * C) +32
3. Write Java program to calculate Average of two numbers, area of rectangle and
volume of the Box. The program is expected to accept input from the users to
display the output.
129.
129
2. Selection Statementsin Java
1. if statement either performs (selects) an action, if a condition is true, or skips it, if the
condition is false.
The if statement is a single-selection statement because it selects or ignores a single action (or, a
single group of actions).
2. if…else statement performs an action if a condition is true and performs a different action if the
condition is false.
The if…else statement is called a double-selection statement because it selects between two
different actions (or groups of actions).
3. switch statement performs one of many different actions, depending on the value of an expression.
The switch statement is called a multiple-selection statement because it selects among many
different actions (or groups of actions).
130.
130
A. if-------statement
Eitherperforms (selects) an action, if a condition is true, or skips it, if the condition is false.
The if statement is a single-selection statement because it selects or ignores a single action (or,
a single group of actions).
Syntax:
if(expression) {
statement1;
}
Look at the following simple java program and the figure to illustrate single selection statement:
if ( studentGrade >= 60 ) {
System.out.println( "Passed" );
}
131.
131
A. if-------statement continued
If the grade is greater than or equal to 60, the program prints “Passed,” then transitions
to the final state of this activity.
If the grade is less than 60, the program immediately transitions to the final state
without displaying a message.
Look at the following Java program to perform the single selection statement.
132.
132
Example 1
class IfSelectionExample2{
public static void main(String args[])
{
int marks =60;
if(marks>=60)
{
System.out.println("Passed");
}
}
}
If the program is expected to accept input from the user the above program is
rewrite as follows:
133.
133
Example 2
import javax.swing.JOptionPane;
classIfSelectionExample {
public static void main(String args[]) {
String Grade;
int marks;
Grade=JOptionPane.showInputDialog("Enter Grade of the Student");
marks=Integer.parseInt(Grade);
if(marks >= 60) {
JOptionPane.showMessageDialog(null,"Passed", "Result of the Student
is",JOptionPane.PLAIN_MESSAGE);
}
} }
134.
134
2. if…else SelectionStatement
is a double-selection statement allows the programmer to specify an action to
perform when the condition is true and a different action when the condition is
false.
performs an indicated action only when the condition is true; otherwise, the action is
skipped.
Syntax:
if(expression) {
Statement1;
else{
Statement2;
}
First, the expression which must be of type boolean
or Boolean is evaluated.
If its value is true, then statement1 is executed;
otherwise, if there is an else clause, statement2 is
executed.
The else clause is optional.
135.
135
2. if…else SelectionStatement continued
You can build a series of tests by joining another if to the else clause of a previous if.
Look the following simple Java Code and its corresponding pictures to illustrate the if-else
selection statement :
if ( grade >= 60 ) {
System.out.println( "Passed" );
}
else{
System.out.println( "Failed" );
}
This indicates that print “Passed” if grade is grater or equal to 60 else print “Failed” if the grade
is less than 60.
Let’s see the following Example to print “Failed” since the variable mark is initialized to 30.
136.
136
Example 1
class IfElseExample{
public static void main(String args[]) {
int marks =30;
if(marks>=60) {
System.out.println("Passed");
}
else{
System.out.println("Failed");
}
}
}
Activity: Rewrite the above program assuming that the output is based on the input given from the user.
137.
137
Exercise
1. Write JavaProgram to identify either the number is “Positive’, or “Negative”
after accepting n number of inputs from the user.
2. Write java program to identify whether the number is “Odd” or “Even” number
after accepting n number of inputs from the user.
3. Write Java program to indicate whether the students are “Promoted” to the next
class or Detained to the class he/she is learning based on average mark used to
promote or detained as a requirement.
138.
138
The if-else-if Lader
A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder.
The general form or syntax of if-else-if is looks like the following:
if(expression1) {
statement1;
}
else if(expression2){
statement2;
}
else if(expression3) {
statement3;
}
. . ………………..
else {
statement n;
}
The if –else-if statements are executed from the top to down.
As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of
the ladder is bypassed.
If none of the conditions is true, then the final else statement
will be executed.
The final else acts as a default condition; that is, if all other
conditional tests fail, then the last else statement is performed.
If there is no final else and all other conditions are false, then
no action will take place.
139.
139
Example 1
//Program todisplay Positive, Negative or Zero after accepting n number of inputs from
the user
import javax.swing.JOptionPane;
public class IfElseIfExample3 {
public static void main(String args[]) {
String Number;
int n;
Number=JOptionPane.showInputDialog("Enter the Number n");
n=Integer.parseInt(Number);
if(n>0) {
140.
140
Example 1 continued
System.out.println("Thenumber n is Positive");
}
else if (n < 0) {
System.out.println("The number n is Negative");
}
else{
System.out.println("The number n is Zero");
}
}
141.
141
Exercise
1. Write JavaProgram based on the following input and output information to illustrate if---else
—if ladder.
Input Output
(marks>=90) and (marks<=100) A
(marks>=80) and (marks<90) B
(marks>=70)and (marks<80) C
(marks>=60)and (marks<70) D
(marks>=30) and (marks<60) F
Otherwise NG
2. Write C++ program that performs the following input and output operation .
Input Output
A Excellent
B Very Good
C Satisfactory
D Not Satisfactory
F Fail
Otherwise Invalid Input
142.
142
3. Switch Statement
is Java's multi-way branch statement.
used to dispatch execution to different parts of your code based on the value of an
expression.
It is often provides a better alternative than a large series of if-else-if statements.
Syntax:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
143.
143
3. Switch continued-----
------
-------
casevalueN:
// statement sequence N
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char.
Each of the values specified in the case statements must be of a type compatible with the
expression.
Each case value must be a unique literal (that is, it must be a constant, not a variable).
144.
144
3. Switch continued-----
Duplicate case values are not allowed.
The switch statement works like this:
The value of the expression is compared with each of the literal values in the case
statements.
If a match is found, the code sequence following that case statement is executed.
If none of the constants matches the value of the expression, then the default statement is
executed.
However, the default statement is optional.
If no case matches and no default is present, then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence.
When a break statement is encountered, execution branches to the first line of code that
145.
145
3. Switch continued-----
This has the effect of "jumping out" of the switch.
// A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
146.
146
3. Switch continued-------
case2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
147.
147
3. Switch continued-------
As you can see, each time through the loop, the statements associated with the case
constant that matches i are executed. All others are bypassed.
After i is greater than 3, no case statements match, so the default statement is executed.
The break statement is optional. If you omit the break, execution will continue on into
the next case.
It is sometimes desirable to have multiple cases without break statements between them.
For example, consider the following program:
// In a switch, break statements are optional.
class MissingBreak {
public static void main(String args[]) {
149
3. Switch continued------
case8:
case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
150.
150
While thepreceding example is, of course, contrived for the sake of illustration,
omitting the break statement has many practical applications in real programs.
To sample its more realistic usage, consider the following rewrite of the season example
shown earlier. This version uses a switch to provide a more efficient
implementation.
// An improved version of the season program.
class SwitchMonth {
public static void main(String args[]) {
int month = 4;
String season;
3. Switch continued------
151.
151
switch (month) {
case12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
3. Switch continued------
152.
152
break;
case 6:
case 7:
case8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
3. Switch continued------
153.
153
default:
season = "BogusMonth";
}
System.out.println("April is in the " + season + ".");
}
}
3. Switch continued------
154.
Exercise
1. Write Javaprogram using switch statement to display a letter grade when users enters different
range of marks. Use the following input and output information for your work.
Input Output
(marks>=90) and (marks<=100) A+
(marks>=80) and (marks<90) A
(marks>=70) and (marks<80) B+
(marks>=65) and (marks<70) B
(marks>=55) and (marks<65) C+
(marks>=45)and (marks<55) C
(marks>=35)and (marks<45) D
(marks>=1) and (marks<35) F
otherwise NG 154
155.
2. Iteration Statements
Java's iteration statements are for, while, and do-while.
These statements create what we commonly called loops.
A loop repeatedly executes the same set of instructions until a termination condition
is met.
A) While Loop
The while loop is Java's most fundamental looping statement.
It executes the body of the loop repeatedly while its controlling expression is true.
Syntax:
while(condition) {
// body of loop
}
155
The condition can be any
Boolean expression
156.
156
2. Iteration Statements-------
The body of the loop will be executed as long as the conditional expression is
true.
When condition becomes false, control passes to the next line of code
immediately following the loop.
The curly braces are unnecessary if only a single statement is being repeated.
Example 1:
Java program using while loop that counts down from 10, printing exactly in one
line:
//Define a class named While
class While {
157.
157
2. Iteration Statements-------
//mainmethod ()
public static void main(String args[]) {
//Declare a variable named n and initialized to 10
int n = 10;
while(n > 0) {
System.out.println(n+” “);
//Decrement n at each iteration
n- -;
}//End of while----loop
} //End of main program ()
} //End of class
158.
158
Example 2
Write Javaprogram to calculate the sum of 10 positive integers.
//Define a class
class WhileSumOf {
public static void main( String args[]) {
//Declaration of int variables named total and initialize to 0 and number initialized to 1
int total=0;
int number=1;
//While Loop to count the number 1 to 10
while (number<=10){
//Calculate the sum of positive numbers
total=(total+number);
159.
159
Example 2---------
//Increment thenumber by 1 at each iteration
number++;
}//End of while loop
//Display outputs
System.out.println("Sum="+total );
}//End of main ()
} //End of class
The body of the while (or any other of Java's loops) can be empty. This is because a null
statement (one that consists only of a semicolon) is syntactically valid in Java.
Consider the following Java program to demonstrate the body of the while---loop to
be empty and the program finds the mid-range between 100 and 200.
160.
160
Example 2---------
// Thetarget of a loop can be empty.
class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while(++i < --j) ; // no body in this loop
System.out.println("Midpoint is " + i);
}
}
This program finds the
midpoint between i and j.
161.
161
Example 2---------
Hereis how the while loop works. The value of i is incremented, and the value of j is
decremented.
These values are then compared with one another.
If the new value of i is still less than the new value of j, then the loop repeats.
If i is equal to or greater than j, the loop stops.
Upon exit from the loop, i will hold a value that is midway between the original values
of i and j.
Of course, this procedure only works when i is less than j to begin with.
As you can see, there is no need for a loop body; all of the action occurs within the
conditional expression, itself.
162.
162
Activity 1
1. WriteJava program to display “Welcome to Java program” “*” five times
respectively.
2. Write Java Program for the sum and average of n natural number using while
Loop. The program is expected to accept any n number as an input from the
user.
3. Write Java program to calculate factorial of n number inputted by the user
using while Loop.
4. Write Java program to calculate sum of the first 10 even number using while
Loop.
5. Write Java program to calculate the sum of the first 10 odd number using
while loop.
6. Write separate Java program to calculate the reverse of sum of 10 even and
odd numbers using while loop.
163.
163
B) do-while Loop
Ifwhile loop is initially false, then the body of the loop will not be executed at all.
However, sometimes it is desirable to execute the body of a while loop at least once,
even if the conditional expression is false to begin with.
In other words, there are times when you would like to test the termination
expression at the end of the loop rather than at the beginning.
The do-while loop always executes its body at least once.
Because its conditional expression is at the bottom of the loop.
Syntax
do {
// body of loop
} while (condition);
164.
164
B) do-while Loop----
Each iteration of the do-while loop first executes the body of the loop and then
evaluates the conditional expression.
If this expression is true, the loop will repeat. Otherwise, the loop terminates.
As with all of Java's loops, condition must be a Boolean expression.
Example 1:
Write Java program to print the number 1 to 10 in a single line using do---while Loop.
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
//Declaration of variables and initialize to 1
int n=1;
165.
165
B) do-while Loop----
//Dowhile ---Loop
do {
//Display n number
System.out.print(+n+" ");
n++;
}
while(n<=10);
}
}
166.
166
Example 2
Write Javaprogram to calculate the sum of multiple positive integers inputted by the
user and the program stops when the user inputs 0.
import java.util.Scanner;
class TestDoWhile {
/** Main method */
public static void main(String[] args) {
//Declaration of variables by the name num
int num;
//Declaration of variables by the name sum and
//initialized to 0
int sum = 0;
167.
167
Example 2
// Createobjects of Scanner class
Scanner input = new Scanner(System.in);
// Keep reading data until the input is 0
do {
// Read the next data
System.out.print("Enter an integer (the input ends if it is 0): ");
//Call the nextInt() to read int values
num = input.nextInt();
//Calculate Sum
sum=(sum+num);
} //End of do()
168.
168
Example 2
//Read untilnum!=0
while (num != 0);
//Display output
System.out.println("Sum=" + sum);
}//End of main ()
} //End of class
169.
169
Activity 2
1. WriteJava Program to print English Upper Case Alphabet using do---While Loop
2. Write Java program to display “Welcome to Java program” and “*” five times
respectively using do—while loop.
3. Write Java Program for the sum and average of n natural number using do----while
Loop. The program is expected to accept any n number from the user.
4. Write Java program to calculate sum of the first 10 even number using while Loop.
5. Write Java program to calculate the sum of the first 10 odd number using while
loop.
6. Write separate Java program to calculate the reverse of sum of 10 even and odd
numbers using while loop.
170.
170
C) for---------Loop
Itis a powerful and versatile construct.
Syntax:
for(initialization; condition; iteration) {
// body of for loop
}
If only one statement is being repeated, there is no need for the curly braces.
The for loop operates as follows:
1. When the loop first starts, the initialization portion of the loop is executed.
And this is an expression that sets the value of the loop control variable, which acts as
a counter that controls the loop.
The initialization expression is only executed once.
171.
171
C) for---------Loop----------
2. Second,the test condition is evaluated.
This must be a Boolean expression.
It usually tests the loop control variable against a target value.
If this expression is true, then the body of the loop is executed. If it is false, the loop
terminates.
3. Thirdly, the iteration portion of the loop is executed.
This is usually an expression that increments or decrements the loop control variable.
The loop then iterates:
First evaluating the conditional expression, executing the body of the loop,
And then executing the iteration expression with each pass.
This process repeats until the controlling expression is false.
172.
172
Example 1
Write Javaprogram to print a number 1 to 10 in a single line using for---loop.
public class ForLoopEx1 {
public static void main(String[] args) {
//Declaration of variables
int i;
//For Loop
for (i=1; i<=10; i++) {
//Body of for Loop
System.out.print(i+" ");
}//End of for Loop
}//End of main
}//End of class
173.
173
Example 2
Write Javaprogram to calculate the sum of the first 10 even numbers using for----
loop:
public class ForLoopSum {
public static void main(String[] args) {
//Declaration of variables named num and initialize to 0
int sum;
sum=0;
//For Loop
for (int num=2; num<=20; num=num+2) {
//Perform sum of even numbers
175
Activity 3
1. WriteJava Program for the sum of n natural number using for statement. The
program is expected to accept any n number from the user.
2. Write Java program to calculate factorial of n number inputted by the user using
for statement.
3. Write Java program for sum of squares of n natural number inputted by the
user.
4. Write Java program to calculate the sum of the first 10 odd number using for
statement.
5. Write separate Java program to calculate the reverse of sum of 10 even and odd
numbers using for statement.
176.
176
Nested for Loops
Like all other programming languages, Java allows loops to be nested.
That is, one loop may be inside another.
For example, here is a program that nests for loops:
public class ForLoopNest {
public static void main(String args[]) {
//Outer for Loop
for(int i=0; i<5; i++) {
//Inner for Loop
for(int j=i; j<5; j++) {
System.out.print("*"+" ");
177.
177
Nested for Loops
//Display*
}//End of inner for Loop
System.out.println();
} //End of outer for loop
} //End of main()
} //End of class
178.
178
Exercise
1. Write ajava program to perform multiplication table.
The program is expected to display the table as
follows.
179.
179
3) Jump Statements
Java supports three jump statements: break, continue, and return.
These statements transfer control to another part of your program.
Note :
In addition to the jump statements discussed here, Java supports one other way that
you can change your program's flow of execution: through exception handling.
Exception handling provides a structured method by which run-time errors can be
trapped and handled by your program.
It is supported by the keywords try, catch, throw, throws, and finally.
In essence, the exception handling mechanism allows your program to perform a
nonlocal branch.
180.
180
A.Using break
In Java,the break statement has three uses.
First, it terminates a statement sequence in switch statement.
Second, it can be used to exit a loop.
Third, it can be used as a "civilized" form of goto.
1. Using break to Exit a Loop
By using break, you can force immediate termination of a loop, by passing the
conditional expression and any remaining code in the body of the loop.
When a break statement is encountered inside a loop:
The loop is terminated and program control resumes at the next statement
following the loop.
181.
181
Example 1
Write Javaprogram to print the values from 1 to 30 but terminate the loop if
i==20. Use the break statement with for---loop.
public class LoopBreak1 {
public static void main(String[] args) {
//For Loop to count the number i to 30
for(int i=1; i<=30; i++) {
// Terminate loop if i is 10
if(i == 10){
break;
} //End of if()
182.
182
Example 1--------
else{
//Print thevalue of i at each iteration
System.out.print(" " + i);
} //End of else()
}//End of for loop
} //End of main ()
} //End of class
183.
183
Example 1-------
Thebreak statement can be used with any of Java's loops, including intentionally
infinite loops.
Write Java program to print the value of i starting from 100 to down and exits the
loop when i==80. Use the break statement with while---loop:
public class BreakLoop2 {
public static void main(String[] args) {
int i;
i=100;
//While Loop to count the number until the condition is evaluated to true
while(i>1) {
184.
184
Example 1-------
//Terminate theloop if i==80
if(i==80){
break;
}//End of break
else{
//Print the Value of i and increment the value of i
System.out.printf("%4d", i);
i--;
}//End of else
}//End of for----loop
}//End of main ()
}//End of class
Note: When we use the break inside a set of
nested loops, the break statement will only break
out of the innermost loop.
185.
185
Activity
1. Use breakstatement with while---loop and write Java program to calculate
Sum of any positive integers <=20. The program terminates the loop when
(sum>=100) and displays the number of positive integers counted and its sum.
2. Use break statement with do------while Loop and write java program to
calculate the sum of the first 10 positive even numbers. The loop terminates
if(sum>=30) .
3. Write Java program to print multiplication table and asterisk printed
diagonally as follows in the next slide. Use nested for----loop for your
program:
187
B. Using breakas a form of goto
The break statement can also be employed by itself to provide a "civilized" form of
the goto statement.
Java does not have a goto statement, because it provides a way to branch in an
arbitrary and unstructured manner.
This usually makes goto-ridden code hard to understand and hard to maintain.
It also prohibits certain compiler optimizations.
There are, however, a few places where the goto is a valuable and legitimate
construct for flow control.
For example, the goto can be useful when you are exiting from a deeply nested set
of loops.
188.
188
B. Using breakas a form of goto----
By using this form of break, you can break out of one or more blocks of code.
These blocks need not be part of a loop or a switch. They can be any block.
Further, you can specify precisely where execution will resume, because this form of
break works with a label.
The general form of the labeled break statement is: break label;
Here, label is the name of a label that identifies a block of code.
When this form of break executes, control is transferred out of the named block of
code.
The labeled block of code must enclose the break statement, but it does not need to
be the immediately enclosing block.
189.
189
B. Using breakas a form of goto-----
But you cannot use break to transfer control to a block of code that does not enclose the
break statement.
To name a block, put a label at the start of it.
A label is any valid Java identifier followed by a colon.
Once you have labeled a block, you can then use this label as the target of a break statement.
Doing so causes execution to resume at the end of the labeled block.
Example:
Let’s see the, the following java program that shows three, nested blocks of code, each with its
own label to demonstrate using break as goto to exit from nested block of code. The break
statement causes execution to jump forward, past the end of the block labeled second, skipping
the two println( ) statements under the first and second block .
190.
190
B. Using breakas a form of goto-----
public class LoopBreakGoTo {
public static void main(String[] args) {
boolean t = true;
//Label for first block of code
first:{
//Label for 2nd block of code
second: {
//Label for third block code
third: {
System.out.println("Before the break.");
//Exit out from the second block
191.
191
B. Using breakas a form of goto-----
break second;
}
System.out.println("This is under the third block");
} //End of third block
System.out.println("This is under the second block");
} //End of Second Block
System.out.println("This is under the first block");
}//End of first block
}//End of main ()
}//End of class
Note: One of the most common uses for a labeled break statement is to exit from nested loops.
192.
192
Example
Let’s seethe following java program to demonstrate the labeled break statement used to
exit from the nested for----loops. The program shows the outer loop executes only once
and terminates both the inner and outer for loops when (j==10):
public class LoopBreakGoTo1 {
public static void main(String args[]) {
//Label the nested for Loop
outer:
for(int i=0; i<3; i++) {
//The outer loop executes only once
System.out.print("Pass " + i + ": ");
193.
193
Example------
for(int j=0; j<50;j++) {
//Exit from both inner and outer for loop if j==10
if(j == 10) {
break outer;
}//End of if()
else{
System.out.print(j + " ");
}//End of else()
}//End of inner for loop
System.out.println("This will not print");
195
C) Using continue
Sometimes it is useful to force an early iteration of a loop.
That is, you might want to continue running the loop, but stop processing the
remainder of the code in its body for this particular iteration.
This is, in effect, a goto just past the body of the loop, to the loop's end.
The continue statement performs such an action.
In while and do-while loops:
A continue statement causes control to be transferred directly to the conditional
expression that controls the loop.
In a for loop:
Control goes first to the iteration portion of the for statement and then to the
conditional expression.
196.
196
C) Using continue------
For all three loops, any intermediate code is bypassed.
Example:
Write Java program using continue statement to cause two numbers to be printed
on each line. The loop continues to execute until i%2==0 is evaluated to true.
The program prints two numbers as follows:
197.
197
Example 1
public classLoopContinue {
public static void main(String args[]) {
int i;
//For Loop to count the no from 0 to 10
for(i=0; i<=10; i++) {
//Print the value of i at each iteration
System.out.print(i + " "+" ");
//Test if i%2==0 to continue the execution of the loop
if (i%2 == 0) {
continue;
}//End of if()
198.
198
Example 1------
//Print newline if i%2!=2
else{
System.out.println("");
}//End of else()
} //End of for Loop
}//End of main()
}//End of class
Note: This code uses the % operator to check if i is even.
If it is, the loop continues without printing a newline.
As with the break statement, continue may specify a label to describe which enclosing
loop to continue.
199.
199
Example 2
WriteJava program that uses continue to label which loop continues to print a
triangular multiplication table for 1 through 6. The program terminates the inner loop
with continue label and continues the outer loop to execute.
public class LoopContinueMult {
public static void main(String args[]) {
//Define a label
outer:
//Outer for Loop
for (int i=1; i<=6; i++) {
//Inner for Loop
for(int j=1; j<=6; j++) {
200.
200
Example 2------
//Execute outerfor loop when (j>i)
if(j > i) {
//Exit the inner for loop after printing newline
//And continue to execute outer for Loop
System.out.println();
continue outer;
}//End of if()
else{
System.out.print(" " + (i * j));
} //End of else
} //End of inner for Loop
201.
201
Example 2------
//System.out.println();
} //Endof outer for Loop
} //End of main ()
}//End of class
The continue statement in the above program terminates the loop counting j and
continues with the next iteration of the loop counting i.
Good uses of continue are rare.
One reason is that Java provides a rich set of loop statements which fit most
applications.
However, for those special circumstances in which early iteration is needed, the
continue statement provides a structured way to accomplish it.
202.
202
D) return
Thereturn statement is used to explicitly return from a method.
That is, it causes program control to transfer back to the caller of the method.
As such, it is categorized as a jump statement.
At any time in a method the return statement can be used to cause execution to
branch back to the caller of the method.
Thus, the return statement immediately terminates the method in which it is
executed.
The following example illustrates this point. Here, return causes execution to
return to the Java run-time system, since it is the run-time system that calls
main( ).
203.
203
D) return------
public classReturnStatement {
public static void main(String args[]) {
//Declaration of Variables and assign true as a value
boolean t = true;
//Print any Statement befor return to the main ()
System.out.println("Before the return");
//Test if t is evaluate as true
//and return to the caller
if(t) {
return;
}//End of if ()
204.
204
D) return------
System.out.println("This statementis not executed");
} //End of main()
}//End of class
As soon as return is executed, control passes back to the caller.
One last point:
In the preceding program, the if(t) statement is necessary.
Without it, the Java compiler would flag an "unreachable code" error, because the
compiler would know that the last println( ) statement would never be executed.
To prevent this error, the if statement is used here to trick the compiler for the sake of
this demonstration.
205.
205
Self-test Exercise
1. Explainthe term Java and why Java is used and list down the applications of Java
programming languages?
2. What is Java platform and list down and explain the java platform components?
3. Write short difference between Java Development Kit(JDK) and Java Runtime
Environment (JRE) components of java platform
4. What is the Java source filename extension, and what is the Java bytecode
filename extension?
5. What are the input and output of a Java compiler?
6. What is the command to compile and run a Java program??
206.
206
Self-test Exercise-----
7. Whatis JVM and show the architecture of JVM graphically and explain the
purpose of each components of the JVM?
8. Can Java run on any machine? What is needed to run Java on any computer?
9. The primary objective of Java programming language creation was to make it
portable, simple and secure programming language. Apart from this, there are
also some excellent features which play an important role in the popularity of
this language. The features of Java are also known as java buzzwords. List
down and explain the features of java or buzzwords?
10. The java program development environment goes through five phases. List
down and explain these development environment?
207.
207
Self-test Exercise-----
11. Selectprogrammers notepad editor and write your own simple java program to
calculate the sum of two numbers. Open cmd, compile and run the program?
12. List down the most common types of Java platform and explain the purpose of
each types of the platform?
13. If a NoClassDefFoundError occurs when you run a program, what is the cause
of the error?
14. If a NoSuchMethodError occurs when you run a program, what is the cause of
the error?
15. Java uses System.out.println(“ “);. Explain the purpose of the term System, out
and println () parts of the statement.