KEMBAR78
UNIT I Java | PDF | Java (Programming Language) | Java Virtual Machine
0% found this document useful (0 votes)
43 views68 pages

UNIT I Java

This document provides an introduction to Java, highlighting its object-oriented features, architecture, and programming structure. It covers Java's key characteristics such as portability, security, and robustness, along with fundamental OOP concepts like classes, inheritance, and polymorphism. Additionally, it outlines the steps to write and run Java code, as well as its applications in various domains.

Uploaded by

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

UNIT I Java

This document provides an introduction to Java, highlighting its object-oriented features, architecture, and programming structure. It covers Java's key characteristics such as portability, security, and robustness, along with fundamental OOP concepts like classes, inheritance, and polymorphism. Additionally, it outlines the steps to write and run Java code, as well as its applications in various domains.

Uploaded by

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

UNIT –I

Introduction: Review of Object-Oriented concepts - Java buzzwords (Platform independence,


Portability, Threads)- JVM architecture –Java Program structure - –Java main method - Java
Console output(System.out) - simple java program - Data types - Variables - type conversion
and casting- Java Console input: Buffered input - operators - control statements - Static Data -
Static Method - String and String Buffer Classes.

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!");
}
}

Steps to Write and Run Java Code


1. Install JDK: Download and install the JDK from Oracle or OpenJDK.
2. Write the Code: Use any text editor or an Integrated Development
Environment (IDE) like IntelliJ IDEA or Eclipse.
3. Compile the Code: Use the javac command to compile the source code.
javac HelloWorld.java
4. Run the Program: Use the java command to run the compiled bytecode.
java HelloWorld

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.

Advantage of OOPs over Procedure-Oriented Programming Language


1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented
programming language, it is not easy to manage if code grows as project size increases.
2) OOPs provides data hiding, whereas, in a procedure-oriented programming
language, global data can be accessed from anywhere.
Figure: Data Representation in Procedure-Oriented Programming

Figure: Data Representation in Object-Oriented Programming


3) OOPs provides the ability to simulate real-world event much more effectively. We
can provide the solution of real word problem if we are using the Object-Oriented
Programming language.
What is the difference between an object-oriented programming language and
object-based programming language?
• Object-based programming language follows all the features of OOPs except
Inheritance.
• JavaScript and VBScript are examples of object-based programming languages.
Filename: OOPs.java
1. // Java program for demonstrating the features and functionalities of OOPs con
cepts in Java.
2. class Animal {
3. private String name;
4.
5. // Constructor
6. public Animal(String name) {
7. this.name = name;
8. }
9.
10. // Encapsulation: Getter method
11. public String getName() {
12. return name;
13. }
14.
15. // Polymorphism: Overridden method
16. public void makeSound() {
17. System.out.println("Some sound");
18. }
19. }
20.
21. // Derived class (Inheritance)
22. class Dog extends Animal {
23. // Constructor
24. public Dog(String name) {
25. super(name);
26. }
27.
28. // Polymorphism: Overriding method
29. @Override
30. public void makeSound() {
31. System.out.println("Woof");
32. }
33. }
34.
35. // Derived class (Inheritance)
36. class Cat extends Animal {
37. // Constructor
38. public Cat(String name) {
39. super(name);
40. }
41.
42. // Polymorphism: Overriding method
43. @Override
44. public void makeSound() {
45. System.out.println("Meow");
46. }
47. }
48.
49. public class OOPs {
50. public static void main(String[] args) {
51. // Creating objects of Dog and Cat classes
52. Dog dog = new Dog("Buddy");
53. Cat cat = new Cat("Whiskers");
54.
55. // Accessing methods of base class through objects of derived classes
56. System.out.println("Dog name: " + dog.getName());
57. dog.makeSound();
58.
59. System.out.println("Cat name: " + cat.getName());
60. cat.makeSound();
61. }
62. }
Output:
Dog name: Buddy
Woof
Cat name: Whiskers
Meow
JVM (Java Virtual Machine) Architecture
1. Java Virtual Machine
2. Internal Architecture of JVM
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.
What it does? 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.
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run
the java program, it is loaded first by the classloader. There are three built-in
classloaders in Java.
1. Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes,
java.util package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent
classloader of System classloader. It loades the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension
classloader. It loads the classfiles from classpath. By default, classpath is set to
current directory. You can change the classpath using "-cp" or "-classpath"
switch. It is also known as Application classloader.

1. //Let's see an example to print the classloader name


