0% found this document useful (0 votes)
2 views

Module 1 Java

Module I introduces Core Java programming, covering its history, features, architecture, and the Java Development Kit (JDK). It explains the differences between Java and C/C++, types of Java programs, and the compilation and execution process. Additionally, it discusses variables, data types, arrays, operators, control statements, and classes in Java.
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)
2 views

Module 1 Java

Module I introduces Core Java programming, covering its history, features, architecture, and the Java Development Kit (JDK). It explains the differences between Java and C/C++, types of Java programs, and the compilation and execution process. Additionally, it discusses variables, data types, arrays, operators, control statements, and classes in Java.
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/ 26

📘 Module I: Introduction to Core Java Programming ( By Santosh )

●​ History and evolution​

●​ Features of Java environment​

●​ Difference from C and C++​

●​ The Java architecture​

●​ Java Development Kit (JDK)​

●​ Types of Java programs​

●​ A sample Java program​

●​ Compilation and Execution​

●​ Variable Declaration​

●​ Data types in Java​

●​ Java Tokens​

●​ Type casting and conversion​

●​ Arrays​

●​ Operators in Java​

○​ Operators Introduction​

○​ Operator Precedence​

●​ Control Statements​

●​ Introduction to classes​

●​ Instance Variables​

●​ Class Variables​
●​ Instance Methods​

●​ Constructors​

●​ Declaring Object​

●​ Garbage Collection​

●​ Method Overloading​

●​ Constructor Overloading​

●​ this reference​

●​ Using objects in methods​

●​ Recursion​

●​ Access Modifiers​

●​ Inner Class​

Module I: Introduction to Core Java Programming

1. History and Evolution of Java

Java was developed by James Gosling and his team at Sun Microsystems in the early 1990s.
Originally named Oak, it was designed for embedded systems in consumer electronics. Later, it
was renamed to Java, inspired by Java coffee.

Key milestones:

●​ 1995: Java 1.0 released.​

●​ 2006: Java became open-source.​

●​ 2010: Oracle acquired Sun Microsystems.​

●​ Now: Java is widely used in enterprise, Android, and web applications.​


2. Features of Java

Java offers powerful features that make it highly popular:

●​ Simple: Easy syntax, similar to C++ but without complex features like pointers.​

●​ Object-Oriented: Based on real-world objects, using classes and inheritance.​

●​ Platform Independent: “Write Once, Run Anywhere” via JVM.​

●​ Secure: No pointers, bytecode verification, and security manager.​

●​ Robust: Strong type checking, exception handling, and garbage collection.​

●​ Multithreaded: Built-in support for multitasking.​

●​ Portable: Java bytecode runs on any device with JVM.​

●​ High Performance: Just-In-Time (JIT) compiler improves speed.​

●​ Distributed: Supports RMI, socket programming, and networking.​

3. Difference from C and C++


Feature Java C/C++

Platform Platform-independent Platform-dependent

Memory Automatic garbage collection Manual memory management

Inheritance Single (via class), multiple (via Multiple via class


interface)

Pointers No pointers Pointers supported

Compilation Compiles to bytecode Compiles to machine code

Object-oriented Fully OOP C++ is partially OOP, C is


procedural

4. Java Architecture

●​ Source Code (.java) → compiled by javac → Bytecode (.class)​


●​ Bytecode is executed by JVM (Java Virtual Machine)​

●​ JDK (Java Development Kit) = JVM + JRE + Tools​

●​ JRE (Java Runtime Environment) = JVM + Libraries​

Flow:​
Source Code (.java) → javac → Bytecode (.class) → java → Output

5. Java Development Kit (JDK)

The JDK provides tools for Java development:

●​ javac – Java compiler​

●​ java – Java application launcher​

●​ javadoc – Documentation generator​

●​ jdb – Debugger​

●​ jar – Archive tool​

6. Types of Java Programs

●​ Standalone Applications: Desktop-based programs​

●​ Applets (deprecated): Programs embedded in browsers​

●​ Web Applications: Using Servlets and JSP​

●​ Enterprise Applications: Large-scale using EJB​

●​ Mobile Applications: Android apps using Java​

7. Compilation and Execution


Java is a compiled and interpreted language. Unlike C/C++, Java source code is not directly
converted to machine language. Instead, it is compiled into bytecode, which is
platform-independent and executed by the Java Virtual Machine (JVM).

What is Execution in Java?

Execution is the process where the compiled bytecode (.class file) is run by the Java Virtual
Machine (JVM) to produce output.

🔷 Steps Involved in Compilation


Steps:

1.​ Write Code: MyProgram.java​

