Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
15 views16 pages

Java Module 1

Uploaded by

hecapa4359
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)
15 views16 pages

Java Module 1

Uploaded by

hecapa4359
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
You are on page 1/ 16

Module-1

Introduction to Java

What is Java?

Java is a high-level, object-oriented, platform-independent programming language


developed by James Gosling and his team at Sun Microsystems (later acquired by Oracle
Corporation). It was officially released in 1995.

Key Characteristics:

 Compiled & Interpreted: Java source code is first compiled to bytecode, which is
then interpreted by the JVM.
 WORA: “Write Once, Run Anywhere” – Java programs can run on any device that
has a JVM.
 Object-Oriented: Java promotes code reusability through classes and objects.
 Robust & Secure: Java handles memory management and offers features like
garbage collection and strong type checking.
 Multithreaded: Supports concurrent execution using threads.
 Portable: Java programs are architecture-neutral due to bytecode.

History of Java

Origins:

 1991: Java was initiated as a project called “Oak” by James Gosling, Mike Sheridan,
and Patrick Naughton at Sun Microsystems. The aim was to create a language for
digital devices like set-top boxes and TVs.
 1995: Oak was renamed Java due to trademark issues.

Why the name “Java”?

 Named after Java coffee, a type of coffee from Indonesia, as the developers
consumed a lot of coffee during development.

Major Milestones:

Description
Year Version/Update

1995 Java 1.0 First public release


1998 Java 2 (J2SE) Major update with Swing, Collections framework
2004 J2SE 5.0 Introduced generics, annotations
2006 Java SE 6 Improved Web Services and scripting support
2011 Java SE 7 Added try-with-resources, switch with strings
2014 Java SE 8 Introduced Lambda expressions, Streams

Java/Sem-3/Module-1/BCA
Description
Year Version/Update

2017 Java SE 9 Introduced the module system (Project Jigsaw)


2021+ Java 17, 21... New LTS versions with pattern matching, records, etc.

Java Editions:

1. Java SE (Standard Edition) – Core Java programming


2. Java EE (Enterprise Edition) – Web and enterprise apps (now Jakarta EE)
3. Java ME (Micro Edition) – Mobile and embedded systems
4. JavaFX – For rich GUI applications

Features of Java

Java is known for its powerful set of features that make it one of the most widely used
programming languages in the world. These features include:

1. Simple

 Java has a clean and easy-to-understand syntax similar to C/C++ but without complex
features like pointers or operator overloading.
 Easy to learn, especially for beginners.

2. Object-Oriented

 Everything in Java is an object (except primitive types).


 Promotes code reuse through concepts like class, inheritance, encapsulation,
polymorphism, and abstraction.

3. Platform Independent

 Java code is compiled into bytecode, which can run on any system that has a Java
Virtual Machine (JVM).
 WORA – Write Once, Run Anywhere.

4. Secure

 Java provides a secure runtime environment by restricting access to memory and


system resources.
 Features like bytecode verification, sandboxing, and no explicit pointers enhance
security.

5. Robust

 Strong memory management, exception handling, and garbage collection help create
error-free and stable applications.

Java/Sem-3/Module-1/BCA
6. Multithreaded

 Java supports multithreading, which allows multiple threads to run concurrently.


 Useful for developing interactive and high-performance applications.

7. High Performance

 Though not as fast as C/C++, Java is relatively fast due to the use of Just-In-Time
(JIT) compiler.
 JIT compiles frequently used bytecode into native machine code at runtime.

8. Distributed

 Java has built-in support for networking using libraries like java.net.
 Java RMI and CORBA are used to create distributed applications.

9. Dynamic

 Java can adapt to an evolving environment.


 It supports dynamic loading of classes, meaning classes are loaded on demand at
runtime.

Applications of Java

Java is used across a wide range of domains due to its portability, performance, and
scalability.

1. Desktop Applications

 Java Swing and JavaFX are used to develop GUI-based desktop applications.
 Example: Calculator, Text Editor, Media Player.

