0% found this document useful (0 votes)
29 views207 pages

Java Introduction

Java a

Uploaded by

xhameater8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views207 pages

Java Introduction

Java a

Uploaded by

xhameater8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 207

Java Programming

By Sanghamitra Panda
Introduction to Java
• Why Java?
Java is an object oriented platform independent computer
programming language, mainly designed to develop internet
applications.
• C, C++ programming languages supports developing only stand alone
application, it can only be executed in current system, cannot be
executed from remote system via remote call.
Check Java Version on Windows
• Open the Windows Start menu in the bottom-left corner and type
cmd in the search bar.
• Then, open the Command Prompt once it appears in the search
results.
• A new window with the command prompt should appear. In it, type
the command java -version and hit Enter.
Java Version

• To check if you have Java installed on a Windows PC, search in the


start bar for Java or type the following in Command Prompt
(cmd.exe):
• Definition of Java
Java is very simple, high level, secured, multithreaded, platform
independent, object-oriented programming language.
• Java is an object-oriented, class-based, secured and general-purpose
computer-programming language. It is a widely used robust
technology.
• History of Java
• Java was developed by James Gosling in SUN micro systems in 1990’s
for developing internet applications. Its first version is released in
January 23, 1996.
• Before Java, its name was Oak. Since Oak was already a registered
company, so James Gosling and his team changed the name from Oak
to Java.
It is used for:
• Mobile applications (specially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
• And much, much more!
• Why Use Java?
• Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
• It is easy to learn and simple to use
• It is open-source and free.It is one of the most popular programming
language in the world
• It is secure, fast and powerful
• It has a huge community support (tens of millions of developers)
• Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
• As Java is close to C++ and C#, it makes it easy for programmers to switch
to Java or vice versa
• What is Platform?
• A platform is hardware or software environment in which a program
runs. For instance, computer platform is (operating System +
Hardware Devices).
• Platform dependent
• An application that is compiled in one operating system, if it is not run
in different operating system then that application is called platform
dependent application. The programming language that is used to
develop this application is called platform dependent language.
Examples are C, C++.
• Platform independent
• If the application’s compiled code is able to run in different operating
systems then that application is called platform independent
application. . The programming language that is used to develop this
application is called platform independent language. Java is a
platform independent language.
• Terminology used in programming languages
Source code: Developer written program; it is written according to the
programming language syntax.
Compiled code: Compiler generated program that is converted from source code
Compiler: It is a translation program that converts source code into machine
language at once.
Interpreter: It is a translation program that converts source code into machine
language but line by line.
Executable code: OS understandable readily executable program (.exe files).
Compilation: it is a process of translating source code into compiled code.
Execution: It is process of running compiled code to get output.
• Types of applications
Based on the way of execution of programs, all available applications
are divided into 2 types
• Stand-alone applications
An application that can only executed in local system with local call
is called stand-alone application.
• Internet applications
An application that can be executed in local system with local call
and also from remote computer via network call is called internet
application.
Setup for Windows

• To install Java on Windows:


• Go to "System Properties" (Can be found on Control Panel > System and
Security > System > Advanced System Settings)
• Click on the "Environment variables" button under the "Advanced" tab
• Then, select the "Path" variable in System variables and click on the "Edit"
button
• Click on the "New" button and add the path where Java is installed,
followed by \bin. By default, Java is installed in C:\Program Files\Java\jdk-
11.0.1 (If nothing else was specified when you installed it). In that case, You
will have to add a new path with: C:\Program Files\Java\jdk-11.0.1\bin
Then, click "OK", and save the settings
• At last, open Command Prompt (cmd.exe) and type java -version to see if
Java is running on your machine
Java Comments
• Comments can be used to explain Java code, and to make it more
readable. It can also be used to prevent execution when testing
alternative code.
• Single-line Comments

• Single-line comments start with two forward slashes (//).


• Any text between // and the end of the line is ignored by Java (will not
be executed).
• Example 1:
• // This is a comment
• System.out.println("Hello World");
• Example 2:
• System.out.println("Hello World"); // This is a comment
• Java Multi-line Comments

• Multi-line comments start with /* and ends with */.

• Any text between /* and */ will be ignored by Java.


• Example 1:
• /* The code below will print the words Hello World
• to the screen, and it is amazing */
• System.out.println("Hello World");
Java Identifiers
• All Java variables must be identified with unique names.
• These unique names are called identifiers.

• Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
• All Java components require names. Names used for classes, variables, and methods are called
identifiers.
• In Java, there are several points to remember about identifiers. They are as follows −

• All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore
(_).
• After the first character, identifiers can have any combination of characters.
• A key word cannot be used as an identifier.
• Most importantly, identifiers are case sensitive.
• Examples of legal identifiers: age, $salary, _value, __1_value.
• Examples of illegal identifiers: 123abc, -salary.
Java Variables

• Variables are containers for storing data values.

• In Java, there are different types of variables, for example:

• String - stores text, such as "Hello". String values are surrounded by double
quotes
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• float - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
• boolean - stores values with two states: true or false
Declaring (Creating) Variables
• To create a variable, you must specify the type and assign it a value:
• Syntax :
type variableName = value;

• Where type is one of Java's types (such as int or String), and variableName is the name of the
variable (such as x or name). The equal sign is used to assign values to the variable.

• To create a variable that should store text, look at the following example:
• Example :
Create a variable called name of type String and assign it the value "John":

• String name = "John";


• System.out.println(name);
• Create a variable called myNum of type int and assign it the value 15:
• int myNum = 15;
• System.out.println(myNum);

• You can also declare a variable without assigning the value, and assign
the value later:
• Example
• int myNum;
• myNum = 15;
• System.out.println(myNum);
• Note that if you assign a new value to an existing variable, it will
overwrite the previous value:
• Example
• Change the value of myNum from 15 to 20:

• int myNum = 15;


• myNum = 20; // myNum is now 20
• System.out.println(myNum);
• Final Variables
• However, you can add the final keyword if you don't want others (or
yourself) to overwrite existing values (this will declare the variable as
"final" or "constant", which means unchangeable and read-only):

