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

Java Programming Basics and Concepts

The document provides a comprehensive introduction to Java, covering its features, execution flow, and the differences between JDK, JRE, and JVM. It explains the structure of Java programs, variables, data types, type casting, and operators, along with practical coding tasks and common mistakes for beginners. Additionally, it includes hands-on assignments and real-world analogies to enhance understanding.

Uploaded by

Harshal Gavali
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 views34 pages

Java Programming Basics and Concepts

The document provides a comprehensive introduction to Java, covering its features, execution flow, and the differences between JDK, JRE, and JVM. It explains the structure of Java programs, variables, data types, type casting, and operators, along with practical coding tasks and common mistakes for beginners. Additionally, it includes hands-on assignments and real-world analogies to enhance understanding.

Uploaded by

Harshal Gavali
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

📅 Day 1 – Java Introduction, Features, JDK/JRE/JVM

1️⃣ What is Java?


●​High-level programming language, developed by Sun Microsystems in
1995 (now owned by Oracle).
●​Designed to be platform independent → You write once, and run
anywhere.
●​Java code is compiled into bytecode (universal language), and then executed
by JVM on any operating system.

Example:If you write a program on Windows, you can copy the .class file to
a Mac or Linux system → it runs without any changes.

2️⃣ Why Learn Java?


●​Used everywhere:
○​Android Apps
○​Banking applications
○​Web servers (Spring Boot)
○​Embedded systems

Stable language: Even after 25+ years, companies still rely on it.

Real-Time Analogy:
Think of Java like English language. Just like English allows people from
different countries to communicate, Java allows programs to run on different
machines without translation.

3️⃣ Java Features (Detailed)


●​Simple: Syntax is easy compared to C++ (no pointers headache).
●​Object-Oriented: Everything revolves around classes & objects.
●​Platform Independent: Bytecode runs anywhere.
●​Robust: Strong memory management + exception handling.
●​Secure: Runs inside JVM sandbox (prevents direct access to memory).
●​Multithreaded: Can run multiple tasks simultaneously.
●​Portable: Code once, run anywhere.
Real-Time Example:
●​Banking System (Core Banking):​

○​A bank has branches in multiple cities.


○​One software (written in Java) runs everywhere (ATM, website, mobile
app) without rewriting.

4️⃣ JVM, JRE, JDK (Deep Dive)


🔹 JDK (Java Development Kit):
●​Tools for developers.
●​Contains: javac (compiler), JRE, debugger, documentation tools.
●​You need JDK to write & compile code.

🔹 JRE (Java Runtime Environment):


●​For users.
●​Contains JVM + libraries to run code.
●​If you only want to run an application (not write), a JRE is enough.

🔹 JVM (Java Virtual Machine):


●​The heart of Java.


●​Converts bytecode → machine code.
●​Provides memory management (Garbage Collection).

5️⃣ How Java Code Runs (Execution Flow)


1.​Write Code → [Link]
2.​ Compile → javac [Link] → Creates [Link] (bytecode)
3.​ Run → java Hello → JVM reads .class file and runs

Real-Time Example:
Think of:
●​Java code = English movie script
●​javac compiler = Translator who converts script into universal subtitles
(bytecode)
●​JVM = Local cinema screen which shows subtitles in audience’s language
(machine code).

6️⃣ First Java Program (Step by Step)
public class Hello {
public static void main(String[] args) {
[Link]("Welcome to Java Training!");
}
}

🔎 Explanation:
●​public class Hello → Blueprint of program.
●​public static void main(String[] args) → Entry point.
●​[Link](...) → Prints message.

7️⃣ Hands-On Coding Tasks (for employees to try in session)


1.​Print your name, age, and city.
2.​ Print today’s date and time.
3.​ Print company’s name 5 times.
4.​ Print “Hello Java” inside a box shape using .
📅 Day 2 – First Java Program & Syntax
1️⃣ What is a Java Program?
A Java program is simply a set of instructions written inside a class that the
computer executes using the JVM.
Key Points:
●​Every program must have at least one class.
●​Execution always starts from the main() method.
●​The program must be compiled first before execution.

2️⃣ Structure of a Java Program


public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

Breakdown:
1.​public class HelloWorld → Class declaration (name must match file
name).
2.​ public static void main(String[] args) → Entry point.
○​public → Accessible everywhere
○​static → JVM can run without creating object
○​void → No return value
○​String[] args → Command-line arguments
3.​ [Link](...) → Used to print output.

3️⃣ Step-by-Step Execution Flow


