0% found this document useful (0 votes)
11 views104 pages

Introduction to Java Programming Basics

Java is a class-based, object-oriented programming language designed for platform independence, allowing code to run anywhere without recompilation. It was created in 1991 by a team at Sun Microsystems and has evolved significantly since its first public release in 1996. The document outlines Java's structure, including its basic components, tokens, statements, and how to handle user input.

Uploaded by

woonna.kumar
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)
11 views104 pages

Introduction to Java Programming Basics

Java is a class-based, object-oriented programming language designed for platform independence, allowing code to run anywhere without recompilation. It was created in 1991 by a team at Sun Microsystems and has evolved significantly since its first public release in 1996. The document outlines Java's structure, including its basic components, tokens, statements, and how to handle user input.

Uploaded by

woonna.kumar
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

JAVA

Introduction to Java
Java is a class-based, object-oriented programming language that is designed to have as few
implementation dependencies as possible. It is intended to let application developers write once, and
run anywhere (WORA), meaning that compiled Java code can run on all platforms that support Java
without the need for recompilation. Java was first released in 1995 and is widely used for developing
applications for desktop, web, and mobile devices. Java is known for its simplicity, robustness, and
security features, making it a popular choice for enterprise-level applications.

History:
Java’s history is very interesting. It is a programming language created in 1991. James Gosling, Mike
Sheridan, and Patrick Naughton, a team of Sun engineers known as the Green team initiated the Java
language in 1991. Sun Microsystems released its first public implementation in 1996 as Java 1.0. It
provides no-cost -run-times on popular platforms. Java1.0 compiler was re-written in Java by Arthur Van
Hoff to strictly comply with its specifications. With the arrival of Java 2, new versions had multiple
configurations built for different types of platforms.

On November 13, 2006, Sun released much of its Java virtual machine as free, open-source software. On
May 8, 2007, Sun finished the process, making all of its JVM’s core code available under open-source
distribution terms.

The principles for creating java programming language were simple, robust, secured, high-performance,
portable, multi-threaded, interpreted, dynamic, etc. In 1995 Java was developed by James Gosling, who
is known as the Father of Java. Currently, Java is used in mobile devices, internet programming, games,
e-business, etc.

WHY JAVA : After the name OAK, the team decided to give it a new name to it and the suggested words
were Silk, Jolt, revolutionary, DNA, dynamic, etc. These all names were easy to spell and fun to say, but
they all wanted the name to reflect the essence of technology. In accordance with James
Gosling, Java the among the top names along with Silk, and since java was a unique name so most of
them preferred it.

Java is the name of an island in Indonesia where the first coffee(named java coffee) was produced. And
this name was chosen by James Gosling while having coffee near his office. Note that Java is just a name,
not an acronym.

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:

• Documentation Section

• Package Declaration

• Import Statements

• Interface Section

• Class Definition

• Class Variables and Variables

• Main Method Class

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

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

For example: //First Java Program.

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