• Example
• final int myNum = 15;
• myNum = 20; // will generate an error: cannot assign a value to a
final variable
• Other Types

• A demonstration of how to declare variables of other types:


• Example

• int myNum = 5;
• float myFloatNum = 5.99f;
• char myLetter = 'D';
• boolean myBool = true;
• String myText = "Hello";
Class
name
Predefined
Method class name
name
Variable name : args, name
Display Variables

• The println() method is often used to display variables.


• To combine both text and a variable, use the + character:

Example
String name = "John";
System.out.println("Hello " + name);
• You can also use the + character to add a variable to another variable:

• Example
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
System.out.println(fullName);
• For numeric values, the + character works as a mathematical operator
(notice that we use int (integer) variables here):

• Example
int x = 5;
int y = 6;
System.out.println(x + y); // Print the value of x + y
Declare Many Variables

• Example

int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
Java Data Types

• Example

• int myNum = 5; // Integer (whole number)


• float myFloatNum = 5.99f; // Floating point number
• char myLetter = 'D'; // Character
• boolean myBool = true; // Boolean
• String myText = "Hello"; // String
• Data types are divided into two groups:

• Primitive data types - includes byte, short, int, long, float, double,
boolean and char
• Non-primitive data types - such as String, Arrays and Classes
Primitive Data Types
• A primitive data type specifies the size and type of variable values,
and it has no additional methods.
• There are eight primitive data types in Java:
• Numbers
• Primitive number types are divided into two groups:
• Integer types stores whole numbers, positive or negative (such as 123 or -
456), without decimals. Valid types are byte, short, int and long. Which type
you should use, depends on the numeric value.

• Floating point types represents numbers with a fractional part, containing


one or more decimals. There are two types: float and double.

• Even though there are many numeric types in Java, the most used for
numbers are int (for whole numbers) and double (for floating point
numbers).
Integer Types

• Byte
• The byte data type can store whole numbers from -128 to 127. This
can be used instead of int or other integer types to save memory
when you are certain that the value will be within -128 and 127:
• Example

byte myNum = 100;


System.out.println(myNum);
• Short
• The short data type can store whole numbers from -32768 to 32767:
• Example

short myNum = 5000;


System.out.println(myNum);
• Int
• The int data type can store whole numbers from -2147483648 to
2147483647. In general, and in our tutorial, the int data type is the
preferred data type when we create variables with a numeric value.
• Example

• int myNum = 100000;


• System.out.println(myNum);
• Long
• The long data type can store whole numbers from -
9223372036854775808 to 9223372036854775807. This is used when
int is not large enough to store the value. Note that you should end
the value with an "L":
• Example:

long myNum = 15000000000L;


System.out.println(myNum);
Floating Point Types

• You should use a floating point type whenever you need a number
with a decimal, such as 9.99 or 3.14515.
• Float
• The float data type can store fractional numbers from 3.4e−038 to
3.4e+038. Note that you should end the value with an "f":
• Example:

float myNum = 5.75f;


System.out.println(myNum);
• Double
• The double data type can store fractional numbers from 1.7e−308 to
1.7e+308. Note that you should end the value with a "d":
• Example:

double myNum = 19.99d;


System.out.println(myNum);
• Use float or double?

• The precision of a floating point value indicates how many digits the
value can have after the decimal point. The precision of float is only
six or seven decimal digits, while double variables have a precision of
about 15 digits. Therefore it is safer to use double for most
calculations.
Scientific Numbers

• A floating point number can also be a scientific number with an "e" to


indicate the power of 10:
• Example

