COS205 Java Basics
COS205 Java Basics
Introduction to Java
Java is a high-level, object-oriented programming language
developed by Sun Microsystems in 1995. It is mostly used for
building desktop applications, web applications, Android apps and
enterprise systems.
Features of Java
Object-Oriented Programming (OOP): Java supports
OOP concepts to create modular and reusable code.
Platform Independence: Java programs can run on any
operating system with a JVM.
Robust and Secure: Java ensures reliability and security
through strong memory management and exception
handling.
Multithreading and Concurrency: Java allows
concurrent execution of multiple tasks for efficiency.
Rich API and Standard Libraries: Java provides
extensive built-in libraries for various programming needs.
Frameworks for Enterprise and Web
Development: Java supports frameworks that simplify
enterprise and web application development.
Open-Source Libraries: Java has a wide range of libraries
to extend functionality and speed up development.
Maintainability and Scalability: Java’s structured design
allows easy maintenance and growth of applications.
Understanding the Hello World Program in
Java
When we learn any programming language, the first step is writing
a simple program to display "Hello World". So, here is a simple Java
program that displays "Hello World" on the screen.
// A Java program to print Hello World!
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello World!");
}
}
Output
Hello World!
Explanation:
Comments in Java
Comments are the notes written inside the code to explain what we
are doing. The comment lines are not executed while we run the
program.
Single-line comment
// This is a comment
Multi-line comment
/*
This is a multi-line comment.
This is useful for explaining larger sections of code.
*/
Curly Braces and Indentation in Java
In Java, curly braces {} are used to define blocks of code. For
example, the body of a class or method is enclosed within curly
braces.
Example:
public class Geeks{
public static void main(String[] args) {
{
[Link]("This is inside the block.");
}
You can simply use this link to download Java for Windows 64 Bit.
After successfully downloading JDK 23, now we need to install the
Java on our Windows System.
Step 3: Go to Downloads and double-click on that
downloaded jdk-23_windows-x64_bin.exe file. So now Java
Installation Wizard get open and then click Next button.
Working of JDK:
Working of JRE:
1. Class Loading: Loads compiled .class files into memory.
2. Bytecode Verification: Ensures security and validity of
bytecode.
3. Execution: Uses the JVM (interpreter + JIT compiler) to
execute instructions and make system calls.
JVM (Java Virtual Machine)
JVM is the core execution engine of Java. It is responsible for
converting bytecode into machine-specific instructions.
Part of both JDK and JRE.
Performs memory management and garbage collection.
Provides portability by executing the same bytecode on
different platforms.
Note:
JVM implementations are platform-dependent.
Bytecode is platform-independent and can run on any JVM.
Modern JVMs rely heavily on Just-In-Time (JIT) compilation
for performance.
Working of JVM:
JVM working
1. Loading: Class loader loads bytecode into memory.
2. Linking: Performs verification, preparation, and resolution.
3. Initialization: Executes class constructors and static
initializers.
4. Execution: Interprets or compiles bytecode into native
code.
JDK vs JRE vs JVM
Aspect JDK JRE JVM
JVM is OS-
Platform- Platform- specific, but
Platform dependent (OS dependent (OS bytecode is
Dependenc specific) specific) platform-
y independent
Convert
Writing and Running a Java
bytecode into
compiling Java application on a
native machine
code system
Use Case code
Java Identifiers
An identifier in Java is the name given to Variables, Classes,
Methods, Packages, Interfaces, etc. These are the unique names
used to identify programming elements. Every Java Variable must
be identified with a unique name.
class Geeks{
public static void main(String[] args){
int x = 9;
}
}
The image below describes Identifiers in this program:
Rules For Naming Java Identifiers
There are certain rules for defining a valid Java identifier. These
rules must be followed, otherwise, we get a compile-time error.
These rules are also valid for other languages like C and C++.
The only allowed characters for identifiers are all
alphanumeric characters([A-Z],[a-z],[0-9]), '$'(dollar sign)
and '_' (underscore). For example, "geek@" is not a valid
Java identifier as it contains a '@', a special character.
Identifiers should not start with digits([0-9]). For example,
"123geeks" is not a valid Java identifier.
Java identifiers are case-sensitive.
There is no limit on the length of the identifier, but it is
advisable to use an optimum length of 4 - 15 letters only.
Reserved Words can't be used as an identifier. For
example, "int while = 20;" is an invalid statement as a
while is a reserved word.
Note: Java has 53 reserved words (including 50 keywords and 3
literals), that are not allowed to be used as identifiers.
Examples of Valid Identifiers
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Examples of Invalid Identifiers
My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character
Java Keywords
Last Updated : 4 Dec, 2025
In Java, keywords are the reserved words that have some
predefined meanings and are used by the Java compiler for some
internal process or represent some predefined actions. These
words cannot be used as identifiers such as variable names,
method names, class names, or object names.
Now, let us go through a simple example before a deep dive into
the article.
class Geeks {
Used to define variable types and specify the kind of data they can
hold.
Keywo
rd Usage
boolea
Defines a variable that holds true or false.
n
Keywo
rd Usage
continu
Skips to the next iteration of a loop.
e
4. Object-Oriented Keywords
Keyword Usage
impleme
Indicates that a class implements an interface.
nts
Keywor
d Usage
packag
Defines a namespace for classes.
e
Keyword Usage
synchroniz Defines critical sections that only one thread can access
ed at a time.
Keywo
rd Usage
transie
Excludes a variable from serialization.
nt
Keywo
rd Usage
Keywo
rd Usage
Keywo
rd Usage
Descripti Defau
Type on lt Size Example Range
JVM-
depende
Logical
false nt true, false —
boole values
(typically
an 1 byte)
8-bit
signed 0 1 byte 10 -128 to 127
byte integer
16-bit
'A', '\
Unicode \u0000 2 bytes 0 to 65,535
u0041'
char character
16-bit
-32,768 to
signed 0 2 bytes 2000
32,767
short integer
-
32-bit 2,147,483,6
signed 0 4 bytes 1000, -500 48 to
integer 2,147,483,6
int 47
64-bit
123456789
signed 0L 8 bytes ±9.22e18
L
long integer
32-bit
~6–7 digits
floating 0.0f 4 bytes 3.14f
precision
float point
floating digits
e point precision
Output
Is Java fun? true
Is fish tasty? false
Output
Age: 25
Temperature: -10
Output
Number of Students: 1000
Temperature: -200
A 64-bit signed integer used when int is not sufficient for large
values.
Syntax:
long longVar;
Size : 8 bytes (64 bits)
public class Geeks {
public static void main(String[] args) {
long worldPopulation = 7800000000L;
long lightYears = 9460730472580800L;
[Link]("World Population: " +
worldPopulation);
[Link]("Light Years: " + lightYears);
}
}
Output
World Population: 7800000000
Light Year Distance: 9460730472580800
Output
Value of Pi: 3.14
Gravity: 9.81
Output
Value of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23
Output
Grade: A
Symbol: $
1. String
Output
Name: Geek1
Message: Welcome to Java
Note: String cannot be modified after creation. Use StringBuilder
for heavy string manipulation.
2. Class
void display() {
[Link](model + " " + year);
}
}
Output
Toyota 2020
3. Object
Output
Car Model: Honda
Car Year: 2021
4. Interface
Output
Woof
5. Array
Output
First number: 1
Second name: Geek2
Java Variables
In Java, variables are containers used to store data in memory.
Variables define how data is stored, accessed, and manipulated.
A variable in Java has three components,
Data Type: Defines the kind of data stored (e.g., int,
String, float).
Variable Name: A unique identifier following Java naming
rules.
Value: The actual data assigned to the variable.
class Geeks {
public static void main(String[] args) {
// Integer variable
int age = 25;
// String variable
String name = "GeeksforGeeks";
// Double variable
double salary = 50000.50;
Variable Declaration
From the image, it can be easily perceived that while declaring a
variable, we need to take care of two things that are data type of
the variable and name.
Output
Simple Interest: 5.5
Speed: 20
Time: 10
Character: h
Java-Operator
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic
operations on primitive and non-primitive data types.
public class GFG{
public static void main(String[] args) {
int a = 10, b = 3;
// Addition
int sum = a + b;
// Subtraction
int diff = a - b;
// Multiplication
int mul = a * b;
// Division
int div = a / b;
// Modulus
int mod = a % b; // Modulus
Output
Sum: 13
Difference: 7
Multiplication: 30
Division: 3
Modulus: 1
2. Unary Operators
Unary Operators need only one operand. They are used to
increment, decrement, or negate a value.
import [Link].*;
// Driver Class
class Geeks{
// Integer declared
int a = 10;
int b = 10;
// Using unary operators
[Link]("Postincrement : " + (a++));
[Link]("Preincrement : " + (++a));
Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
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.
public class GFG{
public static void main(String[] args){
int n = 10;
// n = n + 5
n += 5;
[Link]("After += : " + n);
// n = n * 2
n *= 2;
[Link]("After *= : " + n);
// n = n - 5
n -= 5;
[Link]("After -= : " + n);
// n = n / 2
n /= 2;
[Link]("After /= : " + n);
// n = n % 3
n %= 3;
[Link]("After %= : " + n);
}
}
Output
After += : 15
After *= : 30
After -= : 25
After /= : 12
After %= : 0
Note: Use compound assignments (+=, -=) for cleaner code.
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.
import [Link].*;
class Geeks{
// 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
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.
import [Link].*;
class Geeks {
// Main Function
public static void main (String[] args) {
// 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
general format is,
public class Geeks{
Output
Max of three numbers = 30
7. Bitwise Operators
These operators perform operations at the bit level.
Bitwise Operators manipulate individual bits using AND, OR,
XOR, and NOT.
Shift Operators move bits to the left or right, effectively
multiplying or dividing by powers of two.
import [Link].*;
class Geeks
{
public static void main(String[] args)
{
// 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. instanceof Operator
The instanceof 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. The general format,
public class GFG{
Output
true
true
false
The common mistakes that can occur when working with Java
Operators are listed below:
Confusing == with =: Using == for assignment instead
of = for equality check leads to logical errors.
Incorrect Use of Floating-Point
Comparison: Comparing floating point numbers using ==
can lead to unexpected results due to precision issues.
Integer Division Confusion: Dividing two integers will
result in integer division (truncating the result).
Overusing + for String Concatenation in Loops: Using
+ for concatenating strings in loops leads to performance
issues because it creates new string objects on each
iteration.