0% found this document useful (0 votes)
8 views35 pages

Java Programming Course Guide

The document is a comprehensive guide for a Java programming course, covering the syllabus, key concepts of object-oriented programming, and Java's history. It includes detailed explanations of Java's features, terminologies, and principles such as encapsulation, inheritance, and polymorphism. Additionally, it provides practical examples, exercises, and quiz questions to reinforce learning.

Uploaded by

jenamanoj251
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views35 pages

Java Programming Course Guide

The document is a comprehensive guide for a Java programming course, covering the syllabus, key concepts of object-oriented programming, and Java's history. It includes detailed explanations of Java's features, terminologies, and principles such as encapsulation, inheritance, and polymorphism. Additionally, it provides practical examples, exercises, and quiz questions to reinforce learning.

Uploaded by

jenamanoj251
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming

Course Guide and Study Material

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.

Operators: Arithmetic Operators, Relational Operators, Boolean Logical Operators, The


Assignment Operator, The ? Operator, Operator Precedence, Using Parentheses.

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

Day 1: Introduction to Java and Object-Oriented Programming (OOP)

Topics:
I. Two Programming Paradigms:

In programming languages, the two main paradigms are:

1. Procedural Programming Paradigm

Definition: Procedural programming is a paradigm that is based on the concept of procedure


calls, where programs are divided into a sequence of instructions (or procedures), and the
program executes these in a step-by-step manner.

Features:

- Focuses on a sequence of instructions to be followed.

- Uses functions, subroutines, and procedures to organize code.

- Data is typically passed from one procedure to another.

- Examples of procedural languages: C, Pascal, and Fortran.

- Example:
C -Programming

