0% found this document useful (0 votes)
18 views71 pages

Java Programming - 1 - 1752574457476

This document outlines the syllabus for a Java Programming course for B. Tech 2nd Year, taught by Dr. Anurag Barthwal. It covers Java architecture, operators, decision statements, and includes a case study on a Library Management System. Additionally, it discusses Java's features, execution process, components, variables, data types, type conversion, and input/output handling.

Uploaded by

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

Java Programming - 1 - 1752574457476

This document outlines the syllabus for a Java Programming course for B. Tech 2nd Year, taught by Dr. Anurag Barthwal. It covers Java architecture, operators, decision statements, and includes a case study on a Library Management System. Additionally, it discusses Java's features, execution process, components, variables, data types, type conversion, and input/output handling.

Uploaded by

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

Unit 1: Java Programming

B. Tech. 2nd Year

Instructor: Dr. Anurag Barthwal


Associate Professor

28/10/2025 Dr Anurag Barthwal 1


Syllabus
• Java Architecture – JVM, JRE & JDK, Keywords, Features of Java, Console input
and output statements, variables and Identifiers, Scope of Variables, Data types,
Type Conversion, Comments, Access Modifiers
• Operators – Unary Operator, Arithmetic Operator, Shift Operator, Relational
Operator, Bitwise Operator, Logical Operator, Ternary Operator, and Assignment
Operator
• Decision Statements – if Statements, if-else Branching, switch Statements

• Case Study: Library Management System


Scenario: A university library wants to modernize its book management
system. They need a software solution to keep track of books, borrowers, and
transactions efficiently.
28/10/2025 Dr Anurag Barthwal 2
• Run java programs by installing Eclipse environment:
https://www.eclipse.org/downloads/download.php?file=/
oomph/epp/2025-06/R/eclipse-inst-jre-win64.exe

• Run a java program online using the compiler:


https://www.programiz.com/java-programming/online-compiler/

28/10/2025 Dr Anurag Barthwal 3


What is Java?
• Java is a high-level, object-oriented, and platform-independent
programming language developed by Sun Microsystems (now owned
by Oracle).
• It follows the principle of Write Once, Run Anywhere (WORA),
meaning code written in Java can run on any device that has a Java
Virtual Machine (JVM).
• Java is widely used for building desktop applications, web
applications, enterprise software, and even embedded systems.

28/10/2025 Dr Anurag Barthwal 4


Why Study Java?
• Versatility and Popularity: Java is one of the most widely used programming languages
across industries and remains in high demand.
• Object-Oriented Programming (OOP): Java teaches core OOP concepts like inheritance,
polymorphism, encapsulation, and abstraction.
• Platform Independence: Java programs can run on different operating systems without
modification.
• Strong Community and Libraries: With a large developer community and a rich set of
APIs, Java supports faster and more efficient development.
• Job and Career Opportunities: Knowledge of Java opens doors to careers in software
development, Android development, backend services, and enterprise applications.
• Java is the core language for Android app development.
• Studying Java builds a solid foundation for programming and software development,
making it an excellent starting point for both beginners and experienced coders.
28/10/2025 Dr Anurag Barthwal 5
Tiobe Index

28/10/2025 Dr Anurag Barthwal 6


• The flow chart given below shows how a Java program is executed:

.java (Source Code)



[Compiled by javac]

.class (Bytecode)

[JVM (with Interpreter / JIT)]

Machine Code

Output
28/10/2025 Dr Anurag Barthwal 7
How a Java Program is Executed
• The execution of a Java program involves multiple steps, from writing
the code to running it on a machine. Here's a step-by-step explanation:

1. Writing the Java Code


• You write the source code in a file with a .java extension using any
text editor or IDE (like Eclipse, IntelliJ, or NetBeans).

28/10/2025 Dr Anurag Barthwal 8


2. Compilation (Using Java Compiler - javac)
• The Java compiler converts the .java source code file into bytecode,
which is saved in a .class file.

• Output: Platform-independent bytecode

28/10/2025 Dr Anurag Barthwal 9


3. Execution by Java Virtual Machine (JVM)
• The JVM interprets or compiles the bytecode into machine code
specific to the host operating system using an Interpreter or Just-In-
Time (JIT) Compiler.
• Interpreter: Executes bytecode line by line.
• JIT Compiler: Converts frequently used bytecode into machine code
at runtime for faster execution.

4. Program Output
• After execution of the bytecode, the OS returns the output.

28/10/2025 Dr Anurag Barthwal 10


Java: Architecture and Components
• Java architecture defines the internal working and execution process of
Java applications. It includes: 1) Java Development Kit (JDK), 2) Java
Runtime Environment (JRE), and 3) Java Virtual Machine (JVM).

