0% found this document useful (0 votes)
2 views18 pages

Nme Java Ecs

The document provides an overview of Object-Oriented Programming (OOP) in Java, covering its evolution, core concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It also discusses Java's data types, variables, operators, decision-making, branching, looping, and arrays, along with inheritance types and multithreading. The content is structured into units that detail fundamental programming principles and constructs in Java.

Uploaded by

hemnath
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 views18 pages

Nme Java Ecs

The document provides an overview of Object-Oriented Programming (OOP) in Java, covering its evolution, core concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It also discusses Java's data types, variables, operators, decision-making, branching, looping, and arrays, along with inheritance types and multithreading. The content is structured into units that detail fundamental programming principles and constructs in Java.

Uploaded by

hemnath
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

UNIT I –

Fundamentals of Object-Oriented Programming in Java


1. Introduction to Java and OOP
1.1 Evolution of Programming Paradigms
Programming languages have evolved through several paradigms:
1. Procedure-Oriented Programming (POP) – Focuses on functions or procedures
that operate on data (e.g., C, Pascal).
2. Object-Oriented Programming (OOP) – Focuses on objects that combine both data
and behavior (e.g., Java, Python, C++).
As software systems grew larger, procedural approaches became harder to manage due to
complex data dependencies. OOP addressed this by introducing modular, reusable, and
scalable program structures.
1.2 Introduction to Object-Oriented Programming
Object-Oriented Programming (OOP) organizes a program as a collection of objects that
interact with one another. Each object represents a real-world entity with:
 State (data/attributes)
 Behavior (methods/functions)
Example:
A Car object has:
 Attributes: color, model, speed
 Methods: start(), stop(), accelerate()
In Java, OOP allows combining both data and methods in a single entity (the class).

2. Object-Oriented Paradigm
The Object-Oriented Paradigm represents a new way of thinking about software design.
Instead of focusing on the sequence of steps to perform a task, it models real-world entities
and their interactions.
Aspect Procedure-Oriented Programming Object-Oriented Programming
Emphasis Functions and logic Data and objects
Approach Top-down Bottom-up
Data handling Data shared globally Data hidden within objects
Modularity Based on functions Based on classes and objects
Example languages C, Pascal Java, C++, Python

3. Basic Concepts of Object-Oriented Programming


Java implements OOP through a set of core concepts:
3.1 Classes
A class is a blueprint or template for creating objects. It defines data members (fields) and
methods (functions).
Example:
class Car {
String color;
int speed;

void start() {
[Link]("Car started");
}
}
3.2 Objects
An object is an instance of a class created using the new keyword.
Car myCar = new Car();
[Link] = "Red";
[Link]();
Here, myCar is an object with its own copy of data (color, speed).
3.3 Data Abstraction
It refers to showing only essential features while hiding internal details.
Example:
When you use a Scanner object in Java, you call nextInt() without knowing how it reads input
internally.
3.4 Encapsulation
Encapsulation binds data and methods into a single unit and restricts direct access to data
using access modifiers like private and public.
class Account {
private int balance;

public void deposit(int amt) {


balance += amt;
}
}
3.5 Inheritance
It allows one class to acquire properties and methods from another class using the extends
keyword.
class Vehicle {
void run() { [Link]("Vehicle is running"); }
}

class Bike extends Vehicle {


void show() { [Link]("Bike class"); }
}
3.6 Polymorphism
Means “many forms.” A single method or operator behaves differently depending on context.
Java supports:
 Compile-time Polymorphism: Method overloading
 Runtime Polymorphism: Method overriding
class Shape {
void draw() { [Link]("Drawing shape"); }
}
class Circle extends Shape {
void draw() { [Link]("Drawing circle"); }
}
3.7 Dynamic Binding
The method to be invoked is determined at runtime.
This is implemented via method overriding and upcasting.
3.8 Message Passing
Objects interact by invoking methods of other objects (sending messages).

4. Constants, Variables, and Data Types