float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
Booleans

• A boolean data type is declared with the boolean keyword and can
only take the values true or false:
• Example

boolean isJavaFun = true;


boolean isFishTasty = false;
System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs false
Characters

• The char data type is used to store a single character. The character
must be surrounded by single quotes, like 'A' or 'c':
• Example

char myGrade = 'B';


System.out.println(myGrade);
• Alternatively, you can use ASCII values to display certain characters:
• Example

char myVar1 = 65, myVar2 = 66, myVar3 = 67;


System.out.println(myVar1);
System.out.println(myVar2);
System.out.println(myVar3);
Strings

• The String data type is used to store a sequence of characters (text).


String values must be surrounded by double quotes:
• Example

String greeting = "Hello World";


System.out.println(greeting);
Non-Primitive Data Types
• Non-primitive data types are called reference types because they refer to objects.
• The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and is not defined by Java (except for String).
• Non-primitive types can be used to call methods to perform certain operations,
while primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types starts
with an uppercase letter.
• The size of a primitive type depends on the data type, while non-primitive types
have all the same size.

• Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.


Java Type Casting
• Java Type Casting:
Type casting is when you assign a value of one primitive data type to
another type.

• In Java, there are two types of casting:

• Widening Casting (automatically) - converting a smaller type to a larger type


size
byte -> short -> char -> int -> long -> float -> double

• Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte
Widening Casting

Example:

public class Main {


public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting

Example

public class Main {


public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}
Java Operators
Java divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Arithmetic Operators
• Example:
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x + y);
}
}
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x - y);
}
}
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x * y);
}
}
public class Main {
public static void main(String[] args) {
int x = 12;
int y = 3;
System.out.println(x / y);
}
}
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 2;
System.out.println(x % y);
}
}
• Write a program in a single program use +,-,*,/,% operators using two
variables.
Increment operators (++)
• Pre-increment operators in Java (++a)

• First, the value of the variable a incremented by 1 and store in the memory
location of variable a.
• Second, the value of variable a assign to the variable x.
public class Main {
public static void main(String[] args) {
int x = 5;
++x;
System.out.println(x);
}
}
public class GFG {
public static void main(String[] args)
{

int a = 10;
int b = ++a;

// Printing value inside variable


System.out.println(b);
}
}
Output

11
public class GFG {
public static void main(String[] args)
{
// Declaring and initializing variable
int a = 10;

int b = ++a;

// This is change made in above program


// which reflects error during compilation
b = 10 ++;

// Printing its value


System.out.println(b);
}
}
• Post-increment operators in Java (a++)
• First, the value of the variable a will assign to the variable x.
• Second, the value of the variable a will be incremented by 1 and
store in the memory location of the variable a.
class PostIncrementOperator{
public static void main(String[] args) {
int a, x;
a = 10;
x = a++;
System.out.println("a: "+a);
System.out.println("x: "+x);
}
}

Output:-
a: 11
x: 10
• Decrement Operators ( -- )
• Pre-decrement operator in Java ( --a )
• First, the value of a decremented by 1 and store in the memory
location of variable a.
• Second, the value of the variable a assigned to the variable x.
class PreDecrementOperator{
public static void main(String[] args) {
int a, x;
a = 10;
x = --a;
System.out.println("a: "+a);
System.out.println("x: "+x);
}
}

Output:-
x: 9
y: 9
public class Main {
public static void main(String[] args) {
int x = 5;
--x;
System.out.println(x);
}
}
• Post-decrement operator in Java ( a-- )
• First, value of variable a will assign to the variable x.
• Second, the value of a decremented by 1 and store in the memory
location of the variable a.
class PostDecrementOperator{
public static void main(String[] args) {
int a, x;
a = 10;
x = a--;
System.out.println("a: "+a);
System.out.println("x: "+x);
}
}

Output:-
a: 9
x: 10
Java Comparison Operators
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x == y); // returns false because 5 is not equal to 3
}
}
Output: False
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x != y); // returns true because 5 is not equal to 3
}
}
Output: true
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x > y); // returns true because 5 is greater than 3
}
}
Output: true
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 3;
System.out.println(x >= y); // returns true because 5 is greater, or
equal, to 3
}
}
Output: true
Java Logical Operators
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(x > 3 && x < 10); // returns true because 5 is
greater than 3 AND 5 is less than 10
}
}
Output: true
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(x > 3 || x < 4); // returns true because one of the
conditions are true (5 is greater than 3, but 5 is not less than 4)
}
}
Output: true
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(!(x > 3 && x < 10)); // returns false because ! (not)
is used to reverse the result
}
}
Output: false
Java Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
Example