2. Web Applications

 Java supports web development via Servlets, JSP, Spring, and Struts frameworks.
 Example: E-commerce websites, online banking systems.

3. Mobile Applications

 Java is the foundation for Android development using the Android SDK.
 Example: WhatsApp, Instagram (Android versions).

4. Enterprise Applications

Java/Sem-3/Module-1/BCA
 Java EE (Jakarta EE) is widely used in enterprise-level applications such as CRM,
ERP, HRM systems.
 Example: Banking software, Insurance management systems.

5. Scientific Applications

 Java’s portability, precision, and performance make it ideal for scientific applications
like simulations and calculations.
 Example: MATLAB Java integration.

6. Embedded Systems

 Java is used in embedded systems like smart cards, sensors, and gateways.

7. Games

 Java can be used to develop 2D and 3D games using frameworks like LibGDX.
 Example: Minecraft (originally written in Java).

8. Big Data Technologies

 Java is used in big data platforms like Hadoop, Apache Spark.

9. Cloud-Based Applications

 Java powers many cloud-native apps and services using microservices architecture.
 Common in AWS, Azure, and Google Cloud platforms.

10. Internet of Things (IoT)

 Java ME is used to build IoT applications for devices with limited computing
resources.

Java Development Kit (JDK)

Definition:

JDK is a software development environment used to develop Java applications and applets. It
contains the tools required to write, compile, and run Java programs.

Components of JDK:

 JRE (Java Runtime Environment)


 Development tools (like javac, javadoc, javap, etc.)
 Java libraries and APIs

Java/Sem-3/Module-1/BCA
Example:

To compile and run a Java program:

javac Hello.java // compiler from JDK

java Hello // runs using JRE

Java Runtime Environment (JRE)

Definition:

JRE provides the environment to run Java programs. It contains the JVM and the
necessary libraries and classes to execute bytecode.

Components of JRE:

 Java Virtual Machine (JVM)


 Core Java class libraries
 Java class loader

Note:

You can run Java applications with JRE, but you cannot develop them.

Java Virtual Machine (JVM)

Definition:

JVM is an abstract machine that enables your computer to run Java programs. It converts
bytecode into machine code and handles system memory.

Responsibilities of JVM:

 Loading code
 Verifying code
 Executing code
 Memory management (Heap, Stack)
 Garbage collection
 Security

Important Features:

 Platform-independent execution

Java/Sem-3/Module-1/BCA
 Part of both JRE and JDK

JDK vs JRE vs JVM Summary Table


Feature JDK JRE JVM
Stands for Java Development Kit Java Runtime Environment Java Virtual Machine
Purpose Develop & run Java apps Run Java apps Execute Java bytecode
Contains JRE + Dev tools JVM + libraries Execution engine only
Used by Developers End-users & developers JVM is part of JRE
Includes javac, javadoc, etc. JVM, class libraries Class loader, executor

Java Program Execution Flow (Architecture)

1. Source Code: Hello.java


2. Compilation:
o Java source file is compiled using javac to bytecode (Hello.class)
3. Bytecode Execution:
o JVM loads .class file
o Verifies bytecode
o Executes using Interpreter or JIT Compiler

Diagram: Java Architecture Flow

+--------------------+
| Hello.java | ← Java Source Code
+--------------------+
|
v
+--------------------+
| javac Compiler | ← Converts to bytecode
+--------------------+
|
v
+--------------------+
| Hello.class | ← Bytecode
+--------------------+
|
v
+-----------------------------+
| JVM (Java Virtual Machine) |
| ┌───────────────────────┐ |
| | Class Loader ||
| | Bytecode Verifier | |
| | Execution Engine ||
| | └─ Interpreter / JIT | |
| └───────────────────────┘ |

Java/Sem-3/Module-1/BCA
Setting Up Java Environment

To write and run Java programs, we need to install and configure the Java development
tools.

Step-by-Step Setup:

