0% found this document useful (0 votes)
6 views40 pages

IP Notes Java

Java is a versatile, object-oriented programming language widely used for various applications, including Android development and enterprise software. Its key features include simplicity, robustness, security, platform independence, and support for multi-threading. The document also covers Java's environment, program structure, data types, and constants, providing a comprehensive overview of its capabilities and usage.

Uploaded by

prakashmcsc
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)
6 views40 pages

IP Notes Java

Java is a versatile, object-oriented programming language widely used for various applications, including Android development and enterprise software. Its key features include simplicity, robustness, security, platform independence, and support for multi-threading. The document also covers Java's environment, program structure, data types, and constants, providing a comprehensive overview of its capabilities and usage.

Uploaded by

prakashmcsc
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/ 40

Internet Programming

Introduction :
⮚ Java is a general-purpose, class-based, object-oriented programming language
⮚ It is widely used for developing Java applications in laptops, data centers, game consoles,
scientific supercomputers, cell phones, etc.
⮚ Here are some important Java applications:

● It is used for developing Android Apps


● Helps you to create Enterprise Software
● Wide range of Mobile java Applications
● Scientific Computing Applications
● Use for Big Data Analytics
● Java Programming of Hardware devices
● Used for Server-Side Technologies like Apache, JBoss, GlassFish, etc.

Features of Java
A list of most important features of Java language is given below
✔ Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand. Complex and ambiguous concepts of C++ are either eliminated or re-
implemented in Java. For example, pointer and operator overloading are not used in Java.

✔ Object-Oriented: In Java, everything is in the form of the object. It means it has some
data and behaviour. A program must have at least one class and object.
✔ Robust: Java makes an effort to check error at run time and compile time. It uses a strong
memory management system called garbage collector. Exception handling and garbage
collection features make it strong.

✔ Secure: Java is a secure programming language because it has no explicit pointer and
programs runs in the virtual machine. Java contains a security manager that defines the
access of Java classes.

✔ Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any machine.

✔ Portable: Java Byte code can be carried to any platform. No implementation-dependent


features. Everything related to storage is predefined, for example, the size of primitive
data types.

✔ High Performance: Java is an interpreted language. Java enables high performance with
the use of the Just-In-Time compiler.

✔ Distributed: Java also has networking facilities. It is designed for the distributed
environment of the internet because it supports TCP/IP protocol. It can run over the
internet. EJB and RMI are used to create a distributed system.

✔ Multi-threaded: Java also supports multi-threading. It means to handle more than one
job a time.

COMPARISON OF JAVA WITH C AND C++

S.N. Basis C C++ Java


1 Origin The C language is The C++ language The Java programming language is
based on BCPL. is based on the C based on both C and C++.
language.

2 Programming It is a procedural It is an object- It is a pure object-oriented programming


Pattern language. oriented language.
programming
language.

3 Approach It uses the top- It uses the bottom- It also uses the bottom-up approach.
down approach. up approach.

4 Dynamic or It is a static It is also a static It is a dynamic programming language.


Static programming programming
language. language.

5 Code The code is The code is The code is executed by the JVM.
Execution executed directly. executed directly.

6 Platform It is platform It is platform It is platform-independent because of


Dependency dependent. dependent. byte code.

7 Translator It uses a compiler It also uses a Java uses both compiler and interpreter
only to translate compiler only to and it is also known as an interpreted
the code into translate the code language.
machine language. into machine
language.

8 File It generates the It generates .exe It generates .class file.


Generation .exe, and .bak, file.
files.
9 Number of There There There
Keyword are 32 keywords in are 60 keywords in are 52 keywords
the C language. the C++ language. in the Java
language.

10 Source File The source file has The source file has The source file has a .java extension.
Extension a .c extension. a .cpp extension.

Java and Internet

Java and Internet: Java is strongly associated with the Internet. Internet users can use Java
to create applet programs and run them locally using a "Java-enabled browser" such as HotJava.
They can also use a Java-enabled browser to download an applet located on a computer
anywhere in the Internet and run it on his local computer. In fact, Java applets have made the
Internet a true extension of the storage system of the local computer.
Java Environment
✔ Java Development Kit
✔ Java Standard Library
✔ Java runtime environment

Java Development Kit


