0% found this document useful (0 votes)
2 views84 pages

OOP Java Unit 1

Java is a versatile programming language designed to be simple, secure, and platform-independent, with key features including object-oriented programming, portability, and high performance. It supports dynamic loading of classes, multithreading, and robust memory management, making it suitable for various applications. The document also outlines the steps for setting up a Java environment on different operating systems, including Windows, Linux, and macOS.

Uploaded by

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

OOP Java Unit 1

Java is a versatile programming language designed to be simple, secure, and platform-independent, with key features including object-oriented programming, portability, and high performance. It supports dynamic loading of classes, multithreading, and robust memory management, making it suitable for various applications. The document also outlines the steps for setting up a Java environment on different operating systems, including Windows, Linux, and macOS.

Uploaded by

arobotic06
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Features of Java

The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some
excellent features which play an important role in the popularity of this language. The
features of Java are also known as Java buzzwords.

A list of the most important features of the Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types
of objects that incorporate both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

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

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

There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.

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

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:
o No explicit pointer
o 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 supports dynamic compilation and automatic memory management (garbage


collection).

Java is a general-purpose computer programming language that is


concurrent, class-based, object-oriented, etc. Java applications are
typically compiled to bytecode that can run on any Java virtual machine
(JVM) regardless of computer architecture. The latest version is Java
22. Below are the environment settings for both Linux and Windows. JVM,
JRE, and JDK three are all platform-dependent because the configuration
of each Operating System is different. But, Java is platform-
independent. Few things must be clear before setting up the
environment which can better be perceived from the below image
provided as follows:
 JDK(Java Development Kit): JDK is intended for software developers
and includes development tools such as the Java compiler, Javadoc,
Jar, and a debugger.
 JRE(Java Runtime Environment): JRE contains the parts of the Java
libraries required to run Java programs and is intended for end-users.
JRE can be viewed as a subset of JDK.
 JVM: JVM (Java Virtual Machine) is an abstract machine. It is a
specification that provides a runtime environment in which java
bytecode can be executed. JVMs are available for many hardware and
software platforms.
Now let us discuss the steps for setting up a Java environment with visual
aids. Let’s use the Windows operating system to illustrate visual aids.
Steps: Here we will be proposing steps for three different operating
systems as listed:
1. Windows operating system
2. Linux operating system
3. macOS operating system
A. Windows operating systems
The steps for setting the environment in the Windows operating system
are as follows:
Step 1: Java8 JDK is available at Download Java 8. Click the first link for
Windows(32-bit) and the last link for Windows(64-bit) as highlighted
below.

Step 2: Now you will see a download prompt just accept the term and
conditions and click on the download button
Step 3: If you have an oracle account then sign in or if don’t then create
one and sign in

Step 4: Then your download will start automatically after signing in if


don’t then click on the previous link again

Step 5: After downloading, run the jdk-8u Application(.exe file) and follow
the instructions to install Java on your machine. Once you install Java on
your device, you have to set up the environment variable.
Step 6: Go to Control Panel -> System and Security -> System. Under
the Advanced System Setting option click on Environment Variables as
highlighted below.

Step 7: Now, you have to alter the “Path” variable under System variables
so that it also contains the path to the Java environment. Select the “Path”
variable and click on the Edit button as highlighted below.
Step 8: You will see a list of different paths, click on the New button, and
then add the path where java is installed. By default, java is installed in
“C:\Program Files\Java\jdk\bin” folder OR “C:\Program
Files(x86)\Java\jdk\bin”. In case, you have installed java at any other
location, then add that path.
Step 9: Click on OK, Save the settings, and you are done !! Now to check
whether the installation is done correctly, open the command prompt and
type javac -version. You will see that java is running on your machine.
Note: To make sure whether the compiler is set up, type javac in the
command prompt. You will see a list related to javac.
B. Linux Operating System
In Linux, there are several ways to install java. But we will refer to the
simplest and easy way to install java using a terminal. For Linux, we will
install OpenJDK. OpenJDK is a free and open-source implementation of
the Java programming language. Steps for setting the environment in the
Linux operating system are as follows:
Step 1: Go to Application -> Accessories -> Terminal.
Step 2: Type the command as below as follows:
sudo apt-get install openjdk-8-jdk
Step 3: For the “JAVA_HOME” (Environment Variable) type the command
as shown below, in “Terminal” using your installation path…(Note: the
default path is as shown, but if you have to install OpenJDK at another
location then set that path.)
export JAVA_HOME = /usr/lib/jvm/java-8-openjdk
Step 4: For “PATH” (Environment Value) type command as shown below,
in “Terminal” using your installation path…Note: the default path is as
shown, but if you have to install OpenJDK at another location then set that
path.)
export PATH = $PATH:/usr/lib/jvm/java-8-openjdk/bin
Note: We are done setting up the environment in Java for Linux OS.
Note: Now to check whether the installation is done correctly, type java -
version in the Terminal. You will see that java is running on your machine.
 Notepad/gedit : They are simple text-editors for writing java
programs. Notepad is available on Windows and gedit is available on
Linux.
 Eclipse IDE : It is the most widely used IDE(Integrated Development
Environment) for developing software in java. You can download
Eclipse.
C. MacOS Operating System
Step 1: Open the terminal from the application folder or simply press the
“command” and “shift” key together and write initials of the terminal and
press enter.
It will be good to have package manager such as homebrew installed in
your machine as we can operate to install any software from here itself
simply by using terminal commands.
Step 2: Now in order to configure first write the command ‘java –version ‘
where the message below it will pop that there is no
java --version
javac --version
Note: If it was set up then you would have been getting the version
displayed on the screen as it is shown below where in that machine it was
already set up. So remember to cross-check in your machine once you
have successfully set it up in yours.

Step 2: Once we are done with installing JDK now let us move on setting
up the java_home environment variable for that you will have to look into
something called s ‘bash_profie’ using the below command
ls -al
You will notice that in your terminal there will be no bash_profile set but it
is shown below so here in this machine it is already set up. In order to set
it up if not there we have to create it which lets us prior seek into java
home variables whether it is set up or not.
Step 3: Setting up the home java variable. Use the below command to
check or setup if not installed as follows on the terminal:
echo $JAVA_HOME
If it is showing blank then the java home variable is not set up as
perceived from the above image.
Step 4: Installing bash_profile
Make sure to go to the root folder in the terminal and write the command
‘touch ./bash_profile ‘

Now you will see that bash-profile s created which is as shown in the
step2 in your machine which hone can verify by writing command as
follows:
ls -al
Step 5: Edit the .bash_profile created for java, you just have to write the
command marked in below media and provided below as follows:
export JAVA_HOME=$(/usr/libexec/java_home)
// No need to remember this command

Save this file and relaunch the terminal by closing it.


Step 5: Verifying whether it is installed by entering the following two
commands
source .bash_profile
echo $JAVA_HOME
From the above media, we can see the java variable is all set to go as
earlier there was a blank therein the above media.

