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

JavaUnit 1

Uploaded by

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

JavaUnit 1

Uploaded by

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

What is Java?

Java is a widely used object-oriented programming language and software platform that runs
on billions of devices, including notebook computers, mobile devices, gaming consoles,
medical devices and many others. The rules and syntax of Java are based on the C and C++
languages.

One major advantage of developing software with Java is its portability. Once you have written
code for a Java program on a notebook computer, it is very easy to move the code to a mobile
device. When the language was invented in 1991 by James Gosling of Sun Microsystems
(later acquired by Oracle), the primary goal was to be able to "write once, run anywhere."

Features of Java or Characteristics of Java or Properties of Java


Java is Simple
✓ Java is very easy to learn and its syntax is simple, clean and easy to understand.
✓ Java language is a simple programming language because:
✓ Java syntax is based on C++ (so easier for programmers to learn it after C++).
✓ Java has removed many confusing and rarely-used features e.g. explicit pointers,
operator overloading etc.
✓ There is no need to remove unreferenced objects because there is Automatic Garbage
Collection in java.

Object-oriented
Java is object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporates both data and behaviour.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.

Basic concepts of OOPs are


1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent
Java is platform independent because it is different from other languages like C, C++ etc. which
are compiled into platform specific machines while Java is a write once, run anywhere
language. A platform is the hardware or software environment in which a program runs.

Java provides software-based platform. The Java platform differs from most other platforms in
the sense that it is a software-based platform that runs on the top of other hardware-based
platforms.

It has two components:


1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris, Mac/OS etc.
Java code is compiled by the compiler and converted into bytecode. This bytecode is a
platform-independent code because it can be run on multiple platforms i.e. Write Once and
Run Anywhere (WORA).

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
✓ No explicit pointer
✓ Java Programs run inside virtual machine sandbox

Class loader: Class loader in Java is a part of the Java Runtime Environment (JRE) which is
used to dynamically load Java classes into the Java Virtual Machine. It adds security by
separating the package for the classes of the local file system from those that are imported from
network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate access right
to objects.
Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
Robust
Robust simply means strong. Java is robust because:
✓ It uses strong memory management.
✓ There is lack of pointers that avoids security problems.
✓ There is automatic garbage collection in java which runs on the Java Virtual Machine
to get free of objects which are not being used by a Java application anymore.
✓ There is exception handling and type checking mechanism in java. All these points
make java robust

Architecture-neutral
Java is architecture neutral because there is no implementation dependent features e.g. size of
primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. But in java, it occupies 4 bytes of memory for both 32 and
64 bit architectures.

Portable
Java is portable because it facilitates you to carry the java bytecode to any platform. It doesn't
require any type of implementation.

High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode
is "close" to native code. It is still a little bit slower than a compiled language (e.g. C++). Java
is an interpreted language that is why it is slower than compiled languages e.g. C, C++ etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in java. RMI
(Remote Method Invocation) and EJB (Enterprise Java Beans) are used for creating distributed
applications. This feature of Java makes us able to access files by calling the methods from any
machine on the internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads.

Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages i.e. C and C++.
Java supports dynamic compilation and automatic memory management (garbage collection).

What is JVM?
JVM (Java Virtual Machine) is an abstract machine that enables your computer to run a Java
program.

