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

UNIT I Java

The document provides an overview of Java, a high-level object-oriented programming language created by Sun Microsystems in 1995, highlighting its key features such as portability, security, and robustness. It explains fundamental concepts of object-oriented programming (OOP), including classes, objects, inheritance, polymorphism, abstraction, and encapsulation, along with the architecture of Java programs and their structure. Additionally, it outlines steps to write and run Java code, applications of Java, and the advantages of OOP over procedural programming.

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)
37 views88 pages

UNIT I Java

The document provides an overview of Java, a high-level object-oriented programming language created by Sun Microsystems in 1995, highlighting its key features such as portability, security, and robustness. It explains fundamental concepts of object-oriented programming (OOP), including classes, objects, inheritance, polymorphism, abstraction, and encapsulation, along with the architecture of Java programs and their structure. Additionally, it outlines steps to write and run Java code, applications of Java, and the advantages of OOP over procedural programming.

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/ 88

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 langua+ge. 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 byte code.
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
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 concepts 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 an
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. {
3. public static void main(String[] args)
4. {
System.out.println("Hello, World!");
}
}
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 Private Class, 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 Non Static Main Example, 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
interface. 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.
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }
The flow chart for the for-loop is given below.

Consider the following example to understand the proper functioning of the for loop in java.
Calculation.java
1. public class Calculattion {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. System.out.println("The sum of first 10 natural numbers is " + sum);
9. }
10. }
Output:
The sum of first 10 natural numbers is 55
Java for-each loop
• Java provides an enhanced for loop to traverse the data structures like array or collection.
• In the for-each loop, we don't need to update the loop variable.
The syntax to use the for-each loop in java is given below.
1. for(data_type var : array_name/collection_name){
2. //statements
3. }
Consider the following example to understand the functioning of the for-each loop in Java.
Calculation.java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. System.out.println("Printing the content of the array names:\n");
6. for(String name:names) {
7. System.out.println(name);
8. }
9. }
10. }

Output:
Printing the content of the array names:

Java
C
C++
Python
JavaScript
Java while loop
• The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a while
loop.
• Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
• It is also known as the entry-controlled loop since the condition is checked at the start of the loop.
• If the condition is true, then the loop body will be executed; otherwise, the statements after the loop
will be executed.
The syntax of the while loop is given below.
1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.

Consider the following example.


Calculation .java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. System.out.println(i);
8. i = i + 2;
9. }
10. }
11. }
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Java do-while loop
• The do-while loop checks the condition at the end of the loop after executing the loop statements.
• When the number of iteration is not known and we have to execute the loop at least once, we can use
do-while loop.
• It is also known as the exit-controlled loop since the condition is not checked in advance.
The syntax of the do-while loop is given below.
1. do
2. {
3. //statements
4. } while (condition);
The flow chart of the do-while loop is given in the following image.

Consider the following example to understand the functioning of the do-while loop in Java.
Calculation.java
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
Jump Statements
• Jump statements are used to transfer the control of the program to the specific statements.
• In other words, jump statements transfer the execution control to the other part of the program.
• There are two types of jump statements in Java, i.e., break and continue.
Java break statement
• As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement.
• However, it breaks only the inner loop in the case of the nested loop.
• The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
The break statement example with for loop
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
1. public class BreakExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. System.out.println(i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }
Output:
0
1
2
3
4
5
6
break statement example with labeled for loop
Calculation.java
1. public class Calculation {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. a:
6. for(int i = 0; i<= 10; i++) {
7. b:
8. for(int j = 0; j<=15;j++) {
9. c:
10. for (int k = 0; k<=20; k++) {
11. System.out.println(k);
12. if(k==5) {
13. break a;
14. }
15. }
16. }
17.
18. }
19. }
20.
21.
22. }
Output:
0
1
2
3
4
5
Java continue statement
• Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
1. public class ContinueExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. System.out.println(j);
14. }
15. }
16. }
17.
18. }
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Java static keyword
• The static keyword in Java is used for memory management mainly.
• We can apply static keyword with variables, methods, blocks and nested classes.
• The static keyword belongs to the class than an instance of the class.
The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
• Beyond memory management, the static keyword in Java has several other uses.
• When it comes to variables, it means that the variable is shared by all instances of the class and
belongs to the class as a whole, not just any one instance.
• Static methods are available throughout the programme since they can be called without first
generating an instance of the class.
• When the class loads, static blocks are used to initialise static variables or carry out one-time
operations.
• Furthermore, nested static classes can be instantiated individually but are still linked to the outer
class.
• Moreover, class names can be used to access static variables and methods directly, eliminating the
need to build an object instance.
• This is especially helpful for constants or utility methods.
1) Java static variable
If we declare any variable as static, it is known as a static variable.
o The static variable can be used to refer to the common property of all objects (which is not unique
for each object), for example, the company name of employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
o Static variables in Java are also initialized to default values if not explicitly initialized by the
programmer. They can be accessed directly using the class name without needing to create an instance
of the class.
o Static variables are shared among all instances of the class, meaning if the value of a static variable
is changed in one instance, it will reflect the change in all other instances as well.
Advantages of Static Variable
1. It makes your program memory efficient (i.e., it saves memory).
Understanding The Problem Without Static Variable
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";
5. }