int x = 10;
public class Main {
public static void main(String[] args) {
int x = 5;
x += 3;
System.out.println(x);
}
}
Output :8
public class Main {
public static void main(String[] args) {
int x = 5;
x -= 3;
System.out.println(x);
}
}
public class Main {
public static void main(String[] args) {
int x = 5;
x %= 3;
System.out.println(x);
}
}
// returns the remainder of the two numbers after division.
(/=) operator:

This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the current
value of the variable on the left by the value on the right and then assigning the quotient to
the operand on the left.

Syntax:

num1 /= num2;

Example:

a /= 10
This means,
a = a / 10
class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 20, num2 = 10;

System.out.println("num1 = " + num1);


System.out.println("num2 = " + num2);

// Dividing & Assigning values


num1 /= num2;

// Displaying the assigned values


System.out.println("num1 = " + num1);
}
}
Output
num1 = 20
num2 = 10
num1 = 2
• Bitwise AND (&)
• It is a binary operator denoted by the symbol &. It returns 1 if and only if both bits are 1, else returns 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)
public class BAE
{
public static void main(String[] args)
{
int x = 9, y = 8;
// bitwise and
// 1001 & 1000 = 1000 = 8
System.out.println("x & y = " + (x & y));
}
}

Output

x&y=8
Bitwise OR (|)

This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input values,
i.e., if either of the bits is 1, it gives 1, else it shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)
Bitwise XOR (^)

This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input values,
i.e., if corresponding bits are different, it gives 1, else it shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)
Bitwise Complement (~)

This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement
representation of the input value, i.e., with all bits inverted, which means it makes
every 0 to 1, and every 1 to 0.

Example:

a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5

~ 0101
________
1010 = 10 (In decimal)
// Java program to illustrate
// bitwise operators // bitwise not
// ~0101=1010
public class operators { // will give 2's complement of 1010 = -6
public static void main(String[] args) System.out.println("~a = " + ~a);
{
// Initial values // can also be combined with
int a = 5; // assignment operator to provide shorthand
int b = 7; // assignment
// a=a&b
// bitwise and a &= b;
// 0101 & 0111=0101 = 5 System.out.println("a= " + a);
System.out.println("a&b = " + (a & b)); }
}
// bitwise or Output
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b)); a&b = 5
a|b = 7
// bitwise xor a^b = 2
// 0101 ^ 0111=0010 = 2 ~a = -6
System.out.println("a^b = " + (a ^ b)); a= 5
Java Left Shift Operator Example

public class OperatorExample{


public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}
Java Right Shift Operator Example

public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}
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
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:

10
12
12
10
Exercise
• Write a program to display any message:
• Length and breadth of a rectangle are 5 and 7 respectively. Write a
program to calculate the area and perimeter of the rectangle.
• Write a program to calculate the perimeter of a triangle having sides of
length 2,3 and 5 units.
• Write a program to add 8 to the number 2345 and then divide it by 3. Now,
the modulus of the quotient is taken with 5 and then multiply the resultant
value by 5. Display the final result.
• Now, solve the above question using assignment operators (eg. +=, -=, *=).
• Write a program to check if the two numbers 23 and 45 are equal.
Java Strings
Strings are used for storing text.

A String variable contains a collection of characters surrounded by


double quotes:
Example

Create a variable of type String and assign it a value:

String greeting = "Hello";


String Length

A String in Java is actually an object, which contain methods that can


perform certain operations on strings. For example, the length of a
string can be found with the length() method:
Example

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


System.out.println("The length of the txt string is: " + txt.length());
More String Methods

There are many string methods available, for example toUpperCase()


and toLowerCase():
Example

String txt = "Hello World";


System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"
Finding a Character in a String

The indexOf() method returns the index (the position) of the first
occurrence of a specified text in a string (including whitespace):
Example

String txt = "Please locate where 'locate' occurs!";


System.out.println(txt.indexOf("locate")); // Outputs 7
String Concatenation

The + operator can be used between strings to combine them. This is


called concatenation:
Example

String firstName = "John";


String lastName = “Patra";
System.out.println(firstName + " " + lastName);
Note that we have added an empty text (" ") to create a space between
firstName and lastName on print.
You can also use the concat() method to concatenate two strings:
Example

String firstName = "John ";


String lastName = "Doe";
System.out.println(firstName.concat(lastName));
Adding Numbers and Strings

Java uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:


Example

int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer/number)
If you add two strings, the result will be a string concatenation:
Example

String x = "10";
String y = "20";
String z = x + y; // z will be 1020 (a String)

If you add a number and a string, the result will be a string concatenation:
Example

String x = "10";
int y = 20;
String z = x + y; // z will be 1020 (a String)
Keywords
The Java programming language has total of 50 reserved keywords which have special meaning for
the compiler and cannot be used as variable names. Following is a list of Java keywords in
alphabetical order, click on an individual keyword to see its description and usage example.
abstract assert boolean break byte

case catch char class const

continue default do double else

enum extends final finally float

for goto if implements import

instanceof int interface long native