� The java Development Kit is Collection of Tools its used for developing running a java
Programs.
⮚ Applet viewer (Viewing applet )
⮚ Javac (Compiler )
⮚ Java (interapreter)
⮚ Javap (Disassembler)
⮚ Javah (C Header Files )
⮚ Jdb (Debugger )
Java Standard Library
� Language Support Package: A collection of classes and methods required for
implementing basic features of Java .
� Utilities Package: A collection of classes to provide utility functions such as date and
time functions.
� Input/output Package: Acollection of classes required for input/output manipulation.
� Networking Package: A collection of classes for communicating with other computers
via Internet.
� AWT Package: The Abstract Window Tool Kit package contains classes that
implements platform-independent graphical user interface.
� Applet Package: This includes a set of classes that allows us to create Java applets.
Java runtime environment
⮚ Java virtual machine
⮚ Runtime class libraries
⮚ User interface toolkits
⮚ Deployment technologies
⮚ java plug in
✔ java web start

Java Processing and Execution


� Begin with Java source code in text files: Model.java
� A Java source code compiler produces Java byte code
⮚ Outputs one file per class: Model.class
⮚ May be standalone or part of an IDE
� A Java Virtual Machine loads and executes class files
⮚ May compile them to native code (e.g., x86) internally
Java Program structure
Documentation Section

✔ The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program.
✔ The information includes the author's name, date of creation, version, program name,
company name, and description of the program. It improves the readability of the
program.
✔ To write the statements in the documentation section, we use comments. The comments
may be single-line, multi-line
✔ Single-line Comment: It starts with a pair of forwarding slash (//).
For example://First Java Program

✔ Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols.
For example:
/*It is an example of
multiline comment*/

Java Tokens

✔ The Java compiler breaks the line of code into text (words) is called Java tokens.
✔ These are the smallest element of the Java program.
✔ These tokens are separated by the delimiters. It is useful for compilers to detect errors.

1. token <= identifier | keyword | separator | operator | literal | comment


For example, consider the following code.

public class Demo


{
public static void main(String args[])
{
System.out.println("javatpoint");
}
}

The Java compiler translates these tokens into Java bytecode.Thebytecodes are executed inside
the interpreted Java environment.

Types of Tokens

Java token includes the following:

o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords:
These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the
following keywords:

01.abstract 02. boolean 03. byte 04. break 05. class

Identifier:
Identifiers are used to name a variable, constant, function, class, and array. It is usually
defined by the user. It uses letters, underscores, or a dollar sign as the first character.

The label is also known as a special kind of identifier

There are some rules to declare identifiers are:

o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot
start with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
Literals:
In programming literal is a notation that represents a fixed value (constant) in the source
code. Java provides five types of literals are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean
Implementing a java program
Java is one of the most popular and widely used programming languages and platforms.
Java is fast, reliable, and secure. Java is used in every nook and corner from desktop to web
applications.
Steps to Implement Java Program

Implementation of a Java application program involves the following step.

● Creating the program


● Compiling the program
● Running the program

1. Creating Programs in Java

We can create a program using Text Editor (Notepad) or IDE (NetBeans)

class Test
{
public static void main(String []args)
{
System.out.println("My First Java Program.");
}
};

2. Compiling the Program in Java

To compile the program, we must run the Java compiler (javac), with the name of the source file
on the ―command prompt‖ like as follows
If everything is OK, the ―javac‖ compiler creates a file called ―Test.class‖ containing the byte
code of the program.

3.Running the java program

.The process of Java programming can be simplified in three steps:

● Create the program by typing it into a text editor and saving it to a file – HelloWorld.java.
● Compile it by typing ―javac HelloWorld.java‖ in the terminal window.
● Execute (or run) it by typing ―java HelloWorld‖ in the terminal window.

classHelloWorld {
publicstaticvoidmain(String args[])
{
System.out.println("Hello, World");
}
}

Output
Hello, World

Java Virtual Machine

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM

It is:

1. A specification where working of Java Virtual Machine is specified. But


implementation provider is independent to choose the algorithm. Its implementation
has been provided by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.
4. The JVM performs following operation:

⮚ Loads code
⮚ Verifies code
⮚ Executes code
⮚ Provides runtime environment
JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

Constants

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.

How to declare constant in Java?

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 letter.
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;


Where static and final are the non-access modifiers. The double is the data type and
PRICE is the identifier name in which the value 432.78 is assigned.

Variables

A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
Example

public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

Data Types

Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language.
There are 8 types of primitive data types;
1. boolean data type
2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type
7. float data type
8. double data type
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

Double 0.0d 8 byte

Boolean Data Type:


The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.
Example:

1. Boolean one = false

Byte Data Type

The byte data type is an example of primitive data type.


Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.

Example:

1. byte a = 10, byte b = -20

Short Data Type

The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive).
Example:

1. short s = 10000, short r = -5000

Int Data Type

The int data type is a 32-bit signed two's complement integer.


The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example:

1. int a = 100000, int b = -200000

Long Data Type


● The long data type is a 64-bit two's complement integer.
● The long data type is used when you need a range of values more than those provided by
int.
Example:

1. long a = 100000L, long b = -200000L

Float Data Type

● The float data type is a single-precision 32-bit IEEE 754 floating point
● It is recommended to use a float (instead of double) if you need to save memory in large
arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example:

1. float f1 = 234.5f

Double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited
Example:

1. double d1 = 12.3

Char Data Type

The char data type is a single 16-bit Unicode character.


Example:

1. char letterA = 'A'


Scope of Variables
.
Scope of variable defines how a specific variable is accessible within the program or
across classes.In programming, a variable can be declared and defined inside a class, method, or
block. It defines the scope of the variable i.e. the visibility or accessibility of a variable. Variable
declared inside a block or method are not visible to outside

Example
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;
}
}

Type casting

In Java, type casting is a method or process that converts a data type into another data
type in both ways manually and automatically. The automatic conversion is done by the compiler
and manual conversion performed by the programmer.
Types of Type Casting

There are two types of type casting:

o Widening Type Casting


o Narrowing Type Casting

Widening Type Casting

Converting a lower data type into a higher one is called widening type casting. It is also
known as implicit conversion or casting down.

o Both data types must be compatible with each other.


o The target type must be larger than the source type.
byte -> short -> char -> int -> long -> float -> double
Example:
publicclass Main {
publicstatic void main(String[] args) {
intmyInt = 9;
doublemyDouble = myInt; // Automatic casting: int to double
System.out.println(myInt);
System.out.println(myDouble);
}
}
Output
9
9.0
Narrowing Type Casting

Converting a higher data type into a lower one is called narrowing type casting. I

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

publicclassMain{
publicstaticvoidmain(String[]args){
doublemyDouble=9.78d;
intmyInt=(int)myDouble;
System.out.println(myDouble);
System.out.println(myInt);
}
}
output
9,78
9

is also known as explicit conversion or casting up


Operators and expressions
Operators are symbols that perform operations on variables and values. For example, + is an
operator used for addition, while * is also an operator used for multiplication.
Operators in Java can be classified into 5 types:

1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Unary Operators
6. Bitwise Operators
7. Ternary Operators
8. Special Operators

Java Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on variables and data. For
example, a + b;Here, the + operator is used to add two variables a and b. Similarly, there are
various other arithmetic operators in Java.

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after division)


Example:

classMain {
publicstaticvoidmain(String[] args) {

// declare variables
int a = 12, b = 5;

// addition operator
System.out.println("a + b = " + (a + b));

// subtraction operator
System.out.println("a - b = " + (a - b));

// multiplication operator
System.out.println("a * b = " + (a * b));

// division operator
System.out.println("a / b = " + (a / b));

// modulo operator
System.out.println("a % b = " + (a % b));
}
}
Output:

a + b = 17
a-b=7
a * b = 60
a/b=2
a%b=2

Java Assignment Operators

Assignment operators are used in Java to assign values to variables

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

Example:

classMain {
publicstaticvoidmain(String[] args) {

// create variables
int a = 4;
intvar;

// assign value using =


var = a;
System.out.println("var using =: " + var);

// assign value using =+


var += a;
System.out.println("var using +=: " + var);

// assign value using =*


var *= a;
System.out.println("var using *=: " + var);
}
}

Output:
var using =: 4
var using +=: 8
var using *=: 32

Java Relational Operators


Relational operators are used to check the relationship between two operands.

Operator Description Example

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false

<= Less Than or Equal To 3 <= 5 returns true

Example:

classMain {
publicstaticvoidmain(String[] args) {

// create variables
int a = 7, b = 11;

// value of a and b
System.out.println("a is " + a + " and b is " + b);

// == operator
System.out.println(a == b); // false

// != operator
System.out.println(a != b); // true

// > operator
System.out.println(a > b); // false

// < operator
System.out.println(a < b); // true

// >= operator
System.out.println(a >= b); // false

// <= operator
System.out.println(a <= b); // true
}
}
OUTPUT:
a is 7 b is 11
false
true
false
true
false
true

Java Logical Operators