When you run the Java program, Java compiler first compiles your Java code to bytecode.
Then, the JVM translates bytecode into native machine code (set of instructions that a
computer's CPU executes directly).
Java is a platform-independent language. It's because when you write Java code, it's ultimately
written for JVM but not your physical machine (computer). Since JVM executes the Java
bytecode which is platform-independent, Java is platform-independent.

The JVM performs the following main tasks


1. Loads code
2. Verifies code
3. Executes code
4. Provides runtime environment

JVM generates a .class(Bytecode) file, and that file can be run in any OS, but JVM should have
in OS because JVM is platform dependent.
JVM is the main component of Java architecture, and it is the part of the JRE (Java Runtime
Environment).
A program of JVM is written in C Programming Language, and JVM is Operating System
dependent.
JVM is responsible for allocating the necessary memory needed by the Java program.
JVM is responsible for deallocating memory space.

What is JRE?
JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java
Virtual Machine (JVM), and other components that are required to run Java applications.
JRE is the superset of JVM.
If you want to run Java programs, but not develop them, JRE is what you need.

What is JDK?
JDK (Java Development Kit) is a software development kit required to develop applications in
Java. When you download JDK, JRE is also downloaded with it.

In addition to JRE, JDK also contains a number of development tools (compilers, JavaDoc,
Java Debugger, etc).
If you want to develop Java applications, you have to download JDK.

Java Data Types


Java is statically typed and also a strongly typed language because, in Java, each type of data
is predefined as part of the programming language and all constants or variables defined for a
given program must be described with one of the Java data types.

Java has two categories in which data types are segregated


✓ Primitive Data Type
✓ Non-Primitive Data Type or Object Data type or Reference Type

Primitive Data Type


A primitive data type specifies the size and type of variable values, and it has no additional
methods. Primitive data are only single values and have no special capabilities.
There are 8 data types predefined in Java, known as primitive data types.

boolean type
boolean data type represents only one bit of information either true or false which is intended
to represent the two truth values of logic and Boolean algebra.
Default value: false.
class Main
{
public static void main(String[] args)
{
boolean flag = true;
System.out.println(flag); // prints true
}
}

byte type
✓ The byte data type can have values from -128 to 127 (8-bit signed two's complement
integer).
✓ If it's certain that the value of a variable will be within -128 to 127, then it is used instead
of int to save memory.
✓ Default value: 0
class Main
{
public static void main(String[] args)
{
byte range;
range = 124;
System.out.println(range); // prints 124
}
}

short type
✓ The short data type in Java can have values from -32768 to 32767 (16-bit signed two's
complement integer).
✓ If it's certain that the value of a variable will be within -32768 and 32767, then it is used
instead of other integer data types (int, long).
✓ Default value: 0
class Main
{
public static void main(String[] args)
{
short temperature;
temperature = -200;
System.out.println(temperature); // prints -200
}
}

int type
✓ The int data type can have values from -231 to 231-1 (32-bit signed two's complement
integer).
✓ If you are using Java 8 or later, you can use an unsigned 32-bit integer. This will have
a minimum value of 0 and a maximum value of 232-1.
✓ Default value: 0
class Main
{
public static void main(String[] args)
{
int range = -4250000;
System.out.println(range); // print -4250000
}
}

long type
✓ The long data type can have values from -263 to 263-1 (64-bit signed two's complement
integer).
✓ If you are using Java 8 or later, you can use an unsigned 64-bit integer with a minimum
value of 0 and a maximum value of 264-1.
✓ Default value: 0
class LongExample
{
public static void main(String[] args)
{
long range = -42332200000L;
System.out.println(range); // prints -42332200000
}
}
Notice, the use of L at the end of -42332200000. This represents that it's an integer of the long
type.

double type
✓ The double data type is a double-precision 64-bit floating-point.
✓ It should never be used for precise values such as currency.
✓ Default value: 0.0 (0.0d)
class Main
{
public static void main(String[] args)
{
double number = -42.3;
System.out.println(number); // prints -42.3
}
}

float type
✓ The float data type is a single-precision 32-bit floating-point. Learn more about single-
precision and double-precision floating-point if you are interested.
✓ It should never be used for precise values such as currency.
✓ Default value: 0.0 (0.0f)
class Main
{
public static void main(String[] args)
{
float number = -42.3f;
System.out.println(number); // prints -42.3
}
}
Notice that we have used -42.3f instead of -42.3in the above program. It's because -42.3 is a
double literal.

char type
✓ It's a 16-bit Unicode character.
✓ The minimum value of the char data type is '\u0000' (0) and the maximum value of the
is '\uffff'.
✓ Default value: '\u0000'
class Main
{
public static void main(String[] args)
{
char letter = '\u0051';
System.out.println(letter); // prints Q
}
}

Java Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. all variables have
a scope, which defines their visibility, and a lifetime.

Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s atomic types, or the name of a class or interface. The identifier is the
name of the variable. You can initialize the variable by specifying an equal sign and a value.

Here are several examples of variable declarations of various types. Note that some
include an initialization.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
byte z = 22; // initializes z.

Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows variables
to be initialized dynamically, using any expression valid at the time the variable is declared.
class DynInit
{
public static void main(String args[])
{
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}

Rules for Naming Variables in Java


Java is case sensitive. Hence, age and AGE are two different variables.
Variables must start with either a letter or an underscore, _ or a dollar, $ sign.
Variable names cannot start with numbers.
Variable names can't use whitespace.

There are 4 types of variables in Java programming language:


✓ Instance Variables (Non-Static Fields)
✓ Class Variables (Static Fields)
✓ Local Variables
✓ Parameters
Java literals
Literals are data used for representing fixed values. They can be used directly in the code.

Boolean Literals
In Java, boolean literals are used to initialize boolean data types. They can store two values:
true and false. For example,

boolean flag1 = false;


boolean flag2 = true;

Here, false and true are two boolean literals.

Integer Literals
An integer literal is a numeric value(associated with numbers) without any fractional or
exponential part. There are 4 types of integer literals in Java:

1. binary (base 2)
2. decimal (base 10)
3. octal (base 8)
4. hexadecimal (base 16)
e.g.
// binary
int binaryNumber = 0b10010;
// octal
int octalNumber = 027;

// decimal
int decNumber = 34;

// hexadecimal
int hexNumber = 0x2F; // 0x represents hexadecimal

// binary
int binNumber = 0b10010; // 0b represents binary

In Java, binary starts with 0b, octal starts with 0, and hexadecimal starts with 0x.

Floating-point Literals
A floating-point literal is a numeric literal that has either a fractional form or an exponential
form. For example,

double myDouble = 3.4;


float myFloat = 3.4F;

// 3.445*10^2
double myDoubleScientific = 3.445e2;
The floating-point literals are used to initialize float and double type variables.
Character Literals
Character literals are unicode character enclosed inside single quotes. For example,
char letter = 'a';

Here, a is the character literal.


We can also use escape sequences as character literals. For example, \b (backspace), \t (tab), \n
(new line), etc.

String literals
A string literal is a sequence of characters enclosed inside double-quotes. For example,
String str1 = "Java Programming";

Here, Java Programming is string literals.

Java Identifiers
Java Identifiers can be a class name, method name, variable name, or label.

Rules For Defining Java Identifiers


✓ The only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-
z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore).

✓ Identifiers should not start with digits([0-9]).

✓ Java identifiers are case-sensitive.

✓ There is no limit on the length of the identifier but it is advisable to use an optimum
length of 4 – 15 letters only.

✓ Reserved Words can’t be used as an identifier.

Java Operators
Operators are symbols that perform operations on variables and values.

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

Java Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on variables and data.

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation (Remainder after division)
class DemoArithmatic
{
public static void main(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));
}
}