Object-Oriented Programming (OOP) is a programming paradigm based on


the concept of objects that contain data (fields) and behavior (methods). It
focuses on designing software that closely represents real-world entities. It
is used to:
 Improves code reusability
 Enhances maintainability and scalability
 Makes programs easier to understand and manage
 Closely models real-world entities
Characteristics of an OOP(Object Oriented Programming)
The diagram below demonstrates the Java OOPs Concepts

OOP's concept
1. Class

A Class is a user-defined blueprint or prototype from which objects are


created. It represents the set of properties or methods that are common to
all objects of one type. Using classes, you can create multiple objects with
the same behavior instead of writing their code multiple times. In general,
class declarations can include these components in order:
 Modifiers: A class can be public or have default access (Refer
to this for details).
 Class name: The class name should begin with the initial letter
capitalized by convention.
 Body: The class body is surrounded by braces, { }.
Example: A Car represents a class (blueprint), while BMW, Mercedes, and
Audi represent objects (instances) created from that class.

class-object

2. Object

An Object is a basic unit of Object-Oriented Programming that represents


real-life entities. A typical Java program creates many objects, which as you
know, interact by invoking methods. The objects are what perform your code,
they are the part of your code visible to the viewer/user. An object mainly
consists of:
 State: It is represented by the attributes of an object. It also reflects the
properties of an object.
 Behavior: It is represented by the methods of an object. It also reflects
the response of an object to other objects.
 Identity: It is a unique name given to an object that enables it to interact
with other objects.
 Method: A method is a collection of statements that perform some
specific task and return the result to the caller.
3. Abstraction
Abstraction in Java is the process of hiding implementation details and
showing only the essential features of an object. It helps users focus on
what an object does rather than how it does it.
 Hides complexity: Internal implementation details are hidden from the
user.
 Improves maintainability: Changes in implementation do not affect the
user code.
 Enhances flexibility: Supports loose coupling through abstract classes
and interfaces.
Example: An ATM or a coffee machine represents abstraction, where the
user interacts with simple operations while the internal working and
implementation details remain hidden.

Abstraction

How to Achieve Abstraction

 It is achieved in Java using abstract classes and interfaces.


 Interfaces can provide 100% abstraction, while abstract classes provide
partial abstraction.
4. Encapsulation
Encapsulation is the process of wrapping data and methods into a single
unit, usually a class, and restricting direct access to the data. It acts as a
protective shield that prevents data from being accessed directly from
outside the class.
 Data members are hidden using the private access modifier.
 Access to data is provided through public getter and setter methods.
 It improves data security, maintainability, and controlled access.

Encapsulation

5. Inheritance
Inheritance is a core OOP concept in Java that allows one class to acquire
the fields and methods of another class using the extends keyword. It
represents an “is-a” relationship between classes.
 The class being inherited is called the superclass, and the inheriting
class is the subclass.
 A subclass can use existing features of the superclass and also add its
own.
 Inheritance promotes code reusability and reduces redundancy.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

Inheritance

Types of Inheritance in Java


Java supports the following types of inheritance:
 Single Inheritance: One subclass inherits from one superclass.
 Multilevel Inheritance: A class is derived from another derived class,
forming a chain.
 Hierarchical Inheritance: Multiple subclasses inherit from a single
superclass.
 Multiple Inheritance (through Interface): A class inherits from multiple
interfaces since Java does not support multiple inheritance using
classes.
 Hybrid Inheritance (through Interface): A combination of two or more
types of inheritance, achievable using interfaces.
6. Polymorphism
The word polymorphism means having many forms, and it comes from
the Greek words poly (many) and morph (forms), this means one entity
can take many forms. In Java, polymorphism allows the same method or
object to behave differently based on the context, specially on the project's
actual runtime class.

Polymorphism in Java

Types of Polymorphism

Polymorphism in Java is mainly of 2 types as mentioned below:


1. Compile-time Polymorphism(Method Overloading) :Achieved when
multiple methods have the same name but different parameters. The
method call is resolved at compile time.
2. Runtime Polymorphism (Method Overriding ): Achieved when a
subclass provides a specific implementation of a method already defined in
its superclass. The method call is resolved at runtime based on the object

Structure of Java Program


Java is an object-oriented programming, platform-
independent, and secure programming language that makes it popular. Using the
Java programming language, we can develop a wide variety of applications. So, before
diving in depth, it is necessary to understand the basic structure of Java program in
detail. In this section, we have discussed the basic structure of a Java program. At
the end of this section, you will able to develop the Hello world Java program, easily.

Let's see which elements are included in the structure of a Java program. A typical
structure of a Java program contains the following elements:

o Documentation Section
o Package Declaration
o Import Statements
o Interface Section
o Class Definition
o Class Variables and Variables
o Main Method Class
o Methods and Behaviors

Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes
the author's name, date of creation, version, program name, company
name, and description of the program. It improves the readability of the program.
Whatever we write in the documentation section, the Java compiler ignores the
statements during the execution of the program. To write the statements in the
documentation section, we use comments. The comments may be single-line, multi-
line, and documentation comments.