Download and Install JDK:

 Go to: https://www.oracle.com/java/technologies/javase-downloads.html
 Download the latest JDK (e.g., JDK 21).
 Follow installation instructions for your OS (Windows/Linux/Mac).

Set Environment Variables (Windows):

 JAVA_HOME: Set it to the JDK installation path.


Example: C:\Program Files\Java\jdk-21
 Add to PATH:
Add: %JAVA_HOME%\bin

Verify Installation:

Open Command Prompt or Terminal and type:

java -version
javac -version

You should see the installed Java versions displayed.

Basic Syntax and Structure of Java Program

A Java program is made up of classes and methods. Every Java application must have a
main() method as the entry point.

Structure of a Java Program:

// Class Declaration
public class ClassName {

// Main Method - Entry Point


public static void main(String[] args) {
// Statements to execute
System.out.println("Hello, Java!");
}
}

Java/Sem-3/Module-1/BCA
Explanation:

Part Description

public class ClassName Declares a class

public static void main Main method that is executed

String[] args Stores command-line arguments

System.out.println() Prints text to console

Writing First Java Program (Hello World)

Here is a complete and simple Java program:

Example: HelloWorld.java

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Steps to Compile and Run:

1. Save the file as HelloWorld.java


2. Open terminal/command prompt
3. Compile the program:

bash
CopyEdit
javac HelloWorld.java

This creates a file: HelloWorld.class

4. Run the program:

bash
CopyEdit
java HelloWorld

Output:

Hello, World!

Java/Sem-3/Module-1/BCA
Key Points:

 File name must match the public class name.


 Java is case-sensitive (HelloWorld ≠ helloworld).
 main() method is the starting point of every standalone Java program.
 Statements must end with a semicolon (;).
 Curly braces {} define blocks of code.

1. Data Types in Java

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

Categories of Data Types:


Type Example Size Description
Primitive int, float, char Fixed sizes Basic built-in types
Non-Primitive String, Array Varies Objects or references

🔹 Primitive Data Types

Data Type Size Default Example Use


byte 1 byte 0 byte a = 100; Small integer values
short 2 bytes 0 short s = 1000; Shorter range integers
int 4 bytes 0 int age = 25; Default integer type
long 8 bytes 0L long l = 100000L; Larger integer values
float 4 bytes 0.0f float f = 5.5f; Decimal values with less precision
double 8 bytes 0.0d double d = 9.99; Decimal values with more precision
char 2 bytes '\u0000' char c = 'A'; Single character
boolean 1 bit false boolean flag = true; True or false

Variables in Java

What is a Variable?

A variable is a name given to a memory location used to store data.It is a memory named
space.

Syntax:

dataType variableName = value;

Example:

int number = 10;

Java/Sem-3/Module-1/BCA
String name = "Alice";
float percentage = 89.5f;

Types of Variables:

Type Scope

Local Inside methods or blocks

Instance Declared in a class but outside method

Static Shared among all instances of a class

Operators in Java

Operators are special symbols that perform operations on variables and values.

Types of Operators:

Operator Type Symbols Examples Purpose


Arithmetic +-*/% Basic math operations
Relational == != > < >= <= Compare values
Logical &&. ||, ! More than one condition
Assignment = += -= *= /= %= Assign values
Increment/Decrement ++ -- Operate on a single operand
Bitwise & , | , !, <<, >> Perform at bit level
Ternary ?: Short if-else

Examples of Operators:

Arithmetic:
int a = 10, b = 5;
System.out.println(a + b); // 15
Relational:
System.out.println(a > b); // true
Logical:
System.out.println(a > b && b > 0); // true
Assignment:
a += 2; // a = a + 2
Increment:
int x = 5;
System.out.println(++x); // 6

Java/Sem-3/Module-1/BCA
Ternary:
int max = (a > b) ? a : b;
System.out.println(max);

Types of Casting:

Implicit Casting (Widening Conversion)

 Performed automatically by Java.


 Converts a smaller data type to a larger data type.

Example:

int num = 10;


double result = num; // int to double
System.out.println(result); // Output: 10.0

