Introduction to Java Programming Basics
Introduction to Java Programming Basics
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.
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
• 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.
• Multi-line Comment: It starts with a /* and ends with */. We write between these two symbols.
multiline comment*/
• Documentation Comment: It starts with the delimiter (/**) and ends with */.
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 [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 all the class of the [Link] package
• INTERFACE SECTION :
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
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.
{
String sname; //variable
int id;
double percentage;
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:
{ //statements
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.
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
[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.
• The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start
with digits but may contain digits.
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.
• 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.
• 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.
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.
• 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:
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.
• if Statement
• if-else statement
• if-else-if statement
• switch statement
• for Loop
• while Loop
• do-while Loop
• for-each Loop
• return
• continue
• break
Example of Statement :
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.
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.
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 :
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.
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
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:
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.
[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
Example
Type Description Default Size Literals Range of values
twos-
complement 0 8 bits (none) -128 to 127
byte integer
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
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:
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;
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;
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;
Syntax:
int intVar;
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.
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.
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;
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.
The char data type is a single 16-bit Unicode character with the size of 2 bytes (16 bits).
Syntax:
char charVar;
Example:
Java
// Class
class GFG {
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);
Output
char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532
long: 12121
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
Example:
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.
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.
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.
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.
Java Variables :
Variables are containers for storing data values.
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
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;
Syntax:
larger_data_type variable_name = smaller_data_type_variable;
Java program :
import [Link].*;
class GFG {
int i = 10;
long l = i;
double d = i;
}
}
Output
Integer: 10
Long: 10
Double: 10.0
Syntax:
smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;
Example:
Java
import [Link].*;
class GFG {
double i = 100.245;
short j = (short)i;
int k = (int)i;
Output
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
import [Link].*;
class Animal {
class GFG {
{ // Upcasting
[Link]();
// [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
import [Link].*;
class Animal {
class GFG {
{
Animal animal = new Cat();
[Link]();
// Explicit downcasting
[Link]();
Output
Access specified of member variables doesn’t affect scope of them within a class.
Default Yes No No
Private No No No
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.
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.
o Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0. For
example, 045, 026,
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.
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:
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.
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.
Floating:
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.
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.
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.
Invalid Literals :
There is some invalid declaration of literals.
1. float g = 6_.674f;
2. float g = 6._674F;
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.
[Link]
2. {
4. {
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);
29. [Link](ch2);
30. }
31. }
Output:
987
4534.99
19765.567
2020
26
p
Java
true
55
null
backslash literal
The naming convention for symbolic constants is to use all capital letters with underscores
separating words.
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.
Example:
Java Program
// Java Program to print an Array
import [Link].*;
array[i] = i * 2;
[Link]("Array: ");
[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.
// Use of printf to
// Formatting Integer
import [Link].*;
// Driver Class
class GFG {
// main function
int a=10000;
//[Link]("%,d%n",a);
[Link]("%,d%n",a);
}
Output
10,000
Java
// Number Formatting
import [Link].*;
// Driver Class
class GFG {
// main function
// declaring double
double a = 3.14159265359;
// different Formatting
[Link]("%f\n", a);
[Link]("%5.3f\n", a);
[Link]("%5.2f\n", a);
Output
3.141593
3.142
3.14
Java
// Boolean Formatting
import [Link].*;
// Driver Function
class GFG {
// main function
int a = 10;
Boolean b = true, c = false;
Integer d = null;
[Link]("%b\n", a);
[Link]("%B\n", b);
[Link]("%b\n", c);
[Link]("%B\n", d);
Output
true
TRUE
false
FALSE
Java
//
import [Link].*;
// Driver Class
class GFG {
// main function
char c = 'g';
// Formatting Done
[Link]("%c\n", c);
[Link]("%C\n", c);
Output
Java
import [Link].*;
// Driver Class
class GFG {
// main function
// Uppercase
str = "GFG";
Output
geeksforgeeks
GEEKSFORGEEKS
GFG
GFG
Java
import [Link].*;
import [Link].*;
// Driver Class
class GFG {
// main function
time,time, time);
// Another Method to print the time
time);
Output
%b Any type " true " if non-null, " false " if null
%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.
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.
The name of the class can be used to invoke or access static methods.
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
import [Link].*;
// static variable
// instance variable
int b = 50;
void simpleDisplay()
[Link](a);
[Link](b);
[Link](a);
// main method
[Link]();
staticDisplay();
Output
40
50
40
Example 2: In both static and non-static methods, static methods are directly accessed.
Java
import [Link].*;
// non-static method
void nonstatic()
display();
}
// main method
[Link]();
display();
Output
It can access all attributes of a class. It can access only the static attribute of a class.
It is an example of pass-by-reference
It’s an example of pass-by-value programming.
programming.
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.
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{
3. void run(){
4. speedlimit=400;
5. }
8. [Link]();
9. }
1. class Bike{
3. }
4.
7.
10. [Link]();
11. }
12. }
2.
8. [Link]();
9. }
10. }
1. class Bike{
3. }
6. new Honda2().run();
7. }
8. }
Output:running...
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.
2. int id;
3. String name;
5. ...
6. }
1. class Bike10{
3.
4. Bike10(){
5. speedlimit=70;
6. [Link](speedlimit);
7. }
8.
11. }
12. }
Output: 70
3. static{ data=50;}
5. [Link]([Link]);
6. }
7. }
1. class Bike11{
4. n*n*n;
5. }
8. [Link](5);
9. }
10. }
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
// Arithmetic operators
int a = 10;
int b = 3;
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 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.
– – : 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.
Example:
Java
// Unary Operators
import [Link].*;
// Driver Class
class GFG {
// main function
public static void main(String[] args)
// Interger declared
int a = 10;
int b = 10;
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.
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
// Assignment Operators
import [Link].*;
// Driver Class
class GFG {
// Main Function
// Assignment operators
int f = 7;
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,
==, 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
// Relational Operators
import [Link].*;
// Driver Class
class GFG {
// main function
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
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
&&, Logical AND: returns true when both conditions are true.
Example:
Java
// Logical operators
import [Link].*;
// Driver Class
class GFG {
// Main Function
// Logical operators
boolean x = true;
boolean y = false;
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 above statement means that if the condition evaluates to true, then execute the statements after
the ‘?’ else execute the statements after the ‘:’.
Example:
Java
// ternary operator.
// numbers
result
+ result);
}
Output
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 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
// bitwise operators
import [Link].*;
// Driver class
class GFG {
// main function
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
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-
<<, 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
// shift operators
import [Link].*;
// Driver Class
class GFG {
// main function
int a = 10;
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
// instance of operator
class operators {
class Person {
interface MyInterface {
Output
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
// (* = / = %) > (+ = -)
// prints a+(b/d)
[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 {
// a=b+++c is compiled as
// b++ +c
a = b++ + c;
// a=b+++++c is compiled as
// b++ ++ +c
// a=b+++++c;
// [Link](b+++++c);
Output
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
int x = 5, y = 8;
// concatenates x and y as
// addition of x and y
Output
Concatenation (x+y)= 58
Addition (x+y) = 13
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.
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.
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
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.
1. if(condition) {
3. }
Consider the following example in which we have used the if statement in the java code.
[Link]
[Link]
3. int x = 10;
4. int y = 12;
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) {
3. }
4. else{
6. }
[Link]
3. int x = 10;
4. int y = 12;
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.
1. if(condition 1) {
3. }
4. else if(condition 2) {
6. }
7. else {
9. }
[Link]
5. [Link]("city is meerut");
7. [Link]("city is noida");
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.
1. if(condition 1) {
3. if(condition 2) {
5. }
6. else{
8. }
9. }
[Link]
4.
5. if([Link]("India")) {
6. if([Link]("Meerut")) {
8. }else if([Link]("Noida")) {
10. }else {
11. [Link]([Link](",")[0]);
12. }
13. }else {
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.
o The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
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.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
13. }
Consider the following example to understand the flow of the switch statement.
[Link]
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
2. //block of statements
3. }
Consider the following example to understand the proper functioning of the for loop in java.
[Link]
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
9. }
10. }
Output:
2. //statements
3. }
Consider the following example to understand the functioning of the for-each loop in Java.
[Link]
6. for(String name:names) {
7. [Link](name);
8. }
9. }
10. }
Output:
Java
C++
Python
JavaScript
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.
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
4. int i = 0;
6. while(i<=10) {
7. [Link](i);
8. i = i + 2;
9. }
10. }
11. }
Output:
10
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]
4. int i = 0;
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.
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
[Link]
2.
6. [Link](i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }
Output:
[Link]
2.
5. a:
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:
Consider the following example to understand the functioning of the continue statement in Java.
2.
3. public static void main(String[] args) {
5.
7.
9.
10. if(j == 4) {
11. continue;
12. }
13. [Link](j);
14. }
15. }
16. }
17.
18. }
Output:
3
5
[Link]’s WORD
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 .