4.1 Constants
Constants are fixed values that cannot change during execution.
In Java, constants are declared using the final keyword.
final int MAX = 100;
4.2 Variables
Variables store data values during program execution.
Syntax:
dataType variableName = value;
Example:
int age = 25;
double salary = 52000.50;
4.3 Types of Variables
 Local variables – declared inside methods
 Instance variables – declared inside a class but outside any method
 Static variables – declared using static keyword; shared among all objects

5. Data Types in Java


Java provides strongly typed data types.
Category Type Size Example
Integer byte, short, int, long 1–8 bytes int x = 10;
Floating point float, double 4–8 bytes float a = 2.5f;
Character char 2 bytes (Unicode) char c = 'A';
Boolean boolean 1 bit boolean flag = true;
Reference arrays, classes, interfaces variable String s = "Hello";

6. Declaration and Initialization of Variables


Example:
int a = 10;
float b = 3.5f;
char ch = 'Z';
Java supports both explicit initialization and default initialization (for class-level
variables).
Type Default Value
int 0
double 0.0
boolean false
String/object null

7. Operators in Java
Operators perform specific operations on operands.
7.1 Arithmetic Operators
Operator Operation Example
+ Addition a+b
- Subtraction a-b
* Multiplication a * b
/ Division a/b
% Modulus a%b
7.2 Relational Operators
Operator Meaning Example
== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater or equal a >= b
<= Less or equal a <= b
7.3 Logical Operators
Operator Meaning Example
&& AND (x > 0 && y > 0)
|| OR (x > 0
! NOT !(x == y)
7.4 Assignment Operators
a = b;
a += 5; // a = a + 5
a -= 3;
a *= 2;
a /= 4;
7.5 Increment and Decrement Operators
a++; // post-increment
++a; // pre-increment
a--; // post-decrement
--a; // pre-decrement
7.6 Conditional Operator (Ternary Operator)
result = (a > b) ? a : b;
7.7 Bitwise Operators
Used for operations on individual bits.
Operator Description
& Bitwise AND
| Bitwise OR
^ XOR
~ Bitwise Complement
<< Left shift
Operator Description
>> Right shift
7.8 Special Operators
1. instanceof: checks whether an object is an instance of a class.
2. if (obj instanceof String) { ... }
3. dot (.) operator: used to access class members.
[Link]();

8. Summary
 Java is an object-oriented, platform-independent, and robust programming
language.
 OOP’s core principles (Encapsulation, Inheritance, Polymorphism, Abstraction) make
programs modular and reusable.
 Java supports various data types, variables, and operators for computational logic.
 The final keyword defines constants; variables can be local, instance, or static.
 Operators in Java are similar to C/C++ but include unique ones like instanceof.
UNIT II – Decision Making, Branching, and Looping in Java
1. Introduction
In programming, it’s often necessary to execute certain statements conditionally or
repeatedly.
Java provides control statements to alter the normal flow of execution:
 Decision-making statements (branching)
 Looping statements (iteration)
 Jump statements (transfer control)

2. Decision-Making (Branching) Statements


These statements allow Java programs to choose different paths of execution based on
conditions.

2.1 The if Statement


The simplest decision-making statement. It tests a condition and executes a block of code
only if the condition is true.
Syntax:
if (condition) {
// statements to execute if condition is true
}
Example:
int age = 18;
if (age >= 18) {
[Link]("Eligible to vote");
}
Flow Diagram:
Start → Condition → True → Execute if-block → Next statement

False → Next statement

2.2 The if...else Statement


Used when there are two possible outcomes — one if the condition is true and another if it is
false.
Syntax:
if (condition) {
// true block
} else {
// false block
}
Example:
int num = -5;
if (num > 0)
[Link]("Positive number");
else
[Link]("Negative number");

2.3 Nested if...else Statement


When one if or else block contains another if statement, it’s called nested if.
Example:
int a = 10, b = 20, c = 5;
if (a > b) {
if (a > c)
[Link]("A is largest");
else
[Link]("C is largest");
} else {
if (b > c)
[Link]("B is largest");
else
[Link]("C is largest");
}

2.4 The else if Ladder


Used when multiple conditions must be checked sequentially.
Syntax:
if (condition1)
statement1;
else if (condition2)
statement2;
else if (condition3)
statement3;
else
defaultStatement;
Example:
int marks = 75;
if (marks >= 90)
[Link]("Grade A");
else if (marks >= 75)
[Link]("Grade B");
else if (marks >= 50)
[Link]("Grade C");
else
[Link]("Fail");

2.5 The switch Statement


Used to select one option from multiple possible values of a variable or expression. It is an
alternative to multiple if-else statements.
Syntax:
switch (expression) {
case value1:
statements;
break;
case value2:
statements;
break;
default:
statements;
}
Example:
int day = 3;
switch (day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid day");
}
Flow Diagram:
Start → Evaluate Expression → Match Case → Execute Statements → break → End

No Match → default → End
Note: The break statement prevents “fall-through” behavior.

2.6 The Conditional (Ternary) Operator ?:


A shorthand for simple if...else logic.
Syntax:
variable = (condition) ? value_if_true : value_if_false;
Example:
int a = 10, b = 20;
int max = (a > b) ? a : b;
[Link]("Maximum = " + max);

3. Decision Making and Looping


Loops allow repetitive execution of a block of code as long as a condition holds true.
Types of Loops in Java:
1. while loop
2. do...while loop
3. for loop
4. Enhanced for loop (for arrays/collections)

3.1 The while Loop


Executes a block of code repeatedly as long as the condition is true.
Syntax:
while (condition) {
// body of loop
}
Example:
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
Flow Diagram:
Start → Condition → True → Execute body → Increment → Condition

False → Exit

3.2 The do...while Loop


The do...while loop executes the block at least once, even if the condition is false.
Syntax:
do {
// body of loop
} while (condition);
Example:
int i = 1;
do {
[Link](i);
i++;
} while (i <= 5);
Key Difference:
while checks condition before executing the loop body,
do...while checks after execution.

3.3 The for Loop


Most commonly used looping statement. It combines initialization, condition, and
increment/decrement in a single line.
Syntax:
for (initialization; condition; update) {
// body of loop
}
Example:
for (int i = 1; i <= 5; i++) {
[Link]("Count: " + i);
}
Execution Flow:
1. Initialize variable
2. Test condition
3. Execute loop body
4. Update variable
5. Repeat until condition is false

3.4 Enhanced for Loop (for-each Loop)


Simplifies iteration through arrays or collections.
Syntax:
for (datatype variable : arrayName) {
statements;
}
Example:
int[] nums = {10, 20, 30, 40};
for (int n : nums)
[Link](n);

4. Jump Statements
Jump statements transfer control unconditionally.
4.1 break Statement
Terminates a loop or switch immediately.
for (int i = 1; i <= 10; i++) {
if (i == 5)
break;
[Link](i);
}
Output:
1234

4.2 continue Statement


Skips the current iteration and jumps to the next one.
for (int i = 1; i <= 5; i++) {
if (i == 3)
continue;
[Link](i);
}
Output:
1245

4.3 return Statement


Used to exit from the current method and optionally return a value.
int sum(int a, int b) {
return a + b;
}

4.4 Labeled Loops


Java allows labeling loops to control nested iterations.
Example:
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2)
break outer;
[Link](i + " " + j);
}
}
Output:
11
12
13
21
The break outer; terminates the outer loop instead of just the inner loop.

