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

Module 1

Uploaded by

shadow.range03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views44 pages

Module 1

Uploaded by

shadow.range03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Introduction to Java

MODULE 1

Prepared By
Prof. Bhagya S G
AI&ML Dept. ,
BIET College , Davangere
What is Java? (Brief Overview)
• Java is a high-level, object-oriented programming language developed by
Sun Microsystems.
• It is platform-independent due to its "write once, run anywhere" capability.
• Java is widely used for web, mobile, and enterprise applications.
• It features a robust standard library with built-in functions for various
tasks.
• Java uses a virtual machine (JVM) to execute bytecode across platforms.
• It emphasizes security, simplicity, and performance in software
development.
History and Evolution of Java
• Java was developed by James Gosling at Sun Microsystems in the early
1990s.
• Initially called "Oak," it was renamed "Java" in 1995 due to trademark issues.
• Java was released publicly in 1996, with version 1.0 marking its first major
release.
• Sun Microsystems was acquired by Oracle in 2010, which continues to
develop Java.
• Java has evolved through several versions, adding new features with each
update.
• Its widespread adoption spans industries from finance to gaming and mobile
applications.
Object-Oriented Paradigm in Java
• Java is built around the Object-Oriented Programming paradigm, where everything revolves around
objects and classes.
• It promotes the organization of complex software projects using reusable and maintainable structures.
• OOP in Java allows for encapsulation, inheritance, and polymorphism, providing flexibility in
designing applications.
• Objects are instances of classes, which define data attributes and methods to operate on them.
• It allows modeling of real-world entities and relationships, simplifying complex problem-solving
processes.
• Java's OOP paradigm enables better collaboration, as objects interact through clearly defined interfaces.
Two Programming Paradigms (Procedural vs
Object-Oriented)
• Procedural programming focuses on sequences of instructions executed step by step to solve a problem.
• Object-oriented programming (OOP) emphasizes the creation of objects representing real-world entities,
improving modularity.
• In procedural programming, functions are used to perform operations, while OOP uses methods inside
objects.
• OOP promotes code reusability through inheritance, unlike procedural programming's repetitive code
structures.
• Procedural programming offers simplicity for small tasks, while OOP better manages complex, large-
scale applications.
• Java's object-oriented nature provides flexibility and modular design compared to the linear approach of
procedural programming.
Abstraction in Java
• Abstraction in Java hides implementation details, exposing only essential features to simplify
software design.
• Java supports abstraction through abstract classes and interfaces, defining common behaviors
without specifying details.
• By using abstraction, developers can work with high-level functionalities without worrying about
underlying complexity.
• Abstraction allows for code modification without affecting other parts of the system, enhancing
flexibility.
• Java's abstraction enhances security by restricting access to internal data and methods of classes.
• The concept of abstraction promotes the design of user-friendly, modular, and easily understandable
software systems.
The Three OOP Principles (Encapsulation,
Inheritance, Polymorphism)
• Encapsulation binds data and methods together within a class, ensuring controlled access using access
modifiers.
• Inheritance allows a new class to acquire properties and behaviors of an existing class, promoting code
reuse.
• Polymorphism enables objects to take on different forms, allowing for method overriding and
overloading in Java.
• Encapsulation enhances security by restricting direct access to class data, enforcing proper usage of
class methods.
• Inheritance provides hierarchical structures, allowing for shared functionalities and specialized
behaviors.
• Polymorphism offers flexibility in handling different data types and method signatures using a unified
interface.
Examples of OOP Concepts in Java
• Encapsulation example: A bank account class encapsulates account number, balance, and methods for
deposit and withdrawal.
• Inheritance example: A subclass "Dog" inherits properties from a superclass "Animal," adding unique
behaviors.
• Polymorphism example: A superclass reference can point to subclass objects, allowing method
overriding in Java.
• Abstract class example: A shape class with abstract methods like draw(), implemented differently by
subclasses.
• Interface example: A class implements an interface "Flyable," defining methods for flight without
specifying how.
• Real-world example: A car class with properties like model, speed, and methods to accelerate and brake.
Blocks of Code and Lexical
Issues
Introduction to Blocks of Code (Syntax and
Use)
• A block in Java is a group of statements enclosed in curly braces `{}`.
{
int x = 10;
System.out.println(x);
}

• Blocks define scope for variables, controlling their visibility and


lifecycle.
• Blocks are used in control structures like loops and conditionals.
if (x > 5) {
System.out.println("X is greater than 5");
}
Contd.
• Blocks can be nested within other blocks to structure complex logic.
• Java executes block statements sequentially as defined by the code
structure.
• Blocks help organize code, improving readability and maintainability.
Lexical Issues (Whitespace, Identifiers, and
Literals)
• Whitespace in Java (spaces, tabs, newlines) separates tokens but is
ignored by the compiler. int x = 5; // Whitespace is ignored
int y=10; // Works the same way