Logical operators are used to check whether an expression is true or false. They are used in
decision making.

Operator Example Meaning


true only if
&& (Logica expression1 && expression
both expression1 and expression2 are tru
l AND) 2
e

|| (Logical true if
expression1 || expression2
OR) either expression1 or expression2 is true

! (Logical
!expression true if expression is false and vice versa
NOT)

Example:

classMain {
publicstaticvoidmain(String[] args) {

// && operator
System.out.println((5>3) && (8>5)); // true
System.out.println((5>3) && (8<5)); // false

// || operator
System.out.println((5<3) || (8>5)); // true
System.out.println((5>3) || (8<5)); // true
System.out.println((5<3) || (8<5)); // false

// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5>3)); // false
}
}
OUTPUT:
true
false
true
true
false
true
false
Java Unary Operators
Unary operators are used with only one operand. For example, ++ is a unary operator that
increases the value of a variable by 1. That is, ++5 will return 6.
Different types of unary operators are:
Operator Meaning

+ Unary plus: not necessary to use since numbers are positive without using it

- Unary minus: inverts the sign of an expression

++ Increment operator: increments value by 1

-- Decrement operator: decrements value by 1

! Logical complement operator: inverts the value of a boolean

Increment and Decrement Operators

Java also provides increment and decrement operators: ++ and -- respectively. ++ increases the
value of the operand by 1, while -- decrease it by 1. For example,

intnum = 5;

// increase num by 1
++num;

Here, the value of num gets increased to 6 from its initial value of 5.

Example:

classMain {
publicstaticvoidmain(String[] args) {

// declare variables
int a = 12, b = 12;
int result1, result2;

// original value
System.out.println("Value of a: " + a);

// increment operator
result1 = ++a;
System.out.println("After increment: " + result1);
System.out.println("Value of b: " + b);

// decrement operator
result2 = --b;
System.out.println("After decrement: " + result2);
}
}
output:

value of a is:12

after increment:13

value of b is:12

after decrement:11

JAVA BITWISE OPERATORS

The Java Bitwise Operators allow access and modification of a particular bit inside a section of
the data. It can be applied to integer types and bytes, and cannot be applied to float and double.

OPERATOR MEANING

&Binary AND operator

The Java Bitwise Operators allow access and modification of a particular bit inside a section of
the data. It can be applied to integer types and bytes, and cannot be applied to float and double.
The Java Bitwise Operators allow access and modification of a particular bit inside a section of
the data. It can be applied to integer types and bytes, and cannot be applied to float and double.
The Java Bitwise Operators allow access and modification of a particular bit inside a section of
the data. It can be applied to integer types and bytes, and cannot be applied to float and double.

| Binary OR operator

<< Binary LEFT SHIFT operator

>> Binary RIGHT SHIFT operator

EXAMPLE:

publicclassbitwiseop {
publicstaticvoidmain(String[] args) {
//Variables Definition and Initialization
int num1 =30, num2 =6, num3 =0;

//Bitwise AND
System.out.println("num1 & num2 = "+ (num1 & num2));

//Bitwise OR
System.out.println("num1 | num2 = "+ (num1 | num2) );

//Binary Left Shift Operator


num3 = num1 <<2;
System.out.println("num1 << 1 = "+ num3 );

//Binary Right Shift Operator


num3 = num1 >>2;
System.out.println("num1 >> 1 = "+ num3 );

}
}

OUTPUT:
num1 & num2 = 6
num1 | num2 = 30
num1 << 1 = 120
num1 >>1 = 7

Ternary Operators:

A ternary operator evaluates the test condition and executes a block of code based on the result
of the condition.

Its syntax is:

condition ?expression1 : expression2;

Here, condition is evaluated and


● if condition is true, expression1 is executed.
● And, if condition is false, expression2 is executed.

Example:

importjava.util.Scanner;
classMain {
publicstaticvoidmain(String[] args) {
Scanner input = newScanner(System.in);
System.out.println("Enter your marks: ");
double marks = input.nextDouble();

String result = (marks >40) ?"pass" : "fail";

System.out.println("You " + result + " the exam.");


input.close();
}
}
Output:

Enter your marks:


75
You pass the exam.

The ternary operator takes 3 operands (condition, expression1, and expression2). Hence, the
name ternary operator.
SPECIAL OPERATORS
Java supports some special operators of interest such as instance of operator and
member selection operator(.)

