0% found this document useful (0 votes)
13 views15 pages

Java Object-Oriented Programming Guide

Uploaded by

av4567874
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)
13 views15 pages

Java Object-Oriented Programming Guide

Uploaded by

av4567874
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

Module: 01

Introduction: -
Introduction to Object Oriented Programming Concept: -
Object-Oriented Programming (OOP) in Java is a way of organizing code into "objects" that represent
real-world things. Each object has data (attributes) and actions (methods). The main ideas in OOP are
Encapsulation (hiding details), Abstraction (simplifying complex systems), Inheritance (sharing traits),
and Polymorphism (using the same action in different ways). These concepts help make code easier
to manage, reuse, and improve over time.

Object Oriented Programming Paradigm: -


The Object-Oriented Programming (OOP) paradigm in Java is a way of designing and writing code
using objects. Objects are like real-world things with data (called attributes) and actions (called
methods).

Classes: -
A class is like a blueprint or template for creating objects. It defines the properties (called attributes)
and actions (called methods) that the objects created from that class will have.

For example, a class called Car might have attributes like color and speed, and methods like start()
and stop(). When you create a Car object, it will have those properties and can perform those
actions.

In simple terms, a class is the plan, and objects are the actual things made from that plan.

Abstraction: -
Simplifying complex systems by focusing on important features.

Encapsulation: -
Hiding the details and showing only necessary parts.

Inheritance: -
Allowing new classes to use features of existing ones.

Polymorphism: -
Allowing one action to behave in different ways.

Introduction of Java: -
Java History: -
Java was created in 1991 by James Gosling and his team at Sun Microsystems. Initially, it was called
Oak and was designed for interactive television. Later, it was renamed Java in 1995. Java became
popular because it allowed developers to write code once and run it anywhere because of JVM. In
2010, Oracle Corporation bought Sun Microsystems and took over Java. Today, Java is used to build
everything from websites to mobile apps.

JDK Directory Structure: -


The JDK (Java Development Kit) directory structure contains various folders and files that help you
develop, compile, and run Java programs.

Java Features: -
Platform-Independent: Java can run on any device or operating system because it uses the Java
Virtual Machine (JVM) to run code. This means you can write code once and run it anywhere.

Object-Oriented: Java organizes code into objects that represent real-world things, making it easier
to manage and reuse code.

Simple: Java is easy to learn and use, with a clear syntax and a strong focus on readability.

Secure: Java has built-in security features like a strong memory management system and protection
against viruses, making it a safe choice for web and mobile apps.

Multithreaded: Java can run multiple tasks at the same time (multithreading), making it efficient for
handling complex or large programs.

Distributed: Java supports building networked applications that can work across multiple computers,
making it ideal for internet-based software.

High Performance: Java has features like Just-In-Time (JIT) compilation that improve performance,
even though it is an interpreted language.

Rich API: Java comes with a large set of built-in libraries for various tasks like networking, file
handling, and user interface development.

Portable: Java code can be moved across different platforms without changes, thanks to its
platform-independent design.
Structure of Java Program: -
Elements that are included in the structure of Java Program.

●​ Documentation Section
●​ Package Declaration
●​ Import Statements
●​ Interface Section
●​ Class Definition
●​ Class Variables and Variables
●​ Main Method Class
●​ Methods and Behaviours

Compiling and Interpreting Applications: -


How Java Works: Compilation + Interpretation

1.​ Compilation: Java source code (.java) → Bytecode (.class) using javac.

2.​ Interpretation: JVM reads the bytecode and executes it on any platform.

Why Java Uses Both?

●​ Compilation makes Java fast because it converts code into bytecode before running.

●​ Interpretation allows Java to be platform-independent, as the bytecode can be run on any


system with a JVM.

Example:

1.​ Write the Java code in a file named [Link].


2.​ Compile the code: javac [Link]

3.​ Run the code using the JVM: java HelloWorld

Java Tokens: -
Tokens are the smallest units of a program that have meaning. They are the building blocks of a Java
program. Java has different types of tokens, and each one serves a specific purpose.

Tokens can be classified as follows-

1.​ Keywords:

●​ Reserved words that have a special meaning in Java.

●​ Examples: class, public, int, if, else, for, void, return.

2.​ Identifiers:

●​ Names given to variables, classes, methods, or other user-defined items in a program.

●​ Examples: myVariable, Car, calculateTotal.

3.​ Literals:

●​ Fixed values used in the program.

●​ Examples:

o​ Integer literals: 100, 5

o​ String literals: "Hello", "World"

o​ Boolean literals: true, false

o​ Character literals: 'a', '1'

4.​ Operators:

●​ Symbols that perform operations on variables and values.

●​ Examples: +, -, *, /, =, ==, &&.

5.​ Separators (Punctuation):

●​ Symbols that help structure the code.

●​ Examples:

o​ Semicolon (;): Marks the end of a statement.