5. Summary
 Branching statements (if, if-else, switch) control flow based on conditions.
 Loops (while, do-while, for) enable repetition of code blocks.
 Jump statements (break, continue, return) alter normal loop behavior.
 Labeled loops are used for precise control in nested iterations.
 Using loops effectively makes code shorter, modular, and efficient.

UNIT III – Arrays, Inheritance, Packages, and Multithreading in Java

1. Introduction to Arrays
An array is a collection of variables of the same type stored at contiguous memory locations.
Arrays allow storing multiple values under a single name and accessing them using an
index.
Syntax:
datatype[] arrayName;

1.1 One-Dimensional Arrays


A one-dimensional array stores elements in a single row.
Declaration:
int[] numbers;
Memory Allocation:
numbers = new int[5]; // array of size 5
Initialization:
int[] numbers = {10, 20, 30, 40, 50};
Example Program:
public class ArrayExample {
public static void main(String[] args) {
int[] nums = {5, 10, 15, 20};
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + nums[i]);
}
}
}
Output:
Element at index 0: 5
Element at index 1: 10
Element at index 2: 15
Element at index 3: 20

1.2 Two-Dimensional Arrays


A 2D array stores elements in a table-like structure (rows and columns).
Declaration:
int[][] matrix = new int[3][3];
Initialization:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Example Program:
public class TwoDArray {
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
for(int i=0;i<[Link];i++){
for(int j=0;j<matrix[i].length;j++){
[Link](matrix[i][j] + " ");
}
[Link]();
}
}
}
Output:
123
456
789