• Suppose there are 500 students in my college; now all instance data members will get memory each
time when the object is created.
• All students have their unique rollno and name, so instance data member is good in such case.
• Here, "college" refers to the common property of all objects.
• If we make it static, this field will get the memory only once.
Example of Static Variable
Filename: TestStaticVariable1.java
1. //Java Program to demonstrate the use of static variable
2. class Student{
3. int rollno;//instance variable
4. String name;
5. static String college ="ITS";//static variable
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){System.out.println(rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //Student.college="BBDIT";
21. s1.display();
22. s2.display();
23. }
24. }
Output:
111 Karan ITS
222 Aryan ITS
Explanation
• The usage of static variables is demonstrated in this Java programme.
• In addition to a static variable called college, the Student class defines two instance variables: rollno
and name.
• It has a constructor to set the instance variables' initial values and a display() function to output the
rollno, name, and college values.
• Two Student objects, s1 and s2, with different roll numbers and names, are created via the
TestStaticVariable1 class.
• After that, each object's display() method is called, printing its details.
• The college name can be modified for all objects at once by uncommenting the line
Student.college="BBDIT";, demonstrating how static variables are shared by all
instances of a class

Program of The Counter Without Static Variable


• In this example, we have created an instance variable named count which is incremented in the
constructor.
• Since the instance variable gets the memory at the time of object creation, each object will have a
copy of the instance variable.
• If it is incremented, it won't reflect other objects.
• So each object will have the value 1 in the count variable.
Filename: Counter.java
1. //Java Program to demonstrate the use of an instance variable
2. //which get memory each time when we create an object of the class.
3. class Counter{
4. int count=0;//will get memory each time when the instance is created
5.
6. Counter(){
7. count++;//incrementing value
8. System.out.println(count);
9. }
10.
11. public static void main(String args[]){
12. //Creating objects
13. Counter c1=new Counter();
14. Counter c2=new Counter();
15. Counter c3=new Counter();
16. }
17. }
Output:
1
1
1
Explanation
• The idea of instance variables that are specific to each object derived from a class is demonstrated
by this Java programme.
• The count variable in the Counter class is an instance variable that is allocated memory each time an
object of the class is instantiated.
• It is initialized to zero. Every time an object is produced, the constructor prints the current value of
the count variable and increases it.
• Three Counter objects (c1, c2, and c3) with separate instances of the count variable are generated in
the main procedure.
• Because of this, the count is increased independently for each object that is generated, and the output
shows the count value for each object that increases successively.
Program of Counter by Static Variable
As we have mentioned above, static variable will get the memory only once, if any object changes the
value of the static variable, it will retain its value.
File name: Counter2.java
1. //Java Program to illustrate the use of static variable which
2. //is shared with all objects.
3. class Counter2{
4. static int count=0;//will get memory only once and retain its value
5.
6. Counter2(){
7. count++;//incrementing the value of static variable
8. System.out.println(count);
9. }
10.
11. public static void main(String args[]){
12. //creating objects
13. Counter2 c1=new Counter2();
14. Counter2 c2=new Counter2();
15. Counter2 c3=new Counter2();
16. }
17. }
Output:
1
2
3
Explanation
• This Java program demonstrates the utilization of a static variable, which is shared
among all objects created from the class.
• In the Counter2 class, the count variable is declared as static, ensuring it is allocated
memory only once and retains its value across all instances of the class.
• Each time an object of the class is created, the constructor increments the value of
the static variable count and prints its current value.
• In the main method, three Counter2 objects (c1, c2, and c3) are instantiated, and as
they share the same static variable count, its value increments sequentially across
the objects, reflecting the shared nature of static variables among all instances of a
class.
2) Java Static Method
If we apply a static keyword with any method, it is known as a static method.
• A static method belongs to the class rather than the object of a class
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data members and can change their value of it.