INSTANCE OF OPERATOR
1. The instance of is an object reference operator and returns true if the object on the
left-hand side is an instances if the class given in the right-hand side.
2.This operator allows us to determine whether the object belongs to a particulars class
or not.
Example:
Person instance of student
Is true if the object person belongs to the class student : otherwise it is false.

DOT OPERATOR
The dot operator (.) is used to access the instance variables and methods of class objects,
Examples
Personl.age # Reference to the variable stage
Personal.salary # Reference to the method salary( )
Decision Making
Decision making in Java executes a particular segment of code based on the result of a
booleancondition.It is important because conditions define the flow of programs and the output
of a particular program.

The decision making principles in Java chiefly consist of if else statements, continue, break and
switch statements. It decides the flow of the program control during the execution of the
program.

There are the 6 ways of exercising decision making in Java:

1. if
2. if-else
3. nested-if
4. if-else-if
5. switch-case
6. jump-break,continue,return

1. If Statement in Java

Java if statement is the simplest decision making statement. It encompasses a boolean condition
followed by a scope of code which is executed only when the condition evaluates to true.

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

Example

packagecom.dataflair.decisionmaking;
public class IfStatement {
public static void main(String[] args) {
System.out.println("Understanding if statements.");
String s = "DataFlair";
if (s.equals("DataFlair")) {
System.out.println("The string is DataFlair");
}
}
}
Output
Understanding if statements.
The string is DataFlair
If else statement in Java

This pair of keywords is used to divide a program to be executed into two parts, one being the
code to be executed if the condition evaluates to true and the other one to be executed if the
value is false.

Syntax

if(condition)
{
//code to be executed if the condition is true
}
else
{
//code to be executed if the condition is false
}

EXAMPLE

packagecom.dataflair.decsionmaking;
public class IfElseStatement {
public static void main(String[] args) {
System.out.println("Understanding if statements.");
String s = "DataFlairJava";
if (s.equals("DataFlair")) {
System.out.println("The string is DataFlair");
}
else {
System.out.println("The string is not DataFlair");
}
}
}
Output
The string is not DataFlair
Nested if Statements in Java

The nested if is similar to the nested loops

If the condition of the outer if statement evaluates to true then the inner if statement is evaluated.

Nested if’s are important if we have to declare extended conditions to a previous condition

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

EXAMPLE
packagecom.dataflair.decisionmaking;
public class IfNestedStatement {
public static void main(String[] args) {
System.out.println("Understanding if statements.");
String s = "DataFlair";
if (s.equals("DataFlair")) {
System.out.println("The string is DataFlair");
if (s.charAt(0) == 'D') {
System.out.println("The first character is D! ");
}
}
else {
System.out.println("The string is not DataFlair");
}
}
}
Output
Understanding if statements.
The string is DataFlair
The first character is D!
if-else-if Statements in Java

These statements are similar to the if else statements . The only difference lies in the fact that
each of the else statements can be paired with a different if condition statement. This renders the
ladder as a multiple choice option for the user.

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

EXAMPLE

packagecom.dataflair.decisionmaking;
public class IfElseIfStatement {
public static void main(String[] args) {
System.out.println("Understanding if statements.");
String s = "DataFlairPython";
if (s.equals("DataFlair")) {
System.out.println("The string is DataFlair");
}
else if (s.equals("DataFlairJava")) {
System.out.println("The string is DataFlair and course is Java");
}
else if (s.equals("DataFlairPython")) {
System.out.println("The string is DataFlair and the course is Python");
}
}
}
Output
Understanding if statements.
The string is DataFlair and the course is Python
Switch Statement in Java

Java switch statement is a different form of the if else if ladder statements.

● This saves the hassle of writing else if for every different option.
● It branches the flow of the program to multiple points as and when required or specified by
the conditions.
● It bases the flow of the program based on the output of the expression.

Syntax:
switch(expression)
{
case <value1>:
//code to be executed
break;
case <value2>:
//code to be executed
break;
default:
//code to be defaultly executed
}
EXAMPLE

● package com.dataflair.decisionmaking;
importjava.util. * ;
public class SwitchStatement {
public static void main(String[] args) {
Scanner sc = new Scanner(System. in );
System.out.println("You have two options of courses at DataFlair");
System.out.println("1.Java");
System.out.println("2.Python");
System.out.println("Enter the number of course:");
intch = sc.nextInt();
switch (ch) {
case 1:
System.out.println("Congrats you have chosen Java!");
break;
case 2:
System.out.println("Congrats you have chosen Python!");
break;
default:
System.out.println("Wrong input!");
break;
}
}
}
Output
You have two options of courses at DataFlair
1.Java
2.Python
Enter the number of course:
2
Congrats you have chosen Python!

