KEMBAR78
Unit 1 Java | PDF | Java (Programming Language) | World Wide Web
0% found this document useful (0 votes)
9 views47 pages

Unit 1 Java

The document provides an overview of Object-Oriented Programming (OOP) principles, including encapsulation, inheritance, polymorphism, and abstraction, with examples. It compares C++ and Java, highlighting Java's platform independence and its applications in web and mobile development. Additionally, it covers Java's environment, components, data types, operators, control flow statements, and loops, along with the Java Virtual Machine's role in executing Java programs.
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)
9 views47 pages

Unit 1 Java

The document provides an overview of Object-Oriented Programming (OOP) principles, including encapsulation, inheritance, polymorphism, and abstraction, with examples. It compares C++ and Java, highlighting Java's platform independence and its applications in web and mobile development. Additionally, it covers Java's environment, components, data types, operators, control flow statements, and loops, along with the Java Virtual Machine's role in executing Java programs.
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/ 47

UNIT–I

What is OOP?
• OOP stands for Object-Oriented Programming.
• OOP is a way of writing programs that uses objects and classes.
• Objects represent things from the real world, like cars or people, and classes
are like blueprints that describe how these objects should behave and what
they can do.
• Classes and objects are the two main aspects of object-oriented
programming.
• Everything in Java is associated with classes and objects, along with its
attributes and methods.
• Concept of OOP:
• Objects: These are real-world things in the program (e.g., a car, a dog, a
bank account).
• Classes: These are like blueprints for creating objects, defining what the
objects should have (attributes) and what they can do (methods).
Example of Class and Objects
Principles of OOP:
• Encapsulation: Hiding the details and only showing the necessary parts.
Example: You don't need to know how the engine of a car works, just how to drive
it.
• Inheritance: When one class (like Dog) takes on the properties and behaviors of
another class (like Animal).
Example: A Dog class can inherit behaviors from an Animal class, like eating or
sleeping.
• Polymorphism: The ability to use the same method name but with different
behaviors based on the object.
Example: Both a Dog and a Cat can make a sound, but the sound is different for
each (bark for dog, meow for cat).
•Abstraction: Hiding complex details and showing only the necessary features.
Example: You don’t need to know how a microwave heats food, just how to press
the buttons to use it.
C++ vs JAVA
C++ JAVA
C++ is platform-dependent. Java is platform-independent.
Java is mainly used for application programming. It is
C++ is mainly used for system programming. widely used in Windows-based, web-based,
enterprise, and mobile applications.
More complex and flexible Simpler, easier to learn
Memory Management Manual (using new/delete) Automatic (Garbage Collection)
Faster (compiled to machine code) Slower (JVM adds overhead)
Supports OOP + procedural programming Purely object-oriented
Used System programming, games, embedded Used Web apps, Enterprise apps, Android
Manual thread management Built-in support for multithreading
What is the Internet and WWW?
• The Internet is a global network of computers that are connected and
can communicate with each other.
• World Wide Web (WWW): A system of websites and web pages that
can be accessed via the internet using a web browser. It uses
technologies like HTML, CSS, and JavaScript to display content and
interact with users.
• The World Wide Web (WWW) is a collection of websites and web
pages that you can visit using a web browser like Google Chrome or
Firefox.
How Java Fits into the Internet and WWW:
• Java is a programming language that can be used to create applications
that run on the Internet or as part of a website.
1. Java Applets (Old Technology):In the past, Java Applets were small
programs written in Java that ran inside a web browser.
2. Java Servlets (For Dynamic Websites):Java Servlets are small
programs that run on web servers and respond to requests from
users on websites.
Example: When you fill out a form on a website, a Java Servlet can
process that form and give you a response (like a confirmation message).
3. JavaServer Pages (JSP):JSP lets you create web pages that combine
Java code with HTML, allowing you to create dynamic web pages that
can change based on user input.
Example: A website showing your personalized information (like your
name or preferences) based on what you’ve entered earlier.
4. Java and Mobile Apps (Android):
• Java is used to develop Android apps. Many of these apps connect to
the Internet to fetch data, like news updates or social media posts.
• Example: A weather app on your phone uses Java to pull the latest
weather data from a server.
5. Java and Web APIs:
• APIs let different software programs communicate over the internet.
Java is commonly used to create these APIs, allowing web applications
to exchange data.
• Example: A Java-based service might provide weather data that other
websites or apps can access.
Introduction Java
• Java is a high-level, object-oriented programming language developed by Sun Microsystems (now
owned by Oracle).
• It was designed to be platform-independent, meaning code written in Java can run on any device
that has a Java Virtual Machine (JVM).
• Key Features of Java:
• Object-Oriented: Everything in Java is treated as an object, making it modular and reusable.
• Platform-Independent: Java programs are compiled into bytecode, which can run on any platform
with a JVM.
• Robust and Secure: Java handles memory management automatically and has built-in security
features.
• Multithreaded: Java supports concurrent execution of multiple threads, enhancing performance.
• High Performance: While not as fast as C/C++, Java's performance is optimized through Just-In-
Time (JIT) compilation.
• Distributed: Java can be used to create distributed applications, supporting remote method
invocation (RMI).
Common Java Applications:
• Web Development: Java is used in server-side applications (e.g.,
Spring, Hibernate).
• Mobile Development: Android apps are often written in Java.
• Desktop Applications: GUI applications can be built with JavaFX or
Swing.
• Enterprise Solutions: Java is widely used for large-scale business
applications.
• Game Development: Some game engines are Java-based.
Components of Java
• JDK (Java Development Kit):
• The JDK is a software development kit that includes everything
needed to develop Java applications. It provides tools to compile,
debug, and run Java programs.
• Popular JDKs:
• Oracle JDK
• OpenJDK (Open-source)
• Amazon Corretto
• Adoptium (Eclipse Temurin)
Java Environment:
• The Java environment is the setup needed to write, compile, and run Java
programs. It includes several tools:
• JDK (Java Development Kit):
• For writing and compiling Java programs.
• Contains tools like the compiler (javac) and runtime (java).
• JRE (Java Runtime Environment):
• Used to run Java programs. It contains the Java Virtual Machine (JVM).
• JVM: Executes Java programs by converting bytecode into machine code.
IDE (Integrated Development Environment):
• Software like Eclipse or IntelliJ helps you write Java code faster by
providing tools like auto-complete and debugging.
How Java become Platform Independent?
Basic Hello World Java Program
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
• Class Definition: public class HelloWorld – Every Java program starts with a class. The
class name should match the file name.
• We have to save this in HelloWorld.java file as it has public class named HelloWorld.
• Main Method: public static void main(String[] args) – The main method is where the
program starts running.
• Statements: System.out.println("Hello, World!"); – This prints text to the console.
• String and System are inbuilt Java Classes.
• Classes in java are always written in Camel case.
Java Tokens
• Tokens are the smallest building blocks of a Java program. They are
like the words in a language that Java understands.
• Types of Tokens in Java:
1. Keywords : Reserved words that have special meanings in Java.
Cannot be used as variable names.
Examples: class, public, static, void, int, if, else, for, return
2. Identifiers : User-defined combination of alphanumeric characters.
Name of a variable, function, class, etc.
Rules: Must start with a letter (A-Z or a-z), $, or _ (underscore).
Cannot start with a number.
No spaces or special characters except _ or $.
Case-sensitive (Variable and variable are different).
Examples: number, main, System, sum,pi
3.Literals : Literals are fixed values directly written in the code.
• They represent the actual data that variables can hold.
4. Operators:
• Symbols used to perform operations (like addition or comparison).
• Types:
Arithmetic: +, -, *, /
Relational: ==, !=, >, <
Logical: && (AND), || (OR), ! (NOT)
Assignment: =, +=, -=
Example : int sum = 5 + 3; // '+' is an arithmetic operator
4. Strings
A sequence of characters
Example : “Darshan”, “Hi!”
5. Special Symbols : Symbols that separate code components.
Symbols that have special meaning
Example : #, $, @, %, =, :, ;
6. Comment :
Single-line: // This is a comment
Multi-line: /* This is a multi-line comment */
Java Statement
• A statement in Java is a single instruction that tells the computer to
perform an action. It can be as simple as assigning a value to a variable or
as complex as a loop that runs multiple times.
• Types of Java Statements:
1.Expression Statements : Perform calculations, assign values, or call
methods. Ends with a semicolon (;).
Output : int x = 10; // Assignment
x = x + 5; // Calculation
System.out.println(x); // Method call (Prints value)
2. Declaration Statements: Declare variables and constants.
Can include initialization.
int age = 25; // Declare and initialize
final int MAX = 100; // Declare a constant
String name = "Alice"; // Declare a string
3. Control Flow Statements: Change the flow of the program (decision-
making, loops, etc.).
• Types:
• Conditional Statements (if, else, switch)
• Looping Statements (for, while, do-while)
• Branching Statements (break, continue, return)
4. Method Call Statements: Call methods to perform tasks.
Can pass arguments and receive results.
printMessage();
JAVA virtual machine
• The Java Virtual Machine (JVM) is the engine that runs Java
programs. It acts like a translator between your Java code and the
computer’s hardware.
• Why JVM is Important:
• Platform Independence – Write Java code once and run it anywhere
(Windows, Mac, Linux).
• Memory Management – JVM handles memory allocation and
garbage collection.
• Security – JVM ensures Java programs run safely in a controlled
environment.
How JVM Works (Step by Step):
• Write Java Code – You write Java source code (.java file).
• Compile to Bytecode – The javac (Java Compiler) converts the code
into bytecode (.class file).
• Run with JVM – JVM reads the bytecode and executes it line by line.
Constants and Variables in Java
• What are Variables?
• Variables are containers that store data in Java.
• The value can change during the program's execution.
• You must declare a variable before using it.
• Should follow camelCase naming convention.
Syntax : datatype variableName = value;
Example : int age = 25; // age is a variable holding 25
age = 30; // The value of age changes to 30
What are Constants? (Symbolic Constants )
• Constants are variables whose values cannot change once assigned.
• Use the final keyword to declare a constant.
Syntax : final type CONSTANT_NAME = value;
Example : final int MAX_AGE = 100; // MAX_AGE is a constant
MAX_AGE = 120; // Error! Cannot change final variable
Data Types
Primitive Data Types & Non-Primitive(Reference) Data Types
Primitive Data Types : These are the most basic data types provided by
Java.
Non-Primitive Data Types
• These types can store complex data or multiple values.
Scope of Variables
• Scope defines where a variable can be accessed. In Java, there are
three types of scopes:
1. Local Variables : Declared inside a method, constructor, or block.
Accessible only within the block where declared.
Must be initialized before use.
Example
2. Instance Variable : Declared outside methods but inside a class.
Belongs to an object, and each object has its own copy.
Example:

3. Static Variables : Declared with the static keyword.


Shared among all objects of a class.
Example:
Type Casting in Java
• Type casting is the process of converting one data type into another.
It is essential when you need to store a value of one data type in a
variable of another data type.
Types of Type Casting : 1. Implicit Casting & 2. Explicit Casting
1.Implicit Casting : Automatically done by Java.
Converts a smaller data type to a larger data type (e.g., int to double).
No data loss occurs during widening casting.
Conversion Hierarchy :
Explicit Casting
• Manually done by the programmer.
• Converts a larger data type to a smaller data type (e.g., double to
int).
Syntax :
Operators in Java
• Arithmetic Operators
• Relational (Comparison) Operators
• Logical Operators
• Assignment Operators
• Increment & Decrement Operators
• Conditional (Ternary) Operator
• Bitwise Operators
• Special Operators
Assignment Operator
• An assignment operator is used in programming to assign a value to a
variable. It stores the value on the right side of the operator in the
variable on the left.
+= , Add and assign.
-= , Subtract and assign.
*= , Multiply and assign.
/= , Divide and assign.
%= , Modulo and assign.
Relational Operators
Relational Operators are used to check for relations like equality,
greater than, and less than. They return boolean results after the
comparison and are extensively used in looping statements as well as
conditional if-else statements. The general format is ,
== , Equal to.
!= , Not equal to.
< , Less than.
<= , Less than or equal to.
> , Greater than.
>= , Greater than or equal to.
Logical Operators
• Logical Operators are used to perform “logical AND” and “logical OR”
operations, similar to AND gate and OR gate in digital electronics.
• Conditional operators are:
• &&, Logical AND: returns true when both conditions are true.