2. public class ClassLoaderExample
3. {
4. public static void main(String[] args)
5. {
6. // Let's print the classloader name of current class.
7. //Application/System classloader will load this class
8. Class c=ClassLoaderExample.class;
9. System.out.println(c.getClassLoader());
10. //If we print the classloader name of String, it will print null because it is a
n
11. //in-
built class which is found in rt.jar, so it is loaded by Bootstrap classloader
12. System.out.println(String.class.getClassLoader());
13. }
14. }
Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null
These are the internal classloaders provided by Java. If you want to create your own
classloader, you need to extend the ClassLoader class.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.
3) Heap
It is the runtime data area in which objects are allocated.
4) Stack
• Java Stack stores frames. It holds local variables and partial results, and plays a
part in method invocation and return.
• Each thread has a private JVM stack, created at the same time as thread.
• A new frame is created each time a method is invoked. A frame is destroyed
when its method invocation completes.
5) Program Counter Register
PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.
6) Native Method Stack:It contains all the native methods used in the application.
7) Execution Engine:It contains:
A virtual processor
1. Interpreter: Read bytecode stream then execute the instructions.
2. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT
compiles parts of the byte code that have similar functionality at the same time,
and hence reduces the amount of time needed for compilation. Here, the term
"compiler" refers to a translator from the instruction set of a Java virtual machine
(JVM) to the instruction set of a specific CPU.
8) Java Native Interface
Java Native Interface (JNI) is a framework which provides an interface to communicate
with another application written in another language like C, C++, Assembly etc. Java
uses JNI framework to send output to the Console or interact with OS libraries.
Java Tokens
In Java, the program contains classes and methods. Further, the methods contain the
expressions and statements required to perform a specific operation. These statements
and expressions are made up of tokens. In other words, we can say that the expression
and statement is a set of tokens. The tokens are the small building blocks of a Java
program that are meaningful to the Java compiler. Further, these two components
contain variables, constants, and operators. In this section, we will discuss what is
tokens in Java.
What is token in Java?
The Java compiler breaks the line of code into text (words) is called Java tokens.
These are the smallest element of the Java program. The Java compiler identified these
words as tokens. These tokens are separated by the delimiters. It is useful for compilers
to detect errors. Remember that the delimiters are not part of the Java tokens.
1. token <= identifier | keyword | separator | operator | literal | comment

For example, consider the following code.


1. public class Demo
2. {
3. public static void main(String args[])
4. {
5. System.out.println("javatpoint");
6. }
7. }

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

Literals: In programming literal is a notation that represents a fixed value (constant)


in the source code. It can be categorized as an integer literal, string literal, Boolean
literal, etc. It is defined by the programmer. Once it has been defined cannot be
changed. Java provides five types of literals are as follows:
o Integer
o Floating Point
o Character
o String
o Boolean
Operators: In programming, operators are the special symbol that tells the compiler
to perform a special operation. Java provides different types of operators that can be
classified according to the functionality they provide. There are eight types
of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators
Separators: The separators in Java is also known as punctuators. There are nine
separators in Java, are as follows:
1. separator <= ; | , | . | ( | ) | { | } | [ | ]

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 */.

Data Types in Java


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.
Let's understand in detail about the two major data types of Java in the following
paragraphs.
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.
• Java is a statically-typed programming language.
• It means, all variables must be declared before its use.
• That is why we need to declare variable's type and name.
• In Java, there are mainly eight primitive data types and let's understand about them
in detail in the following paragraphs.
Java 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
double
0.0d
8 byte

Boolean Data Type

• 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

• In Java, short variables are declared using the short keyword.