2. Inheritance
Inheritance allows one class (subclass/child) to acquire properties and behaviors of another
class (superclass/parent).
Syntax:
class ChildClass extends ParentClass { }
Types of Inheritance in Java
1. Single Inheritance: One class inherits another.
2. Multilevel Inheritance: Chain of inheritance (Grandparent → Parent → Child).
3. Hierarchical Inheritance: Multiple subclasses inherit from one parent.
4. Hybrid Inheritance: Combination of two or more types (Java supports via
interfaces).
Example Program (Single Inheritance):
class Vehicle {
void start() {
[Link]("Vehicle started");
}
}

class Car extends Vehicle {


void display() {
[Link]("Car is ready");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Car c = new Car();
[Link]();
[Link]();
}
}
Output:
Vehicle started
Car is ready

3. Packages
A package in Java is a collection of classes, interfaces, and sub-packages that group related
functionality. Packages are used for:
 Modular programming
 Avoiding naming conflicts
 Easier maintenance
3.1 Built-in Packages
 [Link].* – Utility classes (ArrayList, Scanner)
 [Link].* – Input/output classes (File, BufferedReader)
 [Link].* – Core classes automatically imported
3.2 User-Defined Packages
Steps:
1. Create a package:
package myPackage;
public class Hello {
public void display() {
[Link]("Hello from package");
}
}
2. Use the package:
import [Link];
public class TestPackage {
public static void main(String[] args) {
Hello h = new Hello();
[Link]();
}
}

4. Multithreaded Programming
Thread – A lightweight process that runs independently within a program.
4.1 Creating a Thread
Method 1: Extend Thread Class
class MyThread extends Thread {
public void run() {
[Link]("Thread running");
}
}

public class ThreadDemo {


public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]();
}
}
Method 2: Implement Runnable Interface
class MyRunnable implements Runnable {
public void run() {
[Link]("Runnable thread running");
}
}

public class ThreadDemo2 {


public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
[Link]();
}
}
4.2 Thread Lifecycle
1. New: Thread object created
2. Runnable: Ready to run, waiting for CPU
3. Running: Thread executes run()
4. Waiting/Blocked: Thread waits for resources or time
5. Terminated: Thread finishes execution
Diagram (textual):
New → Runnable → Running → Waiting → Running → Terminated
4.3 Thread Methods
 start() – begins thread execution
 run() – contains thread code
 sleep(milliseconds) – pauses thread
 join() – waits for another thread to finish
Example (Multithreading with sleep):
class MyThread extends Thread {
public void run() {
for(int i=1;i<=5;i++){
[Link]("Thread: " + i);
try { [Link](500); } catch(InterruptedException e) {}
}
}
}

public class MultiThreadDemo {


public static void main(String[] args) {
MyThread t1 = new MyThread();
[Link]();
}
}

5. Summary
 Arrays are collections of elements stored under a single name; can be 1D or 2D.
 Inheritance promotes code reuse by enabling classes to derive properties from other
classes.
 Packages provide modularity and prevent naming conflicts.
 Multithreading allows concurrent execution of tasks, improving program
performance.
 Java supports extending Thread class or implementing Runnable to create threads.

You might also like