• Identifiers are names for variables, methods, and classes, starting with
a letter or underscore. int myVar = 10;
String _name = "Java";

• Java literals represent constant values like numbers, characters,


booleans, or strings in code.
int num = 100; // Integer literal
char letter = 'A'; // Character literal
Contd.
• Identifiers are case-sensitive, so MyVar and myvar are different.
• Whitespace is essential for separating keywords, identifiers, and
operators.
int a=10; // Valid, but harder to read
int b = 20; // Easier to read with whitespace

• Literal values are assigned to variables directly during initialization or


in constant expressions.
Java Comments and Separators
• Comments in Java are non-executable and improve code readability and
documentation.
• Single-line comments start with '//' while multi-line comments use '/* */'.
• JavaDoc comments, starting with '/**', generate documentation for
methods and classes.
• Separators in Java include ';', '{}', '()', and '[]' for structuring code syntax.
• The semicolon ';' is used to terminate statements in Java code.
• Curly braces '{}' define code blocks for classes, methods, and control
structures.
The Java Keywords (Importance and Usage)
• Java keywords are reserved words that have predefined meanings and cannot be used as
identifiers.
• Keywords control the flow, declare classes, methods, variables, and define access
permissions.
• Some important keywords include 'class', 'void', 'public', 'if', 'for', and 'return'.
• Keywords like 'static', 'final', and 'abstract' modify classes and methods for specific
purposes.
• Keywords such as 'new' are used to create objects, while 'try-catch' is used for exception
handling.
• Keywords form the foundation of Java syntax, enabling programmers to write structured
code.
Example of Java Keywords in Code
• Java keywords define class structure, variables,
methods, and control flow within programs. public class Example {
public static void main(String[] args) {
• Example demonstrates the use of 'public', 'class', if (true) {
'static', 'void', and 'if' keywords. System.out.println("This is a Java program.");
• Keywords 'public' define access, 'class' declares }
a class, 'static' and 'void' define method }
}
properties.
• The 'if' keyword creates a conditional statement,
demonstrating how Java keywords control logic.
• Correct use of keywords is essential to maintain
proper syntax and program functionality.
Data Types and Variables
Primitive Data Types (Integers, Floating-
Point Types, Characters, Booleans)
• 'Integers' store whole numbers and include types like 'byte', 'short', 'int', and
'long'.
• 'Floating-point' types store decimal values and include 'float' and 'double'.
• 'Character' data type 'char' stores a single Unicode character.
• 'Boolean' data type represents true or false values using 'boolean'.
• Primitive types are stored directly in memory and are fixed in size.
• These types are essential for basic data handling and calculations in Java.
Variables and Scope in Java
• Variables in Java store data values and must be declared with a specific
type.
• Java supports local, instance, and class variables, each having different
lifetimes.
• 'Local variables' exist within a block and are destroyed after execution ends.
• 'Instance variables' belong to an object and are created when the object is
instantiated.
• 'Class variables' are shared across all instances of a class using the 'static'
keyword.
• Scope defines the region in the code where a variable is accessible.
Type Conversion and Casting
• 'Type conversion' automatically changes data from one type to another, such as 'int' to
'double'.
• 'Casting' explicitly converts one type to another using parentheses syntax, like '(int)'.
• Implicit type conversion happens when smaller types convert to larger ones automatically.
• Explicit casting is needed when converting larger types into smaller types, preventing data
loss.
• Casting between incompatible types results in an error unless manually specified.
• Both type conversion and casting allow flexibility when handling different data types in
Java.
Arrays in Java (1D, 2D Arrays)
• An 'array' in Java is a collection of elements, all of the same data type.
• '1D arrays' are linear structures that store elements in a single row.
int[] numbers = {1, 2, 3, 4, 5};

• '2D arrays' are grid structures, storing data in rows and columns like a
matrix. int[][] matrix = {{1, 2}, {3, 4}};

• Arrays are zero-indexed, meaning the first element is at index 0.


• Arrays in Java have a fixed size, which must be specified at the time of
creation.
• Arrays allow efficient storage and access to data in structured formats.
Type Inference with Local Variables
(Introduction)
• 'Type inference' allows the compiler to determine the variable type based on its
value.
• Introduced in Java 10, the 'var' keyword enables type inference for local variables.

var message = "Hello, World!"; // Inferred as a String


• The compiler infers the type at compile-time based on the initialization value.
• Type inference reduces boilerplate code by eliminating explicit type declarations.
• 'var' can only be used with local variables, not fields or method parameters.
• Type inference improves code readability without sacrificing type safety.
Examples of Arrays and Type Inference
• '1D array' example: Storing and accessing integer values in a single-
dimension array. int[] arr = {10, 20, 30};
System.out.println(arr[1]); // Outputs 20