Filename: TestStaticMethod.java
1. //Java Program to demonstrate the use of a static method.
2. class Student{
3. int rollno;
4. String name;
5. static String college = "ITS";
6. //static method to change the value of static variable
7. static void change(){
8. college = "BBDIT";
9. }
10. //constructor to initialize the variable
11. Student(int r, String n){
12. rollno = r;
13. name = n;
14. }
15. //method to display values
16. void display(){System.out.println(rollno+" "+name+" "+college);}
17. }
18. //Test class to create and display the values of object
19. public class TestStaticMethod{
20. public static void main(String args[]){
21. Student.change();//calling change method
22. //creating objects
23. Student s1 = new Student(111,"Karan");
24. Student s2 = new Student(222,"Aryan");
25. Student s3 = new Student(333,"Sonoo");
26. //calling display method
27. s1.display();
28. s2.display();
29. s3.display();
30. }
31. }

Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Explanation
• This Java programme demonstrates how to use a static method inside of a class.
• In addition to a static variable called college, the Student class defines two instance
variables: rollno and name.
• To alter the value of the static variable college, it has a static function called
change().
• In addition, the class has a constructor for initialising instance variables and a
display() method for printing the rollno, name, and college values.
• The main method of the TestStaticMethod class shows how to use the change()
method to modify the college value.
• After then, the display() method is used to create three Student objects (s1, s2, and
s3) with distinct roll numbers and names, and their details are shown.
• This illustrates how the static method change() influences the static variable college
for all instances of the class.
• Let's see another example of a static method that performs a normal calculation.
Filename: Calucalte.java
1. //Java Program to get the cube of a given number using the static method
2.
3. class Calculate{
4. static int cube(int x){
5. return x*x*x;
6. }
7.
8. public static void main(String args[]){
9. int result=Calculate.cube(5);
10. System.out.println(result);
11. }
12. }
Output:
125
Explanation
• This Java programme shows how to find the cube of a given number by using a
static function.
• The static method cube(int x) in the Calculate class multiplies an integer parameter
x three times to return its cube.
• The same class's main method demonstrates how to use the class name Calculate to
directly access the static method cube() without first having to create an instance of
the class.
• The cube() method is used in this example with argument 5, and the outcome is
saved in the variable result before being printed to the console.
• This programme demonstrates how easy and effective it is to use static methods for
routine computations or actions that don't call for object creation.
Restrictions for the Static Method
There are the following two main restrictions for the static method.
1. The static method cannot use non-static data members or call a non-static
method directly.
2. this and super keyword cannot be used in static context.
Filename: A.java
1. class A{
2. int a=40;//non static
3.
4. public static void main(String args[]){
5. System.out.println(a);
6. }
7. }
Output:
Compile Time Error

Explanation
• The Java code provided contains a class called A.
• A defined instance variable with the value 40 that is designated as non-static is
present in class A.
• Nonetheless, an attempt is made to use System.out.println(a); to directly access the
instance variable an in the class A main method.
• Because static methods in Java cannot directly access non-static variables, this will
lead to a compilation problem.
• An instance of class A must first be generated in order to access the non-static
variable an inside the static main method.
• The variable a can then be accessed using that instance.
• It would therefore be OK to use A obj = new A(); System.out.println(obj.a); to
access an in the main method.
Q) Why is the Java main() method static?
Ans) In Java, main() method is static because the object is not required to call a static
method.
If it were a non-static method, the JVM would create an object first and then call the
main() method, which would lead to the problem of extra memory allocation.
3) Java Static Block
o It is used to initialize the static data member.
o It is executed before the main() method at the time of class loading.
Example of Static block
Filename: A2.java
1. class A2{
2. static{System.out.println("static block is invoked");}
3. public static void main(String args[]){
4. System.out.println("Hello main");
5. }
6. }
Output:
static block is invoked
Hello main

