Java Programming Course Guide
Java Programming Course Guide
Module-1 - Syllabus
An Overview of Java: Object-Oriented Programming (Two Paradigms, Abstraction, The Three
OOP Principles), Using Blocks of Code, Lexical Issues (Whitespace, Identifiers, Literals,
Comments, Separators, The Java Keywords).
Data Types, Variables, and Arrays: The Primitive Types (Integers, Floating-Point Types,
Characters, Booleans), Variables, Type Conversion and Casting, Automatic Type Promotion in
Expressions, Arrays, Introducing Type Inference with Local Variables.
Control Statements: Java’s Selection Statements (if, The Traditional switch), Iteration
Statements (while, do-while, for, The For-Each Version of the for Loop, Local Variable Type
Inference in a for Loop, Nested Loops), Jump Statements (Using break, Using continue, return).
Topics:
I. Two Programming Paradigms:
Features:
- Example:
C -Programming
int main() {
add(5, 10);
return 0;
Definition: OOP is a paradigm that is centered around objects, which are instances of classes. It
focuses on bundling data and methods (functions) together and using concepts like inheritance,
polymorphism, encapsulation, and abstraction.
Features:
- Example:
class Calculator {
return a + b;
}
public class Main {
Key Differences:
Introduction to Java
Simple and Secure: Java is designed to be easy to use, with strong memory management,
automatic garbage collection, and built-in security features.
Robust: Java has strong exception handling and memory management, reducing the likelihood
of crashes and bugs.
Multithreaded: Java provides built-in support for multithreading, allowing programs to perform
multiple tasks simultaneously.
Rich API: Java has an extensive set of libraries and APIs, making it powerful and flexible for
developers.
History of Java
Java's history dates back to the early 1990s when it was developed by James Gosling and his
team at Sun Microsystems (now owned by Oracle). The language evolved through the following
key milestones:
Java started as a project called Green, initiated by James Gosling, Mike Sheridan, and Patrick
Naughton at Sun Microsystems. Their goal was to create a language for programming small
embedded devices and consumer electronics.
Java was officially released in 1995. Initially named Oak (after an oak tree outside Gosling's
office), it was later renamed Java, inspired by the coffee popular with the development team.
The first version of Java was bundled with the HotJava browser, showcasing Java's ability to run
applets on web pages.
One of Java's key strengths, WORA, became a major selling point. The Java code would be
compiled into bytecode, which could be executed on any platform with a JVM. This platform-
independence became crucial for web and enterprise applications.
The first official version of Java (Java 1.0) was released with a focus on web applets. It quickly
gained popularity for its ability to run dynamic content on websites.
Late 1990s – Expansion and Growth:
Java gained immense popularity due to its ease of use, object-oriented approach, and cross-
platform capabilities. Major tech companies like IBM and Oracle adopted Java, expanding its use
in enterprise systems and server-side applications.
Java continued to grow with the release of Java 2 (J2SE, J2EE, J2ME), which focused on desktop,
enterprise, and mobile applications.
In 2006, Android was launched, using Java as its primary programming language for mobile app
development, solidifying Java's position in the mobile ecosystem.
In 2009, Oracle acquired Sun Microsystems, becoming the official owner and maintainer of Java.
This acquisition led to new enhancements and versions, keeping Java relevant for both
enterprise and mobile development.
2014 – Java 8:
Java 8 introduced major updates, such as lambda expressions, streams API, and a new date and
time API, revolutionizing how developers wrote Java code and making it more modern and
expressive.
Java continues to evolve, with regular updates to its features, security, and performance.
Versions like Java 11 and Java 17 bring long-term support (LTS) and new features like
modularity, pattern matching, and more.
JAVA Terminologies:
Here are some key terminologies commonly used in Java, along with their definitions:
- An abstract computing machine that enables a computer to run Java programs. It converts Java
bytecode into machine code and is responsible for memory management and garbage
collection.
- A package that provides the necessary libraries and components to run Java applications. It
includes the JVM, core libraries, and other components required for executing Java programs.
3. Java Development Kit (JDK)
- A software development kit that provides the tools needed to develop Java applications,
including the JRE, a compiler (javac), and other development tools.
4. Class
- A blueprint or template for creating objects. A class defines properties (attributes) and
behaviors (methods) that its objects will have.
5. Object
- An instance of a class. It is a self-contained unit that consists of both data (attributes) and
methods (functions or behaviors) that operate on that data.
6. Method
- A block of code within a class that performs a specific task. Methods define the behavior of
objects and can take parameters and return values.
7. Java API
- A collection of classes, interfaces, and packages provided by Java for building applications. The
API provides a wide range of functionality, including data structures, networking, I/O operations,
and more.
8. Java Compiler
- A tool (javac) that converts Java source code (written in `.java` files) into bytecode (in `.class`
files) that can be executed by the JVM.
9. Bytecode
- The intermediate representation of Java code that is generated by the compiler. Bytecode is
platform-independent and can be executed on any system with a JVM.
Setting CLASSPATH:
In the "Environment Variables" window, click "New" in the "System variables" section.
Enter CLASSPATH as the variable name and the necessary paths as the value.
./ refers current work directory as classpath
Setting JAVA_HOME:
In the "Environment Variables" window, click "New" in the "System variables" section.
Enter JAVA_HOME as the variable name and the path to your JDK installation as the
value.
These configurations are essential for Java development and help ensure that your system can
locate the Java tools and libraries it needs.
3. OOP Principles:
What is OOP?
1. Class
Example:
class Car {
String make;
void drive() {
[Link]("Car is moving");
}
}
2. Object
Example:
3. Encapsulation
Combines data (fields) and methods (functions) into a single unit (class).
Data is hidden from outside using private access modifier.
Provides controlled access using public get and set methods.
Enhances data security and integrity.
Supports modular and maintainable code.
4. Abstraction
6. Polymorphism
Example Code:
class Car {
private String make;
private String model;
private int year;
Quiz Questions:
1. What are the two programming paradigms?
3. Explain encapsulation.
4. What is inheritance?
5. What is polymorphism?
Topics:
Java programs are written using a defined set of characters. These characters are
interpreted by the compiler.
Digits 0–9
2. Tokens in Java
Tokens are the smallest elements of a Java program that the compiler recognizes.
1. Keywords
2. Identifiers
3. Literals
4. Variables
5. Constants
6. Operators
2.1 Keywords
e.g.: class, public, static, void, int, if, else, while, return, new abstract, assert,
boolean, break, byte, case, catch, char, class, continue
2.2 Identifiers
Example :
int studentAge;
String name;
finalAmount = 1000;
2.3 Literals
In Java, a literal is a fixed value assigned directly to a variable. These are the actual values
written in code.
Example :
[Link](age + ", " + temp + ", " + grade + ", " + name + ", " + isPass);
}
}
Escape Characters in Java are special sequences used to represent characters that cannot
be typed directly, or that have special meaning (like a newline or tab). They start with a
backslash \ followed by a character.
The Java compiler interprets these escape sequences as single characters.
Escape Meaning
\n Newline
\t Tab
\\ Backslash
Example :
2.4 Variables
Example:
Example:
2.6 Operators
Type Examples
Arithmetic +, -, *, /, %
Relational ==, !=, >, <, >=, <=
Logical &&, `
Assignment =, +=, -=, *=
Unary ++, --, +, -
Bitwise &, `
Ternary ? :
3. Comments:
Java comments are completely ignored by the compiler, so they don’t affect
execution.
2. Multi-line Comment (/* ... */) : Used when the comment spans multiple lines.
Use when:
Syntax:
/*
This is a multi-line comment
Used to describe logic or block of code
*/
int score = 90;
Use when:
Syntax:
/**
* This class performs mathematical operations.
* @author John
* @version 1.0
*/
public class Calculator {
/**
* Adds two integers
* @param a First number
* @param b Second number
* @return Sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
}
Quick Summary :
Token Type Purpose Example
Data Type Defines kind and size of data int, double, char
Quiz Questions:
1. What are blocks of code?
These are the most basic data types in Java. They are not objects and store simple values.
float f = 3.14f;
Floating-point float 4 bytes 0.0f Single-precision (6–7 decimal digits)
double g = 9.81;
double 8 bytes 0.0d Double-precision (15 decimal digits)
Example :
public class DataTypesExample {
public static void main(String[] args) {
byte a = 127;
short b = 32000;
int c = 100000;
long d = 10000000000L;
float e = 3.14f;
double f = 3.1415926535;
char g = 'J';
boolean h = true;
These are user-defined or object-based data types that refer to memory locations.
Example Code:
public class DataTypeExample {
Exercise:
- Write a program that declares variables of all primitive types and prints their values.
Quiz Questions:
1. What are the 8 primitive data types in Java?
1. Variables in Java
What is a Variable?
A variable is a named memory location used to store data that can be modified during
program execution.
🔸 Examples:
int age = 20;
double price = 199.99;
char grade = 'A';
boolean isActive = true;
Types of Variables:
Type Where Declared Scope Life Span
Example:
public class Student {
String name = "Alice"; // instance variable
static int count = 0; // static variable
Happens automatically
When converting smaller → larger data type
No data loss
Example:
int a = 100;
double b = a; // int → double (OK)
[Link](b); // 100.0
This works because double can hold all values that int can.
Order of Widening:
byte → short → int → long → float → double
Explicit Type Casting (Narrowing Conversion)
Syntax:
targetType variable = (targetType) originalValue;
Example:
double x = 10.75;
int y = (int) x; // Narrowing: double → int
[Link](y); // 10 (decimal part lost)
double x = 9.81;
int y = (int) x; // Explicit casting
byte ✔ ✔ ✔ ✔ ✔ ✔
short ✘ ✔ ✔ ✔ ✔ ✔
int ✘ ✘ ✔ ✔ ✔ ✔
long ✘ ✘ ✘ ✔ ✔ ✔
float ✘ ✘ ✘ ✘ ✔ ✔
double ✘ ✘ ✘ ✘ ✘ ✔
Quiz Questions:
1. Arrays in Java
Syntax:
dataType[] arrayName = new dataType[size];
or
Example:
int[] numbers = new int[5]; // declaration + memory allocation
int[] marks = {80, 90, 85, 70}; // initialization
Types of Arrays
1. One-dimensional Array
int[] arr = {1, 2, 3, 4};
2. Two-dimensional Array
int[][] matrix = {
{1, 2},
{3, 4}
};
[Link](matrix[1][0]); // Output: 3
Type inference is a feature introduced in Java 10 (JDK 10) where the compiler infers the
data type of a variable based on the assigned value using the var keyword.
🔑 Syntax:
var variableName = value;
� Examples:
var name = "Java"; // Inferred as String
var age = 20; // Inferred as int
var marks = new int[]{70, 80, 90}; // Inferred as int[]
Key Rules:
Invalid Usages:
var x; // ❌ Error: no initializer
var nullValue = null; // ❌ Cannot infer type from null
Exercise:
- Write a program to declare and initialize an array of integers. Print all elements using a loop.
Quiz Questions:
1. How do you declare an array in Java?
2. What is the default value of an array of integers?
3. What is type inference?
4. Can you create an array of `boolean` values?
5. How do you access an element of an array?
6. What is an array and how is it declared in Java?
7. How do you initialize a 2D array?
8. What happens if you access an index out of array bounds?
9. What is type inference in Java?
10. Can var be used for class-level fields?
11. What is the default value of an array of boolean?
An operator in Java is a symbol that tells the compiler to perform a specific operation
(like addition, comparison, or assignment) on operands (variables or values).
1. Arithmetic Operators
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 2 5
% Modulus (remainder) 10 % 3 1
== Equal to 5 == 5 true
` ` Logical OR
Example:
4. Assignment Operator
= Simple assignment x = 5 –
5. Ternary Operator (? :)
A shorthand for if-else. It evaluates a condition and returns one of two values.
Syntax:
condition ? valueIfTrue : valueIfFalse;
Example:
int age = 20;
String result = (age >= 18) ? "Adult" : "Minor";
[Link](result); // Output: Adult
3 *, /, % Left to Right
4 +, - Left to Right
Precedence Level Operators Associativity
8 `
7. Using Parentheses ()
Example:
int result = 10 + 2 * 5; // 10 + (2*5) = 20
int result2 = (10 + 2) * 5; // (10+2) * 5 = 60
Example Program:
public class OperatorExample {
public static void main(String[] args) {
int a = 10, b = 20;
boolean result = (a < b) && (b > 15);
int max = (a > b) ? a : b;
Exercise:
Write a program that performs all arithmetic and relational operations between two variables.
Write a program that checks if a number is within a certain range using logical operators.
Quiz Questions:
1. What is the modulus operator used for?
2. How does the `==` operator work?
3. What is the difference between `>` and `>=`?
4. Which operator is used for subtraction?
5. Can relational operators be used with boolean values?
6. How does the `&&` operator work?
7. What does the `!` operator do?
8. What is the difference between `&&` and `||`?
9. How is the assignment operator `=` used?
10. Can you assign a boolean value to an integer variable?
Control statements direct the flow of execution in a program. They allow decisions,
loops, and jumps.
Selection Statements
if Statement
if (condition) {
// block of code
}
Example:
int age = 20;
if (age >= 18) {
[Link]("You are an adult.");
}
if-else Statement
else if Ladder
Used for multi-way branching when comparing a single variable against multiple
constant values.
Syntax:
switch (expression) {
case value1:
// block
break;
case value2:
// block
break;
default:
// block
}
Example:
int day = 3;
switch (day) {
case 1: [Link]("Sunday"); break;
case 2: [Link]("Monday"); break;
default: [Link]("Other day");
}
Quiz Questions:
1. What is the syntax of an `if` statement?
while Loop
int i = 0;
while (i < 5) {
[Link](i);
i++;
}
do-while Loop
int i = 0;
do {
[Link](i);
i++;
} while (i < 5);
for Loop
for-each Loop
Nested Loops
Exercise:
- Write a program to print the numbers 1 to 10 using a `for` loop and an enhanced `for` loop to
iterate through an array.
Quiz Questions:
1. What is the syntax for a `for` loop?
continue
return
Exercise:
- Write a program that prints numbers from 1 to 10 but skips 5 and stops at 8 using `continue`
and `break`.
Quiz Questions:
1. What is the purpose of the `break` statement?