Branching Statements in Java


Branching statements are the statements used to jump the flow of execution from one part of a
program to another.
The branching statements allow us to exit from a control statement when a certain condition
meet.
Break statement.
The break statement breaks or terminates the loop and transfers the control outside the loop.
The continue statement skips the current execution and pass the control to the start of the loop.
The return statement returns a value from a method and this process will be done explicitly.
The break Statement

The labeled and unlabeled break statement are the two forms of break statement in Java. The
break statement is used for terminating a loop based on a certain condition.

1) Unlabeled break statement


The unlabeled break statement is used to terminate the loop that is inside the loop. It is also used
to stop the working of the switch statement.
Syntax:
for (int; testExpression; update){
if(condition to break){
break;
}
}
EXAMPLE
class UnlabeledBreakExample {
public static void main(String[] args) {

String[] arr = { "Shubham", "Anubhav", "Nishka", "Gunjan", "Akash" };


String searchName = "Nishka";

int j;
boolean foundName = false;

for (j = 0; j < arr.length; j++) {


if (arr[j] == searchName) {
foundName = true;
break;
}
}
if (foundName) {
System.out.println("The name " + searchName + " is found at index " + j);
} else {
System.out.println("The name " +searchName + " is not found in the array");
}
}
}

Output:

2) Labeled break statement

● Labeled break statement is another form of break statement

● The labeled break statement is capable of terminating the outermost loop.

syntax.

label:
for (int; testExpression; update){

for (int; testExpression; update){

if(condition to break){
break label;
}
}
}
EXAMPLE
class LabeledBreakExample {
public static void main(String[] args) {
int j, k;
outerMost:
for(j=1; j<5; j++) {
innerMost:
for(k=1; k<3; k++ ) {
System.out.println("j = " + j + " and k = " +k);
if ( j == 3)
break outerMost;
}
}
}
}

Output:

The continue Statement

● The continue statement is another branching statement used to immediately jump to the
next iteration of the loop.
● We can use the continue statement for any control flow statements like for, while,
and do-while.

Syntax

control-flow-statement;

continue;

Example

public class ContinueExample {


public static void main(String[] args) {
int x = 1;
int y = 10;
do{
if(x == y/2){
x++;
continue;
}
System.out.println(x);
x++;
}while(x <= y);
}
}
OUTPUT:

The return Statement

The return statement is also a branching statement, which allows us to explicitly return value
from a method. The return statement exits us from the calling method and passes the control flow
to where the calling method is invoked.

Syntax

return value;

Or,

return;

Example

class ReturnExampleWithoutValue {
void increment(int number)
{
if (number < 10)
return;
number++;
System.out.println(number);
}
public static void main(String[] args)
{
ReturnExampleWithoutValue obj = new ReturnExampleWithoutValue();
obj.increment(4);
System.out.println("In main");
obj.increment(12);
System.out.println("In main");
}
}

Output:

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.

For Loop in Java:


The Java for loop repeats the execution of a set of Java statements. A for loop executes a block
of code as long as some condition is true.
SYNTAX

for(initialization;condition;increment/decrement)
{

Statement(s);
}
EXAMPLE

Class ForLoopDemo
{
public static void main(String args[])
{
for(int num = 1; num <= 5; num++)
{
System.out.println(num);
}
}
}
Output:
1
2
3
4
5
While Loop in Java:

The while statement or loop continually executes a block of statements while a particular
condition is true. The while statement continues testing the expression and executing its block
until the expression evaluates to false. The syntax to use while loop in java is given below.

SYNTAX

while(condition)
{
Statement(s);
}

EXAMPLE
class whileLoopDemo
{
public static void main(String args[])
{
int x = 1;
{
System.out.println("Value of x:" + x);
x++;
}
}
}

Output:
value of x:1
Value of x:2
Value of x:3

Do-while Loop in Java:

The difference between do-while and while is that do-while evaluates its expression at the
bottom of the loop instead of the top.
SYNTAX:
do{

Statement(s);
}
while(condition);

class dowhileloopDemo
{
public static void main(String args[])
{
int x = 21;
do
{
System.out.println("Value of x:" + x);
x++;
}
while (x < 20);
}
}
Output: Value of x: 21

Course Code Internet Programming L T P C

Core/Elective/Supportive Core : 4 6 0 0 4

You might also like