Explanation
• In the given Java code, there's a class named A2.
• Inside this class, there's a static block, which is a block of code enclosed within
curly braces and marked with the static keyword.
• Static blocks are executed only once when the class is loaded into memory, before
the execution of the main method or the creation of any object of the class.
• In this case, the static block contains the statement System.out.println("static block
is invoked");, that prints the message "static block is invoked" to the console when
the class A2 is loaded into memory.
• Additionally, there's a main method in the class A2 that prints "Hello main" to the
console when executed.
• However, since the main method is the entry point of the program, it needs to be
invoked explicitly, typically by the Java Virtual Machine (JVM) when executing
the program.
• Therefore, when you run the program, the static block is executed first, printing the
message from the static block, followed by the execution of the main method,
printing "Hello main" to the console.
Q) Can we execute a program without main() method?
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since
JDK 1.7, it is not possible to execute a Java class without the main() method.
Filename: A3.java1. class A3{
2. static{
3. System.out.println("static block is invoked");
4. System.exit(0);
5. }
6. }

Output:
static block is invoked
Since JDK 1.7 and above, output would be:
Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

Explanation
• Class A3 in the provided Java code has a static block that uses System.exit(0); to
end the program after printing "static block is invoked" to the console.
• Because of this, the static block runs when the class loads into memory, printing
the message and stopping the program right away to stop more code from running.
4) Java Nested Classes
In Java, a nested class is a class declared within another class. There are four types of
nested classes:
1. Static Nested Class: A static nested class is declared with the static keyword. It
behaves like a regular top-level class but is nested for packaging convenience.
Static nested classes cannot directly access non-static members of the enclosing
class.
2. Non-static Nested Class (Inner Class): It is also known as an inner class; it is
declared without the static keyword. Inner classes have access to the members,
including private members, of the enclosing class. They are often used to
logically group classes that only have meaning in the context of another class.
3. Local Inner Class: A local inner class is declared within a method or a code
block. It has access to the variables of the enclosing method and can access
members of the enclosing class.
4. Anonymous Inner Class: An anonymous inner class is a local inner class
without a name. It is typically used to create small, one-time-use classes, often
for implementing interfaces or extending classes.

• Nested classes can be sensibly grouped together using classes that are only used
once, improving code organization and encapsulation by concealing the outer
class's implementation specifics.
• Nested classes provide a way to logically group classes that are only used in one
place, thereby increasing encapsulation and code organization.
• They also enhance encapsulation by hiding the implementation details of the outer
class.
Static Method in Java
• Java, a widely acclaimed programming language, stands out for its robust object-
oriented design.
• An indispensable component that distinguishes Java from others is its utilization of
static methods.
• These crucial tools empower developers to craft utility functions, gain access to
class-level variables, and optimize code execution.
• Throughout this article, we will delve deeper into the concept of static methods in
Java, highlight their benefits, and furnish a comprehensive example to demonstrate
their practicality.
• By the end, you'll have a profound understanding of how to harness the power of
static methods to optimize Java programs.
Understanding Static Methods
• In Java, a method can be declared as "static" to indicate that it belongs to the class
rather than an instance of the class.
• This means that static methods are shared among all instances of the class and can
be invoked using the class name itself, without creating an object.
• To declare a static method, we use the "static" keyword before the method
signature.
Advantages of Using Static Methods
1. Simplicity and Readability: Static methods make the code more
straightforward and concise. Since they are not bound to any instance,
developers can call these methods directly from the class itself, eliminating the
need to create an object first.
2. Code Reusability: Static methods are commonly used to create utility functions
that are not dependent on specific instance variables. They can be used across
various classes without modification, promoting code reusability and
maintenance.
3. Memory Efficiency: Unlike instance methods, static methods are loaded into
memory only once when the class is first accessed, regardless of the number of
instances created. This results in lower memory consumption and faster
execution.
4. Global Accessibility: Static methods can be accessed from anywhere in the
program using the class name, making them accessible globally.
5. No Need for Instantiation: As static methods belong to the class itself, they
can be called without creating an object. This feature is particularly beneficial
when we don't need to maintain state between method calls.
Usage of Static Methods
• To illustrate the usage of static methods, let's consider an example where we want
to create a simple utility class for mathematical operations.
• We will design a class named "MathUtils" containing static methods to perform
basic arithmetic operations: addition, subtraction, multiplication, and division.
StaticMethodExample.java
1. // MathUtils class with static methods for basic arithmetic operations
2. public class MathUtils {
3. // Static method for addition
4. public static int add(int a, int b) {
5. return a + b;
6. }
7. // Static method for subtraction
8. public static int subtract(int a, int b) {
9. return a - b;
10. }
11. // Static method for multiplication
12. public static int multiply(int a, int b) {
13. return a * b;
14. }
15. // Static method for division
16. public static double divide(int a, int b) {
17. if (b == 0) {
18. throw new IllegalArgumentException("Cannot divide by zero.");
19. }
20. return (double) a / b;
21. }
22. }
23. // Main class to demonstrate the usage of static methods from MathUtils class
24. public class StaticMethodExample {
25. public static void main(String[] args) {
26. // Input numbers
27. int num1 = 10;
28. int num2 = 5;
29. // Using static methods from MathUtils class to perform arithmetic operati
ons
30. int sum = MathUtils.add(num1, num2);
31. int difference = MathUtils.subtract(num1, num2);
32. int product = MathUtils.multiply(num1, num2);
33. double quotient = MathUtils.divide(num1, num2);
34. // Displaying the results
35. System.out.println("Sum: " + sum);
36. System.out.println("Difference: " + difference);
37. System.out.println("Product: " + product);
38. System.out.println("Quotient: " + quotient);
39. }
40. }