• ||, Logical OR: returns true if at least one condition is true.

• !, Logical NOT: returns true when a condition is false and vice-versa


Conditional /Ternary Operator
• The conditional (ternary) operator is a shorthand way of writing an if-
else statement in a single line. It evaluates a condition and returns
one value if the condition is True and another if it's False.
• Syntax : condition ? if true : if false
Example : int x = 5;
int result = (x > 0) ? 1 : 0; // result = 1 if x > 0, else 0
Bitwise Operators
• Bitwise operators perform operations at the binary level (bit by bit).
They are commonly used in low-level programming, graphics,
cryptography, and optimizing algorithms.
& (Bitwise AND) – returns bit-by-bit AND of input values.
| (Bitwise OR) – returns bit-by-bit OR of input values.
^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
~ (Bitwise Complement) – inverts all bits (one’s complement).
Increment and Decrement Operators
• In Java (and many other programming languages), increment and
decrement operators are used to increase or decrease the value of a
variable by 1.
• Types of Increment/Decrement:
• ++ - Increment by 1 if X= 5 Then x++ or ++x Output : 6
• -- - Decrement by 1 if X= 5 Then x-- or --x Output :4
Expressions & its evaluation
• An expression is a combination of variables, operators, and values.
• Java follows BODMAS (operator precedence) while evaluating
expressions.
• Java follows BODMAS (Operator Precedence).
If statement
• The if statement in Java is used to make decisions based on
conditions. If the condition is true, the code inside the if block runs. If
it's false, the code is skipped.
• Simple if Statement
• Syntax :

• Example :
if-else Statement
• Runs one block if true, another if false.
Syntax:

Example :
Nested if Statements
• if inside another if for more complex conditions.
• Example :
Else if Statement (else-if Ladder )
Checks multiple conditions in sequence.
Syntax :

Example :
Loops
• Loop : A loop in programming is a control structure that allows a set of
instructions to be executed repeatedly until a specific condition is met.
It is used to automate repetitive tasks and reduce code duplication.
• Purpose of Loops
• Perform repetitive tasks efficiently.
• Traverse data structures (like arrays, lists, etc.).
• Automate processes that would otherwise require repeated code.
While Loop
• Repeats a block of code as long as a condition is true.
• Syntax : while (condition) {
// Code to execute
}

Example :
Do-While Loop
• Similar to while, but it always runs the block at least once because
the condition is checked after execution.
• Structure : do {
// Code to execute
} while (condition);
Example :
For Loop
• Use: Used when the number of iterations is known.
Structure : for (initialization; condition; increment/decrement) {
// Code to execute
}
Example :
Jumps in Loops
• Break: Exits the loop immediately.
• Continue: Skips the rest of the current iteration and goes to the next one.

• Example (Break): Continue

You might also like