What is Java ?
Java is a popular high-level,object-oriented programming language that was
originally developed by Sun Microsystems and released in 1995.
Currently, Java is owned by Oracle, and more than 3 billion devices run
Java.
Java runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX.
Today Java is being used to develop numerous types of software
applications, including desktop apps, mobile apps, web apps, games, and
much more.
Java is a general-purpose programming language intended to let
programmers Write Once, Run Anywhere (WORA). This means that
compiled Java code can run on all platforms that support Java without the
need to recompile.
The Genesis of Java / History of Java
Java is a programming language introduced by the Sun Microsystems in
June 1995. Java derives its syntax from C and the object oriented features
are influenced by C++. The original name of this platform independent
programming language was called Oak.
James Gosling, a member of the Green Project Team is one of the inventors
of this programming language. The other members of this team are Bill Joy,
Frank Yellin, Patrick Naughton, Richard Chris Wrath, Mike Sheridan.
Java was originally designed to develop software for consumer electronic
devices. It was not intended to be an Internet programming language. With
the advent of World Wide Web (WWW) that demanded software that was
portable across all the platforms. Java was then adapted as Internet
Programming language.
Byte Code
Byte Code can be defined as an intermediate code generated by the
compiler after the compilation of source code(JAVA Program). This
intermediate code makes Java a platform-independent language.
How is Byte Code is generated?
Compiler converts the source code or the Java program into the Byte Code(or
machine code), and secondly, the Interpreter executes the byte code on the
system. The Interpreter can also be called JVM(Java Virtual Machine).
JVM
JVM stands for Java Virtual Machine. JVM is an interpreter for bytecode.
JVM is an abstract computing machine, or virtual machine. It is a platform-
independent execution environment that converts Java byte codes into
machine language and executes it (i.e) JVM control execution of every Java
program. It enables features such as automated exception handling,
Garbage-collected heap.
JDK(Java Development kit)
Java Development Kit (JDK) is a cross-platform software development kit
that provides tools and libraries needed to build Java-based applications
and applets.
It works together with the JVM (Java Virtual Machine) and JRE (Java
Runtime Environment) as part of the core Java setup.
If we only want to run Java programs, installing JRE is enough.
But if we want to develop Java applications, we need the JDK, which
includes the JRE and additional development tools.
JDK = JRE + Development Tools
JDK contains:
Java Runtime Environment (JRE),
An interpreter/loader (Java),
A compiler (javac),
An archiver (jar) and many more.
Source & JAR files in Java
Java source files
A Java source code file is one that ends [Link] (or, less
commonly,.JAV), that is saved in the Java programming language.
Written in the human-readable form with .java extension.
Contain the actual source code written by developers.
Must be compiled by the javac compiler into .class files before the Java
Virtual Machine (JVM) can run them.
JAR files in Java
A JAR file (Java archive) is a package file format typically used to aggregate many
Java class files and associated metadata and resources (text, images, etc.) into
one file to distribute application software or libraries on the Java platform.
In simple words, a JAR file is a file that contains a compressed version of .class
files, audio files, image files, or directories
Compiling and running java programs
Compiling the Java Program
Once the Java program is written, it needs to be compiled. Compilation is the
process of converting the human-readable Java code into bytecode, which can
be understood by the Java Virtual Machine (JVM).
Command to compile:
javac [Link]
Here:
javac invokes the Java compiler.
[Link] is the file to compile.
Running the Java Program
After successful compilation, you can run the program using the Java
interpreter.
Command to run:
java classname
here the term java invokes java’s interpreter i.e. JVM
Features of Java
1. Simple:
I. It is free from pointer due to this execution time of application is improve.
II. It have rich set of APIs (application programming interface).
III. It have Garbage Collector which is always used to collect un-referenced
(unused) memory locations for improving performance of a Java program.
IV. It contains user friendly syntax for developing any applications.
2. Object Oriented: Java supports OOP features and everything is an Object in
Java. The object model in Java is simple and easy to extend.
3. Robust: Java is robust or strong programming language because of its capability
to handle run-time errors, automatic garbage collection, lack of pointer concept,
exception handling. These entire things make Java is a robust Language.
4. Multi Threading: Java was designed to meet the real-world requirement of
creating interactive, networked programs. To accomplish this, Java supports
multithreaded programming, which allows you to write programs that do many
things simultaneously. The Java run-time system comes with an elegant yet
sophisticated solution for multiprocess synchronization that enables you to
construct smoothly running interactive systems.
5. Architecture-Neutral: Architecture represents processor. A language or
technology is said to be architectural neutral which can run on any processors in
the real world without considering type of architecture and vendor (provider).
6. Interpreted: Java programs are compiled to generate the byte code. This byte
code can be downloaded and interpreted by the interpreter in JVM. If we
consider any other language, only an interpreter or a compile executes the
programs. But in Java, we use both interpreter and compiler for the execution.
7. Dynamic: Java support dynamic memory allocation. Due to this memory
wastage is reduced. The process of allocating the memory space to the program
at a run-time is known as dynamic memory allocation, To allocate memory space
dynamically we use an operator called 'new'. 'new' operator is known as dynamic
memory allocation operator.
8 Secure: It is more secured language compare to other languages; In this,
program is covered into byte code after compilation which is not readable by
human and also Java does not support global variable concept.
9. platform-independent - Java is platform-independent because the code
written in Java can run on any operating system (Windows, macOS, Linux, etc.)
without requiring any changes.
10. Portable: If any language supports platform independent and architectural
neutral features, then that language is portable
Data types in java
Data types in Java define the kind of data a variable can hold and the memory
required to store it. They are broadly divided into two categories:
Primitive Data Types: Store simple values directly in memory.
Non-Primitive (Reference) Data Types: Store memory references to objects.
Primitive Data Types
Primitive types are the fundamental data types that store single values. Java
defines eight primitive data types, summarized below
:
1. boolean Data Type
Represents one of two logical values: true or false. Commonly used for
conditional checks.
Syntax:
Boolean Var;
2. byte Data Type
An 8-bit signed integer used to save memory in large numeric arrays.
Syntax:
Byte Var;
3. short Data Type
A 16-bit signed integer often used when memory is limited and values are
moderate in size.
Syntax:
Short Var;
4. int Data Type
A 32-bit signed integer commonly used for whole numbers.
Syntax:
Int Var;
5. long Data Type
A 64-bit signed integer used when int is not sufficient for large values.
Syntax:
long Var;
6. float Data Type
A 32-bit single-precision floating-point type used for fractional values.
Syntax:
float Var;
7. double Data Type
A 64-bit double-precision floating-point type and the default for decimal
numbers.
Syntax:
double Var;
8. char Data Type
A 16-bit Unicode character used to store single symbols or letters.
Syntax:
Char Var;
Non-Primitive (Reference) Data Types
Non-primitive data types store references (memory addresses) rather than actual
values. They are created by users and include types like String, Class, Object,
Interface, and Array.
1. String
String represents a sequence of characters enclosed in double quotes. Unlike
C/C++, Java strings are objects and are immutable.
Syntax:
String str = "Hello";
2. Class
A class is a user-defined blueprint that defines variables and methods. It
represents a type of object and forms the foundation of Object-Oriented
Programming.
3. Object
An object is an instance of a class representing real-world entities. It has state
(data), behavior (methods), and identity (unique reference).
4. Interface
An interface defines a contract of abstract methods that implementing classes
must define. It provides a way to achieve abstraction and multiple inheritance in
Java.
5. Array
An array stores multiple elements of the same type in a single structure. Java
arrays are objects, dynamically allocated, and indexed from 0.
Literals , Variables & Constants In Java
Literals: In programming, we can use some fixed values/constants in our code.
These fixed values are called Literals. These values are not variables or
expressions but are constants that retain their fixed value throughout the
program.
Types of Literals
In Java, some common types of literals are:
Integers (int) - Integers are whole numbers that do not contain any
decimal points. They can be positive or negative numbers such as 5, -11, 0,
or 12. In Java, the term 'int' refers to this type of integer literal.
int x = 101;
Floating-point numbers (double) - Floating-point numbers are numbers
that contain decimal points. They can also be positive or negative, and they
include values such as 2.5, 6.76, 0.0, or -9.45. In Java, the term 'double' is
used to refer to this type of literal.
double a = 101.12
Char literals - Character literals are used to represent single characters,
letters, or symbols in the program. They are often used when dealing with
individual characters rather than strings of characters. In Java, the keyword
'char' is used to refer to this type of literal.
char ch = 'a';
String (text): A string is a sequence of characters that is enclosed within
double quotation marks. Strings are used to represent text and can include
any combination of letters, numbers, symbols, and spaces. "Hello" and
"Learnyard Java Course" are both examples of String literals in Java.
String s = "Hello";
Boolean literal: A boolean literal can be either true or false, indicating
whether a condition is satisfied or not. These literals are essential for
controlling the flow of the program and making logical decisions based on
specific conditions.
boolean b = true;
Variables
In Java, variables are containers used to store data in memory. Variables define
how data is stored, accessed, and manipulated.
The syntax to create a variable in Java is -
type variableName;
Here, type is one of Java's data types,and variableName is the name of the
variable.
Example
string bookName;
Here,
"bookName" is the name of the variable.
"string" type tells what type of data a variable can hold; in this case, it’s
going to be text
Once variable creation is done, we can assign a value to it. Here’s how we
do it
bookName = "People"
Constants:
Constants are variables whose values, once assigned, cannot be changed during
the program's execution. They are declared using the final keyword.
declaration.
final dataType CONSTANT_NAME = value;
final int marks = 100 ;
constants are used to represent fixed values that should not be modified,
improving code readability, maintainability, and preventing accidental changes.
ARRAYS
In Java, an array is an important linear data structure that allows us to store
multiple values of the same type.
Java arrays can hold both primitive types (like int, char, boolean, etc.) and
objects (like String, Integer, etc.)
Contiguous Memory Allocation : the elements of arrayare stored in
contiguous locations.
Zero-based Indexing: The first element of the array is at index 0.
Fixed Length: After creating an array, its size is fixed; we can not change it.
The general form of array declaration is
// Method 1
type array_name[] ;
[Link] arr[];
// Method 2:
type[]array_name;
[Link][] arr;
initializing array
type[] array_name={values};
Eg. int[] arr = {40, 55, 63, 17, 22};
public class demo {
public static void main(String[] args)
int[] arr = {40, 55, 63, 17, 22}; // initializing array
int n = [Link];// Getting the length of the array
for (int i = 0; i< n; i++)// traversing array [Link](arr[i] + " ");
Output:
40 55 63 17 22
Types of Array in Java
There are two types of arrays:
Single Dimensional Array
Multidimensional Array
Single Dimensional Array
Contains only one level or dimension. It's like a simple list having a
sequence of elements where you can store and retrieve elements using
their position (index) in the row.
Syntax
int[] numbers = new int[]{15, 20, 7, 10, 9, 19, 45};
Multidimensional Array
Contains multiple levels or dimensions. In such cases, data is stored in a
row and column-based
based index known as matrix form
to declare & instantiate a multidimensional aarray, we can use the following
syntax:
dataType[][] arrayName = new dataType[rows][columns];
For instance:
int[][] arr = new int[3][3]; // Creates a 3x3 integer array
Let’s Consider multidimensional array, this time with three dimensions.
dimensions
Consider the following
owing declaration:
int[][][] data = new int[3][4][2];
In this example, data is a three-dimensional
dimensional array capable of holding a
maximum of 24 elements (calculated as 3 * 4 * 2), and each element is of
type int
Operators
operators are special symbols that per
perform
form operations on variables or
values.
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations
on primitive and non-primitive data types.
// Addition +
int sum = a + b;
// Subtraction : -
int diff = a - b;
// Multiplication : *
int ml = a * b;
// Division : /
int div = a / b;
// Modulus : %
int mod = a % b;
2. Unary Operators: Unary Operators need only one operand. They are
used to increment, decrement, or negate a value.
Postincrement : a++
Preincrement : ++a
Both increment a by 1 i.e. a=a+1
Postdecrement : b--
Predecrement : --b;
Both decrement a by 1 i.e. a=a-1
3. Assignment Operator
The assignment operator assigns a value from the right-hand side to a
variable on the left. Since it has right-to-left associativity, the right-hand
value must be declared or constant.
int n = 10;
n += 5 will do n=n+5
4. Relational Operators
Relational 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.
a > b (greater than)
a < b (less than)
a >= b (greater than or equal to)
a <= b (less than or equal to)
a == c ( used for comparasion for equality)
a != c: " + (not equal to)
5. Logical Operators
Logical Operators are used to perform "logical AND" and "logical OR"
operations, similar to AND gate and OR gate in digital electronics. They
have a short-circuiting effect, meaning the second condition is not
evaluated if the first is false.
&& : AND OPERATOR
|| : OR OPERATOR
! : NOT OPERATOR
6. Ternary operator (Or Conditional 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? value if true : value if false ;
int a = 20, b = 10, result;
// result holds max of two numbers
result = a > b ? a : c;
7. Bitwise Operators These operators perform operations at the bit level.
Bitwise Operators manipulate individual bits using AND, OR, XOR, and
NOT.
Operator Description
& Bitwise AND
| Bitwise OR
Operator Description
^ Bitwise XOR
~ Bitwise Complement (NOT
<< Left Shift
>> Signed Right Shift
>>> Unsigned Right Shift
Bitwise AND (&)
This operator is a binary operator, denoted by '&.' It returns bit by bit AND
of input values, i.e., if both bits are 1, it gives 1, else it shows 0.
0101
&0111
________
0101
Bitwise OR (|)
This operator is a binary operator, denoted by '|'. It returns bit by bit OR of
input values, i.e., if either of the bits is 1, it gives 1, else it shows 0.
0101
|0111
________
0111
Bitwise XOR (^)
This operator is a binary operator, denoted by '^.' It returns bit by bit XOR
of input values, i.e., if corresponding bits are different, it gives 1, else it
shows 0.
0101
^0111
________
0010
Bitwise Complement (~)
This operator is a unary operator, denoted by '~.' It returns the one's
complement representation of the input value, i.e., with all bits inverted,
which means it makes every 0 to 1, and every 1 to 0.
~00000101
________
11111010
Bit-Shift Operators (Shift Operators)
Shift 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.
<< The left shift operator moves all bits by a given number of bits to the left.
The right shift operator moves all bits by a given number of bits to the
>>
right.
Conditional statements and Loops in Java
Conditional statements and loops are essential programming constructs used in
almost every programming language.
Conditional Statements
Conditional statements in Java allow a program to make decisions based on
certain conditions. Java has two main types of conditional statements:
if statements and switch statements
If Statements
If statements are the most basic form of conditional statements in Java. They
consist of a boolean expression followed by one or more statements. The
statement(s) inside the if block are executed only if the boolean expression
evaluates to true. If the expression is false, the program skips the if block and
continues with the next statement after it.
if (boolean_expression) {
// code to be executed if the boolean_expression is true
}
If-Else Statement
Java also provides an if-else statement, which allows you to execute a block of
code if the boolean expression is false. Here's the syntax:
if (boolean_expression) {
// code to be executed if the boolean_expression is true
} else {
// code to be executed if the boolean_expression is false
}
If-Else-If Ladder
An if-else-if ladder allows you to test multiple conditions sequentially. The syntax
is as follows:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
}
...
else {
// code to be executed if none of the above conditions is true
}
int age = 65;
if (age < 18) {
[Link]("You are a minor.");
} else if (age >= 18 && age < 60) {
[Link]("You are an adult.");
} else {
[Link]("You are a senior citizen.");
}
Switch Statement
A switch statement is an alternative to the if-else-if ladder. It is used to select one
of several blocks of code to be executed based on the value of a variable or
expression. The syntax is as follows:
switch (expression) {
case value1:
// code to be executed if the expression equals value1
break;
case value2:
// code to be executed if the expression equals value2
break;
...
default:
// code to be executed if the expression does not match any case
}
char grade = 'B';
switch (grade) {
case 'A':
[Link]("Excellent");
break;
case 'B':
[Link]("Good");
break;
case 'C':
[Link]("Average");
break;
case 'D':
[Link]("Poor");
break;
default:
[Link]("Invalid grade");
}
Loops
Loops are used to execute a block of code repeatedly until a specified condition is
met. Java provides four types of loops: while loop, do-while loop, for loop, and
for-each loop.
While Loop
A while loop executes a block of code as long as the specified condition is true.
The syntax is as follows:
while (condition) {
// code to be executed
}
Here's an example:
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
Do-While Loop
A do-while loop is similar to a while loop, but it ensures that the block of code is
executed at least once, even if the condition is false. The syntax is as follows:
do {
// code to be executed
} while (condition);
Here's an example:
int i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
For Loop
A for loop is used to execute a block of code a specific number of times. The
syntax is as follows:
for (initialization; condition; increment/decrement) {
// code to be executed
}
Here's an example:
for (int i = 1; i <= 5; i++) {
[Link](i);
}
For-Each Loop
The for-each loop, also known as the enhanced for loop, is used to iterate over
arrays or collections. The syntax is as follows:
for (data_type variable_name : array/collection) {
// code to be executed
}
Here's an example:
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
[Link](number);
}
Classes, objects & methods in java
Java Class
A class is a blueprint that defines data and behavior for objects. It groups related
fields and methods in a single unit. Memory for its members is allocated only
when an object is created.
Acts as a template to create objects with shared structure.
Does not occupy memory for fields until instantiation.
Can contain fields, methods, constructors, nested classes and interfaces.
Java Objects
An object is an instance of a class created to access its data and operations. Each
object holds its own state.
State: Values stored in fields.
Declaration:
Class object name;
This only declares a reference. The object is not created and the reference
holds null.
Initialization:
object name =new class name();
class Student {
int id;
String n;
Student(int id, String n) //defining constructor of class
[Link] = id;
this.n = n;
void show() //defining method for class
{
[Link](“student’s id= “+”name =”+n);
public static void main(String[] args)
Student s1 = new Student(10, "Alice"); //object s1 created for the class
[Link](); //calling show method using object of class
Java Methods
Java Methods are blocks of code that perform a specific task. A method
allows us to reuse code, improving both efficiency and organization. All
methods in Java must belong to a class. Java program to demonstrate how
to create and use a method.
Syntax of a Method
public class demo
public void print_message() { // An example method
[Link]("Hello, there!");
public static void main(String[] args) {
Geeks obj = new Geeks(); // Create an instance of the class
obj.print_message(); // Calling the method