1.​Save file as [Link]
2.​ Compile → javac [Link] (creates [Link])
3.​ Run → java HelloWorld (executes bytecode inside JVM)

Real-World Analogy:
●​Writing program = writing a recipe
●​Compiling = translating recipe into a universal format
●​Running = cooking using the recipe

4️⃣ Print Statements in Java


●​[Link]() → Prints without new line
●​[Link]() → Prints with new line
●​[Link]() → Prints formatted output

Example:
[Link]("Hello");
[Link](" World!");
[Link]("Value of PI: %.2f", 3.14159);
💡 Output:
Hello World!
Value of PI: 3.14

5️⃣ Real-Time Example (Company Use Case)


Imagine you’re writing software for HR Department. The program should:
●​Print our Company Name
●​Print Employee Details (Name, ID, Department, Role)

6️⃣ Hands-On Practice (During Session)


1.​Write a program to print your name, age, and city.
2.​ Print your favorite quote inside double quotes (" ").
3.​ Write a program to print current year in a banner style using *.

7️⃣ Common Mistakes Beginners Make


●​Saving file with wrong name (must match class name).
●​Forgetting a semicolon at the end of a statement.
●​Using lowercase main instead of Main.
●​Writing [Link] instead of [Link].
8️⃣Discussion Questions
●​Why is main() method static?
●​Can we write a program without main() method?
●​What is the difference between print and println?
●​Why does Java enforce file name = class name?

9️⃣ Mini Case Study (Real-Time)


●​ID Card Generator:​

○​A simple Java program that prints student/employee details in a


formatted way.

10️⃣ Assignment (After Class)


●​Create a program called [Link]
○​Print your Name, Age, City, Favorite Programming Language, and Hobby.
●​Create a program [Link]
○​Print your company name, total employees, and year of establishment.
Day 3 – Variables, Data Types 📅

1️⃣ What is a Variable?


●​A variable is a name given to a memory location where data is stored.
●​Variables allow us to store, reuse, and manipulate values in a program.

Syntax:
datatype variableName = value;
String name =”mohan”;

Example:
int = 25;
double salary = 55000.75;
String name = "Rahul";

2️⃣ Types of Variables in Java


1.​Local Variable – declared inside a method, only accessible within it.
2.​ Instance Variable – declared inside a class, outside methods, each object
gets its own copy.
3.​ Static Variable – declared with static, shared by all objects of the class.
3️⃣ Data Types in Java

🔹 Non-Primitive Data Types


●​String → "Hello"
●​Arrays → {10,20,30}
●​Objects → Instances of classes
4️⃣ Real-Time Analogy for Variables
●​A variable is like a locker in a bank.
○​Locker name = variable name
○​Locker contents = stored value
○​Locker size = data type

Example:
●​int age = 30; → A locker named age that stores 30.
●​double salary = 60000.50; → A locker named salary that stores a decimal
number.

1] Store two numbers and print their sum.


2] Store two decimal numbers and print their multiplication.
3] Store one character and print it, and print its ASCII value.

Assignment
●​Create a program called [Link]
○​Print your Name, Age, City, Favorite Programming Language, and Hobby.
●​Create a program [Link]
○​Print your company name, total employees, and year of establishment.
📅
📅
Day 4 – Type Casting

1. What is Type Casting?


Type casting means converting one data type into another.​
In Java, this happens in two ways:
1.​Implicit Casting (Type Promotion / Widening) → Done automatically
by Java.

2.​ Explicit Casting (Narrowing) → Done manually by the programmer

🔹 Implicit Casting (Widening) – automatic


🔹 (A) Implicit Casting (Widening Conversion)
●​Happens automatically when a smaller type is assigned to a larger type.
●​No data loss.
●​Order of widening:

byte → short → int → long → float → double


✅ Example:
🔹 Explicit Casting (Narrowing) – manual
●​Happens manually when a larger type is assigned to a smaller type.
●​Possible data loss.
●​Must use casting operator (type).

⚠️ Decimal part lost (.99).


3. Special Casting Examples
(i) Char ↔ Int Casting
(ii) Overflow in Casting

⚠️ Data overflow happened.


✅ Summary:
●​Implicit (Widening) → Safe, automatic, no data loss.
●​Explicit (Narrowing) → Manual, may lose data or cause overflow.
6️⃣ Real-Time Example (Company Payroll System)

Imagine you are building a salary calculation program:


●​int empId = 101;
●​String name = "Neha";
●​double basicSalary = 45000.75;
●​boolean isPermanent = true;

7️⃣ Hands-On Coding Tasks


