UNIT I Java
UNIT I Java
Introduction to Java
Java is a popular,
high-level, object-
oriented
programming
language and
platform
developed by Sun
Microsystems (now
owned by Oracle
Corporation). It was
created
by James Gosling
and released in
1995. Java is
designed to have as
few
implementation
dependencies as
possible, making it a
"write once, run
anywhere"
(WORA) language.
Features of Java
The primary
objective of Java
programming
language creation
was to make it
portable,
simple and secure
programming
language. Apart
from this, there are
also some
excellent features
which play an
important role in the
popularity of this
language. The
features of Java are
also known as Java
buzzwords.
A list of the most
important features
of the Java language
is given below.
Introduction to Java
Java is a popular, high-level, object-oriented programming language and platform
developed by Sun Microsystems (now owned by Oracle Corporation). It was created
by James Gosling and released in 1995. Java is designed to have as few
implementation dependencies as possible, making it a "write once, run anywhere"
(WORA) language.
Features of Java
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some
excellent features which play an important role in the popularity of this language. The
features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is
simple, clean and easy to understand.
According to Sun Microsystem, Java
language is a simple programming language
because:
o Java syntax is based on C++ (so easier for
programmers to learn it after C++).
o Java has removed many complicated and
rarely-used features, for example,
explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
Object-oriented
Java is an 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 incorporate both data and behavior.
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.
There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, 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 a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment
(JRE) which is used to load Java classes into the Java Virtual Machine
dynamically. It adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.
Java language provides these securities by default. Some security can also be provided
by an application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features,
for example, the 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. However, it occupies 4 bytes of memory
for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any 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 and EJB 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. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It shares
a common memory area. Threads are important for multi-media, Web applications,
etc.
Dynamic
Java is a dynamic language. It supports the 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 Architecture
1. Java Virtual Machine (JVM)
JVM is an abstract machine that provides a runtime environment to execute
Java bytecode.
o Key Responsibilities: Bytecode interpretation, memory management
(garbage collection), and security enforcement.
2. Java Runtime Environment (JRE)
JRE includes the JVM and libraries required to run Java programs. It’s what
you need to execute Java applications.
3. Java Development Kit (JDK)
JDK is a superset of JRE, including tools like the compiler (javac), debugger,
and other utilities for developing Java programs.
Java Program Structure
A basic Java program includes:
1. Class Definition: Every program begins with a class.
2. main Method: The entry point of a Java application. Syntax:
public static void main(String[] args) { }
Sample Program
Here’s a simple Java program that prints "Hello, World!":
// This is a simple Java program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Applications of Java
• Web Development: Using frameworks like Spring and Struts.
• Mobile Applications: Android apps primarily use Java.
• Enterprise Applications: Banking and finance systems often rely on Java for
its robustness and scalability.
• Big Data Technologies: Hadoop, Spark, and other tools use Java.
• Embedded Systems: Devices like smart cards and IoT systems leverage Java.
OOPs (Object-Oriented Programming) concepts
Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and
maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Apart from these concepts, there are some other terms which are used in Object-
Oriented design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
• Any entity that
has state and
behavior is known as
an object.
• For example, a
chair, pen, table,
keyboard, bike, etc.
It can be physical or
logical.
• An Object can be
defined as an
instance of a class.
• It contains an
address and takes
up some space in
memory.
• Objects can
communicate
without knowing the
details of each
other's data or code.
• The only
necessary thing is
the type of message
accepted and the
type of response
returned by the
objects.
• Example: A dog is
an object because it
has states like color,
name, breed, etc. as
well as behaviors
like wagging the tail,
barking, eating, etc.
Class
Collection of objects
is called class. It is a
logical entity.
A class can also be
defined as a
blueprint from which
you can create an
individual
object. Class does
not consume any
space.
Inheritance
When one object
acquires all the
properties and
behaviors of a
parent object, it is
known as
inheritance.
It provides code
reusability. It is used
to achieve runtime
polymorphism
• Any entity that has state and behavior is known as an object.
• For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
• An Object can be defined as an instance of a class.
• It contains an address and takes up some space in memory.
• Objects can communicate without knowing the details of each other's data or code.
• The only necessary thing is the type of message accepted and the type of response
returned by the objects.
• Example: A dog is an object because it has states like color, name, breed, etc. as
well as behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual
object. Class does not consume any space.
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance.
It provides code reusability. It is used to achieve runtime polymorphism
Polymorphism
• If one task is performed in different ways, it is known as polymorphism.
• For example: to convince the customer differently, to draw something, for example,
shape, triangle, rectangle, etc.
• In Java, we use method overloading and method overriding to achieve
polymorphism.
• Another example can be to speak something; for example, a cat speaks
meow, dog
barks woof, etc.
Abstraction
• Hiding internal implementation and showing functionality only to the user is known
as abstraction. For example, phone call, we do not know the internal processing.
• In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
• Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
• For example, a capsule, it is wrapped with different medicines.
• A Java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.
Coupling
• Coupling refers to the knowledge or information or dependency of another class.
• It arises when classes are aware of each other.
• If a class has the details information of another class, there is strong coupling.
• In Java, we use private, protected, and public modifiers to display the visibility level
of a class, method, and field.
• We can use interfaces for the weaker coupling because there is no concrete
implementation.
Cohesion
• Cohesion refers to the level of a component which performs a single well-defined
task. A single well-defined task is done by a highly cohesive method.
• The weakly cohesive method will split the task into separate parts.
• The java.io package is a highly cohesive package because it has I/O related classes
and interface.
• However, the java.util package is a weakly cohesive package because it has
unrelated classes and interfaces.
Association
• Association represents the relationship between the objects.
• Here, one object can be associated with one object or many objects.
• There can be four types of association between the objects:
1. One to One
2. One to Many
3. Many to One, and
4. Many to Many
• Let's understand the relationship with real-time examples.
• For example, a country can have one prime minister (one to one), and a prime
minister can have many ministers (one to many).
• Also, many MP's can have one prime minister (many to one), and many ministers
can have many departments (many to many).
• Association can be unidirectional or bidirectional.
In the above code snippet, public, class, Demo, {, static, void, main, (, String, args,
[, ], ), System, ., out, println, javatpoint, etc. are the Java tokens.
The Java compiler translates these tokens into Java bytecode. Further, these bytecodes
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
Identifier: Identifiers are used to name a variable, constant, function, class, and array.
It 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 that is used in the goto
statement. Remember that the identifier name must be different from the reserved
keywords. 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.
Some valid identifiers are:
1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid
Note that the first three separators (; , and .) are tokens that separate other tokens, and
the last six (3 pairs of braces) separators are also known as delimiters. For example,
Math.pow(9, 3); contains nine tokens.
o Square Brackets []: It is used to define array elements. A pair of square
brackets represents the single-dimensional array, two pairs of square brackets
represent the two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code
block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It
separates the two statements.
o Period (.): It separates the package name form the sub-packages and class. It
also separates a variable or method from a reference variable.
Comments: Comments allow us to specify information about the program inside our
Java code. Java compiler recognizes these comments as tokens but excludes it form
further processing. The Java compiler treats comments as whitespaces. Java provides
the following two types of comments:
o Line Oriented: It begins with a pair of forwarding slashes (//).
o Block-Oriented: It begins with /* and continues until it founds */.
• In Java, the boolean data type represents a single bit of information with two
possible states: true or false.
• It is used to store the result of logical expressions or conditions.
• Unlike other primitive data types like int or double, boolean does not have a
specific size or range.
• It is typically implemented as a single bit, although the exact implementation may
vary across platforms.
Example:
1. Boolean a = false;
2. Boolean b = true;
• One key feature of the boolean data type is its use in controlling program flow.
• It is commonly employed in conditional statements such as if, while, and for loops
to determine the execution path based on the evaluation of a boolean expression.
• For instance, an if statement executes a block of code if the boolean expression
evaluates to true, and skips it if the expression is false.
Byte Data Type
• The byte data type in Java is a primitive data type that represents an 8-bit signed
two's complement integer.
• It has a range of values from -128 to 127. Its default value is 0.
• The byte data type is commonly used when working with raw binary data or when
memory conservation is a concern, as it occupies less memory than larger integer
types like int or long.
Example:
1. byte a = 10, byte b = -20
• One common use of the byte data type is in reading and writing binary data, such
as files or network streams.
• Since binary data is often represented using bytes, the byte data type provides a
convenient way to work with such data.
• Additionally, the byte data type is sometimes used in performance-critical
applications where memory usage needs to be minimized.
Short Data Type
• The short data type in Java is a primitive data type that represents a 16-bit signed
two's complement integer.
• It has a range of values from -32,768 to 32,767.
• Similar to the byte data type, short is used when memory conservation is a
concern, but more precision than byte is required.
• Its default value is 0.
Example:
1. short s = 10000, short r = -5000
Output:
20
Java Variable Example: Widening
1. public class Simple{
2. public static void main(String[] args){
3. int a=10;
4. float f=a;
5. System.out.println(a);
6. System.out.println(f);
7. }}
Output:
10
10.0
Java Variable Example: Narrowing (Typecasting)
1. public class Simple{
2. public static void main(String[] args){
3. float f=10.5f;
4. //int a=f;//Compile time error
5. int a=(int)f;
6. System.out.println(f);
7. System.out.println(a);
8. }}
Output:
10.5
10
Java Variable Example: Overflow
1. class Simple{
2. public static void main(String[] args){
3. //Overflow
4. int a=130;
5. byte b=(byte)a;
6. System.out.println(a);
7. System.out.println(b);
8. }}
Output:
130
-126
Java Variable Example: Adding Lower Type
1. class Simple{
2. public static void main(String[] args){
3. byte a=10;
4. byte b=10;
5. //byte c=a+b;//Compile Time Error: because a+b=20 will be int
6. byte c=(byte)(a+b);
7. System.out.println(c);
8. }}
Output:
20
Syntax:
1. Destination_datatype = (target_datatype) variable;
2. (data_type) it is known as casting operator
Target_datatype:
• It is the data type in which we want to convert the destination data type.
• The variable defines a value that is to be converted in the target_data type.
• Let's understand the concept of type casting with an example.
• Suppose, we want to convert the float data type into int data type.
• Here, the target data type is smaller than the source data because the size of int is 2
bytes, and the size of the float data type is 4 bytes.
• And when we change it, the value of the float variable is truncated and convert into
an integer variable.
• Casting can be done with a compatible and non-compatible data type.
1. float b = 3.0;
2. int a = (int) b; // converting a float value into integer
Let's understand the type casting through a C program
AreaOfRectangle.c
1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. printf("\n Welcome to Javatpoint tutorials ");
6. float x = 3.5, y = 4.5; // the size of float variable is 4 byte.
7. int area; // the size of the int variable is 2 bytes.
8. area = (int) x * y; // after conversion the product converts into integer
9. printf("\n Area of a Rectangle is : %d", area);
10. printf("\n Here, we convert float data type into the Int data type");
11. getch();
12. }
Filename: HelloWorld.java
1. public class HelloWorld {
public: It is an access specifier. We should use a public keyword before the main()
method so that JVM can identify the execution point of the program. If we use private,
protected, and default before the main() method, it will not be visible to JVM.
Filename: PrivateClass.java
1. public class PrivateClass {
2. private static void main(String[] args) {
3. System.out.println("Hello, World!");
4. }
5. }
Output:
ERROR!
Error: Main method not found in class PrivateClass, please define the main method
as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Static method
We observe that JVM first executes the static block, if it is present in the program.
After that it searches for the main() method. If the main() method is not found, it gives
error.
Example
A program that does not have the main() method gives an error at run time.
1. class DemoStaticBlock
2. {
3. Static //static block
4. {
5. System.out.println("Static block");
6. }
7. }
Output:
Error: Main method not found in the class Demo, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
So the main() method should always be written as:
public static void main(String args[])
We can interchange public and static and write it as follows:
static public void main(String args[])
We can also use the different name for the String type array and write it as:
static public void main(String[] x)
Different ways of writing main() method are:
1. static public void main(String []x)
2. static public void main(String...args)
String...args: It allows the method to accept zero or multiple arguments. There should
be exactly three dots between String and array; otherwise, it gives an error.
Example
A program that has no main() method, but compile and runs successfully.
1. abstract class DemoNoMain extends javafx.application.Application
2. {
3. static //static block
4. {
5. System.out.println("Java");
6. System.exit(0);
7. }
8. }
Output:
Java
Output
Enter your name: Nakul Jain
Welcome Nakul Jain
Java Console Example to read password
1. import java.io.Console;
2. class ReadPasswordTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter password: ");
6. char[] ch=c.readPassword();
7. String pass=String.valueOf(ch);//converting char array into string
8. System.out.println("Password is: "+pass);
9. }
10. }
Output
Enter password:
Password is: 123
Operators in Java
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and --
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}
Output:
22
21
Java Unary Operator Example: ~ and !
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);//-
11 (minus of total positive value which starts from 0)
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c);//false (opposite of boolean value)
10. System.out.println(!d);//true
11. }}
Output:
-11
9
false
true
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Java Arithmetic Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10. }}
Output:
15
5
50
2
0
Java Arithmetic Operator Example: Expression
1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10*10/5+3-1*4/2);
4. }}
Output:
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side
of a specified number of times.
Java Left Shift Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
7. }}
Output:
40
80
80
240
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to right
by the number of bits specified by the right operand.
Java Right Shift Operator Example
1. public OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}
Output:
2
5
2
Java Shift Operator Example: >> vs >>>
1. public class OperatorExample{
2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}
Output:
5
5
-5
1073741819
Java AND Operator Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is
false. It checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true
or false.
1.
2. public class OperatorExample{
3. public static void main(String args[]){
4. int a=10;
5. int b=5;
6. int c=20;
7. System.out.println(a<b&&a<c);//false && true = false
8. System.out.println(a<b&a<c);//false & true = false
9. }}
Output:
false
false
Java AND Operator Example: Logical && vs Bitwise &
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10. }}
Output:
false
10
false
11
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first condition is true.
It checks the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or
false.
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}
Output:
true
true
true
10
true
11
Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else statement and
used a lot in Java programming. It is the only conditional operator which takes three
operands.
Java Ternary Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:
2
Another Example:
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}
Output:
5
Java Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign the
value on its right to the operand on its left.
Java Assignment Operator Example
1. public class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}
Output:
14
16
Java Assignment Operator Example
1. public class OperatorExample{
2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10. a/=2;//18/2
11. System.out.println(a);
12. }}
Output:
13
9
18
9
Java Assignment Operator Example: Adding short
1. public class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}
Output:
Compile time error
rface. It can have abstract and
non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type.
It can hold True and False values only.
3. break: Java break keyword is used to break the loop or switch statement. It
breaks the current flow of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data
values.
5. case: Java case keyword is used with the switch statements to mark blocks of
text.
6. catch: Java catch keyword is used to catch the exceptions generated by try
statements. It must be used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-
bit Unicode characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition.
10. default: Java default keyword is used to specify the default block of code in a
switch statement.
11. do: Java do keyword is used in the control statement to declare a loop. It can
iterate a part of the program several times.
12. double: Java double keyword is used to declare a variable that can hold 64-bit
floating-point number.
13. else: Java else keyword is used to indicate the alternative branches in an if
statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum
constructors are always private or default.
15. extends: Java extends keyword is used to indicate that a class is derived from
another class or interface.
16. final: Java final keyword is used to indicate that a variable holds a constant
value. It is used with a variable. It is used to restrict the user from updating the
value of the variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure.
This block is always executed whether an exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit
floating-point number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the
number of iteration is fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is
true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and
accessible to the current source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an
instance of the specified class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.
25. interface: Java interface keyword is used to declare an interface. It can have
only abstract methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit
integer.
27. native: Java native keyword is used to specify that a method is implemented in
native code using JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to
anything. It removes the garbage value.
30. package: Java package keyword is used to declare a Java package that includes
the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a
method or variable may be accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible
within the package and outside the package but through inheritance only. It can't
be applied with the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an
item is accessible anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution
is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit
integer.
36. static: Java static keyword is used to indicate that a variable or method is a class
method. The static keyword in Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure
portability.
38. super: Java super keyword is a reference variable that is used to refer to parent
class objects. It can be used to invoke the immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code
based on test value. The switch statement tests the equality of a variable against
multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical
sections or methods in multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or
constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The
throw keyword is mainly used to throw custom exceptions. It is followed by an
instance.
43. throws: The Java throws keyword is used to declare an exception. Checked
exceptions can be propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data
member as transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return
value.
47. volatile: Java volatile keyword is used to indicate that a variable may change
asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part
of the program several times. If the number of iteration is not fixed, it is
recommended to use the while loop.
Java Control Statements | Control Flow in Java
Consider the following example in which we have used the if statement in the java
code.
Student.java
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. System.out.println("x + y is greater than 20");
7. }
8. }
9. }
Output:
x + y is greater than 20
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:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Consider the following example.
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
3) if-else-if ladder:
• The if-else-if statement contains the if-statement followed by multiple else-if
statements.
• In other words, we can say that it is the chain of if-else statements that create a
decision tree where the program may enter in the block of code where the condition
is true.
• We can also define an else statement at the end of the chain.
Syntax of if-else-if statement is given below.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Consider the following example.
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. System.out.println("city is meerut");
6. }else if (city == "Noida") {
7. System.out.println("city is noida");
8. }else if(city == "Agra") {
9. System.out.println("city is agra");
10. }else {
11. System.out.println(city);
12. }
13. }
14. }
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside
another if or else-if statement.
Syntax of Nested if-statement is given below.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Consider the following example.
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. String address = "Delhi, India";
4.
5. if(address.endsWith("India")) {
6. if(address.contains("Meerut")) {
7. System.out.println("Your city is Meerut");
8. }else if(address.contains("Noida")) {
9. System.out.println("Your city is Noida");
10. }else {
11. System.out.println(address.split(",")[0]);
12. }
13. }else {
14. System.out.println("You are not living in India");
15. }
16. }
17. }
Output:
Delhi
Switch Statement:
• In Java, Switch statements are similar to if-else-if statements.
• The switch statement contains multiple blocks of code called cases and a single case
is executed based on the variable which is being switched.
• The switch statement is easier to use instead of if-else-if statements.
• It also enhances the readability of the program.
Points to be noted about switch statement:
• The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
• Cases cannot be duplicate
• Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
• Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
• While using switch statements, we must notice that the case expression will be of
the same type as the variable. However, it will also be a constant value.
The syntax to use the switch statement is given below.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Consider the following example to understand the flow of the switch statement.
Student.java
1. public class Student implements Cloneable {
2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. System.out.println("number is 0");
7. break;
8. case 1:
9. System.out.println("number is 1");
10. break;
11. default:
12. System.out.println(num);
13. }
14. }
15. }
Output:
2
• While using switch statements, we must notice that the case expression will be of
the same type as the variable.
• However, it will also be a constant value.
• The switch permits only int, string, and Enum type variables to be used.
Loop Statements
• In programming, sometimes we need to execute the block of code repeatedly while
some condition evaluates to true.
• However, loop statements are used to execute the set of instructions in a repeated
order.
• The execution of the set of instructions depends upon a particular condition.
• In Java, we have three types of loops that execute similarly.
• However, there are differences in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
Let's understand the loop statements one by one.
Java for loop
• In Java, for loop is similar to C and C++.
• It enables us to initialize the loop variable, check the condition, and
increment/decrement in a single line of code.
• We use the for loop only when we exactly know the number of times, we want to
execute the block of code.