Output:
Sum: 15
Difference: 5
Product: 50
Quotient: 2.0

• In this example, we used the static methods from the "MathUtils" class to perform
basic arithmetic operations.
• Since the methods are static, we accessed them directly using the class name
"MathUtils," without creating an instance of the class.
• In summary, Static methods in Java play a vital role in promoting code efficiency,
reusability, and clarity.
• They allow developers to create utility functions that are not tied to any instance,
providing a global accessibility that simplifies their usage across different classes.
• Additionally, static methods contribute to memory efficiency by loading only once,
thus reducing memory overhead.
• Understanding the appropriate use of static methods is crucial in maintaining a well-
structured and optimized codebase.
• By recognizing their advantages and leveraging them judiciously, developers can
harness the power of static methods to enhance their Java programs significantly.
Java StringBuffer Class

• Java StringBuffer class is used to create mutable (modifiable) String objects.


• The StringBuffer class in Java is the same as String class except it is mutable i.e. it
can be changed.
Difference between String and StringBuffer

• There are many differences between String and StringBuffer.


• A list of differences between String and StringBuffer are given below:
Performance Test of String and StringBuffer
ConcatTest.java
1. public class ConcatTest{
2. public static String concatWithString() {
3. String t = "Java";
4. for (int i=0; i<10000; i++){
5. t = t + "Tpoint";
6. }
7. return t;
8. }
9. public static String concatWithStringBuffer(){
10. StringBuffer sb = new StringBuffer("Java");
11. for (int i=0; i<10000; i++){
12. sb.append("Tpoint");
13. }
14. return sb.toString();
15. }
16. public static void main(String[] args){
17. long startTime = System.currentTimeMillis();
18. concatWithString();
19. System.out.println("Time taken by Concating with String: "+(System.curr
entTimeMillis()-startTime)+"ms");
20. startTime = System.currentTimeMillis();
21. concatWithStringBuffer();
22. System.out.println("Time taken by Concating with StringBuffer: "+(Syst
em.currentTimeMillis()-startTime)+"ms");
23. }
24. }

Output:
Time taken by Concating with String: 578ms
Time taken by Concating with StringBuffer: 0ms

The above code, calculates the time required for concatenating a string using the String
class and StringBuffer class.
String and StringBuffer HashCode Test
As we can see in the program given below, String returns new hashcode while
performing concatenation but the StringBuffer class returns same hashcode
InstanceTest.java
1. public class InstanceTest{
2. public static void main(String args[]){
3. System.out.println("Hashcode test of String:");
4. String str="java";
5. System.out.println(str.hashCode());
6. str=str+"tpoint";
7. System.out.println(str.hashCode());
8.
9. System.out.println("Hashcode test of StringBuffer:");
10. StringBuffer sb=new StringBuffer("java");
11. System.out.println(sb.hashCode());
12. sb.append("tpoint");
13. System.out.println(sb.hashCode());
14. }
15. }

Output:
Hashcode test of String:
3254818
229541438
Hashcode test of StringBuffer:
118352462
118352462

1. for(initialization,
condition,
increment/decremen
t) {
2. //block of
statements
3. }
The flow chart for the
for-loop is given
below.

You might also like