o​ Comma (,): Separates items in a list.

o​ Braces ({ }): Define the start and end of a block of code.

o​ Parentheses (( )): Used for method calls or conditions.

▪​ Dot (.): Access members of a class or object.


6.​ Comments:

●​ Text used to explain the code, which the compiler ignores.

●​ Examples:

o​ Single-line comment: // This is a comment

o​ Multi-line comment: /* This is a comment */

Data types and Variables: -


Primitive Data types: -
These are the basic types of data that Java provides. They are not objects and hold simple values.

Data Type- Size Description- Example

byte- 1 byte- small integer values- byte b = 100;

short- 2 bytes- larger integer values than byte- short s = 3000;

int- 4 bytes- Standard integer values- int x = 100000;

long- 8 bytes- Very large integer values- long l = 5000000L;

float- 4 bytes- Decimal numbers (single precision)- float f = 3.14f;

double- 8 bytes- Decimal numbers (double precision)- double d = 3.14159;

char- 2 bytes- Single character (Unicode)- char c = 'A';

boolean- 1 bit- Represents true or false values- boolean isTrue = true;

Non-Primitive Data types: -


non-primitive data types (also called reference types) store references (memory addresses) to
objects or arrays. They include:

Classes: Used to create objects. Example: Car, Student.

Interfaces: Define methods that classes must implement. Example: Runnable, Serializable.

Arrays: Collections of data elements of the same type. Example: int[], String[].
Strings: Represent sequences of characters. Example: "Hello, World!".

Operators: -
Operators are symbols that perform operations on variables and values. Java has several types of
operators.

Arithmetic Operators:

Used for basic arithmetic operations.

+: Addition, -: Subtraction, *: Multiplication, /: Division, %: Modulus (remainder)

Example:

int a = 10, b = 5;

int sum = a + b; // sum = 15

Relational Operators:

Used to compare two values.

==: Equal to, !=: Not equal to, >: Greater than, <: Less than, >=: Greater than or equal to, <=: Less
than or equal to

Example:

int x = 10, y = 5;

boolean result = x > y; // result = true

Logical Operators:

Used to combine boolean values.

&&: Logical AND, ||: Logical OR, !: Logical NOT

Example:

boolean isTrue = true, isFalse = false;

boolean result = isTrue && isFalse; // result = false

Assignment Operators:

Used to assign values to variables.

=: Assigns value, +=: Adds and assigns, -=: Subtracts and assigns, *=: Multiplies and assigns,

/=: Divides and assigns, %=: Modulus and assigns

Example:
int num = 10;

num += 5; // num = 15

Unary Operators:

Used with a single operand.

++: Increment, --: Decrement

Example:

int a = 5;

a++; // a = 6

Ternary Operator:

A shorthand for if-else statements.

condition ? value_if_true : value_if_false

Example:

int age = 20;

String result = (age >= 18) ? "Adult" : "Minor"; // result = "Adult"

Bitwise Operators:

Used for bit-level operations.

&: Bitwise AND, |: Bitwise OR, ^: Bitwise XOR, ~: Bitwise NOT, <<: Left shift, >>: Right shift

Example:

int a = 5, b = 3;

int result = a & b; // result = 1

Instanceof Operator:

Checks if an object is an instance of a specific class or subclass.

instanceof

Example:

String str = "Hello";

boolean result = str instanceof String; // result = true

Implicit Type Conversions: -


Conversion happens when type compatible destination type> source type

Byte-> short-> int-> float-> long-> double

Also called Widening Conversion.


Example-

short s=10;

int i=s;

Explicit Type Conversion: -


Also Called Type Casting or Narrowing Conversion.

Large size data into small size data.

Example-

float f=10.23f;

int i=(int)f;

We can convert (char-> number)

After converting (char-> number)-> It gives the ASCII Value of the char.

Example-

char c=’a’;

int i=c;

[Link](c); //a

[Link](i); //97

Type Promotion in Expression: -


Java automatically promotes each byte short or char operand to int when evaluating an expression.

Example-

char c1=’a’;

char c2=’b’;

Sop(c1+c2); //95

If one operand is long, float or double the whole expression is promoted to long, float or double
respectively.

Example-

int i=10;

float f =20.25f;

long l=25;

double d=30.25;

double result=i+f+l+d;
Sop(result); //85.5

Control Flow Statements: -


These statements help direct the flow of program execution based on certain conditions or loops.

The main types of control flow statements in Java are:

1.​ Decision-Making Statements (Conditional Statements)

These are used to make decisions based on certain conditions.

a.​ if statement

The if statement allows you to execute a block of code if a condition is true.

Example-

int num = 10;

if (num > 5) {

[Link]("Number is greater than 5"); }

b.​ if-else statement

The if-else statement provides an alternative action if the condition is false.

Example-

int num = 10;