• For example, short myShort = 1000; declares a short variable
named myShort and initializes it with the value 1000.
• As with the byte data type, short variables must be explicitly cast when used in
expressions with larger integer types to avoid loss of precision.
Int Data Type
• The int data type in Java is a primitive data type that represents a 32-bit signed two's
complement integer.
• It has a range of values from -2,147,483,648 to 2,147,483,647.
• The int data type is one of the most commonly used data types in Java and is
typically used to store whole numbers without decimal points.
• Its default value is 0.
Example:
1. int a = 100000, int b = -200000
• In Java, int variables are declared using the int keyword.
• For example, int myInt = 100; declares an int variable named myInt and initializes
it with the value 100.
• int variables can be used in mathematical expressions, assigned to other int
variables, and used in conditional statements.
Long Data Type
• The long data type in Java is a primitive data type that represents a 64-bit signed
two's complement integer.
• It has a wider range of values than int, ranging from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807.
• Its default value is 0.0F.
• The long data type is used when int is not large enough to hold the desired value,
or when a larger range of integer values is needed.
Example:
1. long a = 100000L, long b = -200000L
• The long data type is commonly used in applications where large integer values are
required, such as in scientific computations, financial applications, and systems
programming.
• It provides greater precision and a larger range than int, making it suitable for
scenarios where int is insufficient.
Float Data Type
• The float data type in Java is a primitive data type that represents single-precision
32-bit IEEE 754 floating-point numbers.
• It can represent a wide range of decimal values, but it is not suitable for precise
values such as currency.
• The float data type is useful for applications where a higher range of values is
needed, and precision is not critical.
Example:
1. float f1 = 234.5f
• One of the key characteristics of the float data type is its ability to represent a wide
range of values, both positive and negative, including very small and very large
values.
• However, due to its limited precision (approximately 6-7 significant decimal
digits), it is not suitable for applications where exact decimal values are required.
Double Data Type
• The double data type in Java is a primitive data type that represents double-
precision 64-bit IEEE 754 floating-point numbers.
• Its default value is 0.0d.
• It provides a wider range of values and greater precision compared to the float data
type, making it suitable for applications where accurate representation of decimal
values is required.
Example:
1. double d1 = 12.3
• One of the key advantages of the double data type is its ability to represent a wider
range of values with greater precision compared to float.
• It can accurately represent values with up to approximately 15-16 significant
decimal digits, making it suitable for applications that require high precision, such
as financial calculations, scientific computations, and graphics programming.
Char Data Type
• The char data type in Java is a primitive data type that represents a single 16-bit
Unicode character.
• It can store any character from the Unicode character set, that allows Java to support
internationalization and representation of characters from various languages and
writing systems.
Example:
1. char letterA = 'A'
• The char data type is commonly used to represent characters, such as letters, digits,
and symbols, in Java programs.
• It can also be used to perform arithmetic operations, as the Unicode values of
characters can be treated as integers.
• For example, you can perform addition or subtraction operations on char variables
to manipulate their Unicode values.
Non-Primitive Data Types in Java
• In Java, non-primitive data types, also known as reference data types, are used to
store complex objects rather than simple values.
• Unlike primitive data types that store the actual values, reference data types store
references or memory addresses that point to the location of the object in memory.
• This distinction is important because it affects how these data types are stored,
passed, and manipulated in Java programs.
Class
• One common non-primitive data type in Java is the class.
• Classes are used to create objects, which are instances of the class.
• A class defines the properties and behaviors of objects, including variables (fields)
and methods.
• For example, you might create a Person class to represent a person, with variables
for the person's name, age, and address, and methods to set and get these values.
Interface
• Interfaces are another important non-primitive data type in Java.
• An interface defines a contract for what a class implementing the interface must
provide, without specifying how it should be implemented.
• Interfaces are used to achieve abstraction and multiple inheritance in Java, allowing
classes to be more flexible and reusable.
Arrays
• Arrays are a fundamental non-primitive data type in Java that allow you to store
multiple values of the same type in a single variable.
• Arrays have a fixed size, which is specified when the array is created, and can be
accessed using an index.
• Arrays are commonly used to store lists of values or to represent matrices and other
multi-dimensional data structures.
Enum
• Java also includes other non-primitive data types, such as enums and collections.
Enums are used to define a set of named constants, providing a way to represent a
fixed set of values.
• Collections are a framework of classes and interfaces that provide dynamic data
structures such as lists, sets, and maps, which can grow or shrink in size as needed.
• Overall, non-primitive data types in Java are essential for creating complex and
flexible programs.
• They allow you to create and manipulate objects, define relationships between
objects, and represent complex data structures.
• By understanding how to use non-primitive data types effectively, you can write
more efficient and maintainable Java code.
Why char uses 2 byte in Java and what is \u0000?
• It is because Java uses Unicode system not ASCII code system.
• The \u0000 is the lowest range of Unicode system.
• To get detail explanation about Unicode visit next page.
Java 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.
• There are two types of data types in Java: primitive and non-primitive.
Variable
• A variable is the name of a reserved area allocated in memory.
• In other words, it is a name of the memory location.
• It is a combination of "vary + able" which means its value can be changed.
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 to understand the types of variables in java
1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class
Java Variable Example: Add Two Numbers
1. public class Simple{
2. public static void main(String[] args){
3. int a=10;
4. int b=10;
5. int c=a+b;
6. System.out.println(c);
7. }
8. }

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

