JAVA PROGRAMMING
UNIT-1
INTRODUCTION TO JAVA :-
Java was developed by “JAMESH GOSLING” at sun microsystem Incopration in the year 1995
and later acquired by oracle copration .it is a simple programming language.
Java makes writing, compiling and debugging programming easily.
It helps to create resuable code and modular programs java is a class-based, object-oriented
programming language and is designed to hava as few implementation dependencies as
possible
A General purpose programming language made for develpers to write once run any where
that is complied java code can run on all platforms that support java.
Java applications are complied to byte code that can run on any java virtual machine ,The
syntax of java is similar to c/c++.
HISTORY:-
Java’s history is very interesting. It is a programming language created in 1991. James
gosting mike Sheridan ,and Patrick Naughton , a team of sun engineers known as the green
team initiated the java language in 1991.
Sun microsystems released it’s first public implementation in 1996 as java 1.0. it provides
no-cost-run-times on popular platform java 1.0 compiler was re-written in java by “ARTHUR
VAN HOFF” to strictly compile with it’s specifications with the arrival of java 2,new version
had multiple configurations built for different types of platfroms.
In 1997 ,sun microsystems approached the iso standards body and later formlized java but it
soon withdraw from the process ,at one time ,sun made most of it’s java implementation
available without charge ,despite their pro-prietory software status sun generated revenue
from java through the selling of licenses for specialized products such as the java interprise
system .
On November 13,2006 ,sun released much of it’s java virtual machine as free open-
source ,making all of it’s jvm’s core code available under open -source dristribution terms.
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.
Simple
Object-Oriented
Portable
Platform independent
Secured
Robust
Architecture neutral
Interpreted
High Performance
Multithreaded
Distributed
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:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
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.
AdverObject-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
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:
Runtime Environment
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
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.
Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights
to objects.
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:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
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.
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).
MAJORDIFFERENCE BETWEEN C++ AND JAVA:-
The major differences between C++ and Java have been summarised in the following
table:
COMPARISON
INDEX C++ JAVA
PARAMETER
C++ was developed by Bjarne
Java was developed by James Gosling at
Developed / Stroustrup at Bell Labs in 1979.
Sun Microsystems. Now, it is owned by
Founded by It was developed as an
Oracle.
extension of the C language.
It has support for both
Programming Java has support only for object-oriented
procedural programming and
model programming models.
object-oriented programming.
C++ is platform dependent. It is
Platform Java is platform-independent. It is based on
based on the concept of Write
dependence the concept of Write Once Run Anywhere.
Once Compile Anywhere.
C++ supports features like
Java does not support features like
Features operator overloading, Goto
operator overloading, Goto statements,
supported statements, structures,
structures, pointers, unions, etc.
pointers, unions, etc.
Compilation and C ++ is only compiled and
Java can be both compiled and interpreted.
Interpretation cannot be interpreted.
Java, on the other hand, has more diverse
C++ has very limited libraries
Library and Code libraries with a lot of support for code
with low-level functionalities.
reusability reusability. In Java, only calls through the
C++ allows direct calls to native
support Java Native Interface and recently Java
system libraries.
Native Access are allowed.
Memory In C++, memory management In Java, memory management is System
Management is manual. controlled.
C++ is pretty consistent
In Java, semantics differs for primitive and
Type semantics between primitive and object
object types.
types.
In C++, both global and
Global Scope namespace scopes are Java has no support for global scope.
supported.
Access control In C++, a flexible model with
In Java, the model is cumbersome and
10 and object constant protection is
encourages weak encapsulation.
protection available.
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.
int data=50;//Here data is variable
Types of Variables
There are three types of variables in Java:
local variable
instance variable
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:-
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Java Variable Example: Add Two Numbers:-
public class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
[Link](c);
}
}
Output:
20
Java Variable Example: Widening
public class Simple{
public static void main(String[] args){
int a=10;
float f=a;
[Link](a);
[Link](f);
}}
Output:
10
10.0
Java Variable Example: Narrowing (Typecasting)
public class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
[Link](f);
[Link](a);
}}
Output:
10.5
10
Java Variable Example: Overflow
class Simple{
public static void main(String[] args){
//Overflow
int a=130;
byte b=(byte)a;
[Link](a);
[Link](b);
}}
Output:
130
-126
Java Variable Example: Adding Lower Type
class Simple{
public static void main(String[] args){
byte a=10;
byte b=10;
//byte c=a+b;//Compile Time Error: because a+b=20 will be int
byte c=(byte)(a+b);
[Link](c);
}}
Output:
20
Java Constant:-
As the name suggests, a constant is an entity in programming that is immutable. In other
words, the value that cannot be changed. In this section, we will learn about Java
constant and how to declare a constant in Java.
What is constant?
Constant is a value that cannot be changed after assigning it. Java does not directly support
the constants. There is an alternative way to define the constants in Java by using the non-
access modifiers static and final.
How to declare constant in Java?
In Java, to declare any variable as constant, we use static and final modifiers. It is also known
as non-access modifiers. According to the Java naming convention the identifier name must
be in capital letters.
Static and Final Modifiers
The purpose to use the static modifier is to manage the memory.
It also allows the variable to be available without loading any instance of the class in which it
is defined.
The final modifier represents that the value of the variable cannot be changed. It also makes
the primitive data type immutable or unchangeable.
The syntax to declare a constant is as follows:
static final datatype identifier_name=value;
For example, price is a variable that we want to make constant.
static final double PRICE=432.78;
Where static and final are the non-access modifiers. The double is the data type and PRICE is
the identifier name in which the value 432.78 is assigned.
In the above statement, the static modifier causes the variable to be available without an
instance of its defining class being loaded and the final modifier makes the variable fixed.
Here a question arises that why we use both static and final modifiers to declare a constant?
If we declare a variable as static, all the objects of the class (in which constant is defined) will
be able to access the variable and can be changed its value. To overcome this problem, we use
the final modifier with a static modifier.
When the variable defined as final, the multiple instances of the same constant value will be
created for every different object which is not desirable.
When we use static and final modifiers together, the variable remains static and can be
initialized once. Therefore, to declare a variable as constant, we use both static and final
modifiers. It shares a common memory location for all objects of its containing class.
Why we use constants?
The use of constants in programming makes the program easy and understandable which
can be easily understood by others. It also affects the performance because a constant
variable is cached by both JVM and the application.
Points to Remember:
Write the identifier name in capital letters that we want to declare as constant. For
example, MAX=12.
If we use the private access-specifier before the constant name, the value of the constant
cannot be changed in that particular class.
If we use the public access-specifier before the constant name, the value of the constant can
be changed in the program.
Let's see some examples in which we have used constants.
Example 1: Declaring Constant as Private
[Link]
import [Link];
public class ConstantExample1
{
//declaring constant
private static final double PRICE=234.90;
public static void main(String[] args)
{
int unit;
double total_bill;
[Link]("Enter the number of units you have used: ");
Scanner sc=new Scanner([Link]);
unit=[Link]();
total_bill=PRICE*unit;
[Link]("The total amount you have to deposit is: "+total_bill);
}
}
Output:
Example 2:
[Link]
public class ConstantExample2
{
private static final double PRICE=2999;
public static void main(String[] args)
{
[Link]("Old Price of Iron: "+PRICE);
ConstantExample obj = new ConstantExample();
[Link]();
}
}
class ConstantExample
{
private static final double PRICE=3599;
void showPrice()
{
[Link]("New Price of Iron: "+PRICE);
}
}
Output:
Example 3: Declaring Constant as Public
In the following example, we have declared constant PI as public. Inside the main() method,
we have assigned 3.15 in the constant PI. After that, we have invoked the printValue()
method. When we execute the program, it shows an error cannot assign a value to the final
variable PI.
[Link]
public class ConstantExample3
{
//declaring PI as constant
public static final double PI= 3.14;
public static void main(String[] args)
{
printValue();
//trying to assign 3.15 in the constant PI
PI = 3.15;
printValue();
}
void printValue()
{
[Link]("The value of PI cannot be changed to " + PI);
}
}
Java Keywords:-
Java keywords are also known as reserved words. Keywords are particular words that act as
a key to a code. These are predefined words by Java so they cannot be used as a variable or
object name or class name.
List of Java Keywords
A list of Java keywords or reserved words are given below:
abstract: Java abstract keyword is used to declare an abstract class. An abstract class can
provide the implementation of the interface. It can have abstract and non-abstract methods.
boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold
True and False values only.
break: Java break keyword is used to break the loop or switch statement. It breaks the
current flow of the program at specified conditions.
byte: J000000ava byte keyword is used to declare a variable that can hold 8-bit data values.
case: Java case keyword is used with the switch statements to mark blocks of text.
catch: Java catch keyword is used to catch the exceptions generated by try statements. It must
be used after the try block only.
char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode
characters
class: Java class keyword is used to declare a class.
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.
default: Java default keyword is used to specify the default block of code in a switch
statement.
do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of
the program several times.
double: Java double keyword is used to declare a variable that can hold 64-bit floating-point
number.
else: Java else keyword is used to indicate the alternative branches in an if statement.
enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always
private or default.
extends: Java extends keyword is used to indicate that a class is derived from another class or
interface.
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.
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.
float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
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.
if: Java if keyword tests the condition. It executes the if block if the condition is true.
implements: Java implements keyword is used to implement an interface.
import: Java import keyword makes classes and interfaces available and accessible to the
current source code.
instanceof: Java instanceof keyword is used to test whether the object is an instance of the
specified class or implements an interface.
int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
interface: Java interface keyword is used to declare an interface. It can have only abstract
methods.
long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
native: Java native keyword is used to specify that a method is implemented in native code
using JNI (Java Native Interface).
new: Java new keyword is used to create new objects.
null: Java null keyword is used to indicate that a reference does not refer to anything. It
removes the garbage value.
package: Java package keyword is used to declare a Java package that includes the classes.
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.
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.
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.
return: Java return keyword is used to return from a method when its execution is complete.
short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
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.
strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
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.
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.
synchronized: Java synchronized keyword is used to specify the critical sections or methods
in multithreaded code.
this: Java this keyword can be used to refer the current object in a method or constructor.
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.
throws: The Java throws keyword is used to declare an exception. Checked exceptions can be
propagated with throws.
transient: Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
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.
void: Java void keyword is used to specify that a method does not have a return value.
volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
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.
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:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
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.
There are 8 types of primitive data types:
boolean data type
byte data type
char data type
short data type
int data type
long data type
float data type
double data type
Table 1
Data Type Default Value Default size
boolean False 1 bit
char '\u0000' 2 byte
byte 1 byte
short 2 byte
int 4 byte
Long 0L 8 byte
Float 0.0f 4 byte
Double 0.0d 8 byte
Boolean Data Type:-
The Boolean data type is used to store only two possible values: true and false. This data type
is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
Boolean >Byte Data Type:-
The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value
is -128 and maximum value is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used
in place of "int" data type.
Example:
byte a = 10, byte b = -20
Short Data Type:-
The short data type is a 16-bit signed two's complement integer. Its value-range lies between
-32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its
default value is 0.
The short data type can also be used to save memory just like byte data type. A short data
type is 2 times smaller than an integer.
Example:
short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is
no problem about memory.
Example:
int a = 100000, int b = -200000
Long Data Type:-
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you need a
range of values more than those provided by int.
Example:
long a = 100000L, long b = -200000L
Float Data Type:-
The float data type is a single-precision 32-bit IEEE 754 floating [Link] value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example:
float f1 = 234.5f2
Double Data Type:-
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.
Example:
double d1 = 12.3
Char Data Type:-
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000'
(or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
char letterA = 'A'
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.
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. 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. In general, class
declarations can include these components, in order:
Modifiers : A class can be public or has default access. Refer to access specifiers for classes or
interfaces in Java
Class name: The name should begin with an initial letter (capitalized by convention).
Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
Body: The class body is surrounded by braces, { }.
3. Object
An Object is a basic unit of Object-Oriented Programming and represents real-life entities. A
typical Java program creates many objects, which as you know, interact by invoking methods.
An object 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 gives a unique name to an object and enables one object to interact with other
objects.
4. Interface
Like a class, an interface can have methods and variables, but the methods declared in an
interface are by default abstract (only method signature, no body).
Interfaces specify what a class must do and not how. It is the blueprint of the class.
An Interface is about capabilities like a Player may be an interface and any class
implementing Player must be able to (or must implement) move(). So it specifies a set of
methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all functions
specified in the interface, then the class must be declared abstract.
A Java library example is Comparator Interface . If a class implements this interface, then it
can be used to sort a collection.
5. 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] .
Wrapper classes in Java
The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.
Autoboxing and unboxing feature convert primitives into objects and objects into primitives
automatically. The automatic conversion of primitive into an object is known as autoboxing
and vice-versa unboxing.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects many
times like in Collections, Serialization, Synchronization, etc. Let us see the different
scenarios, where we need to use the wrapper classes.
Change the value in Method: Java supports only call by value. So, if we pass a primitive value,
it will not change the original value. But, if we convert the primitive value in an object, it will
change the original value.
Serialization: We need to convert the objects into streams to perform the serialization. If we
have a primitive value, we can convert it in objects through the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.
[Link] package: The [Link] package provides the utility classes to deal with objects.
Collection Framework: Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the [Link] package are known as wrapper classes in Java. The list of
eight wrapper classes are given below:
Primitive Wrapper
Type class
Boolean Boolean
Char Character
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long,
float to Float, boolean to Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.
Wrapper class Example: Primitive to Wrapper
//Java program to convert primitive into objects
//Autoboxing example of int to Integer
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=[Link](a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write [Link](a) internally
[Link](a+" "+i+" "+j);
}}
Output:
20 20 20
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.
Wrapper class Example: Wrapper to Primitive
//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=[Link]();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write [Link]() internally
[Link](a+" "+i+" "+j);
}}
Output:
333
Java Wrapper classes Example
//Java Program to convert all primitives into its corresponding
//wrapper objects and vice-versa
public class WrapperExample3{
public static void main(String args[]){
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;
//Autoboxing: Converting primitives into objects
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;
//Printing objects
[Link]("---Printing object values---");
[Link]("Byte object: "+byteobj);
[Link]("Short object: "+shortobj);
[Link]("Integer object: "+intobj);
[Link]("Long object: "+longobj);
[Link]("Float object: "+floatobj);
[Link]("Double object: "+doubleobj);
[Link]("Character object: "+charobj);
[Link]("Boolean object: "+boolobj);
//Unboxing: Converting Objects to Primitives
byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;
//Printing primitives
[Link]("---Printing primitive values---");
[Link]("byte value: "+bytevalue);
[Link]("short value: "+shortvalue);
[Link]("int value: "+intvalue);
[Link]("long value: "+longvalue);
[Link]("float value: "+floatvalue);
[Link]("double value: "+doublevalue);
[Link]("char value: "+charvalue);
[Link]("boolean value: "+boolvalue);
}}
Output:
---Printing object values---
Byte object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double object: 60.0
Character object: a
Boolean object: true
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: a
boolean value: true
Custom Wrapper class in Java
Java Wrapper classes wrap the primitive data types, that is why it is known as wrapper
classes. We can also create a class which wraps a primitive data type. So, we can create a
custom wrapper class in Java.
//Creating the custom wrapper class
class Javatpoint{
private int i;
Javatpoint(){}
Javatpoint(int i){
this.i=i;
}
public int getValue(){
return i;
}
public void setValue(int i){
this.i=i;
}
@Override
public String toString() {
return [Link](i);
}
}
//Testing the custom wrapper class
public class TestJavatpoint{
public static void main(String[] args){
Javatpoint j=new Javatpoint(10);
[Link](j);
}}
Output:
10
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Java Operator Precedence
Operator Type Category Precedence
postfix expr++ expr--
Unary
prefix ++expr --expr +expr -expr ~ !
multiplicative */%
Arithmetic
additive +-
Shift shift << >> >>>
comparison < > <= >= instanceof
Relational
equality == !=
bitwise AND &
Bitwise bitwise exclusive OR
bitwise inclusive OR
logical AND &&
Logical
logical OR
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
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
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
[Link](a+b);//15
[Link](a-b);//5
[Link](a*b);//50
[Link](a/b);//2
[Link](a%b);//0
}}
Output:
15
5
50
2
0
Java Arithmetic Operator Example: Expression
public class OperatorExample{
public static void main(String args[]){
[Link](10*10/5+3-1*4/2);
}}
Output:
21
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
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
EXPRESSION
In Java, an expression is a combination of variables, operators, and method calls that
evaluates to a single value. Here are some types of expressions in Java:
1. Arithmetic Expressions
- Addition: a + b
- Subtraction: a - b
- Multiplication: a * b
- Division: a / b
- Modulus: a % b
4. Logical Expressions
- AND: a && b
- OR: a || b
- NOT: !a
5. Bitwise Expressions
- Bitwise AND: a & b
- Bitwise OR: a | b
- Bitwise XOR: a ^ b
- Bitwise NOT: ~a
COMMENTS
In Java, comments are used to explain code, make it more readable, and provide
documentation. There are three types of comments in Java:
1. Single-Line Comments
- Start with //
- Everything after // on the same line is ignored
Example:
// This is a single-line comment
[Link]("Hello, World!"); // Printing Hello, World!
2. Multi-Line Comments
- Start with /*
- End with */
- Everything between /* and */ is ignored
Example:
/*
This is a multi-line comment
It spans multiple lines
*/
3. Javadoc Comments
- Start with /**
- End with */
- Used for documenting classes, methods, and variables
- Javadoc tool generates HTML documentation from these comments
Example:
/**
* This is a Javadoc comment
* @author John Doe
* @version 1.0
*/
public class MyClass {
/**
* Prints Hello, World!
*/
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Best Practices:
- Use comments to explain complex logic
- Keep comments concise and clear
- Avoid commenting obvious code
- Use Javadoc comments for public APIs
- Update comments when code changes
Here's an example Java code snippet demonstrating different comment types:
// Single-line comment
public class CommentExample {
/* Multi-line comment
This is a class description */
/**
* Javadoc comment
* @author Meta AI
*/
public static void main(String[] args) {
// Method description
[Link]("Hello, World!"); // Single-line comment
}
}
Java Basic Input and Output
Java Output
In Java, you can simply use
[Link](); or
[Link](); or
[Link]();
to send output to standard output (screen).
Here,
System is a class
out is a public static field: it accepts output data.
Don't worry if you don't understand it. We will discuss class, public, and static in later
chapters.
Let's take an example to output a line.
class AssignmentOperator {
public static void main(String[] args) {
[Link]("Java programming is interesting.");
}
}
Run Code
Output:
Java programming is interesting.
Here, we have used the println() method to display the string.
Difference between println(), print() and printf()
print() - It prints string inside the quotes.
println() - It prints string inside the quotes similar like print() method. Then the cursor
moves to the beginning of the next line.
printf() - It provides string formatting (similar to printf in C/C++ programming).
Example: print() and println()
class Output {
public static void main(String[] args) {
[Link]("1. println ");
[Link]("2. println ");
[Link]("1. print ");
[Link]("2. print");
}
}
Run Code
Output:
1. println
2. println
1. print 2. print
In the above example, we have shown the working of the print() and println() methods. To
learn about the printf() method, visit Java printf().
Example: Printing Variables and Literals
class Variables {
public static void main(String[] args) {
Double number = -10.6;
[Link](5);
[Link](number);
}
}
Run Code
When you run the program, the output will be:
5
-10.6
Here, you can see that we have not used the quotation marks. It is because to display
integers, variables and so on, we don't use quotation marks.
Example: Print Concatenated Strings
class PrintVariables {
public static void main(String[] args) {
Double number = -10.6;
[Link]("I am " + "awesome.");
[Link]("Number = " + number);
}
}
Run Code
Output:
I am awesome.
Number = -10.6
In the above example, notice the line,
[Link]("I am " + "awesome.");
Here, we have used the + operator to concatenate (join) the two strings: "I am
" and "awesome.".
And also, the line,
[Link]("Number = " + number);
Here, first the value of variable number is evaluated. Then, the value is concatenated to the
string: "Number = ".
Java Input
Java provides different ways to get input from the user. However, in this tutorial, you will
learn to get input from user using the object of Scanner class.
In order to use the object of Scanner, we need to import [Link] package.
import [Link];
To learn more about importing packages in Java, visit Java Import Packages.
Then, we need to create an object of the Scanner class. We can use the object to take input
from the user.
// create an object of Scanner
Scanner input = new Scanner([Link]);
// take input from the user
int number = [Link]();
Example: Get Integer Input From the User
import [Link];
class Input {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter an integer: ");
int number = [Link]();
[Link]("You entered " + number);
// closing the scanner object
[Link]();
}
}
Run Code
Output:
Enter an integer: 23
You entered 23
In the above example, we have created an object named input of the Scanner class. We then
call the nextInt() method of the Scanner class to get an integer input from the user.
Similarly, we can use nextLong(), nextFloat(), nextDouble(), and next() methods to
get long, float, double, and string input respectively from the user.
Note: We have used the close() method to close the object. It is recommended to close the
scanner object once the input is taken.
Example: Get float, double and String Input
import [Link];
class Input {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
// Getting float input
[Link]("Enter float: ");
float myFloat = [Link]();
[Link]("Float entered = " + myFloat);
// Getting double input
[Link]("Enter double: ");
double myDouble = [Link]();
[Link]("Double entered = " + myDouble);
// Getting String input
[Link]("Enter text: ");
String myString = [Link]();
[Link]("Text entered = " + myString);
}
}
Run Code
Output:
Enter float: 2.343
Float entered = 2.343
Enter double: -23.4
Double entered = -23.4
Enter text: Hey!
Text entered = Hey!
Decision Making in Java (if, if-else, switch, break, continue, jump)
Last Updated : 18 Feb, 2023
Decision Making in programming is similar to decision-making in real life. In programming
also face some situations where we want a certain block of code to be executed when some
condition is fulfilled.
A programming language uses control statements to control the flow of execution of a
program based on certain conditions. These are used to cause the flow of execution to
advance and branch based on changes to the state of a program.
Java’s Selection statements:
if
if-else
nested-if
if-else-if
switch-case
jump – break, continue, return
1. if: if statement is the most simple decision-making statement. It is used to decide whether
a certain statement or block of statements will be executed or not i.e if a certain condition is
true then a block of statements is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if statement accepts boolean
values – if the value is true then it will execute the block of statements under it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition ) then by default if
statement will consider the immediate one statement to be inside its block. For example,
if(condition) //Assume condition is true
statement1; //part of if block
statement2; // separate from if block
// Here if the condition is true
// if block will consider statement1 as its part and executes in only true condition
// statement2 will be separate from the if block so it will always executes whether the
condition is true or false.
Example:
Java
// Java program to illustrate If statement without curly block
import [Link].*;
class IfDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
[Link]("Inside If block"); // part of if block(immediate one statement after if con
[Link]("10 is less than 15"); //always executes as it is outside of if block
// This statement will be executed
// as if considers one statement by default again below statement is outside of if block
[Link]("I am Not in if");
}
Output
Inside If block
10 is less than 15
I am Not in if
Time Complexity: O(1)
Auxiliary Space : O(1)
2. if-else: The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do something else if
the condition is false? Here comes the else statement. We can use the else statement with the
if statement to execute a block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example:
Java
// Java program to illustrate if-else statement
import [Link].*;
class IfElseDemo {
public static void main(String args[])
{
int i = 10;
if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15");
}
Output
i is smaller than 15
Time Complexity: O(1)
Auxiliary Space : O(1)
3. nested-if: A nested if is an if statement that is the target of another if or else. Nested if
statements mean an if statement inside an if statement. Yes, java allows us to nest if
statements within if statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example:
Java
// Java program to illustrate nested-if statement
import [Link].*;
class NestedIfDemo {
public static void main(String args[])
{
int i = 10;
if (i == 10 || i<15) {
// First if statement
if (i < 15)
[Link]("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
[Link](
"i is smaller than 12 too");
} else{
[Link]("i is greater than 15");
}
}
Output
i is smaller than 15
i is smaller than 12 too
Time Complexity: O(1)
Auxiliary Space: O(1)
4. if-else-if ladder: Here, a user can decide among multiple [Link] if statements are
executed from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that ‘if’ is executed, and the rest of the ladder is bypassed. If none
of the conditions is true, then the final else statement will be executed. There can be as many
as ‘else if’ blocks associated with one ‘if’ block but only one ‘else’ block is allowed with one
‘if’ block.
if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;
Example:
Java
// Java program to illustrate if-else-if ladder
import [Link].*;
class ifelseifDemo {
public static void main(String args[])
{
int i = 20;
if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");
}
Output
i is 20
Time Complexity: O(1)
Auxiliary Space: O(1)
5. switch-case: The switch statement is a multiway branch statement. It provides an easy way
to dispatch execution to different parts of code based on the value of the expression.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Java
/*package whatever //do not write package name here */
import [Link].*;
class GFG {
public static void main (String[] args) {
int num=20;
switch(num){
case 5 : [Link]("It is 5");
break;
case 10 : [Link]("It is 10");
break;
case 15 : [Link]("It is 15");
break;
case 20 : [Link]("It is 20");
break;
default: [Link]("Not present");
}
}
Output
It is 20
NESTING:-
Nesting in Java refers to placing one control structure or block within another. This is useful
for organizing code, reducing complexity, and improving readability. Here are examples of
nesting in Java:
1. Nested If Statements
if (age >= 18) {
if (citizen) {
[Link]("Eligible to vote");
} else {
[Link]("Not a citizen, cannot vote");
}
} else {
[Link]("Underage, cannot vote");
}
2. Nested Loops
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
[Link](i + " * " + j + " = " + (i * j) + "\t");
}
[Link]();
}
3. Nested Switch Statements
int choice = 1;
switch (choice) {
case 1:
switch (choice) {
case 1:
[Link]("Choice 1.1");
break;
case 2:
[Link]("Choice 1.2");
break;
}
break;
case 2:
[Link]("Choice 2");
break;
}
4. Nested Try-Catch Blocks
// Code that may throw exception
try {
// Code that may throw nested exception
} catch (Exception e) {
// Handle nested exception
}
} catch (Exception e) {
// Handle outer exception
}
5. Nested Classes (Inner Classes)
public class OuterClass {
public class InnerClass {
public void innerMethod() {
[Link]("Inner class method");
}
}
public void outerMethod() {
InnerClass inner = new InnerClass();
[Link]();
}
}
Best Practices:
- Use nesting to improve code organization and readability.
- Avoid excessive nesting (more than 3-4 levels).
- Use clear and descriptive variable names.
- Use comments to explain complex nested logic.
By applying nesting techniques effectively, you can write more efficient, readable, and
maintainable Java code.
// I just got executed
JAVA METHOD
A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as [Link](), but you can
also create your own methods to perform certain actions:
ExampleGet your own Java Server
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}
Example Explained
myMethod() is the name of the method
static means that the method belongs to the Main class and not an object of the Main class. You will
learn more about objects and how to access methods through objects
Call a Method
later in this tutorial.
void means that this method does not have a return value. You will learn more about return values
later in this chapter
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main, call the myMethod() method:
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
// Outputs "I just got executed!"
A method can also be called multiple times:
Example
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
}
}
// I just got executed!
// I just got executed!
// I just got executed!
JAVA METHOD PARAMETER
Parameters and Arguments
Information can be passed to methods as a parameter. Parameters act as variables inside the method.
Parameters are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as parameter. When the method
is called, we pass along a first name, which is used inside the method to print the full name:
ExampleGet your own Java Server
public class Main {
static void myMethod(String fname) {
[Link](fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
When a parameter is passed to the method, it is called an argument. So, from the example
above: fname is a parameter, while Liam, Jenny and Anja are arguments.
Multiple Parameters
You can have as many parameters as you like:
Example
public class Main {
static void myMethod(String fname, int age) {
[Link](fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
// Liam is 5
// Jenny is 8
// Anja is 31
Note that when you are working with multiple parameters, the method call must have the same
number of arguments as there are parameters, and the arguments must be passed in the same order.
A Method with If...Else
It is common to use if...else statements inside methods:
Example
public class Main {
// Create a checkAge() method with an integer variable called age
static void checkAge(int age) {
// If age is less than 18, print "access denied"
if (age < 18) {
[Link]("Access denied - You are not old enough!");
// If age is greater than, or equal to, 18, print "access granted"
} else {
[Link]("Access granted - You are old enough!");
}
public static void main(String[] args) {
checkAge(20); // Call the checkAge method and pass along an age of 20
}
}
// Outputs "Access granted - You are old enough!
Return Values
we used the void keyword in all examples, which indicates that the method should not return a value.
If you want the method to return a value, you can use a primitive data type (such as int, char, etc.)
instead of void, and use the return keyword inside the method:
ExampleGet your own Java Server
public class Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
[Link](myMethod(3));
}
}
// Outputs 8 (5 + 3)
This example returns the sum of a method's two parameters:
Example
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
[Link](myMethod(5, 3));
}
}
// Outputs 8 (5 + 3)
You can also store the result in a variable (recommended, as it is easier to read and maintain):
Example
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
int z = myMethod(5, 3);
[Link](z);
}
}
// Outputs 8 (5 + 3)
Java Method OverloadingMethod Overloading
With method overloading, multiple methods can have the same name with different parameter
ExampleGet your own Java Server
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
Consider the following example, which has two methods that add numbers of different type:
Example
static int plusMethodInt(int x, int y) {
return x + y;
}
static double plusMethodDouble(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
[Link]("int: " + myNum1);
[Link]("double: " + myNum2);
}
Instead of defining two methods that should do the same thing, it is better to overload one.
In the example below, we overload the plusMethod method to work for both int and double:
Example
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
public static void main(String[] args) {
int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
[Link]("int: " + myNum1);
[Link]("double: " + myNum2);
}
Java Scope
In Java, variables are only accessible inside the region they are created. This is called scope.
Method Scope
Variables declared directly inside a method are available anywhere in the method following the line
of code in which they were declared:
ExampleGet your own Java Server
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
int x = 100;
// Code here can use x
[Link](x);
}
}
Block Scope
A block of code refers to all of the code between curly braces {}.
Variables declared inside blocks of code are only accessible by the code between the curly braces,
which follows the line in which the variable was declared:
Example
public class Main {
public static void main(String[] args) {
// Code here CANNOT use x
{ // This is a block
// Code here CANNOT use x
int x = 100;
// Code here CAN use x
[Link](x);
} // The block ends here
// Code here CANNOT use x
}
}
Java Recursion
Recursion is the technique of making a function call itself. This technique provides a way to break
complicated problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is to
experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In
the following example, recursion is used to add a range of numbers together by breaking it down into
the simple task of adding two numbers:
ExampleGet your own Java Server
Use recursion to add all of the numbers up to 10.
public class Main {
public static void main(String[] args) {
int result = sum(10);
[Link](result);
}
public static int sum(int k) {
if (k > 0) {
return k + sum(k - 1);
} else {
return 0;
}
}
}
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and
returns the result. When k becomes 0, the function just returns 0. When running, the program follows
these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.
Halting Condition
Just as loops can run into the problem of infinite looping, recursive functions can run into the
problem of infinite recursion. Infinite recursion is when the function never stops calling itself. Every
recursive function should have a halting condition, which is the condition where the function stops
calling itself. In the previous example, the halting condition is when the parameter k becomes 0.
It is helpful to see a variety of different examples to better understand the concept. In this example,
the function adds a range of numbers between a start and an end. The halting condition for this
recursive function is when end is not greater than start:
Example
Use recursion to add all of the numbers between 5 to 10.
public class Main {
public static void main(String[] args) {
int result = sum(5, 10);
[Link](result);
}
public static int sum(int start, int end) {
if (end > start) {
return end + sum(start, end - 1);
} else {
return end;
}
}
}
Java Command-Line Arguments
The command-line arguments in Java allow us to pass arguments during the execution of the
program.
As the name suggests arguments are passed through the command line.
Example: Command-Line Arguments
class Main {
public static void main(String[] args) {
[Link]("Command-Line arguments are");
// loop through all arguments
for(String str: args) {
[Link](str);
}
}
}
Run Code
Let's try to run this program using the command line.
1. To compile the code
javac [Link]
2. To run the code
java Main
Now suppose we want to pass some arguments while running the program, we can pass the
arguments after the class name. For example,
java Main apple ball cat
Here apple, ball, and cat are arguments passed to the program through the command line. Now, we
will get the following output.
Command-Line arguments are
Apple
Ball
Cat
In the above program, the main() method includes an array of string named args as its parameter.
public static void main(String[] args) {...}
The String array stores all the arguments passed through the command line.
Note: Arguments are always stored as strings and always separated by white-space.
Passing Numeric Command-Line Arguments
The main() method of every Java program only accepts string arguments. Hence it is not possible to
pass numeric arguments through the command line.
However, we can later convert string arguments into numeric values.
Example: Numeric Command-Line Arguments
class Main {
public static void main(String[] args) {
for(String str: args) {
// convert into integer type
int argument = [Link](str);
[Link]("Argument in integer form: " + argument);
}
}
}
Run Code
Let's try to run the program through the command line.
// compile the code
javac [Link]
// run the code
java Main 11 23
Here 11 and 23 are command-line arguments. Now, we will get the following output.
Arguments in integer form
11
23
In the above example, notice the line
int argument = [Link](str);
Here, the parseInt() method of the Integer class converts the string argument into an integer.
Similarly, we can use the parseDouble() and parseFloat() method to convert the string
into double and float respectively.
Note: If the arguments cannot be converted into the specified numeric value then an exception
named NumberFormatException occurs
Scanner Class in Java
In Java, Scanner is a class in [Link] package used for obtaining the input of the primitive types like
int, double, etc. and strings.
Using the Scanner class in Java is the easiest way to read input in a Java program, though not very
efficient if you want an input method for scenarios where time is a constraint like in competitive
programming.
Java Scanner Input Types
Scanner class helps to take the standard input stream in Java. So, we need some methods to extract
data from the stream. Methods used for extracting data are mentioned below:
Method Description
nextBoolean() Used for reading Boolean value
nextByte() Used for reading Byte value
nextDouble() Used for reading Double value
nextFloat() Used for reading Float value
nextInt() Used for reading Int value
nextLine() Used for reading Line value
Method Description
nextLong() Used for reading Long value
nextShort() Used for reading Short value
Let us look at the code snippet to read data of various data types.
Examples of Java Scanner Class
Example 1:
Java
// Java program to read data of various types
// using Scanner class.
import [Link];
// Driver Class
public class ScannerDemo1 {
// main function
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner([Link]);
// String input
String name = [Link]();
// Character input
char gender = [Link]().charAt(0);
// Numerical data input
// byte, short and float can be read
// using similar-named functions.
int age = [Link]();
long mobileNo = [Link]();
double cgpa = [Link]();
// Print the values to check if the input was
// correctly obtained.
[Link]("Name: " + name);
[Link]("Gender: " + gender);
[Link]("Age: " + age);
[Link]("Mobile Number: " + mobileNo);
[Link]("CGPA: " + cgpa);
}
Input
Geek
F
40
9876543210
9.9
Output
Name: Geek
Gender: F
Age: 40
Mobile Number: 9876543210
CGPA: 9.9
Sometimes, we have to check if the next value we read is of a certain type or if the input has ended
(EOF marker encountered).
Then, we check if the scanner’s input is of the type we want with the help of hasNextXYZ() functions
where XYZ is the type we are interested in. The function returns true if the scanner has a token of that
type, otherwise false. For example, in the below code, we have used hasNextInt(). To check for a
string, we use hasNextLine(). Similarly, to check for a single character, we use hasNext().charAt(0).
Example 2:
Let us look at the code snippet to read some numbers from the console and print their mean.
Java
// Java program to read some values using Scanner
// class and print their mean.
import [Link];
public class ScannerDemo2 {
public static void main(String[] args)
{
// Declare an object and initialize with
// predefined standard input object
Scanner sc = new Scanner([Link]);
// Initialize sum and count of input elements
int sum = 0, count = 0;
// Check if an int value is available
while ([Link]()) {
// Read an int value
int num = [Link]();
sum += num;
count++;
}
if (count > 0) {
int mean = sum / count;
[Link]("Mean: " + mean);
}
else {
[Link](
"No integers were input. Mean cannot be calculated.");
}
}
Input
12345
Output
Mean: 3
Important Points About Java Scanner Class
To create an object of Scanner class, we usually pass the predefined object [Link], which
represents the standard input stream. We may pass an object of class File if we want to read input
from a file.
To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to
read a value of type short, we can use nextShort()
To read strings, we use nextLine().
To read a single character, we use next().charAt(0). next() function returns the next token/word in
the input as a string and charAt(0) function returns the first character in that string.
The Scanner class reads an entire line and divides the line into tokens. Tokens are small elements
that have some meaning to the Java compiler. For example, Suppose there is an input string: How are
you
In this case, the scanner object will read the entire line and divides the string into tokens: “How”,
“are” and “you”. The object then iterates over each token and reads each token using its different
methods.
Java BufferedReader Class
Java BufferedReader class is used to read the text from a character-based input stream. It can be used
to read data line by line by readLine() method. It makes the performance fast. It
inherits Reader class.
Java BufferedReader class declaration
Let's see the declaration for [Link] class:
public class BufferedReader extends Reader
Java BufferedReader class constructors
Constructor Description
It is used to create a buffered character input
BufferedReader(Reader rd)
default size for an input buffer.
It is used to create a buffered character input
BufferedReader(Reader rd, int size)
specified size for an input buffer.
Java BufferedReader class methods
Method Description
int read() It is used for reading a single character.
It is used for reading characters
int read(char[] cbuf, int off, int len)
into a portion of an array.
It is used to test the input stream support for
boolean markSupported()
method.
String readLine() It is used for reading a line of text.
It is used to test whether the input
boolean ready()
stream is ready to be read.
long skip(long n) It is used for skipping the characters.
It repositions the stream at
void reset() a position the mark method was
last called on this input stream.
It is used for marking the present
void mark(int readAheadLimit)
position in a stream.
It closes the input stream and
void close() releases any of the system resources
associated with the stream.
Java BufferedReader Example
In this example, we are reading the data from the text file [Link] using Java BufferedReader class.
package [Link];
import [Link].*;
public class BufferedReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\[Link]");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=[Link]())!=-1){
[Link]((char)i);
}
[Link]();
[Link]();
}
}
Here, we are assuming that you have following data in "[Link]" file:
Welcome to javaTpoint.
Output:
Welcome to javaTpoint.
Reading data from console by InputStreamReader and BufferedReader
In this example, we are connecting the BufferedReader stream with the InputStreamReader stream
for reading the line by line data from the keyboard.
package [Link];
import [Link].*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader([Link]);
BufferedReader br=new BufferedReader(r);
[Link]("Enter your name");
String name=[Link]();
[Link]("Welcome "+name);
}
}
Output:
Enter your name
Nakul Jain
Welcome Nakul Jain
Another example of reading data from console until user writes stop
In this example, we are reading and printing the data until the user prints stop.
package [Link];
import [Link].*;
public class BufferedReaderExample{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader([Link]);
BufferedReader br=new BufferedReader(r);
String name="";
while(){
[Link]("Enter data: ");
name=[Link]();
[Link]("data is: "+name);
}
[Link]();
[Link]();
}
}
Output:
Enter data: Nakul
data is: Nakul
Enter data: 12
data is: 12
Enter data: stop
data is: stop