/ Division Operator
If we use the division operator with two integers, then the resulting quotient will also be an
integer. And, if one of the operands is a floating-point number, we will get the result will also
be in floating-point.

(5 / 2) is 2
(5.0 / 2) is 2.5

% Modulo Operator
The modulo operator % computes the remainder. When a = 7 is divided by b = 4, the remainder
is 3.

Java Assignment Operators


Assignment operators are used in Java to assign values to variables. For example,

int a;
a = 7;

Here, = is the assignment operator. It assigns the value on its right to the variable on its left.
That is, 7 is assigned to the variable a.

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;

class DemoAssigmentOp
{
public static void main(String[] args)
{
// create variables
int a = 4;
int var;

// 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);
}
}

Java Relational Operators


Relational operators are used to check the relationship between two operands. It returns either
true or false.
Relational operators are used in decision making and looping statements.

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

class DemoRelationalOp
{
public static void main(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
}
}

Java Logical Operators


Logical operators are used to check whether an expression is true or false. They are used in
decision making.
Logical Operator are used to join two or more relational expression.
Operator Example Meaning
&& expression1 && expression2 true only if both expression1 and
(Logical AND) expression2 are true
|| (Logical OR) expression1 || expression2 true if either expression1 or
expression2 is true
! (Logical NOT) !expression true if expression is false and vice
versa

class DemoLogicalOp
{
public static void main(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
}
}
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.

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 operator can be use as pre or post form, for example

//pre increment
++a;

//post increment
a++;

class DemoUnary
{
public static void main(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);
}
}

Java Bitwise Operators


Bitwise operators in Java are used to perform operations on individual bits.
Operator Description
| Bitwise OR
& Bitwise AND
^ Bitwise XOR
~ Bitwise Complement
<< Left Shift
>> Signed Right Shift
>>> Unsigned Right Shift

Java Bitwise OR Operator


The bitwise OR | operator returns 1 if at least one of the operands is 1. Otherwise, it returns 0.
The following truth table demonstrates the working of the bitwise OR operator.

a b a|b
0 0 0
0 1 1
1 0 1
1 1 1

Java Bitwise AND Operator


The bitwise AND & operator returns 1 if and only if both the operands are 1. Otherwise, it
returns 0.
The following table demonstrates the working of the bitwise AND operator.
a b a|b
0 0 0
0 1 0
1 0 0
1 1 1

Java Bitwise XOR Operator