28/10/2025 Dr Anurag Barthwal 11


JAVA Components ..

• JDK (Java Development Kit): JRE + Development tools (compiler,


debugger)

• JRE (Java Runtime Environment): JVM + Libraries for running


Java programs

• JVM (Java Virtual Machine): Executes Java bytecode

28/10/2025 Dr Anurag Barthwal 12


Main Components of Java Architecture
1. Java Development Kit (JDK)
A full-featured software development kit used to develop Java
applications. It includes:
• JRE (Java Runtime Environment)
• Development tools like javac (compiler), javadoc, jar, etc.

28/10/2025 Dr Anurag Barthwal 13


2. Java Runtime Environment (JRE)
Provides the minimum requirements to run Java applications. It includes:
• JVM
• Core libraries (e.g., rt.jar)
• Supporting files

3. Java Virtual Machine (JVM)


Software that runs Java bytecode:
• Converts .class files (bytecode) into machine code at runtime.
Key Responsibilities:
• Memory management
• Garbage collection
• Security
• Platform independence
28/10/2025 Dr Anurag Barthwal 14
* Memory Management
• Allocates and manages memory for class loading, object creation, method calls,
and execution.
• Divides memory into Heap, Stack, Method, PC Register, and Method Stack.

* Garbage Collection
• Automatically detects and removes unused objects from memory to free space.
• Uses algorithms like Mark-and-Sweep or Generational GC to ensure efficient
memory use.

* Security
• Runs code inside a sandbox to prevent malicious activities.
• Performs bytecode verification, enforces access controls, and restricts unsafe
operations.
28/10/2025 Dr Anurag Barthwal 15
Java Program Execution

• Write Code → You write .java files.


• Compile Code → javac compiler converts .java to .class (bytecode).
• Class Loader → Loads .class files into memory.
• Bytecode Verifier → Checks code for security issues and correctness.
• Execution by JVM → Bytecode is interpreted or compiled by JVM
into native machine code using:
• Interpreter or
• JIT (Just-In-Time) Compiler

28/10/2025 Dr Anurag Barthwal 16


Key Features of Java:

• Simple and easy to learn


• Platform Independence: "Write Once, Run Anywhere" via JVM.
• Security: Bytecode verification and sandboxing.
• Automatic Memory Management: JVM handles memory via garbage
collection.
• Robustness and High Performance: Ability to handle errors and
unexpected situations gracefully (exception handling).
• Multi-threaded: allows simultaneous execution of two or more parts of a
java program.
28/10/2025 Dr Anurag Barthwal 17
28/10/2025 Dr Anurag Barthwal 18
Keywords in Java
• In Java, keywords are predefined, reserved words that have specific meanings to the Java
compiler and are used to define the structure and behavior of Java programs.
• They cannot be used as identifiers (like variable names, method names, or class names)
because they are fundamental elements of Java syntax.

Examples of Java keywords:


• Access Modifiers: public, private, protected.
• Data Types: int, boolean, char, byte, short, long, float, double.
• Control Flow: if, else, switch, case, default, for, while, do, break, continue, return
• Class and Object Related: class, new, this, super, abstract, final, static, extends, implements,
interface, enum.

28/10/2025 Dr Anurag Barthwal 19


28/10/2025 Dr Anurag Barthwal 20
• Exception Handling: try, catch, finally, throw, throws
• Other: import, package, void, native, strictfp, synchronized, transient,
volatile, assert, goto (reserved but unused), const (reserved but
unused)

Understanding these keywords is essential for writing valid and efficient


Java code, as they provide the foundation for defining data types,
creating classes, controlling program execution, and handling errors.

28/10/2025 Dr Anurag Barthwal 21


Console Input and Output in Java
1. Console Output (System.out.println / System.out.print):
Used to display output to the console.

• System.out.println("Hello");
→ Prints Hello and moves to the next line.

• System.out.print("Hello");
→ Prints Hello without moving to the next line.

28/10/2025 Dr Anurag Barthwal 22


2. Console Input using Scanner class:
To take input from the user, Java uses the Scanner class (part of java.util
package). Steps:

• Import Scanner → import java.util.Scanner;

• Create Scanner object → Scanner sc = new Scanner(System.in);

• Read input → sc.nextInt(), sc.nextLine(), etc.

28/10/2025 Dr Anurag Barthwal 23