Type Casting and Type Conversion


• The two terms type casting and the type conversion are used in a program to
convert one data type to another data type.
• The conversion of data type is possible only by the compiler when they are
compatible with each other.
• Let's discuss the difference between type casting and type conversion in any
programming language.
What is a type casting?
• When a data type is converted into another data type by a programmer or user while
writing a program code of any programming language, the mechanism is known
as type casting.
• The programmer manually uses it to convert one data type into another.
• It is used if we want to change the target data type to another data type.
• Remember that the destination data type must be smaller than the source data type.
• Hence it is also called a narrowing conversion

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

What is type conversion?


• If a data type is automatically converted into another data type at compile time is
known as type conversion.
• The conversion is performed by the compiler if both data types are compatible with
each other.
• Remember that the destination data type should not be smaller than the source type.
• It is also known as widening conversion of the data type.

• Let's understand the type conversion with an example.


• Suppose, we have an int data type and want to convert it into a float data type.
• These are data types compatible with each other because their types are numeric,
and the size of int is 2 bytes which is smaller than float data type.
• Hence, the compiler automatically converts the data types without losing or
truncating the values.
1. int a = 20;
2. Float b;
3. b = a; // Now the value of variable b is 20.000
/* It defines the conversion of int data type to float data type without losing the
information. */
In the above example, the int data type is converted into the float, which has a larger
size than int, and hence it widens the source data type.
Let's understand type conversion through a C program.
1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. printf("\n Welcome to Javatpoint tutorials ");
6. int x = 3, y = 4; // the size of int variable is 2 byte.
7. float area; // the size of float variable is 4 bytes.
8. area = x * y; /* It is a type conversion that automatically converted by the c
ompiler at the compile time of a program. */
9. printf("\n Area of a Rectangle is : %f", area);
10. printf("\n Here, we convert int data type to the float data type");
11. getch();
12. }
Java main() method
• The main() method in Java holds a special place as the entry point for any
standalone Java application.
• When a Java program is executed, the Java Virtual Machine (JVM) looks for the
main() method to begin execution.
• This method must adhere to a strict signature to be recognized by the JVM.
• Understanding the main() method is crucial for any Java developer, as it serves as
the bridge between the program and the underlying execution environment
provided by the JVM.
• The main() is the starting point for JVM to start execution of a Java program.
• Without the main() method, JVM will not execute the program. The syntax of the
main() method is:

Filename: HelloWorld.java
1. public class HelloWorld {

2. public static void main(String[] args) {


3. System.out.println("Hello, World!");
4. }
5. }
Output:
Hello, World!

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: We can make a method static by using the keyword static.


• We should call the main() method without creating an object.
• Static methods are the method that invokes without creating the objects, so we do
not need any object to call the main() method.
• If we try to run Java code where main is not static, we get an error.
Filename: NonStaticMainExample.java
1. public class NonStaticMainExample {
2. // Incorrectly declaring the main method without 'static'
3. public void main(String[] args) {
4. System.out.println("Hello, World!");
5. }
6. }
Output:
ERROR!
Error: Main method is not static in class NonStaticMainExample, please define the
main method as:
public static void main(String[] args)

• void: In Java, every method has the return type.


• Void keyword acknowledges the compiler that main() method does not return any
value.
• If main() method is not void, we will get an error.
Filename: MainWithReturnType.java
1. public class MainWithReturnType {
2. // Incorrectly defining the main method with a return type other than 'void'
3. public static int main(String[] args) {
4. System.out.println("Hello, World!");
5. return 0; // Attempt to return an integer value
6. }
7. }
Output:
ERROR!
Error: Main method must return a value of type void in class MainWithReturnType,
please
define the main method as:
public static void main(String[] args)

• main(): It is a default signature which is predefined in the JVM.