o Single-line Comment: It starts with a pair of forwarding slash (//). For example:

1. //First Java Program


o Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols. For example:

/*It is an example of
multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends with */. For
example:

1. /**It is an example of documentation comment*/

Package Declaration
The package declaration is optional. It is placed just after the documentation section.
In this section, we declare the package name in which the class is placed. Note that
there can be only one package statement in a Java program. It must be defined
before any class and interface declaration. It is necessary because a Java class can be
placed in different packages and directories based on the module they are used. For
all these classes package belongs to a single parent directory. We use the
keyword package to declare the package name. For example:

1. package javatpoint; //where javatpoint is the package name


2. package [Link]; //where com is the root directory and javatpoint is the subdirectory

Import Statements
The package contains the many predefined classes and interfaces. If we want to use
any class of a particular package, we need to import that class. The import statement
represents the class stored in the other package. We use the import keyword to
import the class. It is written before the class declaration and after the package
statement. We use the import statement in two ways, either import a specific class or
import all classes of a particular package. In a Java program, we can use multiple import
statements. For example:

1. import [Link]; //it imports the Scanner class only


2. import [Link].*; //it imports all the class of the [Link] package

Interface Section
It is an optional section. We can create an interface in this section if required. We use
the interface keyword to create an interface. An interface is a slightly different from
the class. It contains only constants and method declarations. Another difference is
that it cannot be instantiated. We can use interface in classes by using
the implements keyword. An interface can also be used with other interfaces by using
the extends keyword. For example:

1. interface car
2. {
3. void start();
4. void stop();
5. }

Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class,
we cannot create any Java program. A Java program may conation more than one class
definition. We use the class keyword to define the class. The class is a blueprint of a
Java program. It contains information about user-defined methods, variables, and
constants. Every Java program has at least one class that contains the main() method.
For example:

1. class Student //class definition


2. {
3. }
Class Variables and Constants
In this section, we define variables and constants that are to be used later in the
program. In a Java program, the variables and constants are defined just after the class
definition. The variables and constants store values of the parameters. It is used during
the execution of the program. We can also decide and define the scope of variables
by using the modifiers. It defines the life of the variables. For example:

1. class Student //class definition


2. {
3. String sname; //variable
4. int id;
5. double percentage;
6. }

Main Method Class


In this section, we define the main() method. It is essential for all Java programs.
Because the execution of all Java programs starts from the main() method. In other
words, it is an entry point of the class. It must be inside the class. Inside the main
method, we create objects and call the methods. We use the following statement to
define the main() method:

1. public static void main(String args[])


2. {
3. }

For example:

1. public class Student //class definition


2. {
3. public static void main(String args[])
4. {
5. //statements
6. }
7. }

You can read more about the Java main() method here.
Methods and behavior
In this section, we define the functionality of the program by using the methods. The
methods are the set of instructions that we want to perform. These instructions execute
at runtime and perform the specified task. For example:

1. public class Demo //class definition


2. {
3. public static void main(String args[])
4. {
5. void display()
6. {
7. [Link]("Welcome to javatpoint");
8. }
9. //statements
10. }
11. }

When we follow and use the above elements in a Java program, the program looks
like the following.

[Link]

1. /*Program name: Palindrome*/


2. //Author's name: Mathew
3. /*Palindrome is number or string that will remains the same
4. When we write that in reverse order. Some example of
5. palindrome is 393, 010, madam, etc.*/
6. //imports the Scanner class of the [Link] package
7. import [Link];
8. //class definition
9. public class CheckPalindromeNumber
10. {
11. //main method
12. public static void main(String args[])
13. {
14. //variables to be used in program
15. int r, s=0, temp;
16. int x; //It is the number variable to be checked for palindrome
17. Scanner sc=new Scanner([Link]);
18. [Link]("Enter the number to check: ");
19. //reading a number from the user
20. x=[Link]();
21. //logic to check if the number id palindrome or not
22. temp=x;
23. while(x>0)
24. {
25. r=x%10; //finds remainder
26. s=(s*10)+r;
27. x=x/10;
28. }
29. if(temp==s)
30. [Link]("The given number is palindrome.");
31. else
32. [Link]("The given number is not palindrome.");
33. }
34. }

Output:

Java is statically typed and also a strongly typed language because, in


Java, each type of data (such as integer, character, hexadecimal, packed
decimal, and so forth) is predefined as part of the programming language
and all constants or variables defined for a given program must be
described with one of the Java data types.
Data Types in Java
Data types in Java are of different sizes and values that can be stored in
the variable that is made as per convenience and circumstances to cover
up all test cases. Java has two categories in which data types are
segregated
1. Primitive Data Type: such as boolean, char, int, short, byte, long,
float, and double
2. Non-Primitive Data Type or Object Data type: such as String, Array,
etc.
Understanding and effectively using these data types is crucial for writing
efficient and error-free Java code. If you’re aiming to master Java,
exploring detailed resources or Java Programming Course can help you
gain a strong command over data types and other essential Java
concepts

Primitive Data Types Table – Default Value, Size, and Range


Primitive Data Types in Java
Primitive data are only single values and have no special
capabilities. There are 8 primitive data types. They are depicted below in
tabular format below as follows:
Let us discuss and implement each one of the following data types that
are as follows:
Data Default Default
Range
Type Value size

1 byte or 8
byte 0 -128 to 127
bits

2 bytes or
short 0 -32,768 to 32,767
16 bits

4 bytes or
int 0 2,147,483,648 to 2,147,483,647
32 bits

8 bytes or 9,223,372,036,854,775,808 to
long 0
64 bits 9,223,372,036,854,775,807

4 bytes or
float 0.0f 1.4e-045 to 3.4e+038
32 bits

8 bytes or
double 0.0d 4.9e-324 to 1.8e+308
64 bits

2 bytes or
char ‘\u0000’ 0 to 65536
16 bits

1 byte or 2
boolean FALSE 0 or 1
bytes

1. Boolean Data Type


The boolean data type represents a logical value that can be
either true or false. While conceptually it represents a single bit of
information, the size of the Boolean data type is virtual machine-
dependent and is typically one byte (eight bits) in practice. Values of
type boolean are not implicitly or explicitly converted to any other type
(with casts). However, programmers can write conversion code if needed.
Syntax:
boolean booleanVar;
Size: Virtual machine dependent
2. Byte Data Type
The byte data type is an 8-bit signed two’s complement integer. The byte
data type is useful for saving memory in large arrays.
Syntax:
byte byteVar;
Size: 1 byte (8 bits)
3. Short Data Type
The short data type is a 16-bit signed two’s complement integer. Similar to
byte, use a short to save memory in large arrays, in situations where the
memory savings actually matters.
Syntax:
short shortVar;
Size: 2 bytes (16 bits)
4. Integer Data Type
It is a 32-bit signed two’s complement integer.
Syntax:
int intVar;
Size: 4 bytes ( 32 bits )
Remember: In Java SE 8 and later, we can use the int data type to
represent an unsigned 32-bit integer, which has a value in the range [0,
2 32 -1]. Use the Integer class to use the int data type as an unsigned
integer.
5. Long Data Type
The range of a long is quite large. The long data type is a 64-bit two’s
complement integer and is useful for those occasions where an int type is
not large enough to hold the desired value. The size of the Long Datatype
is 8 bytes (64 bits).
Syntax:
long longVar;
Remember: In Java SE 8 and later, you can use the long data type to
represent an unsigned 64-bit long, which has a minimum value of 0 and a
maximum value of 2 64 -1. The Long class also contains methods like
comparing Unsigned, divide Unsigned, etc to support arithmetic
operations for unsigned long.
6. Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating-point.
Use a float (instead of double) if you need to save memory in large arrays
of floating-point numbers. The size of the float data type is 4 bytes (32
bits).
Syntax:
float floatVar;
7. Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating-point.
For decimal values, this data type is generally the default choice. The size
of the double data type is 8 bytes or 64 bits.
Syntax:
double doubleVar;
Note: Both float and double data types were designed especially for
scientific calculations, where approximation errors are acceptable. If
accuracy is the most prior concern then, it is recommended not to use
these data types and use BigDecimal class instead.
It is recommended to go through rounding off errors in java.
8. Char Data Type
The char data type is a single 16-bit Unicode character with the size of 2
bytes (16 bits).
Syntax:
char charVar;
Why is the Size of char 2 bytes in Java?
So, other languages like C/C++ use only ASCII characters, and to
represent all ASCII characters 8 bits is enough. But Java uses
the Unicode system not the ASCII code System and to represent the
Unicode system 8 bits is not enough to represent all characters so Java
uses 2 bytes for characters. Unicode defines a fully international
character set that can represent most of the world’s written languages. It
is a unification of dozens of character sets, such as Latin, Greek, Cyrillic,
Katakana, Arabic, and many more.
Example:
Java
// Java Program to Demonstrate Char Primitive Data Type

// Class
class GFG {

// Main driver method


public static void main(String args[])
{

// Creating and initializing custom character


char a = 'G';

// Integer data type is generally


// used for numeric values
int i = 89;

// use byte and short


// if memory is a constraint
byte b = 4;
// this will give error as number is
// larger than byte range
// byte b1 = 7888888955;

short s = 56;

// this will give error as number is


// larger than short range
// short s1 = 87878787878;

// by default fraction value


// is double in java
double d = 4.355453532;

// for float use 'f' as suffix as standard


float f = 4.7333434f;

// need to hold big range of numbers then we need


// this data type
long l = 12121;

[Link]("char: " + a);


[Link]("integer: " + i);
[Link]("byte: " + b);
[Link]("short: " + s);
[Link]("float: " + f);
[Link]("double: " + d);
[Link]("long: " + l);
}
}

Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
Non-Primitive Data Type or Reference Data Types
The Reference Data Types will contain a memory address of variable
values because the reference types won’t store the variable value directly
in memory. They are strings, objects, arrays, etc.
1. Strings
Strings are defined as an array of characters. The difference between a
character array and a string in Java is, that the string is designed to hold a
sequence of characters in a single variable whereas, a character array is
a collection of separate char-type entities. Unlike C/C++, Java strings are
not terminated with a null character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
// Declare String without using new operator
String s = "GeeksforGeeks";
// Declare String using new operator
String s1 = new String("GeeksforGeeks");
2. Array
An Array is a group of like-typed variables that are referred to by a
common name. Arrays in Java work differently than they do in C/C++. The
following are some important points about Java arrays.
 In Java, all arrays are dynamically allocated. (discussed below)
 Since arrays are objects in Java, we can find their length using
member length. This is different from C/C++ where we find length using
size.
 A Java array variable can also be declared like other variables with []
after the data type.
 The variables in the array are ordered and each has an index
beginning with 0.
 Java array can also be used as a static field, a local variable, or a
method parameter.
 The size of an array must be specified by an int value and not long or
short.
 The direct superclass of an array type is Object.
 Every array type implements the
interfaces Cloneable and [Link] .

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. int data=50;//Here data is variable
Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable
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. [Link](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. [Link](a);
6. [Link](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. [Link](f);
7. [Link](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. [Link](a);
7. [Link](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. [Link](c);
8. }}
Output:

20
Java Wrapper Classes
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as
objects.

The table below shows the primitive type and the equivalent wrapper class:

Primitive Data Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

boolean Boolean

char Character
Sometimes you must use wrapper classes, for example when working with Collection
objects, such as ArrayList, where primitive types cannot be used (the list can only
store objects):

ExampleGet your own Java Server


ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid

ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid

Creating Wrapper Objects


To create a wrapper object, use the wrapper class instead of the primitive type. To
get the value, you can just print the object:

Example
public class Main {

public static void main(String[] args) {

Integer myInt = 5;

Double myDouble = 5.99;

Character myChar = 'A';

[Link](myInt);

[Link](myDouble);

[Link](myChar);

}
Operators in Java
Last Updated : 10 Sep, 2024


Java provides many types of operators which can be used according to the need.
They are classified based on the functionality they provide. In this article, we will
learn about Java Operators and learn all their types.
What are the Java Operators?
Operators in Java are the symbols used for performing specific operations in Java.
Operators make tasks like addition, multiplication, etc which look easy although
the implementation of these tasks is quite complex.
Types of Operators in Java
There are multiple types of operators in Java all are mentioned below:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators

1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive and non-
primitive data types.
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 – : Subtraction
Example:
Java
// Java Program to implement
// Arithmetic Operators
import [Link].*;

// Drive Class
class GFG {
// Main Function
public static void main (String[] args) {

// Arithmetic operators on integers


int a = 10;
int b = 3;

// Arithmetic operators on Strings


String num1 = "15";
String num2 = "25";

// Convert Strings to integers


int a1 = [Link](num1);
int b1 = [Link](num2);

[Link]("a + b = " + (a + b));


[Link]("a - b = " + (a - b));
[Link]("a * b = " + (a * b));
[Link]("a / b = " + (a / b));
[Link]("a % b = " + (a % b));
[Link]("a1 + b1 = " + (a1 + b1));

}
}

Output
a + b = 13
a - b = 7
a * b = 30
a / b = 3
a % b = 1
a1 + b1 = 40
2. Unary Operators
Unary operators need only one operand. They are used to increment, decrement, or
negate a value.
 – : Unary minus, used for negating the values.
 + : Unary plus indicates the positive value (numbers are positive without this,
however). It performs an automatic conversion to int when the type of its
operand is the byte, char, or short. This is called unary numeric promotion.
 ++ : Increment operator, used for incrementing the value by 1. There are two
varieties of increment operators.

o Post-Increment: Value is first used for computing the result and then
incremented.
o Pre-Increment: Value is incremented first, and then the result is
computed.
 – – : Decrement operator, used for decrementing the value by 1. There are
two varieties of decrement operators.

o Post-decrement: Value is first used for computing the result and then
decremented.
o Pre-Decrement: The value is decremented first, and then the result
is computed.
 ! : Logical not operator, used for inverting a boolean value.
Example:
Java
// Java Program to implement
// Unary Operators
import [Link].*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;

// Using unary operators


[Link]("Postincrement : " + (a++));
[Link]("Preincrement : " + (++a));

[Link]("Postdecrement : " + (b--));


[Link]("Predecrement : " + (--b));
}
}

Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has right-to-
left associativity, i.e. value given on the right-hand side of the operator is assigned
to the variable on the left, and therefore right-hand side value must be declared
before using it or should be a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with other operators to
build a shorter version of the statement called a Compound Statement. For
example, instead of a = a+5, we can write a += 5.
 +=, for adding the left operand with the right operand and then assigning it to
the variable on the left.
 -=, for subtracting the right operand from the left operand and then assigning it
to the variable on the left.
 *=, for multiplying the left operand with the right operand and then assigning it
to the variable on the left.
 /=, for dividing the left operand by the right operand and then assigning it to the
variable on the left.
 %=, for assigning the modulo of the left operand by the right operand and then
assigning it to the variable on the left.
Example:
Java
// Java Program to implement
// Assignment Operators
import [Link].*;

// Driver Class
class GFG {
// Main Function
public static void main(String[] args)
{

// Assignment operators
int f = 7;
[Link]("f += 3: " + (f += 3));
[Link]("f -= 2: " + (f -= 2));
[Link]("f *= 4: " + (f *= 4));
[Link]("f /= 3: " + (f /= 3));
[Link]("f %= 2: " + (f %= 2));
[Link]("f &= 0b1010: " + (f &= 0b1010));
[Link]("f |= 0b1100: " + (f |= 0b1100));
}
}

Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
4. Relational Operators
These operators are used to check for relations like equality, greater than, and less
than. They return boolean results after the comparison and are extensively used in
looping statements as well as conditional if-else statements. The general format is,
variable relation_operator value
Some of the relational operators are-
 ==, Equal to returns true if the left-hand side is equal to the right-hand side.
 !=, Not Equal to returns true if the left-hand side is not equal to the right-hand
side.
 <, less than: returns true if the left-hand side is less than the right-hand side.
 <=, less than or equal to returns true if the left-hand side is less than or equal
to the right-hand side.
 >, Greater than: returns true if the left-hand side is greater than the right-hand
side.
 >=, Greater than or equal to returns true if the left-hand side is greater than or
equal to the right-hand side.
Example:
Java
// Java Program to implement
// Relational Operators
import [Link].*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
[Link]("a > b: " + (a > b));
[Link]("a < b: " + (a < b));
[Link]("a >= b: " + (a >= b));
[Link]("a <= b: " + (a <= b));
[Link]("a == c: " + (a == c));
[Link]("a != c: " + (a != c));
}
}

Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations,
i.e., a function similar to AND gate and OR gate in digital electronics. One thing to
keep in mind is the second condition is not evaluated if the first one is false, i.e., it
has a short-circuiting effect. Used extensively to test for several conditions for
making a decision. Java also has “Logical NOT”, which returns true when the
condition is false and vice-versa
Conditional operators are:
 &&, Logical AND: returns true when both conditions are true.
 ||, Logical OR: returns true if at least one condition is true.
 !, Logical NOT: returns true when a condition is false and vice-versa