Integer Input: sc.nextInt()
import java.util.Scanner; // Import the Scanner class
public class NextIntExample {
public static void main(String[] args) {
// Create a Scanner object to read input from the console
Scanner sc = new Scanner(System.in);
// Prompt the user to enter an integer
System.out.print("Enter your age: ");
// Read the integer input using nextInt()
int age = sc.nextInt();
// Print the entered age
System.out.println("You entered: " + age + " years old.");

// Close the scanner to release system resources


sc.close();
}
}
28/10/2025 Dr Anurag Barthwal 24
Character Input: sc.next().charAt(0)
import java.util.Scanner; // Import the Scanner class
public class CharInputExample {
public static void main(String[] args) {
// Create Scanner object to read input from console
Scanner sc = new Scanner(System.in);
// Prompt the user to enter a character
System.out.print("Enter a character: ");
// Read a character using next().charAt(0)
char ch = sc.next().charAt(0);
// Print the entered character
System.out.println("You entered: " + ch);
// Close the scanner
sc.close();
}
}
28/10/2025 Dr Anurag Barthwal 25
Input String: sc.nextline()

• import java.util.Scanner;

• public class InputExample {


• public static void main(String[] args) {
• Scanner sc = new Scanner(System.in);
• System.out.print("Enter your name: ");
• String name = sc.nextLine();
• System.out.println("Hello, " + name);
• }
• }
28/10/2025 Dr Anurag Barthwal 26
Variables and Identifiers
• Variable: A container for storing data
• Types: int, float, double, char, boolean.
• Identifier: Name given to a variable, class, method, object, etc.

Rules for Identifiers:


• Cannot start with a digit
• No spaces or special symbols (except _ , $ )
• Cannot be a keyword

28/10/2025 Dr Anurag Barthwal 27


Variable and Data Types
1. Floating-point Variables
float temperature = 36.5f;
double pi = 3.14159;
• float and double store decimal values (with fractional part)
• float requires an f suffix
• double has higher precision than float

2. Integer Variables
int age = 25;
int salary = 95000;
• Stores whole numbers
• Range: –2,147,483,648 to 2,147,483,647
28/10/2025 Dr Anurag Barthwal 28
6. Byte, Short, Long
byte smallNumber = 100;
short shortNumber = 32000;
long bigNumber = 1234567890L;

• byte: 1 byte, range -128 to 127


• short: 2 bytes
• long: use L suffix for large numbers

• 4. Boolean Variable
boolean isComplete = true;
boolean isLoggedIn = false;
•28/10/2025
Stores true or false Dr Anurag Barthwal 29
3. Character Variables
char grade = 'A';
• char initial = ‘M';
• Stores a single character enclosed in single quotes ' '

5. String Variable
String name = "Alice is a student";
• Stores a sequence of characters (text)
• String is a class, not a primitive type

28/10/2025 Dr Anurag Barthwal 30


28/10/2025 Dr Anurag Barthwal 31
Type Conversion in Java

Type Conversion in Java refers to changing a variable from one data type to another. It is classified into
two types:

1. Implicit Type Conversion (Widening):

int a = 10;
double b = a; // int is automatically converted to double
System.out.println(a); // Output: 10
System.out.println(b); // Output: 10.0

Allowed Conversions:
byte → short → int → long → float → double
28/10/2025 Dr Anurag Barthwal 32
Example 2: Widening
public class WideningExample3 {
public static void main(String[] args) {
byte b = 25; // byte value
int i = b; // byte to int
float f = i; // int to float
double d = f; // float to double

System.out.println("Byte value: " + b);


System.out.println("Int value: " + i);
System.out.println("Float value: " + f);
System.out.println("Double value: " + d);
}
}
28/10/2025 Dr Anurag Barthwal 33
Explicit Type Conversion (Narrowing /
Casting)
• Done manually by the programmer.
• May lead to data loss or precision loss.

Example 1:
double x = 10.543;
int y = (int) x; // Explicit cast from double to int
System.out.println(y); // Output: 10

28/10/2025 Dr Anurag Barthwal 34


Example 2: Convert double to float
public class PrintValue {
public static void main(String[] args) {
double pi=3.1495868677373;
float a = (float)pi;

System.out.println("double variable: " + pi); // This will print the value of a


System.out.println("float variable: " + a); // This will print the value of a
}
}
28/10/2025 Dr Anurag Barthwal 35
public class ExplicitConversion {
public static void main(String[] args) {
double x = 10.99;
int y = (int) x; // double to int (precision lost)

float f = 123.45f;
byte b = (byte) f; // float to byte (may lose data)

System.out.println("double value: " + x);


System.out.println("int value (after casting): " + y);
System.out.println("float value: " + f);
System.out.println("byte value (after casting): " + b);
}
}
28/10/2025 Dr Anurag Barthwal 36
Scope of Variables in Java
• Scope refers to where a variable can be accessed in a program.
• Java defines scope based on the location of variable declaration.

Types of Variable Scope


• Local Variables
• Instance Variables
• Class Variables
• Block Scope

28/10/2025 Dr Anurag Barthwal 37