2.​ Compile: javac MyProgram.java​

3.​ Execute: java MyProgram​

Output is platform-independent due to bytecode and JVM.

What is an Array?
●​ An array is a collection of elements of the same data type stored in a contiguous
block of memory.​

●​ It allows you to store multiple values in a single variable.​

●​ Arrays have a fixed size — you must specify the size when creating the array.​

Declaring and Creating Arrays


Syntax:

dataType arrayName[] = new dataType[size];


Example:

int[] numbers = new int[5]; // array of 5 integers

This creates an array named numbers that can hold 5 integers.

Initializing Arrays
You can initialize an array at the time of declaration:

int[] numbers = {10, 20, 30, 40, 50};

Accessing Array Elements


●​ Use the index to access or change elements.​

●​ Array indices start at 0.​

int first = numbers[0]; // 10

numbers[2] = 35; // changes element at index 2 to 35

Looping Through an Array


for (int i = 0; i < numbers.length; i++) {

System.out.println(numbers[i]);

Important Points
●​ Arrays in Java are objects.​

●​ length is a property of an array (not a method).​

●​ Array size is fixed once created; to change size, create a new array.​

●​ Arrays can hold primitive types (int, char, etc.) or objects (like String).

8. Variables and Data Types

A variable is a named memory location that stores data which can be changed during program
execution.

Key Points about Variables:

●​ Must be declared before use.​

●​ Has a type that defines the kind of data it can store.​

●​ Must follow naming rules:​

○​ Start with a letter, underscore (_), or dollar sign ($)​

○​ Cannot be a keyword​

○​ Case sensitive​

●​ Variable names should be meaningful and follow camelCase convention (e.g.,


userAge).​

Variable Declaration Syntax:


dataType variableName;

Variable Initialization:

You can assign a value at the time of declaration or later:

int age = 25; // Declaration and initialization


age = 30; // Reassignment
Data Types in Java
Java is a strongly typed language, meaning every variable must have a declared type.

1. Primitive Data Types

Java has 8 primitive data types:

Data Type Size Description Example Values

byte 1 byte Small integer -128 to 127

short 2 bytes Small integer -32,768 to 32,767

int 4 bytes Default integer type -2^31 to 2^31-1

long 8 bytes Large integer Very large


numbers

float 4 bytes Single precision floating-point 3.14f

double 8 bytes Double precision floating-point 3.14159

char 2 bytes Single Unicode character 'A', 'z'

boolean 1 bit True or false true, false

2. Reference Data Types

●​ Objects and arrays.​

●​ They store references (addresses) to memory where the actual data is located.​

●​ Examples: String, Array, user-defined classes (Student, Car, etc.)​

String name = "Alice"; // Reference type


int[] numbers = {1, 2, 3};
9. Java Tokens
Tokens are the smallest meaningful units in the Java source code. When the Java compiler
reads your code, it breaks it down into tokens to understand its structure.

●​ Keywords: class, public, static, etc.​

●​ Identifiers: Names for classes, variables, methods​

●​ Literals: Constant values like 10, 'A', "hello"​

●​ Operators: +, -, *, ==, &&, etc.​

●​ Separators: (), {}, ;, [ ]​

10. Type Casting

Type Casting is the process of converting a variable from one data type to another. It’s useful
when you need to work with different types together or store data in a different format.

Types of Type Casting

1.​ Widening Casting (Implicit Casting)​

○​ Converts a smaller data type to a larger data type.​

○​ Automatically done by Java.​

○​ No risk of data loss.​

○​ Happens from lower to higher data types.​

○​ Example: int → long → float → double

Example:​

int i = 100;
double d = i; // int to double automatically
System.out.println(d); // Output: 100.0
2.​ Narrowing Casting (Explicit Casting)​

○​ Converts a larger data type to a smaller data type.​

○​ Must be done manually by the programmer.​

○​ Risk of data loss or overflow.​

○​ Use parentheses to cast.​

○​ Example: double → float → long → int

Example:​

double d = 100.04;
int i = (int) d; // Explicit cast from double to int

System.out.println(i); // Output: 100 (fractional part lost)

Operators in Java — Introduction


Operators are symbols or special characters that perform specific operations on one, two, or
more operands (variables or values) and return a result.

Why use operators?

●​ Perform calculations (like addition, subtraction)​

●​ Compare values (to make decisions)​

●​ Combine boolean expressions​

●​ Assign values​

●​ Manipulate bits

Categories of Operators in Java:


Operator Type Description Examples

Arithmetic Perform mathematical calculations +, -, *, /, %


Relational Compare two values ==, !=, <, >, <=,
>=

Logical Combine boolean expressions && (AND), `

Assignment Assign values to variables =, +=, -=, *=, /=

Unary Operate on a single operand ++, --, +, -, !

Bitwise Operate on bits (binary representation) &, `

Ternary Conditional operation (3 operands) ?:

Operator Precedence in Java


Operator Precedence defines the order in which operators are evaluated in an expression
when there are multiple operators present.

Important Points:

●​ Operators with higher precedence are evaluated before those with lower precedence.​

●​ Operators with the same precedence are evaluated based on associativity (usually left
to right).​

●​ You can always use parentheses () to override the default precedence to ensure the
desired order of evaluation.​

Precedence Table (High to Low)


Precedence Operators Associativity
Level

Highest (), [], . (method/field Left to Right


access)

Unary ++, --, +, -, ! Right to Left

Multiplicative *, /, % Left to Right

Additive +, - Left to Right


Relational <, >, <=, >= Left to Right

Equality ==, != Left to Right

Logical AND && Left to Right

Logical OR `

Ternary ?: Right to Left

Assignment =, +=, -=, etc. Right to Left

Control Statements in Java


Control statements allow you to control the flow of execution of your program — to decide
which code runs and how many times it runs.

Types of Control Statements

1. Conditional Statements

Used to perform different actions based on different conditions.

if statement

Executes a block of code if the condition is true.

if (score > 50) {


System.out.println("You passed!");
}

if-else statement

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

if (score > 50) {


System.out.println("You passed!");
} else {
System.out.println("You failed!");
}

if-else if-else ladder

Checks multiple conditions sequentially.

if (score >= 90) {


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

switch statement

Selects one of many code blocks to execute based on a 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");
}

2. Looping Statements

Execute a block of code repeatedly while a condition holds.

for loop
Used when number of iterations is known.

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


System.out.println(i);
}

while loop

Repeats while condition is true; checks condition before each iteration.

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

do-while loop

Executes the block at least once, then repeats while condition is true.

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

3. Jump Statements

Control the flow inside loops or switch cases.

●​ break: Exits the current loop or switch statement immediately.​

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


if (i == 5) break; // Loop ends when i is 5
System.out.println(i);
}

●​ continue: Skips the current iteration and jumps to the next iteration of the loop.​

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


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

●​ return: Exits from the current method and optionally returns a value.​

public int add(int a, int b) {


return a + b;
}

Classes in Java
What is a Class?

●​ A class is a blueprint or template for creating objects.​

●​ It defines attributes (variables) and behaviors (methods) that the objects created from
the class will have.​

●​ It encapsulates data for the object and methods to manipulate that data.​

Basic Syntax of a Class

public class ClassName {


// Fields (variables)
// Methods (functions)
}
Example of a Class

public class Person {


// Fields (attributes)
String name;
int age;

// Method (behavior)
void sayHello() {
System.out.println("Hello, my name is " + name);
}
}

What is an Object?
●​ An object is an instance of a class.​

●​ When a class is defined, no memory is allocated. When an object is created, memory is


allocated for that object.​

●​ Objects have state (stored in instance variables) and behavior (defined by methods).​

●​ You use objects to access the properties and behaviors defined in the class.​

Creating and Using Objects in Java


Example Class

public class Person {


String name;
int age;

void sayHello() {
System.out.println("Hello, my name is " + name);
}
}

Creating an Object

public class Main {


public static void main(String[] args) {
// Create an object of Person class
Person p1 = new Person();

// Access instance variables and set values


p1.name = "Alice";
p1.age = 30;

// Call methods on the object


p1.sayHello(); // Output: Hello, my name is Alice
}
}

Key Points About Objects


●​ Objects are created using the new keyword (except for some special cases).​

●​ Each object has its own copy of instance variables.​

●​ You can create multiple objects from the same class with different states.​

Person p2 = new Person();


p2.name = "Bob";
p2.age = 25;
p2.sayHello(); // Output: Hello, my name is Bob
Instance Variables

Definition:​
Instance variables are non-static fields defined in a class and are associated with each object
created from that class. Every object has its own copy of these variables. They represent the
state or properties of an object.

Features:

●​ Declared outside methods/constructors.​

●​ Created when an object is instantiated.​

●​ Can have default values (0, null, false, etc.).​

●​ Memory is allocated in the heap.​

Real-life Analogy:​
Think of a Student class. Each student (object) will have a different name and roll number
(instance variables).

Example:

class Student {
int rollNo;
String name;

void display() {
System.out.println("Roll No: " + rollNo + ", Name: " + name);
}
}

Class Variables (Static Variables)

Definition:​
Static variables belong to the class, not to instances of the class. They are shared across all
instances and are initialized only once.

Features:
●​ Declared using the static keyword.​

●​ Stored in method area of memory.​

●​ Can be accessed via class name or object.​

Real-life Analogy:​
If all students belong to the same college, we can declare college as a static variable.

Example:

class Student {
int rollNo;
String name;
static String college = "BBDU";

void display() {
System.out.println(rollNo + " " + name + " " + college);
}
}

Instance Methods

Definition:​
Instance methods are functions that operate on instance variables. These methods require an
object to be called and can modify the object's state.

Features:

●​ Can access both instance and static variables.​

●​ Use this to refer to the calling object.​

●​ Defined without static.​

Example:

class Student {
int marks;
void setMarks(int m) {
this.marks = m;
}

void getMarks() {
System.out.println("Marks: " + marks);
}
}

Constructors

Definition:​
A constructor is a special block of code called automatically when an object is created. It is
used to initialize instance variables.

Features:

●​ Same name as class.​

●​ No return type.​

●​ Overloaded to provide multiple initialization options.​

Types:

●​ Default constructor (no parameters).​

●​ Parameterized constructor.​

Example:

class Student {
int id;
String name;

Student(int i, String n) {
id = i;
name = n;
}
void display() {
System.out.println(id + " " + name);
}
}

Declaring Object

Definition:​
Creating an object involves allocating memory for the class instance using the new keyword.
The constructor initializes the object.

Syntax:

ClassName objName = new ClassName();

Example:

Student s1 = new Student(101, "John");

Real-life Analogy:​
Declaring an object is like creating a new account with specific details (name, ID).

Garbage Collection

Definition:​
Garbage Collection is a process by which Java automatically removes unused objects from
memory to prevent memory leaks and optimize performance.

How it works:

●​ JVM has a background thread for garbage collection.​

●​ Objects with no references are eligible for collection.​

Example:
Student s = new Student();
s = null; // Object becomes unreachable
System.gc(); // Requests garbage collection

Note: You can override the finalize() method to perform cleanup.

Method Overloading

Definition:​
Method Overloading allows defining multiple methods with the same name but different
parameter lists within the same class.

Purpose:

●​ Improves readability.​

●​ Supports polymorphism.​

●​ Allows flexibility for different input types.​

Example:

class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}

Constructor Overloading

Definition:​
Constructor Overloading is the practice of defining multiple constructors in the same class,
each with a different set of parameters.

Use Case:​
Allows object initialization in different ways.

Example:
class Student {
int id;
String name;

Student() {
id = 0;
name = "Unknown";
}

Student(int i, String n) {
id = i;
name = n;
}
}

9. this Reference

Definition:​
The this keyword is a reference variable that refers to the current object inside a class. It's
used to resolve naming conflicts between instance variables and parameters.

Uses:

●​ Refer to instance variables.​

●​ Invoke current class methods or constructors.​

●​ Pass current object as parameter.​

Example:

class Student {
int id;

Student(int id) {
this.id = id; // 'this' refers to the current object
}
}
Using Objects in Methods

Definition:​
Objects can be passed as parameters to methods or returned from methods. This enables
object interaction and modular design.

Example:

class Student {
int id;

void show(Student s) {
System.out.println("ID: " + s.id);
}
}

Usage:

●​ Comparing objects.​

●​ Performing operations on object data.​

11. Recursion

Definition:​
Recursion is the process where a method calls itself repeatedly to solve a smaller
subproblem. It must have a base condition to terminate.

Use Cases:

●​ Factorial calculation​

●​ Fibonacci series​

●​ Tree traversals​

Example:
int factorial(int n) {
if (n == 1)
return 1;
else
return n * factorial(n - 1);
}

12. Access Modifiers

Definition:​
Access Modifiers control the visibility and accessibility of classes, methods, and variables.

Types:

Modifier Clas Packag Subclas World


s e s

private Yes No No No

default Yes Yes No No

protected Yes Yes Yes No

public Yes Yes Yes Yes

Example:

public class Student {


private int id;
protected String name;
public void display() {}
}

13. Inner Class

Definition:​
An inner class is a class defined within another class. It helps logically group classes that are
only used in one place, and enhances encapsulation.

Types:
●​ Non-static inner class: Access outer class members directly.​

●​ Static nested class: Can access static members of outer class.​

●​ Local inner class: Declared inside a method.​

●​ Anonymous inner class: Class without a name used for short-term use.​

Example:

class Outer {
int x = 10;

class Inner {
void display() {
System.out.println("x = " + x);
}
}
}

You might also like