• Documentation Comment: It starts with the delimiter (/**) and ends with */.

For example: /**It is an example of documentation comment*/

• PACKAGE DECLARATION SECTION :

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:

package javatpoint; //where javatpoint is the package name

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:

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

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: interface car {

void start();

void stop();

• 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: class Student //class definition

• CLASS VARIABLES AND CLASS :

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: class Student //class definition

{
String sname; //variable

int id;

double percentage;

• 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:

public static void main(String args[]) {

For example: public class Student //class definition

public static void main(String args[])

{ //statements

• 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: public class Demo //class definition

public static void main(String args[])

void display()
{

[Link]("Welcome to javatpoint");

//statements

JAVA TOKENS :
In Java, the program contains classes and methods. Further, the methods contain the
expressions and statements required to perform a specific operation. These statements and
expressions are made up of tokens. In other words, we can say that the expression and
statement is a set of tokens. The tokens are the small building blocks of a Java program that are
meaningful to the Java compiler. Further, these two components contain variables, constants,
and operators. In this section, we will discuss what is tokens in Java.

What is token in Java?

The Java compiler breaks the line of code into text (words) is called Java tokens. These are the
smallest element of the Java program. The Java compiler identified these words as tokens.
These tokens are separated by the delimiters. It is useful for compilers to detect errors.
Remember that the delimiters are not part of the Java tokens.
For example, consider the following code.
public class Demo

public static void main(String args[])

[Link]("javatpoint");

In the above code snippet, public, class, Demo, {, static, void, main, (, String, args, [, ], ),
System, ., out, println , javatpoint, etc. are the Java tokens.

The Java compiler translates these tokens into Java bytecode. Further, these bytecodes are
executed inside the interpreted Java environment.

TYPES OF TOKENS :
Java token includes the following:

• Keywords

• Identifiers

• Literals

• Operators

• Separators

• Comments

Keywords : These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case.

Java provides the following keywords:


Identifier : Identifiers are used to name a variable, constant, function, class, and array. It
usually defined by the user. It uses letters, underscores, or a dollar sign as the first character.
The label is also known as a special kind of identifier that is used in the goto statement.
Remember that the identifier name must be different from the reserved keywords.

There are some rules to declare identifiers are:

• The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start
with digits but may contain digits.

• The whitespace cannot be included in the identifier.

• Identifiers are case sensitive.

Some valid identifiers are:

PhoneNumber

PRICE
radius

a1

_phonenumber

$circumference

jagged_array

12radius //invalid

Literals: In programming literal is a notation that represents a fixed value (constant) in the
source code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is
defined by the programmer. Once it has been defined cannot be changed. Java provides five
types of literals are as follows:

• Integer

• Floating Point

• Character

• String

• Boolean
Operators: In programming, operators are the special symbol that tells the compiler to
perform a special operation. Java provides different types of operators that can be classified
according to the functionality they provide.

There are eight types of operators in Java, are as follows:

• Arithmetic Operators

• Assignment Operators

• Relational Operators

• Unary Operators

• Logical Operators

• Ternary Operators

• Bitwise Operators

• Shift Operators
Separators: The separators in Java is also known as punctuators. There are nine separators in
Java, are as follows:

Note : that the first three separators (; , and .) are tokens that separate other tokens, and the
last six (3 pairs of braces) separators are also known as delimiters. For example, [Link](9, 3);
contains nine tokens.

• Square Brackets *+: It is used to define array elements. A pair of square brackets represents
the. single-dimensional array, two pairs of square brackets represent the two-
dimensional array.

• Parentheses (): It is used to call the functions and parsing the [Link] Braces
{}: The curly braces denote the starting and ending of a code block.

• Comma (,): It is used to separate two values, statements, and parameters.

• Assignment Operator (=): It is used to assign a variable and constant.

• Semicolon (;): It is the symbol that can be found at end of the statements. It separates the
two statements.

• Period (.): It separates the package name form the sub-packages and class. It also separates
a variable or method from a reference variable.

Comments : Comments allow us to specify information about the program inside our Java
code. Java compiler recognizes these comments as tokens but excludes it form further
processing. The Java compiler treats comments as whitespaces.

Java provides the following two types of comments:

Line Oriented: It begins with a pair of forwarding slashes (//).

Block-Oriented: It begins with /* and continues until it founds */.


TYPES OF STATEMENTS IN JAVA :
Statements are roughly equivalent to sentences in natural languages. In general, statements are
just like English sentences that make valid sense. In this section, we will discuss what is a
statement in Java and the types of statements in Java.

What is statement in Java?


In Java, a statement is an executable instruction that tells the compiler what to perform. It
forms a complete command to be executed and can include one or more expressions. A
sentence forms a complete idea that can include one or more clauses.

Types of Statements :
Java statements can be broadly classified into the following categories:

• Expression Statements

• Declaration Statements

• Control Statements

Expression Statements :
Expression is an essential building block of any Java program. Generally, it is used to generate a
new value. Sometimes, we can also assign a value to a variable. In Java, expression is the
combination of values, variables, operators, and method calls.

There are three types of expressions in Java:


• Expressions that produce a value. For example, (6+9), (9%2), (pi*radius) + 2. Note that the
expression enclosed in the parentheses will be evaluate first, after that rest of the expression.

• Expressions that assign a value. For example, number = 90, pi = 3.14.

• Expression that neither produces any result nor assigns a value. For
example, increment or decrement a value by using increment or decrement operator
respectively, method invocation, etc. These expressions modify the value of a variable or state
(memory) of a program. For example, count++, int sum = a + b; The expression changes only the
value of the variable sum. The value of variables a and b do not change, so it is also a side effect.

Declaration Statements :
In declaration statements, we declare variables and constants by specifying their data type and
name. A variable holds a value that is going to use in the Java program.

For example:

Also, we can initialize a value to a variable.

For example:

Java also allows us to declare multiple variables in a single declaration statement. Note that all the
variables must be of the same data type
Control Statement :
Control statements decide the flow (order or sequence of execution of statements) of a Java program. In
Java, statements are parsed from top to bottom. Therefore, using the control flow statements can
interrupt a particular section of a program based on a certain condition.

There are the following types of control statements :

1. Conditional or Selection Statements :

• if Statement

• if-else statement

• if-else-if statement

• switch statement

2. Loop or Iterative Statements :

• for Loop

• while Loop

• do-while Loop

• for-each Loop

3. Flow Control or Jump Statements :

• return

• continue

• break
Example of Statement :

JAVA COMMAND LINE ARGUMENTS :


The java command-line argument is an argument i.e. passed at the time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an
input.

So, it provides a convenient way to check the behavior of the program for the different values. You can
pass N (1,2,3 and so on) numbers of arguments from the command prompt.

Simple example of command-line argument in java :


Example of command-line argument that prints all the values :

In this example, we are printing all the arguments passed from the command-line. For this purpose, we
have traversed the array using for loop.

OUTPUT :
HOW TO GET INPUT FROM USER :
Java Scanner Class :

Java Scanner class allows the user to take input from the console. It belongs to [Link] package. It is
used to read the input of primitive types like int, double, long, short, float, and byte. It is the easiest way
to read input in Java program.

Syntax :

The above statement creates a constructor of the Scanner class having [Link] as an argument. It
means it is going to read from the standard input stream of the program. The [Link] package should
be import while using Scanner class.

It also converts the Bytes (from the input stream) into characters using the platform's default charset.

METHODS OF JAVA SCANNER CLASS :

Java Scanner class provides the following methods to read different primitives types:
Example of integer input from user :

The following example allows user to read an integer form the [Link].
OUTPUT :

EXAMPLE OF STRING INPUT FROM USER :

Let's see another example, in which we have taken string input.

OUTPUT :
JAVA ESCAPE CHARACTERS / SEQUENCES :
Java Escape Characters :

In this section, we will discuss Java escape characters or escape sequences. Also, we will use
these escape sequences or characters in a Java program.

What are escape characters?

In Java, if a character is preceded by a backslash (\) is known as Java escape sequence or escape
characters. It may include letters, numerals, punctuations, etc. Remember that escape characters must
be enclosed in quotation marks (""). These are the valid character literals. The Java compiler interprets
these characters as a single character that adds a specific meaning to the compiler

List of Java Escape Characters :

In Java, there is a total of eight escape sequences that are described in the following table.
Why do we use escape characters?

Let's understand the uses of escape characters through the following example. Suppose, we have to
print the following statement with double quotes:

The following statements do not print Java enclosed in quotation marks.

While we compile the program with the above two statements, the compiler gives errors, as shown
below.
In such a case, the compiler needs to be told that quotation marks do not signal the start or end of a
string, but instead are to be printed. The following statement prints statements with quotation marks.

Using Escape Characters in Java Program :

[Link]

OUTPUT :
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 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:

Example
Type Description Default Size Literals Range of values

boolean true or false false 8 bits true, false true, false

twos-
complement 0 8 bits (none) -128 to 127
byte integer

‘a’, ‘\u0041’, characters representation


Unicode of ASCII values
\u0000 16 bits ‘\101’, ‘\\’, ‘\’,
character
char ‘\n’, ‘β’ 0 to 255

twos-
complement 0 16 bits (none) -32,768 to 32,767
short integer

-2,147,483,648
twos-
complement 0 32 bits -2,-1,0,1,2 to
intger
int 2,147,483,647

-
twos- 9,223,372,036,854,775,808
complement 0 64 bits -2L,-1L,0L,1L,2L
to
integer
long 9,223,372,036,854,775,807

float IEEE 754 0.0 32 bits 1.23e100f , - upto 7 decimal digits


Example
Type Description Default Size Literals Range of values

floating point 1.23e-


100f , .3f ,3.14F

1.23456e300d ,
IEEE 754
0.0 64 bits -123456e- upto 16 decimal digits
floating point
double 300d , 1e1d

Let us discuss and implement each one of the following data types that are as follows:

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;

Example:

Java

// Java Program to Demonstrate Char Primitive Data Type

// Class

class GFG {

// Main driver method

public static void main(String args[])

char a = 'G';

int i = 89;

byte b = 4;

// byte b1 = 7888888955;

short s = 56;

// short s1 = 87878787878;

double d = 4.355453532;

float f = 4.7333434f;

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

1. Modifiers : A class can be public or has default access. Refer to access specifiers for classes or
interfaces in Java

2. Class name: The name should begin with an initial letter (capitalized by convention).

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

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

5. 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 :

1. State : It is represented by the attributes of an object. It also reflects the properties of an object.

2. Behavior : It is represented by the methods of an object. It also reflects the response of an


object to other objects.

3. 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] .

Java Variables :
Variables are containers for storing data values.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by double quotes

 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99

 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

 boolean - stores values with two states: true or false

Declaring (Creating) Variables :


To create a variable, you must specify the type and assign it a value:

Syntax :
type variableName = value;

Where type is one of Java's types (such as int or String), and variableName is the name of the variable
(such as x or name). The equal sign is used to assign values to the variable.

Typecasting in Java :
Typecasting in Java is the process of converting one data type to another data type using the casting
operator. When you assign a value from one primitive data type to another type, this is known as type
casting. To enable the use of a variable in a specific manner, this method requires explicitly instructing
the Java compiler to treat a variable of one data type as a variable of another data type.

Syntax:
<datatype> variableName = (<datatype>) value;

Types of Type Casting


There are two types of Type Casting in java:

 Widening Type Casting

 Narrow Type Casting

Widening Type Casting


A lower data type is transformed into a higher one by a process known as widening type casting. Implicit
type casting and casting down are some names for it. It occurs naturally. Since there is no chance of data
loss, it is secure. Widening Type casting occurs when:

 The target type must be larger than the source type.


 Both data types must be compatible with each other.

Syntax:
larger_data_type variable_name = smaller_data_type_variable;

Java program :

// Java program to demonstrate Widening TypeCasting

import [Link].*;

class GFG {

public static void main(String[] args)

int i = 10;

// Wideing TypeCasting (Automatic Casting)

// from int to long

long l = i;

// Wideing TypeCasting (Automatic Casting)

// from int to double

double d = i;

[Link]("Integer: " + i);

[Link]("Long: " + l);

[Link]("Double: " + d);

}
}

Output

Integer: 10

Long: 10

Double: 10.0

Narrow Type Casting


The process of downsizing a bigger data type into a smaller one is known as narrowing type casting.
Casting up or explicit type casting are other names for it. It doesn’t just happen by itself. If we don’t
explicitly do that, a compile-time error will occur. Narrowing type casting is unsafe because data loss
might happen due to the lower data type’s smaller range of permitted values. A cast operator assists in
the process of explicit casting.

Syntax:
smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;

Example:

 Java

// Java Program to demonstrate Narrow type casting

import [Link].*;

class GFG {

public static void main(String[] args)

double i = 100.245;

// Narrowing Type Casting

short j = (short)i;

int k = (int)i;

[Link]("Original Value before Casting" + i);


[Link]("After Type Casting to short " + j);

[Link]("After Type Casting to int "+ k);

Output

Original Value before Casting100.245

After Type Casting to short 100

After Type Casting to int 100

Types of Explicit Casting


Mainly there are two types of Explicit Casting:

 Explicit Upcasting

 Explicit Downcasting

Explicit Upcasting
Upcasting is the process of casting a subtype to a supertype in the inheritance tree’s upward direction.
When a sub-class object is referenced by a superclass reference variable, an automatic process is
triggered without any further effort.

Example:

 Java

// Java Program to demonstrate Explicit Upcasting

import [Link].*;

class Animal {

public void makeSound()

[Link]("The animal makes a sound");


}

class Dog extends Animal {

public void makeSound()

[Link]("The dog barks");

public void fetch()

[Link]("The dog fetches a ball");

class GFG {

public static void main(String[] args)

{ // Upcasting

Animal animal = new Dog();

// Calls the overridden method in Dog class

[Link]();

// This would give a compile error as fetch() is not

// a method in Animal class

// [Link]();

Output
The dog barks

Explicit Downcasting
When a subclass type refers to an object of the parent class, the process is referred to as downcasting. If
it is done manually, the compiler issues a runtime ClassCastException error. It can only be done by using
the instanceof operator. Only the downcast of an object that has already been upcast is possible.

Example:

 Java

// Java Program to demonstrate Explicit downcasting

import [Link].*;

class Animal {

public void eat()

[Link]("The animal is eating.");

class Cat extends Animal {

public void meow()

[Link]("The cat is meowing.");

class GFG {

public static void main(String[] args)

{
Animal animal = new Cat();

[Link]();

// Explicit downcasting

Cat cat = (Cat)animal;

[Link]();

Output

The animal is eating.

The cat is meowing.

Scope of Variables In Java :


Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all
identifiers are lexically (or statically) scoped, [Link] of a variable can be determined at compile time
and independent of function call stack.
Java programs are organized in the form of classes. Every class is part of some package. Java scope rules
can be covered under following categories.

Member Variables (Class Level Scope) :


These variables must be declared inside class (outside any function). They can be directly accessed
anywhere in class. Let’s take a look at an example:

public class Test


{
// All variables defined directly inside a class
// are member variables
int a;
private String b;
void method1() {....}
int method2() {....}
char c;
}

 We can declare class variables anywhere in class, but outside methods.

 Access specified of member variables doesn’t affect scope of them within a class.

 Member variables can be accessed outside a class with following rules

Modifier Package Subclass World

Public Yes Yes Yes

Protected Yes Yes No

Default Yes No No

Private No No No

Local Variables (Method Level Scope) :


Variables declared inside a method have method level scope and can’t be accessed outside the method.

public class Test


{
void method1()
{
// Local variable (Method level scope)
int x;
}
}

Note : Local variables don’t exist after method’s execution is over.

Here’s another example of method scope, except this time the variable got passed in as a parameter to
the method:

class Test
{
private int x;
public void setX(int x)
{
this.x = x;
}
}

The above code uses this keyword to differentiate between the local and class variables.

Literals in Java :
In Java, literal is a notation that represents a fixed value in the source code. In lexical analysis, literals of
a given type are generally known as tokens. In this section, we will discuss the term literals in Java.

Literals :
In Java, literals are the constant values that appear directly in the program. It can be assigned directly to
a variable. Java has various types of literals. The following figure represents a literal.

Types of Literals in Java

There are the majorly four types of literals in Java:

1. Integer Literal

2. Character Literal

3. Boolean Literal

4. String Literal
Integer Literals :
Integer literals are sequences of digits. There are three types of integer literals:

o Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a
positive (+) or negative (-) Note that between numbers commas and non-digit characters are not
permitted. For example, 5678, +657, -89, etc.

int decVal = 26;

o Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0. For
example, 045, 026,

int octVal = 067;

o Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as hexadecimal


integers. It may also include a character from a to f or A to F that represents numbers
from 10 to 15, respectively. For example, 0xd, 0xf,

int hexVal = 0x1a;

o Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary
literals in Java SE 7 and later). Prefix 0b represents the Binary system. For example, 0b11010.

int binVal = 0b11010;

Real Literals :
The numbers that contain fractional parts are known as real literals. We can also represent real literals
in exponent form. For example, 879.90, 99E-3, etc.
Backslash Literals :
Java supports some special backslash character literals known as backslash literals. They are used in
formatted output. For example:

\n: It is used for a new line

\t: It is used for horizontal tab

\b: It is used for blank space

\v: It is used for vertical tab

\a: It is used for a small beep

\r: It is used for carriage return

\': It is used for a single quote

\": It is used for double quotes

Character Literals :
A character literal is expressed as a character or an escape sequence, enclosed in a single quote ('') mark.
It is always a type of char. For example, 'a', '%', '\u000d', etc.

String Literals :
String literal is a sequence of characters that is enclosed between double quotes ("") marks. It may be
alphabet, numbers, special characters, blank space, etc. For example, "Jack", "12345", "\n", etc.

Floating Point Literals :


The vales that contain decimal are floating literals. In Java, float and double primitive types fall into
floating-point literals. Keep in mind while dealing with floating point literal

o Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc. It is a 32-bit
float literal.

o Floating-point literals for double type end with D or d. It is optional to write D or d. For
example, 6d, 8.354D, etc. It is a 64-bit double literal.

o It can also be represented in the form of the exponent.

Floating:

1. float length = 155.4f;


Decimal:

1. double interest = 99658.445;

Decimal in Exponent form:

1. double val= 1.234e2;

Boolean Literals :
Boolean literals are the value that is either true or false. It may also have values 0 and 1. For
example, true, 0, etc.

1. boolean isEven = true;

Null Literals :
Null literal is often used in programs as a marker to indicate that reference type object is unavailable.
The value null may be assigned to any variable, except variables of primitive types.

1. String stuName = null;

2. Student age = null;

Class Literals :
Class literal formed by taking a type name and appending .class extension. For example, [Link].
It refers to the object (of type Class) that represents the type itself.

1. class classType = [Link];

Invalid Literals :
There is some invalid declaration of literals.

1. float g = 6_.674f;

2. float g = 6._674F;

3. long phoneNumber = 99_00_99_00_99_L;

4. int x = 77_;

5. int y = 0_x76;

6. int z = 0X_12;

7. int z = 0X12_;
Restrictions to Use Underscore (_) :
o It can be used at the beginning, at the end, and in-between of a number.

o It can be adjacent to a decimal point in a floating-point literal.

o Also, can be used prior to an F or L suffix.

o In positions where a string of digits is expected.

Why use literals?


To avoid defining the constant somewhere and making up a label for it. Instead, to write the value of a
constant operand as a part of the instruction.

How to use literals?


A literal in Java can be identified with the prefix =, followed by a specific value.

Let's create a Java program and use above discussed literals.

[Link]

1. public class LiteralsExample

2. {

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

4. {

5. int count = 987;

6. float floatVal = 4534.99f;

7. double cost = 19765.567;

8. int hexaVal = 0x7e4;

9. int binary = 0b11010;

10. char alpha = 'p';

11. String str = "Java";

12. boolean boolVal = true;

13. int octalVal = 067;


14. String stuName = null;

15. char ch1 = '\u0021';

16. char ch2 = 1456;

17. [Link](count);

18. [Link](floatVal);

19. [Link](cost);

20. [Link](hexaVal);

21. [Link](binary);

22. [Link](alpha);

23. [Link](str);

24. [Link](boolVal);

25. [Link](octalVal);

26. [Link](stuName);

27. [Link](ch1);

28. [Link]("\t" +"backslash literal");

29. [Link](ch2);

30. }

31. }

Output:

987

4534.99

19765.567

2020

26

p
Java

true

55

null

backslash literal

Java – symbolic constants :


In Java, a symbolic constant is a named constant value defined once and used throughout a program.
Symbolic constants are declared using the final keyword.

 Which indicates that the value cannot be changed once it is initialized.

 The naming convention for symbolic constants is to use all capital letters with underscores
separating words.

Syntax of Symbolic Constants :


final data_type CONSTANT_NAME = value;

 final: The final keyword indicates that the value of the constant cannot be changed once it is
initialized.

 data_type: The data type of the constant such as int, double, boolean, or String.

 CONSTANT_NAME: The name of the constant which should be written in all capital letters with
underscores separating words.

 value: The initial value of the constant must be of the same data type as the constant.

Initializing a symbolic constant:


final double PI = 3.14159;

Example:

 Java Program
// Java Program to print an Array

import [Link].*;

public class Example {

public static final int MAX_SIZE = 10;

public static void main(String[] args)

int[] array = new int[MAX_SIZE];

for (int i = 0; i < MAX_SIZE; i++) {

array[i] = i * 2;

[Link]("Array: ");

for (int i = 0; i < MAX_SIZE; i++) {

[Link](array[i] + " ");

[Link]();

Output

Array: 0 2 4 6 8 10 12 14 16 18
Formatted Output in Java using printf() :
Sometimes in programming, it is essential to print the output in a given specified format. Most users are
familiar with the printf function in C. Let us discuss how we can Formatting Output with printf() in Java
in this article.

Formatting Using Java Printf() :


printf() uses format specifiers for formatting. There are certain data types are mentioned below:

 For Number Formatting

 Formatting Decimal Numbers

 For Boolean Formatting

 For String Formatting

 For Char Formatting

 For Date and Time Formatting

i). For Number Formatting :


The number itself includes Integer, Long, etc. The formatting Specifier used is %d.

Below is the implementation of the above method:

// Java Program to demonstrate

// Use of printf to

// Formatting Integer

import [Link].*;

// Driver Class

class GFG {

// main function

public static void main (String[] args) {

int a=10000;

//[Link]("%,d%n",a);

[Link]("%,d%n",a);
}

Output

10,000

ii). For Decimal Number Formatting :


Decimal Number Formatting can be done using print() and format specifier %f .

Below is the implementation of the above method:

Java

// Java Programs to demonstrate

// Use of Printf() for decimal

// Number Formatting

import [Link].*;

// Driver Class

class GFG {

// main function

public static void main(String[] args)

// declaring double

double a = 3.14159265359;

// Printing Double Value with

// different Formatting

[Link]("%f\n", a);
[Link]("%5.3f\n", a);

[Link]("%5.2f\n", a);

Output

3.141593

3.142

3.14

iii). For Boolean Formatting :


Boolean Formatting can be done using printf and ( ‘%b’ or ‘%B’ ) depending upon the result needed.

Below is the implementation of the above method:

Java

// Java Programs to demonstrate

// Use of Printf() for decimal

// Boolean Formatting

import [Link].*;

// Driver Function

class GFG {

// main function

public static void main(String[] args)

int a = 10;
Boolean b = true, c = false;

Integer d = null;

// Fromatting Done using printf

[Link]("%b\n", a);

[Link]("%B\n", b);

[Link]("%b\n", c);

[Link]("%B\n", d);

Output

true

TRUE

false

FALSE

iv). For Char Formatting :


Char Formatting is easy to understand as it need printf() and Charracter format specifier used are ‘%c’
and ‘%C’.

Below is the implementation of the above method:

Java

// Java Program to Formatt

//

import [Link].*;
// Driver Class

class GFG {

// main function

public static void main(String[] args)

char c = 'g';

// Formatting Done

[Link]("%c\n", c);

// Converting into Uppercase

[Link]("%C\n", c);

Output

v). For String Formatting :


String Formatting requires the knowledge of Strings and format specifier used ‘%s’ and ‘%S’.

Below is the implementation of the above method:

Java

// Java Program to implement


// Printf() for String Formatting

import [Link].*;

// Driver Class

class GFG {

// main function

public static void main(String[] args)

String str = "geeksforgeeks";

// Formatting from lowercase to

// Uppercase

[Link]("%s \n", str);

[Link]("%S \n", str);

str = "GFG";

// Vice-versa not possible

[Link]("%S \n", str);

[Link]("%s \n", str);

Output

geeksforgeeks

GEEKSFORGEEKS

GFG
GFG

vi). For Date and Time Formatting :


Formatting of Date and Time is not as easy as the data-type used above. It uses more than simple format
specifier knowledge can be observed in the example mentioned below.

Below is the implementation of the above method:

Java

// Java Program to demonstrate use of

// printf() for formatting Date-time

import [Link].*;

import [Link].*;

// Driver Class

class GFG {

// main function

public static void main(String[] args)

Date time = new Date();

[Link]("Current Time: %tT\n", time);

// Another Method with all of them Hour

// minutes and seconds seperated

[Link]("Hours: %tH Minutes: %tM Seconds: %tS\n",

time,time, time);
// Another Method to print the time

// Followed by am/pm , time in milliseconds

// nanoseconds and time-zone offset

[Link]("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n",

time);

Output

Current Time: 11:32:36

Hours: 11 Minutes: 32 Seconds: 36

11:32:36 am 198 198000000 +0000

Note: [Link]() is equivalent to printf() and can also be used.

Java String Format Specifiers :


Here, we are providing a table of format specifiers supported by the Java String.

Format Data Type Output


Specifier

%a floating point ( except BigDecima l) Returns Hex output of floating-point number.

%b Any type " true " if non-null, " false " if null

%c Character Unicode character

%d integer ( incl. byte, short, int, long, Decimal Integer


bigint )

%e floating point Decimal number in scientific notation

%f floating point Decimal number

%g floating point Decimal number, possibly in scientific notation


depending on the precision and value.

%h any type Hex String of value from hashCode( ) method.

%n None Platform-specific line separator.

%o integer ( incl. byte, short, int, long, Octal number


bigint )

%s any type String value

%t Date/Time ( incl. long, Calendar, %t is the prefix for Date/Time conversions. More
Date and TemporalAccessor ) formatting flags are needed after this. See Date/Time
conversion below.

%x integer ( incl. byte, short, int, long, bigint ) Hex string.

Static Method in Java With Examples :


The static keyword is used to construct methods that will exist regardless of whether or not any
instances of the class are generated. Any method that uses the static keyword is referred to as a static
method.

Features of static method:


 A static method in Java is a method that is part of a class rather than an instance of that class.

 Every instance of a class has access to the method.


 Static methods have access to class variables (static variables) without using the class’s object
(instance).

 Only static data may be accessed by a static method. It is unable to access data that is not static
(instance variables).

 In both static and non-static methods, static methods can be accessed directly.

Syntax to declare the static method:


Access_modifier static void methodName()
{
// Method body.
}

The name of the class can be used to invoke or access static methods.

Syntax to call a static method:


[Link]();

Example 1: The static method does not have access to the instance variable

The JVM runs the static method first, followed by the creation of class instances. Because no objects are
accessible when the static method is used. A static method does not have access to instance variables.
As a result, a static method can’t access a class’s instance variable.

Java

// Java program to demonstrate that

// The static method does not have

// access to the instance variable

import [Link].*;

public class GFG {

// static variable

static int a = 40;

// instance variable

int b = 50;
void simpleDisplay()

[Link](a);

[Link](b);

// Declaration of a static method.

static void staticDisplay()

[Link](a);

// main method

public static void main(String[] args)

GFG obj = new GFG();

[Link]();

// Calling static method.

staticDisplay();

Output

40

50

40
Example 2: In both static and non-static methods, static methods are directly accessed.

Java

// Java program to demonstrate that

// In both static and non-static methods,

// static methods are directly accessed.

import [Link].*;

public class StaticExample {

static int num = 100;

static String str = "GeeksForGeeks";

// This is Static method

static void display()

[Link]("static number is " + num);

[Link]("static string is " + str);

// non-static method

void nonstatic()

// our static method can accessed

// in non static method

display();

}
// main method

public static void main(String args[])

StaticExample obj = new StaticExample();

// This is object to call non static method

[Link]();

// static method can called

// directly without an object

display();

Output

static number is 100

static string is GeeksForGeeks

static number is 100

static string is GeeksForGeeks

Why use Static Methods?


1. To access and change static variables and other non-object-based static methods.

2. Utility and assist classes frequently employ static methods.

Restrictions in Static Methods:


1. Non-static data members or non-static methods cannot be used by static methods, and static
methods cannot call non-static methods directly.
2. In a static environment, this and super aren’t allowed to be used.

Why is the main method in Java static?


It’s because calling a static method isn’t needed of the object. If it were a non-static method, JVM would
first build an object before calling the main() method, resulting in an extra memory allocation difficulty.

Difference Between the static method and instance method :

Instance Methods Static Methods

It requires an object of the class. It doesn’t require an object of the class.

It can access all attributes of a class. It can access only the static attribute of a class.

The methods can be accessed only using object


The method is only accessed by class name.
reference.

Syntax: [Link]() Syntax: [Link]()

It is an example of pass-by-reference
It’s an example of pass-by-value programming.
programming.

Final Keyword In Java :


The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:

1. variable

2. method

3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank
final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final
variable can be static also which will be initialized in the static block only. We will have detailed learning
of these. Let's first learn the basics of final keyword.

1) Java final variable :


If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be
changed because final variable once assigned a value can never be changed.

1. class Bike9{

2. final int speedlimit=90;//final variable

3. void run(){

4. speedlimit=400;

5. }

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

7. Bike9 obj=new Bike9();

8. [Link]();

9. }

10. }//end of class

Output:Compile Time Error


2) Java final method :
If you make any method as final, you cannot override it.

Example of final method

1. class Bike{

2. final void run(){[Link]("running");}

3. }

4.

5. class Honda extends Bike{

6. void run(){[Link]("running safely with 100kmph");}

7.

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

9. Honda honda= new Honda();

10. [Link]();

11. }

12. }

Output:Compile Time Error

3) Java final class :


If you make any class as final, you cannot extend it.

Example of final class

1. final class Bike{}

2.

3. class Honda1 extends Bike{

4. void run(){[Link]("running safely with 100kmph");}


5.

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

7. Honda1 honda= new Honda1();

8. [Link]();

9. }

10. }

Output:Compile Time Error

Q) Is final method inherited?


Ans) Yes, final method is inherited but you cannot override it. For Example:

1. class Bike{

2. final void run(){[Link]("running...");}

3. }

4. class Honda2 extends Bike{

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

6. new Honda2().run();

7. }

8. }

Output:running...

Q) What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final variable.

If you want to create a variable that is initialized at the time of creating object and once initialized may
not be changed, it is useful. For example PAN CARD number of an employee.

It can be initialized only in constructor.

Example of blank final variable


1. class Student{

2. int id;

3. String name;

4. final String PAN_CARD_NUMBER;

5. ...

6. }

Que) Can we initialize blank final variable?


Yes, but only in constructor. For example:

1. class Bike10{

2. final int speedlimit;//blank final variable

3.

4. Bike10(){

5. speedlimit=70;

6. [Link](speedlimit);

7. }

8.

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

10. new Bike10();

11. }

12. }

Output: 70

static blank final variable :


A static final variable that is not initialized at the time of declaration is known as static blank final
variable. It can be initialized only in static block.

Example of static blank final variable


1. class A{

2. static final int data;//static blank final variable

3. static{ data=50;}

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

5. [Link]([Link]);

6. }

7. }

Q) What is final parameter?


If you declare any parameter as final, you cannot change the value of it.

1. class Bike11{

2. int cube(final int n){

3. n=n+2;//can't be changed as n is final

4. n*n*n;

5. }

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

7. Bike11 b=new Bike11();

8. [Link](5);

9. }

10. }

Output: Compile Time Error

Q) Can we declare a constructor final?


No, because constructor is never inherited.
OPERATORS :
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

9. instance of operator

1. Arithmetic Operators :
They are used to perform simple arithmetic operations on 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

int a = 10;

int b = 3;

[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));

Output

a + b = 13

a-b=7

a * b = 30
a/b=3

a%b=1

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));