• '2D array' example: Defining a 2D array to store matrix-like data.


• 'Type inference' example: Using 'var' for an inferred type based on
initialization. var count = 10; // Inferred as an int
var names = new String[] {"Alice", "Bob"}; // Inferred as
String[]

• These examples showcase arrays for structured data and type inference
for simplifying variable declarations.
Arithmetic Operators (Examples)
• Arithmetic operators perform basic mathematical operations like addition,
subtraction, multiplication, and division.
• Common operators include '+' for addition, '-' for subtraction, '*' for
multiplication, and '/' for division.
• The '%' operator calculates the remainder of a division, known as the modulus
operator.
• Unary operators like '++' (increment) and '--' (decrement) change the value of
variables by one.
• Arithmetic operators can be used
int result = 10 +with both10integers
5; // Adds and
and 5, result floating-point values.
is 15

• These operators are commonly used for calculations in loops and functions.
Relational Operators and Boolean Logical
Operators
• Relational operators compare two values and return 'true' or 'false' as a result.
• Common relational operators include '==' (equal to), '!=' (not equal to), '>' (greater
than), and '<' (less than).
• Boolean logical operators include '&&' (AND), '||' (OR), and '!' (NOT).
• '&&' evaluates to 'true' only if both operands are true, while '||' evaluates to 'true' if
either operand is true.
• '!' reverses the boolean value, turning true to false and vice versa.
• These operators are used in control flow statements like 'if' and 'while'.
Assignment Operator and Conditional (?
Operator)
• The assignment operator '=' assigns a value to a variable.
int x = 5; // Assigns 5 to variable x

• The conditional operator '? :' is a shorthand for 'if-else' statements.


int result = (x > 10) ? 100 : 50; // If x is greater than 10, result
is 100, else 50

• The left side of '=' is the variable, and the right side is the value being assigned.
• The '? :' operator evaluates a condition and returns one of two values depending
on the result.
• Assignment and conditional operators are frequently used in loops and decision-
making logic.
Operator Precedence and Parentheses Usage
• Operator precedence defines the order in which operators are evaluated in an expression.
• Operators like '*' and '/' have higher precedence than '+' and '-', meaning they are
executed first.
• Parentheses '()' can be used to override default precedence and force specific
evaluations.
int result = (2 + 3) * 4; // Parentheses ensure addition happens
before multiplication

• Without parentheses, expressions are evaluated based on precedence rules.


• Proper use of parentheses ensures clarity and correct execution of mathematical
operations.
• Using parentheses also improves code readability, especially in complex expressions.
Java’s Selection Statements (if Statement)
• The 'if' statement evaluates a boolean expression to decide whether a block of code
should execute.
• If the expression is true, the code inside the 'if' block runs.
• An 'else' statement can be added to execute code if the condition is false.
• 'else if' allows multiple conditions to be checked sequentially for different outcomes.
if (x > 10) {
System.out.println("x is greater than 10");
} else {
System.out.println("x is 10 or less");
}
• Used for decision-making based on dynamic conditions during program execution.
• The 'if' statement is foundational in controlling program flow.
Traditional switch Statement in Java
• The 'switch' statement compares an expression against multiple 'case' values.
• Each 'case' defines code to run when it matches the expression's value.
• The 'break' statement exits the switch block, preventing fall-through to other cases.
switch (day) {
case 1: System.out.println("Sunday"); break;
case 2: System.out.println("Monday"); break;
default: System.out.println("Invalid day");
}

• The 'default' case runs if no other 'case' matches the expression.


• 'switch' is useful when working with multiple discrete values like enums or
integers.
Iteration Statements (while, do-while, for)
• The 'while' loop executes repeatedly as long as the condition is true.
• The 'do-while' loop executes the block at least once before checking the condition.
do {
System.out.println(x);
x++;
} while (x < 5);

• The 'for' loop includes initialization, condition, and iteration expressions for
compact syntax. for (int i = 0; i < 5; i++) {
System.out.println(i);
}

• These loops automate repetitive tasks like processing data and performing
calculations.
For-Each Loop and Type Inference in Loops
• The 'for-each' loop simplifies iteration over arrays and collections,
automatically handling each element.
• It eliminates the need to manage loop counters and indices explicitly.
for (String name : names) {
System.out.println(name);
}

• Type inference with


for (var'var'
num :can be used
numbers) { to simplify variable declarations in loops.
System.out.println(num);
}