Local Variables
• Declared inside a method, constructor, or block.
• Accessible only within that method or block.
• Not visible to other parts of the class.

void example() {
int x = 10; // Local variable
System.out.println(x);
}

28/10/2025 Dr Anurag Barthwal 38


Instance Variables
• Declared inside a class but outside methods.
• Each object has its own copy.
• Accessible by all non-static methods.

public class Demo {


int count = 5; // Instance variable
}

28/10/2025 Dr Anurag Barthwal 39


Class Variables (Static)
• Declared using the static keyword.
• Shared among all objects of the class.
• Can be accessed using the class name.

• public class Demo {


• static int max = 100; // Class variable
•}

28/10/2025 Dr Anurag Barthwal 40


Block Scope

• Variables inside {} are limited to that block.

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


System.out.println(i); // 'i' is in block scope
}

28/10/2025 Dr Anurag Barthwal 41


• Example:

28/10/2025 Dr Anurag Barthwal 42


28/10/2025 Dr Anurag Barthwal 43
Operators
• Operators are special symbols or keywords used to perform
operations on variables and values.

28/10/2025 Dr Anurag Barthwal 44


Operators in Java
• Java provides various operators to perform operations on variables and
values. These are categorized as follows:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Bitwise operators
6. Ternary operators
1. Arithmetic Operators
+ : Addition (a + b)
- : Subtraction (a - b)
* : Multiplication (a * b)
/ : Division (a / b)
% : Modulus (a % b)
2. Relational Operators
== : Equal to (a == b)
!= : Not equal to (a != b)
> : Greater than (a > b)
< : Less than (a < b)
>= : Greater than or equal to (a >= b)
<= : Less than or equal to (a <= b)
3. Logical Operators

&& : Logical AND (a > 0 && b > 0)


|| : Logical OR (a > 0 || b > 0)
! : Logical NOT (!a)
6. Bitwise Operators

& : Bitwise AND (a & b)


| : Bitwise OR (a | b)
^ : Bitwise XOR (a ^ b)
~ : Bitwise complement (~a)
7. Ternary Operator
• The ternary operator in Java, provides a concise way
to write simple if-else statements. It is the only operator
in Java that takes three operands.
• Syntax:
variable = condition ? value if true : value if true;
• Example 1:
int a = 10, b = 20;
String result = (a > b) ? "A is greater" : "B is
greater";
System.out.println(result);
Example 2

int x = 5, y = 3;
int min = (x < y) ? x : y;
System.out.println("Minimum is: " + min);
5. Unary Operators

+ : Unary plus (+a)


- : Unary minus (-a)
++ : Increment (a++ or ++a)
-- : Decrement (a-- or --a)
4. Assignment Operators
= : Assign (a = b)
+= : Add and assign (a += b)
-= : Subtract and assign (a -= b)
*= : Multiply and assign (a *= b)
/= : Divide and assign (a /= b)
%= : Modulus and assign (a %= b)
Assignment Operators
Operator Description Equivalent To Example (a = 10, b = 5) Result (a)

= Assign a=b a = b; a=5

+= Add and assign a=a+b a += b; a = 15

-= Subtract and assign a=a-b a -= b; a=5

*= Multiply and assign a=a*b a *= b; a = 50

/= Divide and assign a=a/b a /= b; a=2

%= Modulus and assign a=a%b a %= b; a=0


Decision Statements in Java
(if, if-else, and switch statements)
if
• Executes a block of code only if the condition is true.

• Example:
int age = 18;
if (age >= 18) {
System.out.println("Eligible to vote");
}
if-else statement
• Chooses between two paths: true or false condition.

• Example:
int number = 7;
if (number % 2 == 0) {
System.out.println("Even");
}
else {
System.out.println("Odd");
}
switch
Replaces multiple if-else statements for fixed values.

• Example:
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
Access modifiers in Java
• Access modifiers control the visibility of classes, methods, and
variables in Java. They decide which parts of the program can access
certain members.
• Access modifiers control the visibility of classes, methods, and
variables:
1. public
2. private
3. protected
4. default
Public
Public
• Accessible from anywhere in the program.

Example:

public class MyClass {


public int data = 40;

public void show() {


System.out.println("Public method");
}
}
Private
• Accessible only within the same class.
• Most restrictive.

Example:

class MyClass {
private int data = 10;

private void show() {


System.out.println("Private method");
}
}
Protected
• Accessible within the same package and by subclasses in other packages.

• Example:

class MyClass {
protected int data = 30;
protected void show() {
System.out.println("Protected method");
}
}
default
• Accessible only within the same package (package-private).
• Example:

class MyClass {
int data = 20; // default access

void show() {
System.out.println("Default access method");
}
}

You might also like