Example:
Java
// Java Program to implemenet
// Logical operators
import [Link].*;

// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;

[Link]("x && y: " + (x && y));


[Link]("x || y: " + (x || y));
[Link]("!x: " + (!x));
}
}

Output
x && y: false
x || y: true
!x: false
6. Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has three
operands and hence the name Ternary.
The general format is:
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the
statements after the ‘?’ else execute the statements after the ‘:’.
Example:
Java
// Java program to illustrate
// max of three numbers using
// ternary operator.
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;

// result holds max of three


// numbers
result
= ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
[Link]("Max of three numbers = "
+ result);
}
}

Output
Max of three numbers = 30
7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a
number. They can be used with any of the integer types. They are used when
performing update and query operations of the Binary indexed trees.
 &, Bitwise AND operator: returns bit by bit AND of input values.
 |, Bitwise OR operator: returns bit by bit OR of input values.
 ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
 ~, Bitwise Complement Operator: This is a unary operator which returns the
one’s complement representation of the input value, i.e., with all bits inverted.
Java
// Java Program to implement
// bitwise operators
import [Link].*;

// Driver class
class GFG {
// main function
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
[Link]("d & e: " + (d & e));
[Link]("d | e: " + (d | e));
[Link]("d ^ e: " + (d ^ e));
[Link]("~d: " + (~d));
[Link]("d << 2: " + (d << 2));
[Link]("e >> 1: " + (e >> 1));
[Link]("e >>> 1: " + (e >>> 1));
}
}