if (num > 5) {

[Link]("Number is greater than 5");

} else {

[Link]("Number is less than or equal to 5");

c.​ if-else if-else ladder

This allows you to check multiple conditions.

Example-

int num = 10;

if (num > 20) {

[Link]("Number is greater than 20");

} else if (num > 10) {

[Link]("Number is greater than 10 but less than or equal to 20");

} else {
[Link]("Number is 10 or less");

d.​ switch statement

The switch statement is used when you need to select one of many blocks of code based on the
value of a variable. It's more efficient than using multiple if-else statements when dealing with
several possible values for a variable.

Example-

int day = 3;

switch (day) {

case 1:

[Link]("Monday");

break;

case 2:

[Link]("Tuesday");

break;

case 3:

[Link]("Wednesday");

break;

case 4:

[Link]("Thursday");

break;

case 5:

[Link]("Friday");

break;

case 6:

[Link]("Saturday");

break;

case 7:

[Link]("Sunday");

break;

default:

[Link]("Invalid day");
}

2.​ Looping Statements (Iterative Statements)


These allow you to repeatedly execute a block of code as long as a condition is true.

a.​ while loop

The while loop repeats a block of code as long as the condition is true.

Syntax-

Initialization;

while(condition){​
//statements;

increment/decrement;

Example-

int i = 0;

while (i < 5) {

[Link]("i = " + i);

i++;

b.​ for loop

The for loop is used when you know beforehand how many times you need to repeat a block of code.

Syntax-

for (initialization; condition; increment/decrement) {

// statements

Example-

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

[Link]("i = " + i);

c.​ do-while loop

The do-while loop is similar to the while loop, except that the condition is checked after the loop
body is executed. This guarantees that the block of code will be executed at least once.

Syntax-
Initialization;

do{

//statements;

Increment/ decrement;

}while(condition);

Example-

int i = 0;

do {

[Link]("i = " + i);

i++;

} while (i < 5);

3.​ Jump Statements (Changing the Flow)

These are used to jump out of loops or skip certain parts of a loop.

a.​ break statement

The break statement is used to terminate the current loop or switch statement.

Example-

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

if (i == 3) {

break; // Exits the loop when i equals 3

[Link]("i = " + i);

b.​ continue statement

The continue statement is used to skip the current iteration of a loop and move to the next iteration.

Example-

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

if (i == 3) {

continue; // Skips the rest of the loop when i equals 3

[Link]("i = " + i);


}

c.​ return statement

The return statement is used to exit from a method and optionally return a value.

Example-

public int add(int a, int b) {

return a + b; // Exits the method and returns the sum

Introduction to Object-Oriented Programming: -


Object: A thing that has properties (attributes) and actions (methods).

Class: A blueprint for creating objects.

Encapsulation: Hiding details and providing access only through methods.

Inheritance: Creating new classes from existing ones.

Polymorphism: Having many forms (overloading/overriding methods).

Abstraction: Hiding complexity and showing only essential features.

Input and Output Scanner: -


Input and Output (I/O) refers to the process of reading data from the user (input) and displaying
data to the user (output).

1.​ Reading Input from the User (Input)

To get data from the user in Java, we use the Scanner class. It is a part of the [Link] package, and
you need to import this package to use it.

Example-

import [Link]; // Import the Scanner class

public class Main {

public static void main(String[] args) {

// Create a Scanner object

Scanner scanner = new Scanner([Link]);

// Ask the user for input and read it

[Link]("Enter your name: ");

String name = [Link](); // Read a line of text (string)

[Link]("Enter your age: ");


int age = [Link](); // Read an integer (number)

// Display the collected input

[Link]("Hello, " + name + "!");

[Link]("You are " + age + " years old.");

// Close the scanner

[Link]();

2.​ Displaying Output (Output)

In Java, to display or print data to the user, we use the built-in [Link] object. The most common
method for displaying output is [Link]().

Example-

public class Main {

public static void main(String[] args) {

[Link]("Hello, World!"); // Prints the message and goes to the next line.

[Link]("This is ");

[Link]("Java!"); // Prints the message without going to the next line.

[Link]()-
The printf() method is used for formatted output. You can control how the information is displayed
using placeholders (like %d, %s, etc.) and specify things like the number of decimal places, alignment,
padding, etc.

●​ printf() is helpful when you want to format numbers or align text in a specific way.
●​ It allows you to specify how data should be printed, such as numbers with a specific number of
decimal places or strings with certain spacing.

Example-

public class Main {

public static void main(String[] args) {

int age = 25;

double price = 19.99;

[Link]("I am %d years old.\n", age); // %d for integers


[Link]("The price is $%.2f.\n", price); // %.2f for formatting decimals

Explanation:

●​ %d is a placeholder for an integer, so the variable age is printed as 25.

●​ %.2f is a placeholder for a floating-point number with two decimal places, so the variable
price is printed as 19.99.

You might also like