[Link]("f ^= 0b1010: " + (f ^= 0b1010));

[Link]("f <<= 2: " + (f <<= 2));

[Link]("f >>= 1: " + (f >>= 1));

[Link]("f >>>= 1: " + (f >>>= 1));

Output

f += 3: 10

f -= 2: 8

f *= 4: 32

f /= 3: 10

f %= 2: 0

f &= 0b1010: 0

f |= 0b1100: 12

f ^= 0b1010: 6

f <<= 2: 24

f >>= 1: 12

f >>>= 1: 6

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

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

9. instanceof operator :
The instance of the operator is used for type checking. It can be used to test if an object is an instance of
a class, a subclass, or an interface. General format-
object instance of class/subclass/interface

Java

// Java program to illustrate

// instance of operator

class operators {

public static void main(String[] args)

Person obj1 = new Person();

Person obj2 = new Boy();

// As obj is of type person, it is not an

// instance of Boy or interface

[Link]("obj1 instanceof Person: "

+ (obj1 instanceof Person));

[Link]("obj1 instanceof Boy: "

+ (obj1 instanceof Boy));

[Link]("obj1 instanceof MyInterface: "

+ (obj1 instanceof MyInterface));

// Since obj2 is of type boy,

// whose parent class is person

// and it implements the interface Myinterface

// it is instance of all of these classes


[Link]("obj2 instanceof Person: "

+ (obj2 instanceof Person));

[Link]("obj2 instanceof Boy: "

+ (obj2 instanceof Boy));

[Link]("obj2 instanceof MyInterface: "

+ (obj2 instanceof MyInterface));

class Person {

class Boy extends Person implements MyInterface {

interface MyInterface {

Output

obj1 instanceof Person: true

obj1 instanceof Boy: false

obj1 instanceof MyInterface: false

obj2 instanceof Person: true

obj2 instanceof Boy: true

obj2 instanceof MyInterface: true

Precedence and Associativity of Java Operators


Precedence and associative rules are used when dealing with hybrid equations involving more than one
type of operator. In such cases, these rules determine which part of the equation to consider first, as
there can be many different valuations for the same equation. The below table depicts the precedence
of operators in decreasing order as magnitude, with the top representing the highest precedence and
the bottom showing the lowest precedence.

Interesting Questions about Java Operators

1. Precedence and Associativity:

There is often confusion when it comes to hybrid equations which are equations having multiple
operators. The problem is which part to solve first. There is a golden rule to follow in these situations. If
the operators have different precedence, solve the higher precedence first. If they have the same
precedence, solve according to associativity, that is, either from right to left or from left to right. The
explanation of the below program is well written in comments within the program itself.

Java

public class operators {


public static void main(String[] args)

int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;

// precedence rules for arithmetic operators.

// (* = / = %) > (+ = -)

// prints a+(b/d)

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

// if same precedence then associative

// rules are followed.

// e/f -> b*d -> a+(b*d) -> a+(b*d)-(e/f)

[Link]("a+b*d-e/f = "

+ (a + b * d - e / f));

Output

a+b/d = 20

a+b*d-e/f = 219

2. Be a Compiler:

The compiler in our systems uses a lex tool to match the greatest match when generating tokens. This
creates a bit of a problem if overlooked. For example, consider the statement a=b+++c; too many of the
readers might seem to create a compiler error. But this statement is absolutely correct as the token
created by lex is a, =, b, ++, +, c. Therefore, this statement has a similar effect of first assigning b+c to a
and then incrementing b. Similarly, a=b+++++c; would generate an error as the tokens generated are a, =,
b, ++, ++, +, c. which is actually an error as there is no operand after the second unary operand.

Java
public class operators {

public static void main(String[] args)

int a = 20, b = 10, c = 0;

// a=b+++c is compiled as

// b++ +c

// a=b+c then b=b+1

a = b++ + c;

[Link]("Value of a(b+c), "

+ " b(b+1), c = " + a + ", " + b

+ ", " + c);

// a=b+++++c is compiled as

// b++ ++ +c

// which gives error.

// a=b+++++c;

// [Link](b+++++c);

Output

Value of a(b+c), b(b+1), c = 10, 11, 0

3. Using + over ():

When using the + operator inside [Link]() make sure to do addition using parenthesis. If we
write something before doing addition, then string addition takes place, that is, associativity of addition
is left to right, and hence integers are added to a string first producing a string, and string objects
concatenate when using +. Therefore it can create unwanted results.

Java

public class operators {

public static void main(String[] args)

int x = 5, y = 8;

// concatenates x and y as

// first x is added to "concatenation (x+y) = "

// producing "concatenation (x+y) = 5"

// and then 8 is further concatenated.

[Link]("Concatenation (x+y)= " + x + y);

// addition of x and y

[Link]("Addition (x+y) = " + (x + y));

Output

Concatenation (x+y)= 58

Addition (x+y) = 13

Advantages of Operators in Java

The advantages of using operators in Java are mentioned below:

1. Expressiveness: Operators in Java provide a concise and readable way to perform complex
calculations and logical operations.
2. Time-Saving: Operators in Java save time by reducing the amount of code required to perform
certain tasks.

3. Improved Performance: Using operators can improve performance because they are often
implemented at the hardware level, making them faster than equivalent Java code.

Disadvantages of Operators in Java

The disadvantages of Operators in Java are mentioned below:

1. Operator Precedence: Operators in Java have a defined precedence, which can lead to
unexpected results if not used properly.

2. Type Coercion: Java performs implicit type conversions when using operators, which can lead to
unexpected results or errors if not used properly.

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++

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

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

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:

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:

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:

3
5

[Link]’s WORD

Common questions

Powered by AI

When choosing between primitive and reference data types in Java, several factors should be considered. Primitive data types are simpler and more efficient for basic operations; they store actual values and offer fast processing. Examples include int, char, and double, each having their specific size and range . Reference data types, on the other hand, include objects, arrays, and strings. They store references to the actual data rather than the data itself, providing more functionality and flexibility at the cost of more overhead and potential complexity in memory management. Reference types can store null values, which can indicate uninitialized or non-existent objects, and are handled differently regarding memory allocation and garbage collection . Additionally, operations on reference data types can introduce issues like null pointer exceptions, which necessitate careful handling .

In Java, float and double are both floating-point data types, but they differ in precision and usage. The float is a single-precision 32-bit IEEE 754 floating-point and is often used when the need is to save memory in large arrays of floating-point numbers. Conversely, double is a double-precision 64-bit IEEE 754 floating-point, providing more precision and typically used as the default choice for decimal values due to its capacity for handling larger numbers and higher precision calculations . Double uses more memory compared to float (8 bytes for double vs. 4 bytes for float), and float literals must be explicitly defined with an 'F' or 'f' suffix, unlike doubles where the 'D' or 'd' suffix is optional .

Java provides three primary loop constructs: for, while, and do-while, each serving different use cases. The 'for' loop is beneficial when the number of iterations is known upfront, such as iterating over arrays or collections with a fixed size . The 'while' loop is suitable for scenarios where the number of iterations is determined by a condition that is not initially based on a countable sequence, an example being reading inputs until a user decides to stop . The 'do-while' loop guarantees that the loop body is executed at least once before checking the condition, making it ideal when the body of the loop must execute before the condition is evaluated, such as in menu-driven programs where options must be shown at least once to the user .

Java's class literals differ from object instances in that class literals are references to the object that represents the class type itself, rather than an instance of the class. A class literal is formed by appending .class to a type name, such as Scanner.class, and it refers to an object of type Class representing the type metadata . On the contrary, an object instance is an actual creation of the class in memory, with its own set of properties and methods allocated typically during runtime and manipulated through references . Class literals are typically used in situations involving reflection or when examining class metadata, while object instances are used to perform application logic and actions. Thus, class literals encapsulate design-type information, whereas object instances encapsulate functionality and data operations specific to an individual object .

In Java, underscores can be used in numeric literals to enhance readability by segregating larger numbers into groups, like commas in written numbers. However, their use comes with restrictions: underscores cannot be placed at the beginning or the end of a number, directly adjacent to a decimal point, or immediately before an 'F' or 'L' suffix in floating-point literals or long literals, respectively. Moreover, underscores cannot be directly after a 0x or 0X in hexadecimal numbers or 0b or 0B in binary literals . These restrictions help maintain clear separation of numeric digit groups without interfering with the semantic interpretation of the literals .

The Long datatype is preferable over the Integer datatype in Java when a larger range of integral values is needed. Specifically, the Long datatype provides a 64-bit signed integer range, allowing it to accommodate much larger numbers than the 32-bit Integer datatype. Furthermore, in Java SE 8 and later, the Long datatype can also represent unsigned 64-bit values, expanding its maximum value to 2^64-1, thus accommodating even larger numbers .

Symbolic constants in Java, declared using the final keyword, provide several benefits, including readability, maintainability, and preventing accidental data modification. By defining constants once and using them throughout a program, code becomes easier to read and manage, reducing the risk of errors when values that appear multiple times need to be changed . However, potential pitfalls include the initial learning curve for newcomers to understand when and how to use them properly and the requirement to follow naming conventions (all upper-case with underscores) to avoid confusion. Additionally, while symbolic constants enhance security by preventing value changes, they also reduce flexibility if the constants need to be altered across different executions of the program .

It is advised to avoid using float and double for high-precision calculations because both types are subject to rounding errors due to their binary floating-point nature, particularly when handling large numbers or requiring high accuracy. These data types are designed to balance memory usage and precision, often allowing approximation errors that can accumulate in significant computations. For precise numeric operations, such as those required in financial calculations, the BigDecimal class is recommended over float or double to ensure accuracy by avoiding these inherent rounding issues .

A Java developer might choose a do-while loop when it is necessary to execute the loop body at least once, regardless of the condition, because do-while loops check the condition after the execution of the loop body. This guarantees that the loop body is executed first and the condition is validated afterwards, making it ideal for situations like user-interactive menus where the options should be displayed to the user at least once before any conditional verification occurs . In scenarios where the loop must run before any validations can logically be performed, using do-while constructs provides an effective solution .

Literals in Java are constants that represent fixed values directly in the code, such as numeric values, characters, or strings. They simplify coding by embedding these constant values directly within the program, alleviating the need to define them separately as variables or constants elsewhere. Java supports various types of literals, including integer literals (e.g., 123, 0x4A), floating-point literals (e.g., 3.14f, 1.0e2), char literals (e.g., 'A', '\u0041'), string literals (e.g., "Hello"), Boolean literals (true, false), and null literals. Floating-point literals for float data types must end with an 'F' or 'f', while double can optionally end with 'D' or 'd'. Literals can be identified by their direct fixed representation in code, expressed through Java's syntax without the need for computation .

You might also like