new package private protected public

return short static strictfp super

switch synchronized this throw throws

transient try void volatile while


• The following table shows the keywords grouped by category:

Category Keywords
Access modifiers private, protected, public
Class, method, abstract, class, extends, final, implements,
variable modifiers interface, native,new, static, strictfp, synchronized, transient,
volatile
Flow control break, case, continue, default, do,
else, for, if, instanceof, return,switch, while
Package control import, package
Primitive types boolean, byte, char, double, float, int, long, short
Error handling assert, catch, finally, throw, throws, try
Enumeration enum
Others super, this, void
Unused const, goto
Java Control Statements | Control Flow in Java

• 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.

Decision Making statements


• if statements
• switch statement
Loop statements
• do while loop
• while loop
• for loop
• for-each loop
Jump statements
• break statement
• continue statement
Decision-Making statements:

• As the name suggests, decision-making statements decide which


statement to execute and when. Decision-making statements
evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two
types of decision-making statements in Java, i.e., If statement and
switch statement.
1) If Statement:

• 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. In Java, there are four types of if-statements given below.

• Simple if statement
• if-else statement
• if-else-if ladder
• Nested if-statement
1) Simple if statement:

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
}
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");
}
}
}
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
2) if-else statement

The if-else statement


is an extension to the if-statement, which uses another block of code, i.e., else
block. The else block is executed if the condition of the if-block is evaluated as false.

Syntax:

if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
Exercise
• 1. Write a Java program to get a number from the user and print
whether it is positive or negative.
• Write a Java program to solve quadratic equations (use if, else if and
else)
• 3. Take three numbers and print the greatest number.
• 4. Write a Java program to find the number is even or odd.
• 5.Write a Java program that takes a year from user and print whether
that year is a leap year or not
public class Exercise1 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
int input=5;
if (input > 0)
{
System.out.println("Number is positive");
}
else if (input < 0)
{
System.out.println("Number is negative");
}
else
{
System.out.println("Number is zero");
}
}
}
public class Main { else if (determinant == 0) {
// two real and equal roots
public static void main(String[] args) { // determinant is equal to 0
// so -b + 0 == -b
// value a, b, and c root1 = root2 = -b / (2 * a);
double a = 2.3, b = 4, c = 5.6; System.out.format("root1 = root2 = %.2f;", root1);
double root1, root2; }

// calculate the determinant (b2 - 4ac) // if determinant is less than zero


double determinant = b * b - 4 * a * c; else {

// check if determinant is greater than 0 // roots are complex number and distinct
if (determinant > 0) { double real = -b / (2 * a);
double imaginary = Math.sqrt(-determinant) / (2 * a);
// two real and distinct roots System.out.format("root1 = %.2f+%.2fi", real, imaginary);
root1 = (-b + Math.sqrt(determinant)) / (2 * a); System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary);
root2 = (-b - Math.sqrt(determinant)) / (2 * a); }
}
System.out.format("root1 = %.2f and root2 = %.2f", root1, root2); }
}

// check if determinant is equal to 0


public class JavaExample{

public static void main(String[] args) {

int num1 = 10, num2 = 20, num3 = 7;

if( num1 >= num2 && num1 >= num3)


System.out.println(num1+" is the largest Number");

else if (num2 >= num1 && num2 >= num3)


System.out.println(num2+" is the largest Number");

else
System.out.println(num3+" is the largest Number");
}
}
//A Java Program to demonstrate the use of if-else statement.
//It is a program of odd and even number.
public class IfElseExample {
public static void main(String[] args) {
//defining a variable
int number=13;
//Check if the number is divisible by 2 or not
if(number%2==0){
System.out.println("even number");
}else{
System.out.println("odd number");
}
}
}
Leap Year Example:

A year is leap, if it is divisible by 4 and 400. But, not by 100.

public class LeapYearExample {


public static void main(String[] args) {
int year=2020;
if(((year % 4 ==0) && (year % 100 !=0)) || (year % 400==0)){
System.out.println("LEAP YEAR");
}
else{
System.out.println("COMMON YEAR");
}
}
}
Short Hand If...Else

• There is also a short-hand if else, which is known as the ternary


operator because it consists of three operands.

• It can be used to replace multiple lines of code with a single line, and
is most often used to replace simple if else statements:
• Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Example

int time = 20;


