JAVA UNIT 1
JAVA UNIT 1
Statements are roughly equivalent to sentences in natural languages. In general, statements are just
like English sentences that make valid sense.
In Java, a statement is an executable instruction that tells the compiler what to perform. It forms a
complete command to be executed and can include one or more expressions. A sentence forms a
complete idea that can include one or more clauses.
Types of Statements
Statement Description
Empty statement These are used during program development.
Variable declaration It defines a variable that can be used to store the values.
statement
Labeled statement A block of statements is given a label. The labels should notbe keywords,
previously used labels, or already declared local variables.
Expression statement Most of the statements come under this category. There are seven types of
expression statements that include assignment, method call and allocation,
pre-increment, postincrement, pre-decrement, and post decrement statements.
Control statement This comprises selection, iteration, and jump statements.
Selection statement In these statements, one of the various control flows is selected when a
certain condition expression is true.
Iteration statement These involve the use of loops until some condition for the termination of
loop is satisfied. There are three types ofiteration statements that make use of
while, do, and for.
Jump statement In these statements, the control is transferred to the beginning or end of the
current block or to a labeled statement. There are four types of Jump
statements including break, continue, return, and throw.
Synchronization statement These are used with multi-threading
Guarding statement These are used to carry out the code safely that may cause exceptions
These statements make use of try and catch block, and finally
JAVA PROGRAMMING 4 KKVPRASAD@CSE
Some of the Java Statements are as follows:
Expression Statements
Declaration Statements
Control Statements
Expression Statements
Expression is an essential building block of any Java program. Generally, it is used to generate a new
value. Sometimes, we can also assign a value to a variable. In Java, expression is the combination of values,
variables, operators, and method calls.
There are three types of expressions in Java:
Expressions that produce a value. For example, (6+9), (9%2), (pi*radius) + 2. Note that the
expression enclosed in the parentheses will be evaluate first, after that rest of the expression.
Expressions that assign a value. For example, number = 90, pi = 3.14.
Expression that neither produces any result nor assigns a value. For
example, increment or decrement a value by using increment or decrement operator
respectively, method invocation, etc. These expressions modify the value of a variable or state
(memory) of a program. For example, count++, int sum = a + b; The expression changes only the
value of the variable sum. The value of variables a and b do not change, so it is also a side effect.
Declaration Statements
In declaration statements, we declare variables and constants by specifying their data type and name.
A variable holds a value that is going to use in the Java program. For example:
int quantity;
boolean flag;
String message;
Also, we can initialize a value to a variable. For example:
int quantity = 20;
boolean flag = false;
String message = "Hello";
Control Statement
Control statements decide the flow (order or sequence of execution of statements) of a Java program.
In Java, statements are parsed from top to bottom. Therefore, using the control flow statements can interrupt
a particular section of a program based on a certain condition.
There are the following types of control statements:
1. Conditional or Selection Statements
if Statement
if-else statement
if-else-if statement
switch statement
2. Loop or Iterative Statements
for Loop
while Loop
do-while Loop
for-each Loop
3. Flow Control or Jump Statements
return
continue
Break
In this example, we are receiving only one argument and printing it.To run this java program, you
must pass at least one argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first name is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample Krishna
Output:
Your first argument is: Krishna
The above statement creates a constructor of the Scanner class having System.inM as an argument.
It means it is going to read from the standard input stream of the program. The java.util package should be
import while using Scanner class.
Programming style refers to the technique used in writing the source code for a computer program.
Most programming styles are designed to help programmers quickly read and understands the
program as well as avoid making errors.
The goal of good programming style is to provide understandable, straightforward, elegant code.
The programming style used in a various program may be derived from the coding standards or code
conventions of a company or other computing organization, as well as the preferences of the actual
programmer.
Some general rules or guidelines in respect of programming style:
1. Clarity and simplicity of Expression: The programs should be designed in such a manner so that
the objectives of the program is clear.
2. Naming: In a program, you are required to name the module, processes, and variable, and so on.
Care should be taken that the naming style should not be cryptic and non-representative.
For Example:
a = 3.14 * r * r
area of circle = 3.14 * radius * radius;
3. Control Constructs: It is desirable that as much as a possible single entry and single exit constructs
used.
4. Information hiding: The information secure in the data structures should be hidden from the rest of
the system where possible. Information hiding can decrease the coupling between modules and make
the system more maintainable.
5. Nesting: Deep nesting of loops and conditions greatly harm the static and dynamic behavior of a
program. It also becomes difficult to understand the program logic, so it is desirable to avoid deep
nesting.
6. User-defined types: Make heavy use of user-defined data types like enum, class, structure, and
union. These data types make your program code easy to write and easy to understand.
7. Module size: The module size should be uniform. The size of the module should not be too big or
too small. If the module size is too large, it is not generally functionally cohesive. If the module size
is too small, it leads to unnecessary overheads.
8. Module Interface: A module with a complex interface should be carefully examined.
9. Side-effects: When a module is invoked, it sometimes has a side effect of modifying the program
state. Such side-effect should be avoided where as possible.
Here, the output displays several types of variable values. Java variable declaration is necessary to
allocate data memory and display relevant data.
Java Variable Declaration Example: Without Initialization
Java language needs to create multiple variables with different data formats. Here, Java requires int,
float, string, boolean, and other data types.
Create variable in the default method.
Initialize value with the respective variable name and data type.
Then return value in the method.
DeclareVariable.java
public class DeclareVariable {
public static void main(String[] args) {
int student_id;
String student_name;
double numbers;
Boolean shows;
float nan;
student_id = 21;
student_name = "java programmer";
numbers = 45.22;
shows = false;
nan= 6.8f;
System.out.println( "Name:" +student_name+ "\n Age:" +student_id);
System.out.println( "Number:" +numbers+ "\n Boolean:" +shows);
System.out.println( "float:" +nan);
} }
Output:
For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's see an
example.
WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
} }
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0
Narrowing Type Casting
Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not perform casting
then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
JAVA PROGRAMMING 14 KKVPRASAD@CSE
In the following example, we have performed the narrowing type casting two times. First, we have
converted the double type into long data type after that long data type is converted into int type.
NarrowingTypeCastingExample.java
public class NarrowingTypeCastingExample {
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166
Demo.java
public class Demo {
//instance variable
String name = "Andrew";
//class and static variable
static double height= 5.9;
public static void main(String args[]) {
//local variable
int marks = 72;
}
}
VariableScopeExample1.java
public class VariableScopeExample1
{
public static void main(String args[])
{
int x=10;
{
//y has limited scope to this block only
int y=20;
System.out.println("Sum of x+y = " + (x+y));
}
//here y is unknown
y=100;
//x is still known
x=50;
}
}
Output:
We see that y=100 is unknown. If you want to compile and run the above program remove or comment the
statement y=100. After removing the statement, the above program runs successfully and shows the
following output.
Sum of x+y = 30
There is another variable named an instance variable. These are declared inside a class but outside
any method, constructor, or block. When an instance variable is declared using the keyword static is known
as a static variable. Their scope is class level but visible to the method, constructor, or block that is defined
inside the class.
Product.java
public class Product
{
//variable visible to any child class
public String pName;
//variable visible to product class only
private double pPrice;
In the above example, we have passed a variable as a parameter. We have used this keyword that
differentiates the class variable and local variable.
Declaring a Variable Inside a Constructor : VariableInsideConstructor.java
public class VariableInsideConstructor
{
//creating a default constructor
VariableInsideConstructor()
{
int age=24;
System.out.println("Age is: "+age);
}
//main() method
public static void main(String args[])
{
//calling a default constructor
VariableInsideConstructor vc=new VariableInsideConstructor();
}
}
Output:
Age is: 24
Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:
As the name suggests, a constant is an entity in programming that is immutable. In other words, the
value that cannot be changed.
Constant is a value that cannot be changed after assigning it. Java does not directly support the
constants. There is an alternative way to define the constants in Java by using the non-access modifiers static
and final.
In Java, to declare any variable as constant, we use static and final modifiers. It is also known
as non-access modifiers. According to the Java naming convention the identifier name must be in capital
letters.
Static and Final Modifiers
The purpose to use the static modifier is to manage the memory.
It also allows the variable to be available without loading any instance of the class in which it is
defined.
The final modifier represents that the value of the variable cannot be changed. It also makes the
primitive data type immutable or unchangeable.
The syntax to declare a constant is as follows:
static final datatype identifier_name=value;
For example, price is a variable that we want to make constant.
static final double PRICE=432.78;
Why we use constants?
The use of constants in programming makes the program easy and understandable which can be
easily understood by others. It also affects the performance because a constant variable is cached by both
JVM and the application.
Example 1: Declaring Constant as Private
ConstantExample1.java
import java.util.Scanner;
public class ConstantExample1 {
//declaring constant
private static final double PRICE=234.90;
public static void main(String[] args) {
int unit;
double total_bill;
System.out.print("Enter the number of units you have used: ");
Scanner sc=new Scanner(System.in);
unit=sc.nextInt();
total_bill=PRICE*unit;
System.out.println("The total amount you have to deposit is: "+total_bill);
} }
Output:
The printf() method of Java PrintStream class is a convenience method to write a String which is
formatted to this output Stream. It uses the specified format string and arguments.
There is an invocation of this method of the form "out.printf(format, args)" which behaves exactly same as
the follows:-
out.format( format, args)
Syntax :
public PrintStream printf(String format, Object... args)
Parameter :
format - a format string as described in Format string syntax
Returns :
The printf() method returns this output stream.
Throws
This method throws:
1. IllegarArgumentException - If a format string contains an illegal syntax, a format specifier that is
incompatible with the given arguments, insufficient arguments given the format string, or other
illegal conditions.
2. NullPointerException - If the format is null.
The printf() method of Java PrintStream class is a convenience method which is used to write a
String which is formatted to this output Stream. It uses the specified format string and arguments to write the
string.
There is an invocation of this method of the form " out.printf(l, format, args)" which behaves exactly same
as the follows:-
out.format(l, format, args)
Syntax
public PrintStreamprintf(Locale l, String format, Object... args)
Parameter
l - the locale to apply during formatting. If it is null then no localised is applied.
format - a format string as described in Format string syntax
args - Arguments referenced by the format specifiers in the format string.
Returns
The printf() method returns this output stream.
Throws
This method throws:
1. IllegarArgumentException - If a format string contains an illegal syntax, a format specifier that is
incompatible with the given arguments, insufficient arguments given the format string, or other
illegal conditions.
2. NullPointerException - if the format is null.
Java assignment operator is one of the most common operators. It is used to assign the value on its
right to the operand on its left.
Java Assignment Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:
14
16
Java Assignment Operator Example: Adding short
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:
Compile time error
After type cast:
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Output:
20
Increment Operator
Increment Operators are the unary operators used to increment or add 1 to the operand value. The
Increment operand is denoted by the double plus symbol (++).
It has two types, Pre Increment and Post Increment Operators.
Pre-increment Operator
The pre-increment operator is used to increase the original value of the operand by 1 before
assigning it to the expression.
Syntax
X = ++A;
In the above syntax, the value of operand 'A' is increased by 1, and then a new value is assigned to
the variable 'B'.
Post increment Operator
The post-increment operator is used to increment the original value of the operand by 1 after
assigning it to the expression.
Syntax
X = A++;
In the above syntax, the value of operand 'A' is assigned to the variable 'X'. After that, the value of
variable 'A' is incremented by 1.
Decrement Operator
Decrement Operator is the unary operator, which is used to decrease the original value of the
operand by 1. The decrement operator is represented as the double minus symbol (--). It has two types, Pre
Decrement and Post Decrement operators.
Pre-Decrement Operator
The Pre-Decrement Operator decreases the operand value by 1 before assigning it to the
mathematical expression. In other words, the original value of the operand is first decreases, and then a new
value is assigned to the other variable.
Syntax
B = --A;
In the above syntax, the value of operand 'A' is decreased by 1, and then a new value is assigned to the
variable 'B'.
Post decrement Operator:
Post decrement operator is used to decrease the original value of the operand by 1 after assigning to
the expression.
Syntax
B = A--;
In the above syntax, the value of operand 'A' is assigned to the variable 'B', and then the value of A is
decreased by 1.
Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
JAVA PROGRAMMING 29 KKVPRASAD@CSE
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and --
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}}
Output:
22
21
TernaryOperatorExample.java
public class TernaryOperatorExample {
public static void main(String args[])
{
int x, y;
x = 20;
y = (x == 1) ? 61: 90;
System.out.println("Value of y is: " + y);
y = (x == 20) ? 61: 90;
System.out.println("Value of y is: " + y);
}
}
Output
Value of y is: 90
Value of y is: 61
JAVA PROGRAMMING 30 KKVPRASAD@CSE
LargestNumberExample.java
public class LargestNumberExample {
public static void main(String args[])
{
int x=69;
int y=89;
int z=79;
int largestNumber= (x > y) ? (x > z ? x : z) : (y > z ? y : z);
System.out.println("The largest numbers is: "+largestNumber);
}
}
Output
The largest number is: 89
Operatoror Meaning
== Is equal to
!= Is not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
1.3.1 INTRODUCTION
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear.
However, Java provides statements that can be used to control the flow of Java code. Such
statements are called control flow statements.
It is one of the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
Conditional or Selection Statements
if Statement
if-else statement
if-else-if statement
switch statement
Loop or Iterative Statements
for Loop
while Loop
do-while Loop
for-each Loop
Flow Control or Jump Statements
return
continue
Break
1.3.2 IF EXPRESSION
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
Student.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
default:
code to be executed if all cases are not matched;
}
SwitchExample.java
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:
20
In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true.
However, loop statements are used to execute the set of instructions in a repeated order. The
execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.
1. while loop
2. do-while loop
3. for loop
4. for each
JAVA PROGRAMMING 37 KKVPRASAD@CSE
1.3.7 WHILE EXPRESSION
The while loop is also used to iterate over the number of statements multiple times. However, if we
don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If
the condition is true, then the loop body will be executed; otherwise, the statements after the loop
will be executed.
Syntax:
while(condition){
//looping statements
}
Calculation .java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
} } }
Output:
Printing the list of first 10 even numbers
0 2 4 6 8 10
The do-while loop checks the condition at the end of the loop after executing the loop statements.
When the number of iteration is not known and we have to execute the loop at least once, we can use
do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax
of the do-while loop is given below.
Syntax:
do
{
//statements
} while (condition);
Calculation.java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:
Printing the list of first 10 even numbers
0 2 4 6 8 10
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code.
We use the for loop only when we exactly know the number of times, we want to execute the block
of code.
for(initialization, condition, increment/decrement) {
//block of statements
}
Calculation.java
public class Calculattion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
} }
Output:
The sum of first 10 natural numbers is 55
If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes
completely whenever outer loop executes.
PyramidExample.java
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
} }}
Output:
*
**
***
****
*****
Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-
each loop, we don't need to update the loop variable.
for(data_type var : array_name/collection_name){
//statements
}
Calculation.java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
JAVA PROGRAMMING 39 KKVPRASAD@CSE
for(String name:names) {
System.out.println(name);
} } }
Output:
As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement.
However, it breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
BreakExample.java
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
} } } }
Output:
0123456
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.
import java.util.*;
public class GFG {
public static void main(String args[])
{
for (int i = 0; i <= 15; i++) {
if (i == 10 || i == 12) {
// Using continue statement to skip the
// execution of loop when i==10 or i==12
continue;
}
System.out.print(i + " ");
} }}
Output:
0 1 2 3 4 5 6 7 8 9 11 13 14 15
*****
JAVA PROGRAMMING 40 KKVPRASAD@CSE