• 'for-each' improves code readability and reduces errors when iterating over
collections.
Using break Statement in Loops
• The 'break' statement is used to exit a loop immediately, regardless of the iteration.
• When 'break' is encountered, control jumps out of the loop and continues after it.
• Typically used to terminate a loop early based on a specific condition.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Loop terminates when i equals 5
}
System.out.println(i);
}

• It is commonly used in both 'for' and 'while' loops for conditional exits.
• 'break' is also used in 'switch' statements to exit a particular case block.
Using continue Statement
• The 'continue' statement skips the current iteration of a loop and moves to the next
iteration.
• When 'continue' is encountered, the remaining code inside the loop is not executed for
that iteration.
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // Skips the rest of the code for i = 5
}
System.out.println(i);
}

• It is useful when you want to skip certain values but continue looping.
• 'continue' works with 'for', 'while', and 'do-while' loops to control flow within iterations.
The return Statement
• The 'return' statement exits a method and optionally returns a value to
the calling method.
• In 'void' methods, 'return' simply exits the method without any value.
int add(int a, int b) {
return a + b; // Returns the sum of a and b
}

• It is often used to send results back from a method.


• 'return' can also terminate a method early, exiting at any point before
reaching the end.
Examples of Jump Statements in Java
• 'break', 'continue', and 'return' are examples of jump statements that alter the flow of
execution.
• 'break' exits a loop or switch, stopping execution at a specific condition.
• 'continue' skips the rest of the loop's current iteration, moving to the next iteration.
• 'return' exits a method and can return a value to the method's caller.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Example of break
}
}

• These jump statements provide control over the flow of loops and methods in Java.
Understanding Nested Loops
• Nested loops are loops inside other loops, allowing multiple levels of iteration.
• The outer loop controls the number of complete iterations of the inner loop.
• The inner loop completes all its iterations for each iteration of the outer loop.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}

• Useful for working with multidimensional arrays or complex problem-solving tasks.


• Be cautious with nested loops as they can increase time complexity.
Using Type Inference in Loops
• Type inference allows the compiler to determine the variable type
automatically in loops.
• The 'var' keyword introduced in Java 10 enables type inference in loops.
var numbers = List.of(1, 2, 3);
for (var number : numbers) {
System.out.println(number); // 'var' infers the type as Integer
}

• It simplifies the code by reducing explicit type declarations.


• Type inference makes the code cleaner and easier to maintain without
sacrificing type safety.
Examples of Nested Loops in Java
• Nested loops are used to process elements in multidimensional arrays or
structures.
int[][] matrix = {{1, 2}, {3, 4}};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.println(matrix[i][j]); // Outputs each element of
the 2D array
}
}
• They allow iterating through multiple dimensions, such as rows and columns of a
table.
• Proper use of nested loops is essential for maintaining performance and
readability.
Advanced Iteration Techniques (For-Each with Local
Variable Type Inference)
• The 'for-each' loop allows simple iteration over collections and arrays without
needing explicit indices.
• 'var' can be used in 'for-each' loops to automatically infer the type of each element.

var names = List.of("Alice", "Bob");


for (var name : names) {
System.out.println(name); // 'var' infers String type
}

• This combination reduces boilerplate code and simplifies loop declarations.


• Advanced iteration techniques make code more readable, efficient, and easier to
write.
Best Practices for Control Statements
• Keep control statements simple and clear for better readability and
maintainability.
• Always use braces '{}' even for single-line 'if', 'else', and loop statements.
• Avoid deeply nested control structures to prevent complex and hard-to-read code.
• Use 'switch' statements when working with multiple discrete values instead of
numerous 'if-else' blocks.
• Ensure conditions in loops and 'if' statements are necessary and meaningful to
avoid unnecessary checks.
• Comment on complex control logic to explain its purpose and behavior.
Best Practices for Operator Usage
• Use parentheses '()' to explicitly define operation precedence and avoid ambiguity.
• Avoid using the '==' operator for object comparison; instead, use '.equals()' for
reference types.
• Be cautious with floating-point arithmetic due to potential precision loss with
'double' and 'float'.
• Use the '++' and '--' operators wisely to maintain clear and predictable code
behavior.
• Rely on the ternary ('? :') operator only when it simplifies code, avoiding
excessive nesting.
• Follow proper operator precedence rules to prevent unexpected results in
expressions.
Best Practices for Variables and Data Types
• Choose appropriate data types based on the requirements (e.g., 'int' for integers,
'double' for precision).
• Avoid unnecessary type casting, especially when precision loss is a concern.
• Use descriptive and meaningful variable names to make the code self-explanatory.
• Declare variables as close to their usage as possible to improve code clarity and
memory efficiency.
• Utilize 'final' for constants to enforce immutability and enhance code reliability.
• Leverage type inference ('var') when the variable type is clear from the context,
but avoid overusing it.
THANK YOU

You might also like