String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);
Java if-else-if ladder Statement

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Example: }
else if(marks>=80 && marks<90){
//Java Program to demonstrate the use of If else-if ladder. System.out.println("A grade");
//It is a program of grading system for fail, D grade, C grade, B }else if(marks>=90 && marks<100){
grade, A grade and A+.
System.out.println("A+ grade");
public class IfElseIfExample {
}else{
public static void main(String[] args) {
System.out.println("Invalid!");
int marks=65;
}
}
if(marks<50){
}
System.out.println("fail");
}
Output:
else if(marks>=50 && marks<60){
System.out.println("D grade");
C grade
}
else if(marks>=60 && marks<70){
System.out.println("C grade");
}
else if(marks>=70 && marks<80){
System.out.println("B grade");
public class PositiveNegativeExample {
public static void main(String[] args) {
int number=-13;
if(number>0){
System.out.println("POSITIVE");
}else if(number<0){
System.out.println("NEGATIVE");
}else{
System.out.println("ZERO");
}
}
}

Output:

NEGATIVE
Java Nested if statement

The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.

Syntax:

if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
Example:

//Java Program to demonstrate the use of Nested If Statement.


public class JavaNestedIfExample {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=20;
int weight=80;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
}
}
}}
//Java Program to demonstrate the use of Nested If Statement.
public class JavaNestedIfExample2 {
public static void main(String[] args) {
//Creating two variables for age and weight
int age=25;
int weight=48;
//applying condition on age and weight
if(age>=18){
if(weight>50){
System.out.println("You are eligible to donate blood");
} else{
System.out.println("You are not eligible to donate blood");
}
} else{
System.out.println("Age must be greater than 18");
}
} }
Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement. The switch statement works with byte, short, int, long, enum types, String.
Points to Remember
• There can be one or N number of case values for a switch expression.
• The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.
• The case values must be unique. In case of duplicate value, it renders compile-time error.
• The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and
string.
• Each case statement can have a break statement which is optional. When control reaches to
the break statement, it jumps the control after the switch expression. If a break statement is not
found, it executes the next case.
• The case value can have a default label which is optional.
Syntax:

switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
Example:

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");
}
}
}
//Java Program to demonstrate the example of Switch statement case 6: monthString="6 - June";
//where we are printing month name for the given number break;
public class SwitchMonthExample { case 7: monthString="7 - July";
public static void main(String[] args) { break;
//Specifying month number case 8: monthString="8 - August";
int month=7; break;
String monthString=""; case 9: monthString="9 - September";
//Switch statement break;
switch(month){ case 10: monthString="10 - October";
//case statements within the switch block break;
case 1: monthString="1 - January"; case 11: monthString="11 - November";
break; break;
case 2: monthString="2 - February"; case 12: monthString="12 - December";
break; break;
case 3: monthString="3 - March"; default:System.out.println("Invalid Month!");
break; }
case 4: monthString="4 - April"; //Printing month of the given number
break; System.out.println(monthString);
case 5: monthString="5 - May"; }
break; }
public class SwitchVowelExample { case 'A':
public static void main(String[] args) { System.out.println("Vowel");
char ch='O'; break;
switch(ch) case 'E':
{ System.out.println("Vowel");
case 'a': break;
System.out.println("Vowel"); case 'I':
break; System.out.println("Vowel");
case 'e': break;
System.out.println("Vowel"); case 'O':
break; System.out.println("Vowel");
case 'i': break;
System.out.println("Vowel"); case 'U':
break; System.out.println("Vowel");
case 'o': break;
System.out.println("Vowel"); default:
break; System.out.println("Consonant");
case 'u': }
System.out.println("Vowel"); }
break; }
//Java Switch Example where we are omitting the
//break statement
public class SwitchExample2 {
public static void main(String[] args) {
int number=20;
//switch expression with int value
switch(number){
//switch cases without break statements
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}
//Java Program to demonstrate the case "Beginner": level=1;
use of Java Switch break;
//statement with String case "Intermediate": level=2;
public class SwitchStringExample { break;
public static void main(String[] args) case "Expert": level=3;
{
break;
//Declaring String variable
default: level=0;
String levelString="Expert";
break;
int level=0;
}
//Using String in Switch
expression System.out.println("Your Level is:
"+level);
switch(levelString){
}
//Using String Literal in Switch
case }
Java Nested Switch Statement
//Java Program to demonstrate the use of Java Nested break; case 4:
Switch
case 'M': switch( branch )
public class NestedSwitchExample {
System.out.println("Drawing, Manufacturing {
public static void main(String args[]) Machines");
case 'C':
{ break;
System.out.println("Data Communication
//C - CSE, E - ECE, M - Mechanical } and Networks, MultiMedia");
char branch = 'C'; break; break;
int collegeYear = 4; case 3: case 'E':
switch( collegeYear ) switch( branch ) System.out.println("Embedded System,
Image Processing");
{ {
break;
case 1: case 'C':
case 'M':
System.out.println("English, Maths, Science"); System.out.println("Computer Organization,
MultiMedia"); System.out.println("Production Technology,
break; Thermal Engineering");
break;
case 2: break;
case 'E':
switch( branch ) }
System.out.println("Fundamentals of Logic
{ Design, Microelectronics"); break;
case 'C': break; }
System.out.println("Operating System, Java, case 'M': }
Data Structure");
System.out.println("Internal Combustion }
break; Engines, Mechanical Vibration");
case 'E': break;
System.out.println("Micro processors, Logic }
switching theory");
break;
• Loops in Java

• The Java for loop is used to iterate a part of the program several
times. If the number of iteration is fixed, it is recommended to use for
loop.

• There are three types of for loops in Java.


Java Simple for Loop

• A simple for loop is the same as C/C++. We can initialize the variable, check
condition and increment/decrement value. It consists of four parts:
• Initialization: It is the initial condition which is executed once when the
loop starts. Here, we can initialize the variable, or we can use an already
initialized variable. It is an optional condition.
• Condition: It is the second condition which is executed each time to test
the condition of the loop. It continues execution until the condition is false.
It must return boolean value either true or false. It is an optional condition.
• Increment/Decrement: It increments or decrements the variable value. It
is an optional condition.
• Statement: The statement of the loop is executed each time until the
second condition is false.
Syntax:

for(initialization; condition; increment/decrement){


//statement or code to be executed
}
//Java Program to demonstrate the example of for loop
//which prints table of 1
public class ForExample {
public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=10;i++){
System.out.println(“this is table 1\n”);
System.out.println(i);
}
}
}
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x + 1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
This will produce the following result −
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Java Nested for Loop

public class NestedForExample { Output:


public static void main(String[] args) { 11
//loop of i 12
for(int i=1;i<=3;i++){ 13
//loop of j 21
for(int j=1;j<=3;j++){ 22
System.out.println(i+" "+j); 23
}//end of i 31
}//end of j 32
} 33
}
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:

*
**
***
****
*****
ForExample.java

//Java program to demonstrate the use of infinite for loop


//which prints an statement
public class ForExample {
public static void main(String[] args) {
//Using no condition in for loop
for(;;){
System.out.println("infinitive loop");
}
}
}

Output:

infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
1.Write a program to print even values between 0 and 10:

2.Write a program to print pattern like this.

******
*****
****
***
**
*
3. . Write a program to print pattern like this.
12
23
44
56
78
1.public class even {
public static void main(String[] args) {

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


System.out.println(i);
}
2.public class PyramidExample2 {
public static void main(String[] args) {
int term=6;
for(int i=1;i<=term;i++){
for(int j=term;j>=i;j--){
System.out.print("* ");
}
System.out.println();//new line
}
}
}
3.//Java For-each loop example which prints the
//elements of the array
public class ForEachExample {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Java While Loop

The Java while loop is used to iterate a part of the program repeatedly
until the specified Boolean condition is true. As soon as the Boolean
condition becomes false, the loop automatically stops.

The while loop is considered as a repeating if statement. If the number


of iteration is not fixed, it is recommended to use the while loop.
Syntax:

while (condition){
//code to be executed
I ncrement / decrement statement
}
Example:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}

Output:
1
2
3
4
5
6
7
8
9
10
Example
public class Test {

public static void main(String args[]) {


int x = 10;

while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

This will produce the following result −


Output

value of x : 10
value of x : 11
value of x : 12
The Do/While Loop

• The do/while loop is a variant of the while loop. This loop will execute the
code block once, before checking if the condition is true, then it will repeat
the loop as long as the condition is true.

Syntax

do {
// code block to be executed
}
while (condition);
Example

int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
Output:

1
2
3
4
5
6
7
8
9
10
Java Break Statement

When a break statement is encountered inside a loop, the loop is immediately


terminated and the program control resumes at the next statement following the
loop.

The Java break statement is used to break loop or switch


statement. It breaks the current flow of the program at specified condition. In case
of inner loop, it breaks only inner loop.

We can use Java break statement in all types of loops such as for loop
, while loop
and do-while loop
//Java Program to demonstrate the use of break statement
//inside the for loop.
public class BreakExample {
public static void main(String[] args) {
//using for loop
for(int i=1;i<=10;i++){
if(i==5){
//breaking the loop
break;
}
System.out.println(i);
}
}
}

Output:

1
2
3
4
Java Continue Statement

The continue statement is used in loop control structure when you need to
jump to the next iteration of the loop immediately. It can be used with for
loop or while loop.

The Java continue statement is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition. In case of an inner loop, it continues the inner loop only.

We can use Java continue statement in all types of loops such as for loop,
while loop and do-while loop.
//Java Program to demonstrate the use of
continue statement
//inside the for loop.
Output:
public class ContinueExample {
public static void main(String[] args) { 1
//for loop
2
for(int i=1;i<=10;i++){ 3
if(i==5){ 4
//using continue statement
6
continue;//it will skip the rest statement 7
} 8
System.out.println(i);
9
} 10
}
}
Java Methods

• A method is a block of code which only runs when it is called.

• You can pass data, known as parameters, into a method.

• Methods are used to perform certain actions, and they are also
known as functions.

• Why use methods? To reuse code: define the code once, and use it
many times.
Create a Method

• A method must be declared within a class. It is defined with the name of the method,
followed by parentheses (). Java provides some pre-defined methods, such as
System.out.println(), but you can also create your own methods to perform certain
actions:
• Example

• Create a method inside Main:

• public class Main {


• static void myMethod() {
• // code to be executed
• }
• }
• static void myMethod()
• myMethod() is the name of the method
• static means that the method belongs to the Main class and not an
object of the Main class. You will learn more about objects and how
to access methods through objects later in this tutorial.
• void means that this method does not have a return value. You will
learn more about return values later in this chapter
Call a Method
• To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
• In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main, call the myMethod() method:

public class Main {


static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}

// Outputs "I just got executed!"


• A method can also be called multiple times:
Example

public class Main {


static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
myMethod();
myMethod();
}
}

// I just got executed!


// I just got executed!
// I just got executed!
Java Method Parameters

• Parameters and Arguments

• Information can be passed to methods as parameter. Parameters act


as variables inside the method.

• Parameters are specified after the method name, inside the


parentheses. You can add as many parameters as you want, just
separate them with a comma.
The following example has a method that takes a String called fname as parameter. When the method is called, we pass along a first
name, which is used inside the method to print the full name:
Example

public class Main {


static void myMethod(String fname) {
System.out.println(fname + " Refsnes");
}

public static void main(String[] args) {


myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
When a parameter is passed to the method, it is called an argument. So, from the example above: fname is a parameter, while Liam,
Jenny and Anja are arguments.
Multiple Parameters

You can have as many parameters as you like:


Example

public class Main {


static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}

public static void main(String[] args) {


myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}

// Liam is 5
// Jenny is 8
// Anja is 31
Return Values

The void keyword, used in the examples above, indicates that the method should not return a value.
If you want the method to return a value, you can use a primitive data type (such as int, char, etc.)
instead of void, and use the return keyword inside the method:
Example

public class Main {


static int myMethod(int x) {
return 5 + x;
}

public static void main(String[] args) {


System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)
This example returns the sum of a method's two parameters:
Example:

public class Main {


static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


System.out.println(myMethod(5, 3));
}
}
// Outputs 8 (5 + 3)
You can also store the result in a variable (recommended, as it is easier to read and maintain):
Example

public class Main {


static int myMethod(int x, int y) {
return x + y;
}

public static void main(String[] args) {


int z = myMethod(5, 3);
System.out.println(z);
}
}
// Outputs 8 (5 + 3)
• A Method with If...Else
• It is common to use if...else statements inside methods:
Example
public class Main {
// Create a checkAge() method with an integer variable called age
static void checkAge(int age) {
// If age is less than 18, print "access denied"
if (age < 18) {
System.out.println("Access denied - You are not old enough!");
// If age is greater than, or equal to, 18, print "access granted"
} else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(20); // Call the checkAge method and pass along an age of 20
}
}

// Outputs "Access granted - You are old enough!"


Method Overloading

• With method overloading, multiple methods can have the same


name with different parameters:
• Example

int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Consider the following example, which has two methods that add numbers of different type:
Example
static int plusMethodInt(int x, int y) {
return x + y;
}

static double plusMethodDouble(double x, double y) {


return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
Instead of defining two methods that should do the same thing, it is better to overload one.

In the example below, we overload the plusMethod method to work for both int and double:
Example

static int plusMethod(int x, int y) {


return x + y;
}

static double plusMethod(double x, double y) {


return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);

Note: Multiple methods can have the same name as long as the number and/or type of parameters are different.
Exercise
• Write a program with a method named getTotal that accepts two integers
as an argument and return its sum. Call this method from main( ) and print
the results.
• Write a method named isEven that accepts an int argument. The method
should return true if the argument is even, or false otherwise.
• A prime number is a number that is evenly divisible only by itself and 1. For
example, the number 5 is prime because it can be evenly divided only by 1
and 5. The number 6, however, is not prime because it can be divided
evenly by 1, 2, 4, and 6.Write a method named isPrime, which takes an
integer as an argument and returns true if the argument is a prime number,
or false otherwise. Also write main method that displays prime numbers
between 1 to 500.
class Prime /*Simple prime program*/
{
public static void main(String[] args)
{
int n=9;
boolean prime =true;
for(int i=2;i<n; i++)
{
if(n%i ==0)
{
prime=false;
break;
}
}
System.out.println(prime);
}
public class PrimeNumbers
{
public static void main(String[] args)
{
for(int i = 1; i <= 500; i++)
{
if(isPrime(i))
{
System.out.print(i + " "); } } }
public static boolean isPrime(int number)
{
for(int j = 2; j < number; j++)
{
if(number % j== 0)
{
return false;
}
}
return true;
}
}

You might also like