Output
d & e: 8
d | e: 14
d ^ e: 6
~d: -11
d << 2: 40
e >> 1: 6
e >>> 1: 6

Bitwise Operator in Java


In Java, an operator is a symbol that performs the specified operations. In this section,
we will discuss only the bitwise operator and its types with proper examples.

Types of Bitwise Operator


There are six types of the bitwise operator in Java:

o Bitwise AND
o Bitwise exclusive OR
o Bitwise inclusive OR
o Bitwise Compliment
o Bit Shift Operators

Operators Symbol Uses

Bitwise AND & op1 & op2

Bitwise exclusive OR ^ op1 ^ op2

Bitwise inclusive OR | op1 | op2

Bitwise Compliment ~ ~ op

Bitwise left shift << op1 << op2

Bitwise right shift >> op1 >> op2

number of
Unsigned Right Shift Operator >>> op >>>
places to shift

Let's explain the bitwise operator in detail.

Bitwise AND (&)


It is a binary operator denoted by the symbol &. It returns 1 if and only if both bits are 1,
else returns 0.

Let's use the bitwise AND operator in a Java program.

[Link]

1. public class BitwiseAndExample


2. {
3. public static void main(String[] args)
4. {
5. int x = 9, y = 8;
6. // bitwise and
7. // 1001 & 1000 = 1000 = 8
8. [Link]("x & y = " + (x & y));
9. }
10. }
Output

x&y=8

Bitwise exclusive OR (^)


It is a binary operator denoted by the symbol ^ (pronounced as caret). It returns 0 if both
bits are the same, else returns 1.

Let's use the bitwise exclusive OR operator in a Java program.

[Link]

1. public class BitwiseXorExample


2. {
3. public static void main(String[] args)
4. {
5. int x = 9, y = 8;
6. // bitwise XOR
7. // 1001 ^ 1000 = 0001 = 1
8. [Link]("x ^ y = " + (x ^ y));
9. }
10. }
Output

x^y=1

Bitwise inclusive OR (|)


It is a binary operator denoted by the symbol | (pronounced as a pipe). It returns 1 if either
of the bit is 1, else returns 0.
Let's use the bitwise inclusive OR operator in a Java program.

[Link]

1. public class BitwiseInclusiveOrExample


2. {
3. public static void main(String[] args)
4. {
5. int x = 9, y = 8;
6. // bitwise inclusive OR
7. // 1001 | 1000 = 1001 = 9
8. [Link]("x | y = " + (x | y));
9. }
10. }
Output

x|y=9

Bitwise Complement (~)


It is a unary operator denoted by the symbol ~ (pronounced as the tilde). It returns the
inverse or complement of the bit. It makes every 0 a 1 and every 1 a 0.

Let's use the bitwise complement operator in a Java program.

[Link]

1. public class BitwiseComplimentExample


2. {
3. public static void main(String[] args)
4. {
5. int x = 2;
6. // bitwise compliment
7. // ~0010= 1101 = -3
8. [Link]("~x = " + (~x));
9. }
10. }
Output
~x = -3

8. Shift Operators
These operators are used to shift the bits of a number left or right, thereby
multiplying or dividing the number by two, respectively. They can be used when
we have to multiply or divide a number by two. General format-
number shift_op number_of_places_to_shift;
 <<, Left shift operator: shifts the bits of the number to the left and fills 0 on
voids left as a result. Similar effect as multiplying the number with some power
of two.
 >>, Signed Right shift operator: shifts the bits of the number to the right and
fills 0 on voids left as a result. The leftmost bit depends on the sign of the initial
number. Similar effect to dividing the number with some power of two.
 >>>, Unsigned Right shift operator: shifts the bits of the number to the right
and fills 0 on voids left as a result. The leftmost bit is set to 0.
Java
// Java Program to implement
// shift operators
import [Link].*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;

// using left shift


[Link]("a<<1 : " + (a << 1));

// using right shift


[Link]("a>>1 : " + (a >> 1));
}
}