• It is called by JVM to execute a program line by line and end the execution after
completion of this method.
• We can also overload the main() method.
• If we change the name while initiating main method, we will get an error.
Filename: IncorrectMainName.java
1. public class IncorrectMainName {
2. // Incorrectly naming the main method as 'startMain' instead of 'main'
3. public static void startMain(String[] args) {
4. System.out.println("This won't run as expected.");
5. }
6. }
Output:
Error: Could not find or load main class IncorrectMainName
String args[]: The main() method also accepts some data from the user.
It accepts a group of strings, which is called a string array.
It is used to hold the command line arguments in the form of string values.
main(String args[])
Here, agrs[] is the array name, and it is of String type. It means that it can store a group
of string. Remember, this array can also store a group of numbers but in the form of
string only. Values passed to the main() method is called arguments. These arguments
are stored into args[] array, so the name args[] is generally used for it.
Filename: CommandLineExample.java
1. public class CommandLineExample {
2. public static void main(String args[]) { // Declaring the string array with the
syntax `String args[]`
3. // Check if any command-line arguments were passed
4. if (args.length > 0) {
5. System.out.println("List of command-line arguments received:");
6. for (int i = 0; i < args.length; i++) {
7. System.out.println((i + 1) + ": " + args[i]);
8. }
9. } else {
10. System.out.println("No command-line arguments were received.");
11. }
12. }
13. }
Output:
javac CommandLineExample.java
java CommandLineExample Hello World 123
List of command-line arguments received:
1: Hello
2: World
3: 123

What happens if the main() method is written without String args[]?


• The program will compile, but not run, because JVM will not recognize the main()
method.
• Remember JVM always looks for the main() method with a string type array as a
parameter.
Execution Process
First, JVM executes the static block, then it executes static methods, and then it
creates the object needed by the program.
• Finally, it executes the instance methods. JVM executes a static block on the highest
priority basis.
• It means JVM first goes to static block even before it looks for the main() method
in the program.
Example
1. class Demo
2. {
3. static //static block
4. {
5. System.out.println("Static block");
6. }
7. public static void main(String args[]) //static method
8. {
9. System.out.println("Static method");
10. }
11. }
Output:
Static block

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

Overloading of main() Method


We can also overload the main() method. We can define any number of main() method
in the class, but the method signature must be different.
Example
1. class OverloadMain
2. {
3. public static void main(int a) //overloaded main method
4. {
5. System.out.println(a);
6. }
7. public static void main(String args[])
8. {
9. System.out.println("main method incoked");
10. main(6);
11. }
12. }
Output:
main method invoked
6
Java Console Class
• The Java Console class is be used to get input from console.
• It provides methods to read texts and passwords.
• If you read password using Console class, it will not be displayed to the user.
• The java.io.Console class is attached with system console internally.
• The Console class is introduced since 1.5.
Let's see a simple example to read text from console.
1. String text=System.console().readLine();
2. System.out.println("Text is: "+text);

Java Console class declaration


Let's see the declaration for Java.io.Console class:
1. public final class Console extends Object implements Flushable
How to get the object of Console
System class provides a static method console() that returns the singleton instance of
Console class.
1. public static Console console(){}
Let's see the code to get the instance of Console class.
1. Console c=System.console();

Java Console Example


1. import java.io.Console;
2. class ReadStringTest{
3. public static void main(String args[]){
4. Console c=System.console();
5. System.out.println("Enter your name: ");
6. String n=c.readLine();
7. System.out.println("Welcome "+n);
8. }
9. }

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

o Operator in Java is a symbol that is used to perform operations.


o For example: +, -, *, / etc.
o There are many types of operators in Java which are given below:
1. Unary Operator,
2. Arithmetic Operator,
3. Shift Operator,
4. Relational Operator,
5. Bitwise Operator,
6. Logical Operator,
7. Ternary Operator and
8. Assignment Operator
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean
Java Unary Operator Example: ++ and --
1. public class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}

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

• Java compiler executes the code from top to bottom.


• The statements in the code are executed according to the order in which they appear.
However, Java provides statements that can be used to control the flow of Java
code.
• Such statements are called control flow statements.
• It is one of the fundamental features of Java, which provides a smooth flow of
program.
Java provides three types of control flow statements.
1. Decision Making statements
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
Decision-Making statements:
• As the name suggests, decision-making statements decide which statement to
execute and when.
• Decision-making statements evaluate the Boolean expression and control the
program flow depending upon the result of the condition provided.
• There are two types of decision-making statements in Java, i.e., If statement and
switch statement.
1) If Statement:
• In Java, the "if" statement is used to evaluate a condition.
• The control of the program is diverted depending upon the specific condition.
• The condition of the If statement gives a Boolean value, either true or false.
In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
Let's understand the if-statements one by one.
1) Simple if statement:
• It is the most basic statement among all control flow statements in Java.
• It evaluates a Boolean expression and enables the program to enter a block of code
if the expression evaluates to true.
Syntax of if statement is given below
1. if(condition) {
2. statement 1; //executes when condition is true
3. }

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.

You might also like