JAVA_-_UNIT_1
JAVA_-_UNIT_1
JAVA - UNIT 1
Summary of Page 1 (Unit-I: Introduction to Java)
Java 1.0 (1996): First official version. Famous for "Write Once, Run Anywhere"
capability—Java programs can run on any platform with a Java Virtual
Machine (JVM).
Java 9 and beyond: Newer versions include modularity in Java 9 and long-
term support (LTS) starting with Java 11.
Strongly Typed: Data types are strictly enforced to prevent errors at compile-
time.
Rich Standard Library: Offers a vast set of libraries for tasks like I/O,
networking, and data structures.
2. Choose an IDE: Common Java IDEs are Eclipse, IntelliJ IDEA, and NetBeans.
JAVA - UNIT 1 1
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
4. Compile and Run: Use the javac command to compile and the java command
to run the program.
Java applications don’t necessarily need a graphical user interface (GUI); they
can run without it.
Applets were popular for adding interactive content to websites, but their use
has diminished with the rise of modern web technologies.
JAVA - UNIT 1 2
Summary of Page 3 (Variables in Java)
What is a Variable?
A variable is a memory location used to store data, which can change during
program execution.
They are essentially names for reserved memory locations that can hold
different types of data.
data_type : The type of data the variable will hold (e.g., int , String ).
Example:
int age;
Example:
Method scope: Variables inside a method are accessible only within that
method (local variables).
JAVA - UNIT 1 3
3.5 Naming Conventions for Variables
Variables are case-sensitive.
Conventions:
Example:
2. Instance Variables:
Example:
int marks;
Example:
What is an Operator?
An operator is a symbol used to perform operations on variables or values.
JAVA - UNIT 1 4
1. Arithmetic Operators: Used for mathematical operations.
Example:
int a = 10;
int b = 5;
int sum = a + b; // 15
Example:
int a = 10;
a += 5; // a = a + 5; Result: a = 15
Equal to ( == ), Not equal to ( != ), Greater than ( > ), Less than ( < ), Greater
than or equal to ( >= ), Less than or equal to ( <= ).
Example:
Example:
Example:
JAVA - UNIT 1 5
Example:
int a = 5;
a++; // a becomes 6
Left Shift ( << ), Right Shift ( >> ), Unsigned Right Shift ( >>> ).
Example:
Example:
Operator Precedence
Determines the order in which operators are evaluated.
2. Non-Primitive Data Types: More complex types like arrays, classes, and
interfaces.
JAVA - UNIT 1 6
Primitive data types hold a single value and include:
1. Integer Types:
Example:
Example:
float pi = 3.14f;
double bigDecimal = 123456.789;
3. Character Type:
Example:
4. Boolean Type:
Example:
These are more complex data structures used to store multiple values or
objects.
JAVA - UNIT 1 7
int 32-bit -2^31 to 2^31-1 int i = 50000;
long l =
long 64-bit -2^63 to 2^63-1 100000L;
boolean b =
boolean 1-bit true or false true;
This table summarizes the most common primitive data types in Java along with
their size, range, and examples of usage.
What is a Token?
A token is the smallest unit in a Java program. It is the basic building block
used to write code.
They can contain alphabets, digits, $ , and _ , but cannot start with a digit
or contain spaces.
Types of literals:
JAVA - UNIT 1 8
Examples: + , , , / , = , && .
Examples:
These five token types are the foundation of all Java programs, making up the
building blocks that the Java compiler uses to interpret the code.
6.1 Keywords
Keywords are reserved words predefined by the Java language, which cannot
be used as identifiers (names for variables, methods, etc.).
Java has 50 keywords like int , float , class , static , void , etc.
Example:
JAVA - UNIT 1 9
6.2 Identifiers
Identifiers are names given to variables, methods, classes, etc.
$technoname , tech_21
(keyword).
Example:
6.3 Literals
Literals are constant values directly used in the program.
Types of literals:
JAVA - UNIT 1 10
n" is a string literal
}
Summary Table:
Term Description Example
6.4 Operators
Operators in Java are special symbols used to perform operations on
variables and values.
Types of Operators
1. Arithmetic Operators: Used for mathematical calculations.
Symbols: + , , , / , %
Examples:
int a = 10, b = 5;
int sum = a + b; // sum = 15
int difference = a - b; // difference = 5
int product = a * b; // product = 50
int quotient = a / b; // quotient = 2
int remainder = a % b; // remainder = 0
Symbols: = , += , = , = , /= , %=
Examples:
Examples:
JAVA - UNIT 1 11
int a = 10, b = 20;
boolean result1 = (a == b); // false
boolean result2 = (a < b); // true
Symbols: && , || , !
Examples:
Symbols: & , | , ^ , ~
Examples:
Symbols: ++ , - , , + , !
Examples:
int a = 10;
int increment = ++a; // a becomes 11
int decrement = --a; // a becomes 10 again
Examples:
Example:
JAVA - UNIT 1 12
int a = 10, b = 20;
int max = (a > b) ? a : b; // max = 20
Operators with higher precedence are evaluated before those with lower
precedence.
Precedence Order
Here’s a simplified list of operator precedence from highest to lowest:
1 Parentheses ()
2 Postfix Increment/Decrement ++ , --
3 Unary Increment/Decrement ++ , -- , - , + , ! , ~
5 Multiplicative *, /, %
6 Additive +, -
9 Equality == , !=
JAVA - UNIT 1 13
10 Bitwise AND &
11 Bitwise XOR ^
12 Bitwise OR `
14 Logical OR `
15 Ternary Operator ?:
16 Assignment = , += , -= ...
4.9.1 Associativity
Associativity determines the order of evaluation when two operators of the
same precedence appear in an expression.
However, some operators like the assignment operator ( = ) and the ternary
operator ( ?: ) are right-to-left associative.
17)) .
Logical && , ` `
5. DATA TYPES
JAVA - UNIT 1 14
Data types specify the type of data that can be stored in a variable, the
operations that can be performed on that data, and the size of memory
allocation.
short s =
short 16-bit -32,768 to 32,767 1000;
-9,223,372,036,854,775,808 to long l =
long 64-bit 100000L;
9,223,372,036,854,775,807
float f =
float 32-bit Single-precision floating point 3.14f;
double d =
double 64-bit Double-precision floating point 1.23;
2. Floating-point Types:
3. Character Type:
4. Boolean Type:
JAVA - UNIT 1 15
Interfaces: Abstract types that represent a contract of methods.
Summary
Understanding data types is essential for effective programming in Java. It
helps in memory management, data manipulation, and determining the
operations you can perform on different types of data. Java is a strongly
typed language, meaning variables must be declared with a data type before
they can be used.
1. Classes:
Example:
// Method
void displayInfo() {
System.out.println("Name: " + name + ", Age: "
JAVA - UNIT 1 16
+ age);
}
}
2. Interfaces:
Example:
3. Arrays:
Example:
Example:
JAVA - UNIT 1 17
Example of Non-Primitive Data Types in Java:
// Using an array
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number); // Output: 1, 2, 3,
4, 5
}
// Using a String
String message = "Welcome to Java!";
System.out.println(message); // Output: Welcome to J
ava!
}
}
This example demonstrates the use of non-primitive data types, including a class
( Person ), an array, and a string in Java. Understanding both primitive and non-
primitive data types is crucial for effective programming in Java.
6. TOKENS
Tokens are the smallest individual units of a Java program, serving as the
building blocks of the language.
6.1 Keywords
Keywords are reserved words defined by the Java language. They cannot be
used as identifiers.
Examples include:
6.2 Identifiers
JAVA - UNIT 1 18
Identifiers are names given to variables, methods, classes, and other entities.
Valid Identifiers:
Invalid Identifiers:
6.3 Literals
Literals are constant values that are directly used in the code.
Types of literals:
JAVA - UNIT 1 19
Summary
Understanding tokens is fundamental to programming in Java, as they are the
essential components that form the structure and syntax of the code.
Each token type serves a specific purpose and plays a critical role in how a
Java program is constructed and executed.
Types of Operators
1. Arithmetic Operators:
Symbols: + , , , / , %
Examples:
int a = 10, b = 5;
int sum = a + b; // sum = 15
int difference = a - b; // difference = 5
int product = a * b; // product = 50
int quotient = a / b; // quotient = 2
int remainder = a % b; // remainder = 0
2. Assignment Operators:
Symbols: = , += , = , = , /= , %=
Examples:
3. Relational Operators:
Examples:
JAVA - UNIT 1 20
4. Logical Operators:
Symbols: && , || , !
Examples:
5. Bitwise Operators:
Symbols: & , | , ^ , ~
Examples:
6. Unary Operators:
Symbols: ++ , - , , !
Examples:
7. Shift Operators:
Examples:
8. Ternary Operator:
JAVA - UNIT 1 21
Example:
Operators with higher precedence are evaluated before those with lower
precedence.
Precedence Order
Here’s a list of operator precedence from highest to lowest:
1 Parentheses ()
2 Postfix Increment/Decrement ++ , --
3 Unary Increment/Decrement ++ , -- , - , + , ! , ~
5 Multiplicative *, /, %
6 Additive +, -
JAVA - UNIT 1 22
9 Equality == , !=
11 Bitwise XOR ^
12 Bitwise OR `
14 Logical OR `
15 Ternary Operator ?:
16 Assignment = , += , -= ...
4.9.1 Associativity
Associativity determines the order of evaluation when two operators of the
same precedence appear in an expression.
However, some operators, like the assignment operator ( = ) and the ternary
operator ( ?: ), are right-to-left associative.
17)) .
Logical && , ` `
JAVA - UNIT 1 23
Data types in Java dictate the kind of data a variable can hold, the size of
memory allocated, and the operations allowed on that data.
Non-Primitive Example:
// Using a class
class Car {
String model;
int year;
}
JAVA - UNIT 1 24
// Using an array
int[] scores = {85, 90, 78}; // Non-primitive data type (a
rray)
Summary
Java's rich set of primitive and non-primitive data types provides flexibility in
handling various data requirements in programming. The choice of data type
affects how data is stored, manipulated, and processed, making it essential for
developers to choose the appropriate type for their needs.
1 Parentheses ()
2 Postfix Increment/Decrement ++ , --
3 Unary Increment/Decrement ++ , -- , - , + , ! , ~
5 Multiplicative *, /, %
6 Additive +, -
JAVA - UNIT 1 25
7 Shift << , >> , >>>
9 Equality == , !=
11 Bitwise XOR ^
12 Bitwise OR `
14 Logical OR `
15 Ternary Operator ?:
16 Assignment = , += , -= ...
Most operators are left-to-right associative, meaning they are evaluated from
left to right.
Summary of Associativity
Understanding both operator precedence and associativity is essential for
writing clear and correct expressions in Java.
Conclusion
Operator precedence and associativity are fundamental concepts in Java
programming that affect how expressions are evaluated. Mastering these
concepts will help prevent logical errors in code and enhance overall
programming skills.
JAVA - UNIT 1 26
short: 16-bit signed integer, range -32,768 to 32,767.
// Outputting Values
System.out.println("Age: " + age);
System.out.println("Year: " + year);
System.out.println("Population: " + population);
System.out.println("Distance: " + distance);
System.out.println("Value of Pi: " + pi);
System.out.println("Value of e: " + e);
System.out.println("Initial: " + initial);
System.out.println("Is Java fun? " + isJavaFun);
}
}
Conclusion
JAVA - UNIT 1 27
Understanding data types is fundamental to programming in Java, as they
dictate how data is stored, manipulated, and processed.
The example illustrates how to declare and use various primitive data types
effectively, providing a solid foundation for further Java programming
concepts.
1. Classes:
Example:
2. Interfaces:
Example:
JAVA - UNIT 1 28
}
}
3. Arrays:
Example:
4. Strings:
Example:
// Using Interface
Dog dog = new Dog();
dog.sound(); // Output: Bark
// Using Array
int[] scores = {85, 90, 78};
for (int score : scores) {
System.out.println("Score: " + score);
}
// Using String
String message = "Welcome to Java!";
System.out.println(message); // Output: Welcome to
Java!
JAVA - UNIT 1 29
}
}
Conclusion
Understanding both primitive and non-primitive data types is essential for
effective Java programming.
Non-primitive types allow for more complex data handling and organization,
enabling the creation of robust applications.
Key Takeaways
Primitive Data Types: Basic types like int , float , char , and boolean .
If Statement:
Example:
if (condition) {
// code to execute if condition is true
}
If-Else Statement:
Example:
JAVA - UNIT 1 30
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Else If Ladder:
Example:
if (condition1) {
// code if condition1 is true
} else if (condition2) {
// code if condition2 is true
} else {
// code if both conditions are false
}
Switch Statement:
Example:
switch (expression) {
case value1:
// code for value1
break;
case value2:
// code for value2
break;
default:
// code if no case matches
}
2. Looping Statements:
For Loop:
Example:
JAVA - UNIT 1 31
While Loop:
Example:
while (condition) {
// code to execute
}
Do-While Loop:
Example:
do {
// code to execute
} while (condition);
3. Jump Statements:
Break Statement:
Example:
Continue Statement:
Skips the current iteration of a loop and moves to the next iteration.
Example:
Return Statement:
Exits from the current method and returns control to the calling
method.
JAVA - UNIT 1 32
Example:
Conclusion
Control structures are fundamental for creating dynamic and functional Java
programs.
Key Takeaways
Decision-Making Statements: Determine the execution path based on
conditions.
Jump Statements: Change the flow of execution within loops and methods.
These structures are essential for implementing logic and behavior in Java
applications. Understanding how to use them will enhance your programming
skills and allow for the development of more sophisticated applications.
Syntax:
Example:
JAVA - UNIT 1 33
System.out.println(fruit); // Outputs each fruit
}
2. Nested Loops:
Example:
Common Keywords:
finally: Block of code that executes after try and catch, regardless of the
outcome.
1. Try-Catch Block:
Example:
try {
int result = 10 / 0; // This will cause an Arithmet
icException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.ge
tMessage());
}
2. Finally Block:
Example:
try {
// code that may throw an exception
JAVA - UNIT 1 34
} catch (Exception e) {
// handling exception
} finally {
System.out.println("This will always execute.");
}
3. Throwing Exceptions:
Example:
Indicates that a method may throw exceptions, allowing the calling method
to handle them.
Example:
Conclusion
Mastering control structures, loops, and exception handling is essential for
effective Java programming.
Key Takeaways
For-Each Loop: Simplifies iteration over arrays and collections.
JAVA - UNIT 1 35
7. OBJECT-ORIENTED PROGRAMMING (OOP) IN JAVA
Object-Oriented Programming (OOP) is a programming paradigm based on the
concept of "objects," which can contain data and methods. Java is a fully object-
oriented language.
Example:
// Method
void displayInfo() {
System.out.println("Model: " + model + ", Colo
r: " + color);
}
}
2. Encapsulation:
Example:
JAVA - UNIT 1 36
// Method to access private attribute
public double getBalance() {
return balance;
}
3. Inheritance:
Example:
4. Polymorphism:
JAVA - UNIT 1 37
Achieved through method overriding (runtime polymorphism) and method
overloading (compile-time polymorphism).
Method Overloading:
Example:
Method Overriding:
Example:
Conclusion
OOP is a fundamental concept in Java that enhances code organization,
reusability, and scalability.
Key Takeaways
Classes and Objects: Central to OOP; classes are blueprints for objects.
JAVA - UNIT 1 38
Inheritance: Allows code reuse by deriving new classes from existing ones.
Mastering these OOP concepts will greatly enhance your ability to design and
implement robust Java applications.
Abstract Class:
Example:
Interface:
Example:
JAVA - UNIT 1 39
interface Drawable {
void draw(); // Method signature
}
2. Composition:
Example:
class Engine {
void start() {
System.out.println("Engine starting");
}
}
class Car {
Engine engine; // Car "has-a" engine
Car() {
engine = new Engine();
}
void startCar() {
engine.start(); // Delegation
System.out.println("Car starting");
}
}
JAVA - UNIT 1 40
Encapsulate Your Data: Use private access modifiers and provide public
getters/setters.
Conclusion
Object-Oriented Programming (OOP) is a powerful paradigm in Java that
facilitates better software design through concepts like encapsulation,
inheritance, polymorphism, abstraction, and composition.
Mastery of these concepts will enable you to write more organized, reusable,
and maintainable code.
Key Takeaways
Abstraction: Hides complex implementation details.
These principles are fundamental for developing robust Java applications and for
adapting to complex software design requirements. Understanding and applying
these OOP concepts will significantly improve your programming skills in Java.
JAVA - UNIT 1 41