Output
a<<1 : 20
a>>1 : 5
Bit Shift Operators
Shift operator is used in shifting the bits either right or left. We can use shift operators if
we divide or multiply any number by 2. The general format to shift the bit is as follows:

1. variable << or >> number of places to shift;


For example, if a=10

1. a>>2; //shifts two bits


2. a>>4; //shifts 4 bits
Java provides the following types of shift operators:

o Signed Right Shift Operator or Bitwise Right Shift Operator


o Unsigned Right Shift Operator
o Signed Left Shift Operator or Bitwise Left Shift Operator

Note: Java does not support the unsigned left shift operator (<<<).

Signed Right Shift Operator (>>)


The signed right shift operator shifts a bit pattern of a number towards the right with a
specified number of positions and fills 0. The operator is denoted by the symbol >>. It also
preserves the leftmost bit (sign bit). If 0 is presented at the leftmost bit, it means the
number is positive. If 1 is presented at the leftmost bit, it means the number is negative.

In general, if we write a>>n, it means to shift the bits of a number toward the right with a
specified position (n). In the terms of mathematics, we can represent the signed right shift
operator as follows:

Note: When we apply right shift operator on a positive number, we get the positive
number in the result also. Similarly, when we apply right shift operator on a negative
number, we get the negative number in the result also.

Example: Apply the signed right shift operator with specified positions 4 if x = 256
and x = -256.

If x = 256

256 >> 4

256/24 = 16

If x = -256

-256 >> 4
-256/24 = -16

In the above example, we have observed that after shifting the operator 256 converted
into 16 and -256 converted into -16.

Let's create a Java program and implement the left shift operator.

[Link]

1. public class SignedRightShiftOperatorExample


2. {
3. public static void main(String args[])
4. {
5. int x = 50;
6. [Link]("x>>2 = " + (x >>2));
7. }
8. }
Output

x>>2 = 12

Signed Left Shift Operator (<<)


The signed left shift operator (<<) shifts a bit pattern to the left. It is represented by the
symbol <<. It also preserves the leftmost bit (sign bit). It does not preserve the sign bit.

In general, if we write a<<n, it means to shift the bits of a number toward the left with
specified position (n). In the terms of mathematics, we can represent the signed right shift
operator as follows:

Example 1: What will be the result after shifting a<<3. The value of a is 20.

Representation of 20 in binary is = 00010100

After performing the left shift operator, we get:

a << 3 = 10100000 (last three bits are the filled bits)

a << 3 = 160

Let's check the result by using the formula.

20 << 3
20*23 = 20*8 = 160

Example 2: What will be the result after shifting a<<2. The value of a is -10.

Representation of -10 in binary is = 11110110

a<<2 = 11011000 = -40

Let's check the result by using the formula.

-10 << 3

-10*22 = -10*4 = -40

Let's create a Java program and implement the signed left shift operator.

[Link]

1. public class SignedLeftShiftOperatorExample


2. {
3. public static void main(String args[])
4. {
5. int x = 12;
6. [Link]("x<<1 = " + (x << 1));
7. }
8. }
Output

x<<1 = 24

Unsigned Right Shift Operator (>>>)


It shifts a zero at the leftmost position and fills 0. It is denoted by the symbol >>>. Note
that the leftmost position after >> depends on the sign bit. It does not preserve the sign
bit.

Example: If a=11110000 and b=2, find a>>>b?

a >>> b = 11110000 >>> 2 = 00111100

The left operand value is moved right by the number of bits specified by the right operand
and the shifted bits are filled up with zeros. Excess bits shifted off to the right are
discarded.

Therefore, before shifting the bits the decimal value of a is 240, and after shifting the bits
the decimal value of a is 60.

Let's create a Java program and use the unsigned right shift operator.

[Link]
1. public class UnsignedRightShiftOperatorExample
2. {
3. public static void main(String args[])
4. {
5. int x = 20;
6. [Link]("x>>>2 = " + (x >>>2));
7. }
8. }

Output

x>>>2 = 5

[Link] in Java
Last Updated : 12 Jan, 2024


Java [Link]() is used to print an argument that is passed to it.
Parts of [Link]()
The statement can be broken into 3 parts which can be understood separately:
1. System: It is a final class defined in the [Link] package.
2. out: This is an instance of PrintStream type, which is a public and static
member field of the System class.
3. println(): As all instances of the PrintStream class have a public method
println(), we can invoke the same on out as well. This is an upgraded version of
print(). It prints any argument passed to it and adds a new line to the output. We
can assume that [Link] represents the Standard Output Stream.
Syntax:
[Link](parameter)
Parameters: The parameter might be anything that the user wishes to print on the
output screen.
Example of Java [Link]()
Example 1:
Below is the implementation of [Link] :
 Java

// Java code to illustrate

// [Link]();

import [Link].*;

// Driver Class