The bitwise XOR ^ operator returns 1 if and only if one of the operands is 1. However, if both
the operands are 0 or if both are 1, then the result is 0.
The following truth table demonstrates the working of the bitwise XOR operator.
a b a^b
0 0 0
0 1 1
1 0 1
1 1 0

Java Bitwise Complement Operator


The bitwise complement operator is a unary operator (works with only one operand). It is
denoted by ~. It changes binary digits 1 to 0 and 0 to 1.

It is important to note that the bitwise complement of any integer N is equal to - (N + 1).
Java Shift Operators
There are three types of shift operators in Java:
1. Signed Left Shift (<<)
2. Signed Right Shift (>>)
3. Unsigned Right Shift (>>>)

Java Left Shift Operator


The left shift operator shifts all bits towards the left by a certain number of specified bits. It is
denoted by <<.

As we can see from the image above, we have a 4-digit number. When we perform a 1 bit left
shift operation on it, each individual bit is shifted to the left by 1 bit.

As a result, the left-most bit (most-significant) is discarded and the right-most position(least-
significant) remains vacant. This vacancy is filled with 0s.

Java Signed Right Shift Operator


The signed right shift operator shifts all bits towards the right by a certain number of specified
bits. It is denoted by >>.

When we shift any number to the right, the least significant bits (rightmost) are discarded and
the most significant position (leftmost) is filled with the sign bit. For example

// right shift of 8
8 = 1000 (In Binary)

// perform 2 bit right shift


8 >> 2:
1000 >> 2 = 0010 (equivalent to 2)
Here, we are performing the right shift of 8 (i.e. sign is positive). Hence, there no sign bit. So
the leftmost bits are filled with 0 (represents positive sign).

// right shift of -8
8 = 1000 (In Binary)

1's complement = 0111

2's complement:
0111
+1
_______
1000

Signed bit = 1

// perform 2 bit right shift


8 >> 2:
1000 >> 2 = 1110 (equivalent to -2)

Here, we have used the signed bit 1 to fill the leftmost bits.

class DemoRightShift
{
public static void main(String[] args)
{
int number1 = 8;
int number2 = -8;

// 2 bit signed right shift


System.out.println(number1 >> 2); // prints 2
System.out.println(number2 >> 2); // prints -2
}
}

Java Unsigned Right Shift Operator


Java also provides an unsigned right shift. It is denoted by >>>.
Here, the vacant leftmost position is filled with 0 instead of the sign bit. For example,
// unsigned right shift of 8
8 = 1000
8 >>> 2 = 0010

// unsigned right shift of -8


-8 = 1000 (see calculation above)
-8 >>> 2 = 0010

Java instanceof Operator


The instanceof operator checks whether an object is an instanceof a particular class. For
example,
class Demoinstance
{
public static void main(String[] args)
{
String str = "Programiz";
boolean result;

// checks if str is an instance of the String class


result = str instanceof String;
System.out.println("Is str an object of String? " + result);
}
}
Here, str is an instance of the String class. Hence, the instanceof operator returns true.

Java Ternary Operator


The ternary operator (conditional operator) is shorthand for the if-then-else statement.

Syntax
variable = Expression ? expression1 : expression2;

Here's how it works.


✓ If the Expression is true, expression1 is assigned to the variable.
✓ If the Expression is false, expression2 is assigned to the variable.

class DemoTernary
{
public static void main(String[] args)
{
int num = 7;
String result;

// ternary operator
result = (num % 2 == 0) ? "even-number" : "odd-number";
System.out.println( num + “ “ + result);
}
}

Type Conversion and Casting


Java’s Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion
will take place if the following two conditions are met:
1. The two types are compatible.
2. The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For example, the
int type is always large enough to hold all valid byte values, so no explicit cast statement is
required.

For widening conversions, the numeric types, including integer and floating-point types,
are compatible with each other. There are no automatic conversions from the numeric types to
char or boolean. char and boolean are not compatible with each other.

Casting Incompatible Types


To create a conversion between two incompatible types, you must use a cast. A cast is
simply an explicit type conversion. For example, what if you want to assign an int value to a
byte variable? This conversion will not be performed automatically, because a byte is smaller
than an int. This kind of conversion is sometimes called a narrowing conversion, since you
are explicitly making the value narrower so that it will fit into the target type.
Syntax for type casting
(target-type) value

Here, target-type specifies the desired type to convert the specified value to. For example, the
following fragment casts an int to a byte. If the integer’s value is larger than the range of a
byte, it will be reduced modulo (the remainder of an integer division by the) byte’s range.