void add(int a, int b) {

printf("Sum: %d", a + b);

int main() {

add(5, 10);

return 0;

2. Object-Oriented Programming (OOP) Paradigm

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:

- Emphasizes real-world modeling using objects and classes.

- Promotes reusability through inheritance.

- Encapsulation keeps data safe by restricting access to it.

- Polymorphism allows objects to be treated as instances of their parent class.

- Examples of OOP languages: Java, C++, Python.

- Example:

class Calculator {

int add(int a, int b) {

return a + b;

}
public class Main {

public static void main(String[] args) {

Calculator calc = new Calculator();

[Link]("Sum: " + [Link](5, 10));

Key Differences:

2. Introduction to Java and its history.

Introduction to Java

Java is a high-level, class-based, object-oriented programming language that is designed to be


simple, secure, and platform-independent. It is widely used for building a variety of applications,
from desktop and web applications to mobile and enterprise systems. Java is known for its
"Write Once, Run Anywhere" (WORA) capability, which means that code written in Java can run
on any device that supports the Java Virtual Machine (JVM), without needing to be recompiled.

Key Features of Java:

Object-Oriented: Java follows the object-oriented paradigm, which promotes modularity,


reusability, and scalability through classes and objects.
Platform-Independent: Java applications are compiled into bytecode, which can be executed on
any system with a JVM, making it cross-platform.

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:

1991 – The Beginning (Project Green):

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.

1995 – Public Release:

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.

"Write Once, Run Anywhere" (WORA):

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.

1996 – Java 1.0:

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.

2000s – Enterprise and Mobile Development:

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.

2009 – Oracle Acquires Sun Microsystems:

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.

2020s – Java's Ongoing Evolution:

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:

1. Java Virtual Machine (JVM)

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

2. Java Runtime Environment (JRE)

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

10. Just-In-Time (JIT) Compiler

Definition: A Just-In-Time compiler is a hybrid approach that combines aspects of both


compilation and interpretation. It compiles code into machine code at runtime rather than
before execution. Generally faster than pure interpreters because frequently executed code can
be optimized and reused without recompilation.

11. Environment Variables (PATH, CLASSPATH & JAVA_HOME)


Setting PATH:

 Right-click on "This PC" or "Computer" and select "Properties."


 Click on "Advanced system settings."
 Click on the "Environment Variables" button.
 In the "System variables" section, find and select Path and click "Edit."
 Add the path to the JDK's bin directory and save.

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?

Object-Oriented Programming (OOP) is a programming model based on objects,


which are instances of classes. It helps structure programs using reusable blueprints,
improving modularity and maintainability.
OOP Principles in Java

1. Class

 A class is a blueprint or template that defines the structure and behavior


(methods) of objects.
 It contains fields (variables) and methods (functions).
 It does not consume memory until an object is created.

Example:

class Car {
String make;
void drive() {
[Link]("Car is moving");
}
}

2. Object

 An object is an instance of a class.


 Each object has its own copy of instance variables.
 Created using the new keyword.
 Objects allow real-world modeling in code.

Example:

Car myCar = new Car();


[Link]();

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

 Hides internal implementation details and shows only essential features.


 Achieved using abstract classes or interfaces.
 Promotes clean and simplified code structure.
 Helps in focusing on "what" an object does instead of "how".
 Reduces system complexity and increases efficiency.
5. Inheritance

 Enables a class to inherit fields and methods from another class.


 Promotes code reusability.
 Supports hierarchical classification.
 Uses extends keyword.
 Allows override or extension of base class behavior.

6. Polymorphism

 Allows a single action to behave differently in different contexts.


 Method Overloading (compile-time) – same method name, different parameters.
 Method Overriding (runtime) – subclass redefines parent method.
 Promotes flexibility and scalability in code.
 Enables dynamic method dispatch.

Concept Purpose Achieved Through


Class Blueprint for creating objects class keyword
Object Instance of a class new keyword
Encapsulation Hide internal details private + getters/setters
Abstraction Show only relevant info abstract class/interface
Inheritance Reuse fields and methods extends keyword
Polymorphism One interface, many implementations overloading/overriding

Example Code:
class Car {
private String make;
private String model;
private int year;

public Car(String make, String model, int year) {


[Link] = make;
[Link] = model;
[Link] = year;
}
public String getDetails() {
return year + " " + make + " " + model;
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car("Toyota", "Corolla", 2022);
[Link]([Link]());
}
}
Exercise:
- Create a `Car` class with encapsulated fields (`make`, `model`, `year`).

- Provide getters and setters to access and modify the fields.

Quiz Questions:
1. What are the two programming paradigms?

2. Define abstraction in OOP.

3. Explain encapsulation.

4. What is inheritance?

5. What is polymorphism?

Day 2: Blocks of Code & Lexical Issues

Topics:

1. Using Blocks of Code:


Blocks are code segments enclosed in `{}`.

2. Lexical Terms in JAVA:

1. Character Sets in Java

Java programs are written using a defined set of characters. These characters are
interpreted by the compiler.

 Java uses Unicode Character Set


o Supports most written languages in the world.
o Each character is represented by a unique code point.

Common Characters in Java:


Category Examples

Letters A–Z, a–z

Digits 0–9

Special + - * / = < > ! @ # $ % ^ & ( ) etc

Whitespace space, tab (\t), newline (\n)

2. Tokens in Java

Tokens are the smallest elements of a Java program that the compiler recognizes.

Major types of tokens:

1. Keywords
2. Identifiers
3. Literals
4. Variables
5. Constants
6. Operators

2.1 Keywords

 Reserved words in Java with special meaning.


 Cannot be used as identifiers (variable/class names).
 Java has 50+ 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

 Names used to identify variables, classes, methods, etc.


 Can consist of letters, digits, underscores ( _), and dollar signs ($).
 Must not start with a digit and not match any keyword.

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.

Literal Type Syntax Example Notes

Integer 100, 0xFF, 012, 0b101 No quotes, can use bases

Floating Point 3.14, 9.8f, 2.3e5 f for float, e for exponent

Character 'A', '\n', '\u0041' Single quotes

String "Hello" Double quotes

Boolean true, false Only two values

Null null Used with reference types

Example :

public class LiteralDemo {


public static void main(String[] args) {
int age = 20; // Integer
float temp = 36.5f; // Float
char grade = 'A'; // Character
String name = "Alice"; // String
boolean isPass = true; // Boolean
String empty = null; // Null literal

[Link](age + ", " + temp + ", " + grade + ", " + name + ", " + isPass);
}
}

2.4 Escape characters

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.

Special escape sequences:

Escape Meaning

\n Newline

\t Tab

\' Single quote

\" Double quote

\\ Backslash

Example :

public class EscapeDemo {


public static void main(String[] args) {
[Link]("This is line one.\nThis is line two."); // \n
[Link]("Java\tProgramming"); // \t
[Link]("She said, \"Hello!\""); // \"
[Link]("Path: C:\\Users\\Name"); // \\
[Link]("Backspace\bDemo"); // \b
}
}

2.4 Variables

 A named memory location to store a value.


 Must be declared with a data type.
 Must begin with a letter, _ or $.
 Cannot use keywords.
 Case-sensitive (Age and age are different).

Example:

int age = 21;


double price = 999.99;
2.5 Constants

 A variable whose value cannot be changed once assigned.


 Declared using the final keyword.
 const keyword is deprecated in Java
 final is the keyword used for constants

Example:

final double PI = 3.14159;

2.6 Operators

 Symbols that perform operations on variables and values.

Type Examples
Arithmetic +, -, *, /, %
Relational ==, !=, >, <, >=, <=
Logical &&, `
Assignment =, +=, -=, *=
Unary ++, --, +, -
Bitwise &, `
Ternary ? :

3. Comments:

What are Comments?

Comments are non-executable lines in a program used to:

 Explain code, Provide usage instructions


 Provide documentation, Document assumptions/logic
 Temporarily disable parts of code
 Improve readability
 Debugging/troubleshooting aid

Java comments are completely ignored by the compiler, so they don’t affect
execution.

1. Single-line Comment (//) - Used for brief comments on one line.


Use when:

 need to explain a line or variable


 want to temporarily disable a line
Example :
// This is a single-line comment

int age = 18; // declaring age

2. Multi-line Comment (/* ... */) : Used when the comment spans multiple lines.

Use when:

 Explaining a block of code


 Writing notes or documentation for others

Syntax:

/*
This is a multi-line comment
Used to describe logic or block of code
*/
int score = 90;

3. Documentation Comment (/** ... */)

 Special comment used to generate JavaDoc documentation.


 It's parsed by tools like javadoc to produce HTML documentation for APIs.

Use when:

 Creating public APIs or library code


 Adding structured documentation with tags like @param, @return, @author

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

Keyword Reserved word in Java if, class, public

Identifier Name of variable, method, or class studentName, main()

Literal Fixed value written directly "Hello", 123, 'A'

Variable Storage location with a name int age = 18;

Constant Variable that cannot be changed final double PI = 3.14;

Operator Performs operation on variables/values +, ==, &&

Data Type Defines kind and size of data int, double, char

Quiz Questions:
1. What are blocks of code?

2. How does whitespace affect Java code?

3. What are identifiers?

4. What is the significance of comments in Java?

5. What is a literal in Java?

Day 3: Java Primitive Data Types

Data Types in Java :


Java is strongly typed, meaning each variable must be declared with a data type.

Java data types are classified into two main categories:

1. Primitive Data Types (Built-in, 8 types)

2. Non-Primitive Data Types (User-defined / Reference types)


1. Primitive Data Types (8 total)

These are the most basic data types in Java. They are not objects and store simple values.

Category Data Type Size Default Value Example


0 byte a = 10;
Integer byte 1 byte Range: -128 to 127
short b = 200;
short 2 bytes 0 Range: -32,768 to 32,767
int c = 1000;
int 4 bytes 0 Range: ~ -2 billion to +2 billion
long 8 bytes 0L long d = 10000L;

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)

Character char 2 bytes '\u0000' char ch = 'A';

Boolean boolean 1 bit false boolean flag = true;

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;

[Link]("Byte: " + a);


[Link]("Short: " + b);
[Link]("Int: " + c);
[Link]("Long: " + d);
[Link]("Float: " + e);
[Link]("Double: " + f);
[Link]("Char: " + g);
[Link]("Boolean: " + h);
}
}
2. Non-Primitive (Reference) Data Types

These are user-defined or object-based data types that refer to memory locations.

Type Description Example

String Sequence of characters String name = "Java";

Array Collection of same-type elements int[] nums = {1, 2, 3};

Class Blueprint for creating objects class Student { ... }

Interface Abstract type with method contracts interface Drawable { ... }

Enum Fixed set of named constants enum Color { RED, GREEN }

Differences: Primitive vs. Non-Primitive


Feature Primitive Non-Primitive

Memory Type Stack Heap

Contains Actual values Address/reference to object

Size Fixed Dynamic

Null Assignment Not allowed Allowed (String s = null;)

Default Values Zero-based null

Example Code:
public class DataTypeExample {

public static void main(String[] args) {

int num = 100;

double price = 99.99;


char letter = 'A';

boolean isValid = true;

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

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

[Link]("Character: " + letter);

[Link]("Boolean: " + isValid);

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?

2. What is the size of an `int` in Java?

3. What is the difference between `float` and `double`?

4. What is the `char` type used for?

5. What values can a `boolean` hold?

Day 4: Variables, Type Conversion, and Casting

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.

Variable Declaration Syntax:


dataType variableName = value;

🔸 Examples:
int age = 20;
double price = 199.99;
char grade = 'A';
boolean isActive = true;
Types of Variables:
Type Where Declared Scope Life Span

Inside that Destroyed after block


Local Variable Inside a method/block
block/method ends

Instance Inside a class, outside


Whole object As long as object exists
Variable methods

With static keyword in a Shared among all


Static Variable Lives till program ends
class objects

Example:
public class Student {
String name = "Alice"; // instance variable
static int count = 0; // static variable

public void printInfo() {


int rollNo = 101; // local variable
[Link](name + " - " + rollNo);
}
}

2. Type Conversion in Java

What is Type Conversion?

Type conversion refers to changing one data type to another.

Implicit Type Conversion (Widening Conversion)

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

 Done manually by the programmer


 Larger → smaller data type
 May cause data loss

Syntax:
targetType variable = (targetType) originalValue;

Example:
double x = 10.75;
int y = (int) x; // Narrowing: double → int
[Link](y); // 10 (decimal part lost)

Possible Issues in Casting:


Problem Example Result

Data loss (int) 3.14 3

Overflow (byte) 130 -126 (wraps around)

Runtime errors String s = (String) new Object(); Throws ClassCastException

Example Program with Both Conversions:


public class TypeConversionExample {
public static void main(String[] args) {
int a = 50;
double b = a; // Implicit conversion

double x = 9.81;
int y = (int) x; // Explicit casting

[Link]("Implicit (int to double): " + b);


[Link]("Explicit (double to int): " + y);
}
}
Type Conversion Table:

From / To byte short int long float double

byte ✔ ✔ ✔ ✔ ✔ ✔

short ✘ ✔ ✔ ✔ ✔ ✔

int ✘ ✘ ✔ ✔ ✔ ✔

long ✘ ✘ ✘ ✔ ✔ ✔

float ✘ ✘ ✘ ✘ ✔ ✔

double ✘ ✘ ✘ ✘ ✘ ✔

✔ = Allowed automatically (widening), ✘ = Requires explicit casting

Quiz Questions:

1. What is the difference between implicit and explicit type conversion?


2. Is it safe to convert int to double implicitly? Why?
3. What will be the output of (int) 9.99?
4. Can you assign a long value to an int variable directly?
5. What is the purpose of the static keyword with variables?
6. Write a program that converts a `double` value to an `int` using casting.

7. What is implicit type conversion?


8. How do you explicitly cast a double to an int?
9. Can you cast an `int` to `char` in Java?
10. What is type promotion?
11. What is the result of casting a `float` to `int`?

Day 5: Arrays and Type Inference

1. Arrays in Java

An array is a collection of elements of the same data type, stored in contiguous


memory locations.

 Arrays are fixed in size.


 They can store primitive types or objects.
 Array elements are accessed using indexing, starting from 0.

Array Declaration and Initialization

Syntax:
dataType[] arrayName = new dataType[size];

or

dataType[] arrayName = {value1, value2, value3};

Example:
int[] numbers = new int[5]; // declaration + memory allocation
int[] marks = {80, 90, 85, 70}; // initialization

Accessing Array Elements


[Link](marks[0]); // First element
marks[2] = 95; // Assign a value

Iterating through Arrays

1. Using for loop:

for (int i = 0; i < [Link]; i++) {


[Link](marks[i]);
}

2. Using for-each loop:

for (int mark : marks) {


[Link](mark);
}

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

Common Errors with Arrays


Mistake Example

Accessing out of bounds arr[10] when array size is 5

Using length() instead of length [Link]() → ❌

Mixing types int[] arr = {1, "text"}; → ❌

2. Type Inference in Java

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;

The compiler determines the type at compile time, not at runtime.

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

 Only works for local variables, not class or method parameters.


 Must be initialized at the time of declaration.
 Cannot be used with null assignments:
 var data = null; // ❌ Not allowed
 var is not a keyword — it is a reserved type name.

Valid Use Cases:


Code Inferred Type

var x = 100; int

var y = 12.5; double

var flag = true; boolean

var list = new ArrayList<String>(); ArrayList

Invalid Usages:
var x; // ❌ Error: no initializer
var nullValue = null; // ❌ Cannot infer type from null

Type Inference in Loops:

int[] nums = {1, 2, 3};

for (var num : nums) {


[Link](num);
}

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?

Day 6 & 7 Arithmetic and Relational Operators Boolean Logical Operators


and Assignment Operator

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

Used to perform basic mathematical operations.

Operator Description Example Result

+ Addition 10 + 5 15

- Subtraction 10 - 5 5

* Multiplication 10 * 5 50

/ Division 10 / 2 5

% Modulus (remainder) 10 % 3 1

Integer division discards the decimal:

int x = 5 / 2; // Result: 2, not 2.5

2. Relational (Comparison) Operators

Used to compare values. Returns a boolean result (true or false).


Operator Meaning Example Output

== Equal to 5 == 5 true

!= Not equal to 5 != 3 true

> Greater than 7 > 4 True

< Less than 7 < 4 False

>= Greater or equal 6 >= 6 True

<= Less or equal 3 <= 2 False

3. Boolean Logical Operators

Used to perform logical operations on boolean expressions.

Operator Description Example Result

&& Logical AND true && false false

` ` Logical OR

! Logical NOT !true false

Example:

int a = 10, b = 20;


[Link]((a < b) && (b < 30)); // true

4. Assignment Operator

Used to assign values to variables.


Operator Description Example Equivalent To

= Simple assignment x = 5 –

+= Add and assign x += 5 x = x + 5

-= Subtract and assign x -= 3 x = x - 3

*= Multiply and assign x *= 2 x = x * 2

/= Divide and assign x /= 4 x = x / 4

%= Modulus and assign x %= 3 x = x % 3

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

6. Operator Precedence in Java

Determines the order in which operators are evaluated in expressions.

Precedence Level Operators Associativity

1 (Highest) (), [], . Left to Right

2 ++, --, !, ~ Right to Left

3 *, /, % Left to Right

4 +, - Left to Right
Precedence Level Operators Associativity

5 <, >, <=, >= Left to Right

6 ==, != Left to Right

7 && Left to Right

8 `

9 ?: (Ternary) Right to Left

10 (Lowest) =, +=, -=, *= etc. Right to Left

7. Using Parentheses ()

You can use parentheses to override precedence and ensure clarity.

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;

[Link]("Logical Result: " + result);


[Link]("Max Value: " + max);
}
}

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?

11. What is the use of the % operator?


12. How is the == operator different from =?
13. What is the output of 5 + 10 * 2?
14. Write an expression using a ternary operator to find the smaller of two numbers.
15. What is the purpose of += operator?
16. How do you control the order of execution in an expression?

Day 8: Control Statements - Selection Statements

Control statements direct the flow of execution in a program. They allow decisions,
loops, and jumps.

Selection Statements

Used to make decisions based on conditions.

if Statement

Executes a block if a condition is true.

if (condition) {
// block of code
}

Example:
int age = 20;
if (age >= 18) {
[Link]("You are an adult.");
}

if-else Statement

Executes one block if true, another if false.


if (condition) {
// true block
} else {
// false block
}

else if Ladder

Used to test multiple conditions.

if (marks >= 90) {


[Link]("Grade A");
} else if (marks >= 80) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}

switch Statement (Traditional)

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?

2. How do you write a `switch` statement?

3. Can you use `switch` with strings in Java?


4. What is the `else if` statement used for?

5. What does the `default` keyword do in a `switch` statement?

Day 9: Control Statements - Iteration Statements


Iteration (Looping) Statements

Used to repeat code multiple times.

while Loop

Checks condition before each iteration.

int i = 0;
while (i < 5) {
[Link](i);
i++;
}

do-while Loop

Runs the block at least once, then checks the condition.

int i = 0;
do {
[Link](i);
i++;
} while (i < 5);

for Loop

Best for known number of repetitions.

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


[Link](i);
}

for-each Loop

Used to iterate through arrays/collections.

int[] numbers = {1, 2, 3};


for (int num : numbers) {
[Link](num);
}
for Loop with Type Inference (var)

Introduced in Java 10 for local variables.

int[] arr = {10, 20, 30};


for (var value : arr) {
[Link](value);
}

Nested Loops

A loop inside another loop.

for (int i = 1; i <= 3; i++) {


for (int j = 1; j <= 2; j++) {
[Link]("i=" + i + ", j=" + j);
}
}

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?

2. What is the difference between `while` and `do-while`?

3. How does the enhanced `for` loop work?

4. When would you use a `while` loop instead of a `for` loop?

5. Can you nest loops in Java?

Day 10: Control Statements - Jump Statements

Jump Statements Used to alter flow suddenly.


break

Exits the nearest enclosing loop or switch.

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


if (i == 5) break;
[Link](i);
}

continue

Skips the rest of the loop for the current iteration.

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


if (i == 2) continue;
[Link](i); // skips 2
}

return

Used to exit from a method.

public static int square(int x) {


return x * x;
}

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?

2. How does `continue` affect the flow of loops?

3. What is the role of the `return` statement?

4. Can you use `break` in a `switch` statement?

5. How does `continue` impact the iteration?

You might also like