1.​Question 1:​
Write a Java program to convert a double value 45.78 into an int using
type casting.
2.​ Question 2:​
Write a Java program to convert a char value 'A' into its ASCII value (int)
using type casting.
3.​ Question 3:​
Write a Java program to convert an int value 150 into a byte and print the
result.​
(Hint: Notice the effect of narrowing conversion).
4.​ Question 4:​
Write a Java program to convert a float value 23.56f into a long.
5.​ Question 5:​
Write a Java program where you take a short value 32000 and cast it into
an int.

8️⃣ Common Mistakes Beginners Make


●​Forgetting to initialize variables before using them.
●​Using the wrong type → e.g., storing decimals in int.
●​Not adding f for float values (3.14f).
📝 Assignment (After Class)
1.​Create [Link]
○​Variables: productId, productName, price, quantity.
○​Print details.

2.​ Create [Link]


○​Store salary as double.
○​Add bonus of 10% and print new salary.
📅 Day 5 – Operators in Java

1️⃣ What are Operators?


Operators are symbols that perform operations on variables and values.​
Think of them as tools that let you calculate, compare, and make decisions.
🔹 Relational Operators in Java 🔹
1️⃣ What are Relational Operators?
Relational operators are used to compare two values (operands) and return
a Boolean result (true or false).

Mostly used in decision making (if, while, for), comparisons, and


validations.
Normal Example

4️⃣ Summary – Where We Use Them in Real Life

●​> / < → Comparing quantities (age, salary, items).


●​>= / <= → Minimum or maximum conditions (bank balance, temperature,
speed limits).
●​== → Validation (password check, ID matching).
●​!= → Error detection, mismatches, unique checks.

✅ Q1: Check if a 40 number is greater than 100


Q2: Compare ages of two people and print who is older(Use > , == to
operator)
Q3: Check if a student has exactly the passing marks = 50
Q4: Check if the temperature is within a safe limit (≤ 40)
Q5: Verify if two employee IDs are not equal
🔹 Logical Operators in Java 🔹
1️⃣ What are Logical Operators?
Logical operators are used to combine or modify Boolean conditions.​
They return true/false depending on the logical evaluation.
Mostly used in decision-making, loops, and validations.
5️⃣ Summary

●​&& (AND) → Used when all conditions must be true (loan approval, job
eligibility).
●​|| (OR) → Used when at least one condition is enough (shopping
discount, admission).
●​! (NOT) → Used when reversing conditions (access control, restrictions).

🔹 Practice Questions – Logical Operators


✅ Q1: Check if a person is eligible for a loan (age ≥ 21 AND salary ≥ 30000)
✅ Q2: Check if a student can get admission (marks ≥ 50 OR has sports quota)
✅ Q3: Check if today is NOT a holiday
✅ Q5: Check if an order gets free delivery (purchase amount ≥ 1000 OR user has premium
membership) ( boolean isPremiumMember)
🔹 Assignment Operators in Java 🔹
1️⃣ What are Assignment Operators?
Assignment operators are used to assign values to variables.​
They can also perform operations and assign the result in a single step.

👉 Example (Shopping Discount):


🔹 Increment / Decrement Operators 🔹
1.​ Pre-Increment
2.​ Post-Increment
3.​ Pre-Decrement
4.​ Post-Decrement

1️⃣ Pre-Increment (++a)
First, increase the value by 1, then use it.
✅ Normal Example

✅ Real-Time Example (ATM Balance Update)


You deposit money, and the balance is updated immediately before using.
2️⃣ Post-Increment (a++)

First,use the current value, then increase it by 1.


✅ Normal Example

3️⃣ Pre-Decrement (--a)


First decrease the value by 1, then use it.

When a product is sold, stock decreases immediately.


4️⃣ Post-Decrement (a--)
First use the current value, then decrease it by 1.

✅ Real-Time Example (Movie Ticket Booking)


System shows available tickets first, then decreases after booking.

🔑 Key Differences Recap


●​Pre (++a / --a) → Update first, then use
●​Post (a++ / a--) → Use first, then update

Q1: Assign a value to a variable and print it.


Q2: Add 200 to the total bill using +=.

Q3: Deduct 15 marks from a student’s score using -=.

Q4: Double the stock of products using *=.


Q5: Find the remaining chocolates when 95 are divided among 12 kids using
%=.
🔹 Ternary Operator (?:) in Java 🔹
1️⃣ What is the Ternary Operator?
●​The only conditional operator in Java that works with three operands.
●​Acts as a short form of if-else statement.
●​Syntax:

1.​Evaluate condition.
2.​ If the condition is true, assign/return value_if_true.
3.​ If the condition is false, assign/return value_if_false.
2️⃣ ✅ Normal Example

👉 Output: Eligible to vote


✅ Real-Time Example 3: Student Grade System

🔑 Advantages of the Ternary Operator


1.​Shorter and cleaner code (replaces simple if-else).
2.​ Useful inside print statements or assignments.
3.​ Improves readability for small conditions.
4️⃣ ✅ Summary
●​Ternary Operator = Shorthand for if-else.
●​Best for single-line decisions.
●​Commonly used for max/min, pass/fail, odd/even, eligibility checks.

Q1: Check if a number is positive or negative.


Q2: Find the maximum of two numbers.
Q3: Check if a student passed or failed (passing marks = 40).
Q4: Check whether a number is even or odd.
Q5: Decide discount eligibility (purchase amount ≥ 1000).

🔹 Bitwise Operators in Java 🔹


1️⃣ What are Bitwise Operators?
●​Bitwise operators are used to perform operations on binary representations
of numbers.
●​They work at the bit level (0s and 1s).
●​Mostly used in low-level programming, performance optimization,
encryption, device drivers, and graphics.
(A) Bitwise AND &

🟡 Step 2: Bitwise AND (&)


Rule: 1 & 1 = 1, otherwise 0.
0101 (5)
& 0011 (3)
------------
0001 (1)

(B) Bitwise OR | 🟡 Step 3: Bitwise OR (|)


Rule: 1 | 0 = 1, 0 | 1 = 1, 1 | 1 = 1, only 0 | 0 = 0.
0000 0101 (5)
| 0000 0011 (3)
------------
0000 0111 (7)
(C) Bitwise XOR ^ 🟡 Step 4: Bitwise XOR (^)
Rule: Same bits → 0, Different bits → 1.
0000 0101 (5)
^ 0000 0011 (3)
------------
0000 0110 (6)

(D) Bitwise NOT ~

(E) Left Shift <<

(F) Right Shift >>


(G) Unsigned Right Shift >>>

●​& → AND (check if both bits are set)


●​| → OR (combine permissions/values)
●​^ → XOR (toggle/change)
●​~ → NOT (invert bits)
●​<< → Left shift (multiply by 2ⁿ)
●​>> → Right shift (divide by 2ⁿ)
●​>>> → Unsigned right shift (ignores sign bit, fills with 0)

🔹 Real-World Examples
●​Bitwise AND (&) → Checking permissions in security systems (read, write,
execute bits).
●​Bitwise OR (|) → Combine multiple flags (turn ON multiple features at once).
●​Bitwise XOR (^) → Used in encryption and error detection.
●​Bitwise NOT (~) → Used in bit masking (invert selected bits).
●​Left Shift (<<) → Fast multiplication by powers of 2 (e.g., x << 3 = x*8).
●​Right Shift (>>) → Fast division by powers of 2 (e.g., x >> 2 = x/4).
●​Unsigned Right Shift (>>>) → Used when working with binary file formats
or network protocols where numbers are unsigned.
COMMENTS IN JAVA

🔹 What are Comments?


👉
Comments are notes written inside the code for explanation.​

👉
They are ignored by the compiler (not executed).​
Used for documentation, understanding, and debugging.
Think of comments like sticky notes you leave in your notebook — they don’t affect
the actual work but help explain it.

🔹 Types of Comments in Java


1. Single-Line Comment
●​Starts with //
●​Used for short explanations.
✅ Example:

2.
Multi-Line Comment
●​Starts with /* and ends with */
●​Used for longer explanations or to temporarily disable a block of code.
✅ Example:
3. Documentation Comment
●​Starts with /** and ends with */
●​Used for generating Java documentation (Javadoc).
●​Placed before classes and methods to describe their purpose.

/**
* This class represents a Calculator.
* It has a method to add two numbers.
*/

🔹 Real-Life Example
Imagine a recipe book:
Ingredients (code) → actual program logic.
Notes written by chef (comments) → extra information for understanding.

🔹 Practice Questions
1.​Write a Java program that prints your name, and add a single-line
comment explaining the code.​

2.​ Write a Java program with multi-line comments describing what the
program does.​

3.​ Create a Car class and use documentation comments to explain its
purpose.​

4.​ Use comments to temporarily disable a piece of code (e.g., disable


printing a line).​

5.​ Write a program to calculate the sum of two numbers and explain each
line using comments.

You might also like