int a;
byte b;
// ...
b = (byte) a;

The Type Promotion Rules


Java defines several type promotion rules that apply to expressions. They are as follows: First,
all byte, short, and char values are promoted to int. Then, if one operand is a long, the whole
expression is promoted to long. If one operand is a float, the entire expression is promoted to
float. If any of the operands is double, the result is double.

Java if...else Statement


In programming, we use the if..else statement to run a block of code among more than one
alternatives.

Java if Statement
Syntax
if (condition)
{
// statements
}

Here, condition is a boolean expression such as age >= 18.


if condition evaluates to true, statements are executed
if condition evaluates to false, statements are skipped

Working of if Statement
Java if...else (if-then-else) Statement
The if statement executes a certain section of code if the test expression is evaluated to true.
However, if the test expression is evaluated to false, it does nothing.

In this case, we can use an optional else block. Statements inside the body of else block are
executed if the test expression is evaluated to false. This is known as the if-...else statement in
Java.
Syntax
if (condition)
{
// codes in if block
}
else
{
// codes in else block
}
Here, the program will do one task (codes inside if block) if the condition is true and another
task (codes inside else block) if the condition is false.

Working of if...else statement

Java if...else...if Statement


In Java, we have an if...else...if ladder, that can be used to execute one block of code among
multiple other blocks.
Syntax
if (condition1)
{
// codes
}
else if(condition2)
{
// codes
}
else if (condition3)
{
// codes
}
.
.
else
{
// codes
}
Here, if statements are executed from the top towards the bottom. When the test condition is
true, codes inside the body of that if block is executed. And, program control jumps outside the
if...else...if ladder.
If all test expressions are false, codes inside the body of else are executed.

Working of if...else...if ladder

Java Nested if..else Statement


In Java, it is also possible to use if..else statements inside an if...else statement. It's called the
nested if...else statement.

Java switch Statement


The switch statement allows us to execute a block of code among many alternatives.
Syntax
switch (expression)
{
case value1:
// code
break;
case value2:
// code
break;
...
default:
// default statements
}
The expression is evaluated once and compared with the
values of each case.
If expression matches with value1, the code of case value1 are
executed. Similarly, the code of case value2 is executed if
expression matches with value2.If there is no match, the code
of the default case is executed.

The expression must be of type byte, short, int, or char; each


of the values specified in the
case statements must be of a type compatible with the
expression.

The break statement is used inside the switch to terminate a


statement sequence. When a break statement is encountered,
execution branches to the first line of code that follows the
entire switch statement.

The switch statement also includes an optional default case. It is executed when the expression
doesn't match any of the cases.

Java for Loop


Java for loop is used to run a block of code for a certain number of times.
Syntax
for (initialExpression; testExpression; updateExpression)
{
// body of the loop
}
Here,
✓ The initial expression initializes and/or declares
variables and executes only once.
✓ The condition is evaluated. If the condition is true, the
body of the for loop is executed.
✓ The update expression updates the value of initial
expression.
✓ The condition is evaluated again. The process
continues until the condition is false.
Java for-each Loop
The Java for loop has an alternative syntax that makes it easy to iterate through arrays and
collections.,
Syntax
for(dataType item : array)
{
...
}
Here,
array - an array or a collection
item - each item of array/collection is assigned to this variable
dataType - the data type of the array/collection

// print array elements


class DemoFor
{
public static void main(String[] args)
{
// create an array
int[] numbers = {3, 7, 5, -5};

// iterating through the array


for (int number: numbers)
{
System.out.println(number);
}
}
}

Java while loop


Java while loop is used to run a specific code until a certain condition is met.
Syntax
while (test expression)
{
// body of loop
}
Here,
✓ A while loop evaluates the text expression inside
the parenthesis ().
✓ If the text expression evaluates to true, the code
inside the while loop is executed.
✓ The text expression is evaluated again.
✓ This process continues until the text expression
is false.
✓ When the text expression evaluates to false, the
loop stops.
Java do...while loop
The do...while loop is similar to while loop. However, the body of do...while loop is
executed once before the test expression is checked.
Syntax
do
{
// body of loop
} while(test Expression);
Here,
✓ The body of the loop is executed at first. Then the
test expression is evaluated.
✓ If the test expression evaluates to true, the body of
the loop inside the do statement is executed again.
✓ The test expression is evaluated once again.
✓ If the test expression evaluates to true, the body of
the loop inside the do statement is executed again.
✓ This process continues until the test expression
evaluates to false. Then the loop stops.

You might also like