class GFG {

// main function
public static void main(String[] args)

[Link]("Welcome");

[Link]("To");

[Link]("GeeksforGeeks");

Output
Welcome
To
GeeksforGeeks

Example 2:
Below is the implementation of [Link] :
 Java

// Java code to illustrate

// [Link]();

import [Link].*;

// Driver Class

class GFG {

// main function

public static void main(String[] args)


{

// Declaring variable

int num1 = 10, num2 = 20, sum;

// Printing the variables

[Link]("The addition of ");

[Link](

num1 + " and " + num2 + " is: ");

// Printing the result after operation

[Link](num1 + num2);

Output
The addition of 10 and 20 is: 30

Using Scanner Class for Taking Input in Java


It is an advanced version of BufferedReader which was added in later
versions of Java. The scanner can read formatted input. It has different
functions for different types of data types.
 The scanner is much easier to read as we don’t have to write throws as
there is no exception thrown by it.
 It was added in later versions of Java
 It contains predefined functions to read an Integer, Character, and
other data types as well.
Syntax of Scanner class:
Scanner scn = new Scanner([Link]);
Importing Scanner Class:
‘To use the Scanner we need to import the Scanner class from the util
package as
import [Link];
Inbuilt Scanner functions are as follows:
 Integer: nextInt()
 Float: nextFloat()
 String : next() and nextLine()
Hence, in the case of Integer and String in Scanner, we don’t require
parsing as we did require in BufferedReader.
Java
// Java Program to show how to take
// input from user using Scanner Class

import [Link].*;

class GFG {

public static void main(String[] args)


{
// Scanner definition
Scanner scn = new Scanner([Link]);

// input is a string ( one word )


// read by next() function
String str1 = [Link]();

// print String
[Link]("Entered String str1 : " + str1);

// input is a String ( complete Sentence )


// read by nextLine()function
String str2 = [Link]();

// print string
[Link]("Entered String str2 : " + str2);

// input is an Integer
// read by nextInt() function
int x = [Link]();

// print integer
[Link]("Entered Integer : " + x);

// input is a floatingValue
// read by nextFloat() function
float f = [Link]();

// print floating value


[Link]("Entered FloatValue : " + f);
}
}

Output:
Entered String str1 : Geeks
Entered String str2 : Geeks For Geeks
Entered Integer : 123
Entered FloatValue : 123.090
Example 2:
Java
// Java Program to implement
// Scanner Class to take input
import [Link].*;
import [Link];

// Driver Class
class Easy {
// main function
public static void main(String[] args)
{
// creating the instance of class Scanner
Scanner obj = new Scanner([Link]);
String name;
int rollno;
float marks;

[Link]("Enter your name");

// taking string input


name = [Link]();
[Link]("Enter your rollno");

// taking integer input


rollno = [Link]();
[Link]("Enter your marks");

// taking float input


marks = [Link]();

// printing the output


[Link]("Name=" + name);
[Link]("Rollno=" + rollno);
[Link]("Marks=" + marks);
}
}

Output:
Enter your name
Geeks
Enter your rollno
5
Enter your marks
84.60
Name=Geeks
Rollno=5
Marks=84.60

Using the Buffered Reader Class


The BufferedReader class is the classical method to take input, introduced
in JDK 1.0. This method is used by wrapping the [Link] (standard input
stream) in an InputStreamReader, which is wrapped in a BufferedReader.
We can read input from the user in the command line.
 Input is buffered, making it faster for large inputs.
 Suitable for competitive programming and performance-critical
applications.
 Slightly verbose and harder to remember compared to Scanner.
import [Link];
import [Link];
import [Link];

public class Geeks {


public static void main(String[] args) throws IOException
{

BufferedReader r = new BufferedReader(


new InputStreamReader([Link]));

String s = [Link]();
[Link](s);
}
}
Input:
Geek
Output:

Note: To read other types, we use functions like [Link](),


[Link](). To read multiple values, we use split().
2. Using Scanner Class
Scanner Class is probably the most preferred method to take input,
Introduced in JDK 1.5. The main purpose of the Scanner class is to parse
primitive types and strings using regular expressions; however, it is also can
be used to read input from the user in the command line.
 Easy to use and understand.
 Provides built-in methods like nextInt(), nextFloat(), etc.
 Slightly slower than BufferedReader due to parsing overhead.
import [Link];

class Geeks {
public static void main(String args[]) {

Scanner s = new Scanner([Link]);

String s1 = [Link]();
[Link]("You entered string " + s1);

int a = [Link]();
[Link]("You entered integer " + a);

float b = [Link]();
[Link]("You entered float " + b);

[Link]();
}
}
Input:
GeeksforGeeks
12
3.4
Output:

Using Command line argument


Command line argument available since JDK 1.0, are used to pass inputs
to a Java program at runtime, commonly in competitive coding. The inputs
are stored as strings in the args[] array and can be converted to numeric
values using methods like [Link]() or [Link]().
class Geeks {
public static void main(String[] args) {

if ([Link] > 0) {
[Link]("The command line arguments
are:");
for (String val : args)
[Link](val);
} else {
[Link]("No command line arguments
found.");
}
}
}
Command Line Arguments:
javac [Link]
java Main Hello World
Output:

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.

[Link]

[Link]

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. [Link]("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.

[Link]

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. [Link]("x + y is less than 10");
7. } else {
8. [Link]("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.

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. [Link]("city is meerut");
6. }else if (city == "Noida") {
7. [Link]("city is noida");
8. }else if(city == "Agra") {
9. [Link]("city is agra");
10. }else {
11. [Link](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.

[Link]

1. public class Student {


2. public static void main(String[] args) {
3. String address = "Delhi, India";
4.
5. if([Link]("India")) {
6. if([Link]("Meerut")) {
7. [Link]("Your city is Meerut");
8. }else if([Link]("Noida")) {
9. [Link]("Your city is Noida");
10. }else {
11. [Link]([Link](",")[0]);
12. }
13. }else {
14. [Link]("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:

o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o 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.

[Link]

1. public class Student implements Cloneable {


2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. [Link]("number is 0");
7. break;
8. case 1:
9. [Link]("number is 1");
10. break;
11. default:
12. [Link](num);
13. }
14. }
15. }
Output:

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.

[Link]

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. [Link]("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.

[Link]

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. [Link]("Printing the content of the array names:\n");
6. for(String name:names) {
7. [Link](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. [Link]("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. [Link](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.

[Link]

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. [Link]("Printing the list of first 10 even numbers \n");
6. do {
7. [Link](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.

[Link]

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. [Link](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

[Link]

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. [Link](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. [Link](j);
14. }
15. }
16. }
17.
18. }
Output:

0
1
2
3
5
1
2
3
5
2
3
5

Basics of Arrays in Java


Array Declaration
To declare an array in Java, use the following syntax:
type[] arrayName;
 type: The data type of the array elements (e.g., int, String).
 arrayName: The name of the array.
Array Declaration Example:
Here’s an example of declaring an integer array:
int[] numbers; // Declaring an integer array
 This statement declares an array named numbers that will hold
integers. Note: The array is not yet initialized.
Create an Array
To create an array, you need to allocate memory for it using
the new keyword:
numbers = new int[5]; // Creating an array of 5 integers
 This statement initializes the numbers array to hold 5 integers. The
default value for each element is 0.
Access an Element of an Array
We can access array elements using their index, which starts from 0:
numbers[0] = 10; // Setting the first element of the array
int firstElement = numbers[0]; // Accessing the first element
 The first line sets the value of the first element to 10. The second line
retrieves the value of the first element.
Change an Array Element
To change an element, assign a new value to a specific index:
numbers[0] = 20; // Changing the first element to 20
 This statement updates the value of the first element from 10 to 20.
Array Length
We can get the length of an array using the length property:
int length = [Link]; // Getting the length of the array
This retrieves the number of elements in the numbers array, which is 5 in
this case.
The above are the basic details of Arrays in Java. Now, if you want to go
through the in-depth concepts of Java Arrays, then scroll down below
and go through the diagrams, examples, and explanations.
In-depth Concepts of Java Array
Following are some important points about Java arrays.
Arrays in Java
 In Java, all arrays are dynamically allocated.
 Arrays may be stored in contiguous memory [consecutive memory
locations].
 Since arrays are objects in Java, we can find their length using the
object property length. This is different from C/C++, where we find
length using size of.
 A Java array variable can also be declared like other variables with []
after the data type.
 The variables in the array are ordered, and each has an index
beginning with 0.
 Java array can also be used as a static field, a local variable, or a
method parameter.
An array can contain primitives (int, char, etc.) and object (or non-
primitive) references of a class, depending on the definition of the array.
In the case of primitive data types, the actual values might be stored in
contiguous memory locations (JVM does not guarantee this behavior). In
the case of class objects, the actual objects are stored in a heap
segment. To learn more about Java Array, go through Java programming
course here.

Note: This storage of arrays helps us randomly access the elements of an


array [Support Random Access].
Creating, Initializing, and Accessing an Arrays in Java
The general form of array declaration is
-- type var-name[];
-- type[] var-name;
 An array declaration has two components: the type and the name.
 type declares the element type of the array.
 The element type determines the data type of each element that
comprises the array.
 Like an array of integers, we can also create an array of other primitive
data types like char, float, double, etc., or user-defined data types
(objects of a class).
 Thus, the element type for the array determines what type of data the
array will hold.
Example:
// both are valid declarations
int intArray[];
int[] intArray;
// similar to int we can declare
// byte , short, boolean, long, float
// double, char
// an array of references to objects of
// the class MyClass (a class created by user)
MyClass myClassArray[];
// array of Object
Object[] ao,
// array of Collection
// of unknown type
Collection[] ca;
 Although the first declaration establishes that int Array is an array
variable, no actual array exists.
 It merely tells the compiler that this variable (int Array) will hold an
array of the integer type.
 To link int Array with an actual, physical array of integers, you must
allocate one using new and assign it to int Array.
Instantiating an Array in Java
When an array is declared, only a reference of an array is created. To
create or give memory to the array, you create an array like this: The
general form of new as it applies to one-dimensional arrays appears as
follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size determines the
number of elements in the array, and var-name is the name of the array
variable that is linked to the array. To use new to allocate an array, you
must specify the type and number of elements to allocate.
Example:
//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];
Note: The elements in the array allocated by new will automatically be
initialized to zero (for numeric types), false (for boolean), or null (for
reference types). Do refer to default array values in Java.
Obtaining an array is a two-step process. First, you must declare a
variable of the desired array type. Second, you must allocate the memory
to hold the array, using new, and assign it to the array variable. Thus, in
Java, all arrays are dynamically allocated.
Array Literal in Java
In a situation where the size of the array and variables of the array are
already known, array literals can be used.
// Declaring array literal
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
 The length of this array determines the length of the created array.
 There is no need to write the new int[] part in the latest versions of
Java.
Accessing Java Array Elements using for Loop
Each element in the array is accessed via its index. The index begins with
0 and ends at (total array size)-1. All the elements of array can be
accessed using Java for Loop.
// accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i + " : "+
arr[i]);
Implementation:
Java
// Java program to illustrate creating an array
// of integers, puts some values in the array,
// and prints each value to standard output.

class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i
+ " : " + arr[i]);
}
}

Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space: O(1)
Types of Arrays in Java
Java supports different types of arrays:
1. Single-Dimensional Arrays
These are the most common type of arrays, where elements are stored in
a linear order.
int[] singleDimArray = {1, 2, 3, 4, 5}; // A single-dimensional
array
2. Multi-Dimensional Arrays
Arrays with more than one dimension, such as two-dimensional arrays
(matrices).
int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}; // A 2D array (matrix)
You can also access java arrays using for each loops.
Arrays of Objects in Java
An array of objects is created like an array of primitive-type data items in
the following way.
Student[] arr = new Student[5]; //Student is a user-defined class
Syntax:
-- data type[] arrName;
-- datatype arrName[];
-- datatype [] arrName;
Example of Arrays of Objects
Example 1:
Below is the implementation of the above mentioned topic:
Java
import [Link].*;

class GFG {
public static void main (String[] args) {

int [] arr=new int [4];


// 4 is the size of arr
[Link]("Array Size:"+[Link]);
}
}

Output
Array Size:4
 The Student Array contains five memory spaces each of the size of
Student class in which the address of five Student objects can be
stored.
 The Student objects have to be instantiated using the constructor of
the Student class, and their references should be assigned to the array
elements in the following way.
Example 2:
Below is the implementation of the above mentioned topic:
Java
// Java program to illustrate creating
// an array of objects

class Student {
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
[Link] = name;
}
}

// Elements of the array are objects of a class Student.


public class GFG {
public static void main(String[] args)
{
// declares an Array of Student
Student[] arr;

// allocating memory for 5 objects of type Student.


arr = new Student[5];

// initialize the first elements of the array


arr[0] = new Student(1, "aman");

// initialize the second elements of the array


arr[1] = new Student(2, "vaibhav");

// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");
// accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link]("Element at " + i + " : "
+ arr[i].roll_no + " "
+ arr[i].name);
}
}

Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)
Example 3:
An array of objects is also created like :
Java
// Java program to illustrate creating
// an array of objects

class Student
{

public String name;


Student(String name)
{
[Link] = name;
}
@Override
public String toString(){
return name;
}
}

// Elements of the array are objects of a class Student.


public class GFG
{
public static void main (String[] args)
{
// declares an Array and initializing the elements of the array
Student[] myStudents = new Student[]{new Student("Dharma"),new
Student("sanvi"),new Student("Rupa"),new Student("Ajay")};
// accessing the elements of the specified array
for(Student m:myStudents){
[Link](m);
}
}
}

Output
Dharma
sanvi
Rupa
Ajay

Multidimensional Arrays in Java


Multidimensional arrays are arrays of arrays with each element of the
array holding the reference of other arrays. These are also known
as Jagged Arrays. A multidimensional array is created by appending one
set of square brackets ([]) per dimension.
Syntax:
There are 2 methods to declare Java Multidimensional Arrays as
mentioned below:
datatype [][] arrayrefvariable;
datatype arrayrefvariable[][];

Declaration:
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
Java Multidimensional Arrays Examples
Example 1:
Java
// Java Program to demonstrate
// Java Multidimensional Array
import [Link].*;

// Driver class
class GFG {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column

// Number of Rows
[Link]("Number of Rows:"+
[Link]);

// Number of Columns
[Link]("Number of Columns:"+
arr[0].length);
}
}

Output
Number of Rows:3
Number of Columns:3
Example 2:
Java
// Java Program to Multidimensional Array

// Driver Class
public class multiDimensional {
// main function
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
[Link](arr[i][j] + " ");

[Link]();
}
}
}

Output
2 7 9
3 6 1
7 4 2

Unit 1 Questions Bank

1. Discuss the history and features of Java programming.


2. Differentiate between object-oriented programming and structured programming.
3. Explain the working of JVM architecture with a block diagram and describe the function of
each component.
4. Explain the Object-Oriented Programming (OOP) concepts in Java.
5. Write a Java program that demonstrates the use of different variables and data types by
declaring, initializing, and using them in meaningful operations.
6. Write a Java program that demonstrates the various types of operators.
7. Develop a Java program that demonstrates input handling using the Scanner class and the
BufferedReader class and explain in short.
8. Discuss the Vector and ArrayList classes in Java and illustrate the use of their methods through
examples.
9. Develop a Java program to illustrate decision-making statements.
10. Discuss while loop, Do while loop and for loops in Java with example.
11. Develop a Java program that demonstrates the use of various String methods to manipulate
and process text, and briefly explain the results obtained.
12. Write a Java program that uses the StringBuffer class to perform operations such as
appending, inserting, deleting, and reversing strings, and explain the output of each operation.

You might also like