UNIT-I Object-Oriented Programming Updated
UNIT-I Object-Oriented Programming Updated
Introduction
1. Class: A blueprint for objects. It defines properties (attributes) and behaviors (methods)
of objects.
2. Object: An instance of a class. Objects represent real-world entities.
3. Inheritance: The mechanism by which one class can inherit properties and behaviors
from another class.
4. Polymorphism: The ability of a variable, function, or object to take multiple forms. It
allows methods to do different things based on the object it is acting upon.
5. Abstraction: Hiding complex implementation details and showing only the essential
features of the object.
6. Encapsulation: The wrapping of data (variables) and code (methods) into a single unit,
typically a class. It restricts direct access to some of an object's components.
Let's write a simple Java program that prints "Hello, World!" to the console.
java
Copy code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
3. Compile and run the program:
o Compile: javac HelloWorld.java
1. Keywords: Reserved words that have a predefined meaning in Java, such as class,
public, static, void, if, else, etc.
2. Identifiers: Names given to classes, variables, methods, etc. Identifiers must start with a
letter, underscore (_), or dollar sign ($), followed by letters, digits, underscores, or dollar
signs.
3. Literals: Fixed values assigned to variables. Java supports several types of literals
including integer, floating-point, character, string, and boolean.
4. Operators: Symbols that perform operations on variables and values, such as +, -, *, /,
=, ==, etc.
5. Separators: Characters that separate tokens in a Java program, such as ;, ,, ., (), {}, [].
6. Comments: Text in the code that is not executed. Used to explain the code. Java supports
single-line (//) and multi-line (/* ... */) comments.
Java Statements
Statements are instructions executed by the Java interpreter. They form the basic building blocks
of a Java program.
java
Copy code
int age;
double salary;
2. Expression Statements: Execute operations and assign values.
java
Copy code
age = 25;
salary = 50000.0;
3. Control Flow Statements: Control the flow of execution (e.g., if, for, while).
java
Copy code
if (age > 18) {
System.out.println("Adult");
}
4. Method Calls: Invoke methods.
java
Copy code
System.out.println("Hello, World!");
Command line arguments are parameters passed to the main method when a Java program is
executed. They are stored in the args array.
Example:
java
Copy code
public class CommandLineExample {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
}
Java provides several ways to accept user input. One common way is using the Scanner class.
Example:
java
Copy code
import java.util.Scanner;
Escape Sequences: Special characters in string literals, such as \n (new line), \t (tab),
\" (double quote), \\ (backslash).
java
Copy code
System.out.println("Hello, \nWorld!"); // prints Hello, (new line)
World!
Comments:
o Single-line comment: // This is a comment
Programming Styles
java
Copy code
public class Example {
public static void main(String[] args) {
int number = 5;
if (number > 0) {
System.out.println("Positive number");
} else {
System.out.println("Non-positive number");
}
}
}
Java Statements
Statements in Java are the building blocks of any program. They are instructions that the Java
Virtual Machine (JVM) executes.
Types of Statements
3. Control Flow Statements: Direct the flow of execution (e.g., if, for, while).
Example:
java
Copy code
int a = 10; // Declaration statement
a = a + 5; // Expression statement
System.out.println(a); // Expression statement
Compound Statements
Compound statements (also known as blocks) group multiple statements and are enclosed in
braces {}.
Example:
java
Copy code
{
int b = 20;
System.out.println(b);
}
Java programs can accept command line arguments, which are passed to the main method as a
String array.
Example:
java
Copy code
public class CommandLineExample {
public static void main(String[] args) {
for (String arg : args) {
System.out.println(arg);
}
}
}
Copy code
java CommandLineExample arg1 arg2 arg3
The Scanner class is commonly used to get user input from the console.
Example:
java
Copy code
import java.util.Scanner;
Escape Sequences
Escape sequences are special characters used in string literals to perform certain tasks.
\\: Backslash
Example:
java
Copy code
public class EscapeSequenceExample {
public static void main(String[] args) {
System.out.println("Hello,\nWorld!");
System.out.println("Tab\tSpace");
System.out.println("Backslash: \\");
System.out.println("Double quote: \"");
}
}
Comments
Comments are used to describe and explain the code. They are ignored by the compiler.
Types of Comments
3. Documentation comments: Enclosed between /** and */, used by Javadoc tool
Example:
java
Copy code
public class CommentExample {
public static void main(String[] args) {
// This is a single-line comment
System.out.println("Hello, World!"); /* This is a multi-line comment
*/
}
}
Programming Styles
Programming style refers to the conventions and best practices used to write clean, readable, and
maintainable code.
1. Naming Conventions: Use camelCase for variables and methods, PascalCase for classes.
2. Indentation: Use consistent indentation to enhance readability.
3. Code Documentation: Write comments and use Javadoc to document your code.
4. Modularization: Break down your code into small, reusable methods and classes.
Example:
java
Copy code
public class ProgrammingStyleExample {
public static void main(String[] args) {
int userAge = 25; // CamelCase for variable names
System.out.println("User age: " + userAge);
}
Javadoc
Javadoc is a tool for generating API documentation in HTML format from doc comments in the
source code.
Example:
java
Copy code
/**
* This is a Javadoc comment.
* @author John
*/
public class JavadocExample {
/**
* This method prints a greeting message.
* @param name The name to greet.
*/
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
}
Introduction
Understanding data types, variables, and operators is fundamental to writing effective Java
programs. This section covers the basics of data types, how to declare and use variables, and the
different operators available in Java.
Java is a statically-typed language, meaning all variables must be declared with a specific data
type. Data types specify the size and type of values that can be stored in variables.
Example:
java
Copy code
byte b = 100;
short s = 10000;
int i = 100000;
long l = 100000L;
float f = 10.5f;
double d = 10.5;
char c = 'A';
boolean bool = true;
Non-primitive data types (reference types) include classes, interfaces, and arrays. Examples
include String, ArrayList, and custom classes.
Example:
java
Copy code
String str = "Hello, World!";
int[] numbers = {1, 2, 3, 4, 5};
Declaration of Variables
A variable is a container for storing data values. Variables must be declared with a type before
they can be used.
Syntax:
java
Copy code
type variableName;
type variableName = value;
Example:
java
Copy code
int age;
double salary = 50000.0;
Type Casting
Type casting is converting a variable from one data type to another. There are two types of
casting in Java:
java
Copy code
int i = 100;
long l = i; // implicit casting
float f = l; // implicit casting
2. Explicit (Narrowing) Casting: Manually converting a larger type to a smaller type size.
java
Copy code
double d = 9.78;
int i = (int) d; // explicit casting
The scope of a variable is the part of the program where the variable is accessible. Java has
several types of variable scope:
1. Local Variables: Declared inside a method or block. Accessible only within that method
or block.
2. Instance Variables: Declared inside a class but outside any method. Accessible by all
methods in the class.
3. Class/Static Variables: Declared with the static keyword inside a class but outside any
method. Shared among all instances of the class.
Literal Constants: Fixed values assigned to variables. Examples include 100, 3.14, 'A',
"Hello", true.
Symbolic Constants: Variables declared as final to represent constant values.
Example:
java
Copy code
final int MAX_VALUE = 100;
The printf() method in Java allows formatted output. It is similar to the printf() function in
C.
Example:
java
Copy code
System.out.printf("Name: %s, Age: %d, Salary: %.2f", "John", 25, 30000.00);
Static Variables: Variables that are shared among all instances of a class. Declared using
the static keyword.
Static Methods: Methods that belong to the class rather than any object instance. Can be
called without creating an instance of the class.
Example:
java
Copy code
public class Example {
static int count = 0;
The final keyword is used to declare constants. A final variable's value cannot be changed
once it is initialized.
Example:
java
Copy code
final int MAX_VALUE = 100;
// MAX_VALUE = 200; // This will cause a compile-time error
Operators in Java
Operators are special symbols that perform operations on variables and values.
Arithmetic Operators
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Modulus (%)
Example:
java
Copy code
int a = 10;
int b = 5;
System.out.println("a + b = " + (a + b)); // 15
System.out.println("a - b = " + (a - b)); // 5
System.out.println("a * b = " + (a * b)); // 50
System.out.println("a / b = " + (a / b)); // 2
System.out.println("a % b = " + (a % b)); // 0
Increment (++)
Decrement (--)
Example:
java
Copy code
int x = 10;
x++; // x is now 11
x--; // x is now 10 again
Relational Operators
Equal to (==)
Not equal to (!=)
Example:
java
Copy code
int a = 10;
int b = 5;
System.out.println(a == b); // false
System.out.println(a != b); // true
System.out.println(a > b); // true
System.out.println(a < b); // false
System.out.println(a >= b); // true
System.out.println(a <= b); // false
Example:
java
Copy code
boolean a = true;
boolean b = false;
System.out.println(a && b); // false
System.out.println(a || b); // true
System.out.println(!a); // false
Example:
java
Copy code
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
System.out.println(a & b); // 0001 (1 in decimal)
System.out.println(a | b); // 0111 (7 in decimal)
System.out.println(a ^ b); // 0110 (6 in decimal)
System.out.println(~a); // 1010 (two's complement representation of -6)
System.out.println(a << 1); // 1010 (10 in decimal)
System.out.println(a >> 1); // 0010 (2 in decimal)
System.out.println(a >>> 1); // 0010 (2 in decimal)
Type Casting
Type casting is the process of converting one data type into another.
java
Copy code
int num = 10;
double d = num; // Implicit casting
System.out.println(d); // 10.0
2. Explicit Casting (Narrowing Conversion)
o Manual conversion of a larger type to a smaller type.
java
Copy code
double d = 10.5;
int num = (int) d; // Explicit casting
System.out.println(num); // 10
The scope of a variable determines where the variable can be accessed and modified.
1. Local Variables
o Declared inside a method or block.
java
Copy code
public void someMethod() {
int localVar = 5; // Local variable
System.out.println(localVar);
}
2. Instance Variables
o Declared inside a class but outside any method.
o Accessible by all methods of the class.
java
Copy code
public class Example {
int instanceVar = 10; // Instance variable
java
Copy code
public class Example {
static int staticVar = 100; // Static variable
Literal Constants
Literals are fixed values assigned to variables. They can be of different types:
java
Copy code
int num = 10; // Integer literal
char letter = 'A'; // Character literal
String text = "Hello"; // String literal
boolean flag = true; // Boolean literal
Symbolic Constants
Symbolic constants are declared using the final keyword and cannot be changed once assigned.
java
Copy code
final int MAX_VALUE = 100;
MAX_VALUE = 200; // Error: Cannot assign a value to final variable 'MAX_VALUE'
Format Specifiers
%d: Integer
%f: Floating-point number
%s: String
%c: Character
java
Copy code
int age = 25;
double salary = 50000.50;
String name = "John";
Static Variables
java
Copy code
public class Example {
static int staticVar = 0;
Static Methods
java
Copy code
public class Example {
static void display() {
System.out.println("This is a static method.");
}
Attribute final
The final keyword is used to declare constants, prevent inheritance, and prevent method
overriding.
Final Variables
java
Copy code
final int MAX_VALUE = 100;
Final Methods
java
Copy code
public class Example {
public final void display() {
System.out.println("This is a final method.");
}
}
Final Classes
Cannot be subclassed.
java
Copy code
public final class FinalClass {
// class code
}
Operators
Operators are special symbols or keywords used to perform operations on variables and values.
Java supports various types of operators:
1. Arithmetic Operators
2. Assignment Operators
3. Increment and Decrement Operators
4. Relational Operators
5. Logical Operators
6. Bitwise Operators
7. Ternary Operator
Operator precedence determines the order in which operations are performed in an expression.
Associativity determines the direction in which an expression is evaluated when operators of the
same precedence appear together.
Example:
java
Copy code
int a = 10; // assigns the value 10 to the variable a
java
Copy code
int sum = 10 + 5; // sum is 15
2. Subtraction (-): Subtracts the second operand from the first.
java
Copy code
int difference = 10 - 5; // difference is 5
3. Multiplication (*): Multiplies two operands.
java
Copy code
int product = 10 * 5; // product is 50
4. Division (/): Divides the first operand by the second.
java
Copy code
int quotient = 10 / 5; // quotient is 2
5. Modulus (%): Returns the remainder when the first operand is divided by the second.
java
Copy code
int remainder = 10 % 3; // remainder is 1
Increment and decrement operators are used to increase or decrease the value of a variable by
one.
java
Copy code
int a = 10;
int b = ++a; // a is incremented to 11, then b is assigned the
value 11
o Postfix Increment (variable++): Increments the value after the expression is
evaluated.
java
Copy code
int a = 10;
int b = a++; // b is assigned the value 10, then a is incremented
to 11
2. Decrement Operator (--): Decreases the value of a variable by one.
o Prefix Decrement (--variable): Decrements the value before the expression is
evaluated.
java
Copy code
int a = 10;
int b = --a; // a is decremented to 9, then b is assigned the
value 9
o Postfix Decrement (variable--): Decrements the value after the expression is
evaluated.
java
Copy code
int a = 10;
int b = a--; // b is assigned the value 10, then a is decremented
to 9
Here is a summary of the precedence and associativity of some common operators in Java:
Ternary Operator
The ternary operator is a shorthand for the if-else statement. It takes three operands and is used
to evaluate a boolean expression, returning one of two values based on the result.
Syntax
java
Copy code
condition ? expression1 : expression2;
condition: A boolean expression.
expression1: The value returned if the condition is true.
Example
java
Copy code
int a = 10;
int b = 20;
int max = (a > b) ? a : b; // max will be 20
System.out.println("The maximum value is " + max);
Relational Operators
Relational operators are used to compare two values. They return a boolean result ( true or
false).
==: Equal to
!=: Not equal to
Example
java
Copy code
int a = 10;
int b = 20;
Boolean logical operators are used to perform logical operations on boolean values.
!: Logical NOT
Example
java
Copy code
boolean a = true;
boolean b = false;
Short-Circuit Evaluation
Logical AND (&&) and OR (||) use short-circuit evaluation, meaning the second operand is
evaluated only if necessary.
Example
java
Copy code
int x = 5;
int y = 10;
Bitwise operators perform operations on the individual bits of integer values. They are mainly
used for low-level programming.
Example
java
Copy code
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
Practical Usage
Bitwise operators are often used in systems programming, cryptography, and situations where
performance is critical.
java
Copy code
int x = 5;
int y = 10;
boolean result = (x < y) && ((x + y) < 20) ? true : false; // true
System.out.println(result);
Control statements allow you to manage the flow of execution in a Java program. They include
conditional statements, loops, and branching statements.
Control statements enable decision-making, looping, and branching in programs, making them
more dynamic and responsive to different conditions and inputs.
Conditional Statements
If Expression
Syntax:
java
Copy code
if (condition) {
// code to be executed if condition is true
}
Example:
java
Copy code
int age = 18;
if (age >= 18) {
System.out.println("You are an adult.");
}
Nested If Expression
Syntax:
java
Copy code
if (condition1) {
// code to be executed if condition1 is true
if (condition2) {
// code to be executed if condition2 is true
}
}
Example:
java
Copy code
int number = 10;
if (number > 0) {
System.out.println("Number is positive.");
if (number % 2 == 0) {
System.out.println("Number is even.");
}
}
If-Else Expression
The if-else statement executes one block of code if the condition is true, and another block if
the condition is false.
Syntax:
java
Copy code
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Example:
java
Copy code
int age = 16;
if (age >= 18) {
System.out.println("You are an adult.");
} else {
System.out.println("You are not an adult.");
}
Ternary Operator
The ternary operator (? :) is a shorthand for the if-else statement. It takes three operands and
returns a value based on a condition.
Syntax:
java
Copy code
variable = (condition) ? valueIfTrue : valueIfFalse;
Example:
java
Copy code
int age = 18;
String message = (age >= 18) ? "You are an adult." : "You are not an adult.";
System.out.println(message);
Switch Statement
The switch statement executes one block of code from multiple options based on the value of an
expression.
Syntax:
java
Copy code
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// you can have any number of case statements
default:
// code to be executed if expression doesn't match any case
}
Example:
java
Copy code
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");
}
Iteration Statements
While Loop
The while loop repeatedly executes a block of code as long as a specified condition is true.
Syntax:
java
Copy code
while (condition) {
// code to be executed
}
Example:
java
Copy code
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Do-While Loop
The do-while loop is similar to the while loop, but it guarantees that the block of code is
executed at least once.
Syntax:
java
Copy code
do {
// code to be executed
} while (condition);
Example:
java
Copy code
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
For Loop
The for loop is used to execute a block of code a specific number of times.
Syntax:
java
Copy code
for (initialization; condition; update) {
// code to be executed
}
Example:
java
Copy code
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
The enhanced for loop is used to iterate over elements in an array or a collection.
Syntax:
java
Copy code
for (type element : array) {
// code to be executed
}
Example:
java
Copy code
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
java
Copy code
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
java
Copy code
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
System.out.println(i);
}
While Loop
The while loop repeats a block of code as long as a specified condition is true.
Syntax
java
Copy code
while (condition) {
// Code to be executed
}
Example
java
Copy code
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Do-While Loop
The do-while loop is similar to the while loop, but it guarantees that the loop body will be
executed at least once because the condition is evaluated after the loop body.
Syntax
java
Copy code
do {
// Code to be executed
} while (condition);
Example
java
Copy code
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
For Loop
The for loop is commonly used for iterating a specific number of times. It consists of three
parts: initialization, condition, and increment/decrement.
Syntax
java
Copy code
for (initialization; condition; increment/decrement) {
// Code to be executed
}
Example
java
Copy code
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Nested For Loop
A nested for loop is a for loop inside another for loop. It is used to iterate over multi-
dimensional arrays or to perform more complex iterations.
Example
java
Copy code
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i = " + i + ", j = " + j);
}
}
For-Each Loop
The for-each loop, also known as the enhanced for loop, is used to iterate over arrays or
collections.
Syntax
java
Copy code
for (type variable : array/collection) {
// Code to be executed
}
Example
java
Copy code
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
Break Statement
The break statement is used to exit from a loop or switch statement prematurely.
Example
java
Copy code
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println(i);
}
Continue Statement
The continue statement is used to skip the current iteration of a loop and continue with the next
iteration.
Example
java
Copy code
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
Both break and continue can be used to control the flow of loops effectively.
Example
java
Copy code
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
Practical Usage
Loops and control statements are fundamental tools in programming. They allow for efficient
and concise code, especially when dealing with repetitive tasks and complex logic.