Explicit Casting (Narrowing Conversion)

 Must be done manually by the programmer.


 Converts a larger data type into a smaller one.

Example:

double d = 9.78;
int i = (int) d; // double to int
System.out.println(i); // Output: 9

Comments in Java

Comments are used to explain code and improve readability. They are ignored during
compilation.

Types of Comments:

Single-line Comment
// This is a single-line comment
Multi-line Comment
/*
This is a multi-line comment.
It can span multiple lines.
*/
Documentation Comment (for API docs)
/**

Java/Sem-3/Module-1/BCA
* This class prints Hello World.
*/
public class HelloWorld {
// ...
}

Input & Output in Java

Output using System.out.println()

System.out.println("Welcome to Java!");

 System.out.print(): Prints without a newline.


 System.out.println(): Prints with a newline.

Scanner Class for User Input

Java provides the Scanner class (in java.util package) for input from the user.

Example:

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.print("Enter your age: ");


int age = sc.nextInt();

System.out.println("Hello " + name + ", you are " + age + " years old.");
}
}

Common Scanner Methods:

Method Description Example

next() Reads a single word sc.next();

nextLine() Reads an entire line sc.nextLine();

Java/Sem-3/Module-1/BCA
Method Description Example

nextInt() Reads an integer sc.nextInt();

nextDouble() Reads a double sc.nextDouble();

nextBoolean() Reads a boolean (true/false) sc.nextBoolean();

Output Formatting

Java supports formatting using printf() and String.format().

Example: System.out.printf()

double price = 123.456;


System.out.printf("Price: %.2f\n", price); // Output: Price: 123.46

Format Specifiers:

Specifier Description

%d Integer

%f Floating-point number

%s String

%.2f Two decimal places

\n Newline

\t Tab

Control Statements in Java

Control statements manage the flow of execution in a Java program. They include:

 Decision-making statements
 Looping statements
 Jumping statements

Decision-Making Statements

Java/Sem-3/Module-1/BCA
a) if Statement

Used to execute a block of code if a specified condition is true.

int x = 10;
if (x > 0) {
System.out.println("Positive number");
}

b) if-else Statement

Executes one block if the condition is true, another if false.

int x = -5;
if (x >= 0) {
System.out.println("Positive");
} else {
System.out.println("Negative");
}

c) else-if Ladder

Tests multiple conditions in sequence.

int marks = 75;


if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 60) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}

d) switch-case Statement

Selects one block of code to run based on a variable’s value.

int day = 3;
switch(day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Invalid Day");
}

Java/Sem-3/Module-1/BCA
🔸 switch works with int, byte, short, char, String (since Java 7).

Looping Constructs in Java

Loops are used to execute a block of code repeatedly until a condition is false.

a) for Loop

Used when the number of iterations is known.

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


System.out.println("i = " + i); }

b) while Loop

Used when the number of iterations is not known and condition is checked before the loop
runs.

int i = 1;

while (i <= 5) {
System.out.println(i);
i++;
}

c) do-while Loop

Executes the code block once before checking the condition.

int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);

Useful when the loop body must execute at least once.

Jumping Statements

Used to alter the normal flow of loops or methods.

a) break Statement

Terminates the loop or switch block immediately.

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


if (i == 5) break;

Java/Sem-3/Module-1/BCA
System.out.println(i); // Outputs 1 to 4
}

b) continue Statement

Skips the current iteration and continues with the next loop cycle.

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


if (i == 3) continue;
System.out.println(i); // Skips 3
}

c) return Statement

Exits from the current method and optionally returns a value.

public static int square(int n) {


return n * n;
}

Summary Table:

Statement Use
if Single condition check
if-else Two-way branching
else-if Multiple condition checks
switch Multi-way branching (fixed cases)
for Definite loop
while Indefinite loop (entry check)
do-while Indefinite loop (exit check)
break Exits loop/switch
continue Skips to next iteration
return Exits a method

**************************Thank You********************************

Java/Sem-3/Module-1/BCA

You might also like