Unit4 1
Unit4 1
1991:
o Java was initiated as part of the Green Project by James Gosling, Mike
Sheridan, and Patrick Naughton at Sun Microsystems.
o Initially designed for embedded systems in consumer electronics.
o The original language was called Oak, named after the oak tree outside
Gosling's office.
1995:
o Oak was renamed Java after discovering that Oak was already a registered
trademark.
o Java 1.0 was officially released on May 23, 1995.
o The slogan: "Write Once, Run Anywhere" (WORA) highlighted its
platform independence.
Java 5 (2004):
o Renamed to Java SE 5.
o Introduced generics, enhanced for-loop, and annotations.
Java 6 (2006):
o Improved Web Services support and performance enhancements.
Java 7 (2011):
o Introduced try-with-resources, switch with strings, and the diamond operator.
Java 8 (2014):
o Introduced Lambda expressions, Stream API, and Date-Time API.
o Considered a revolutionary version with functional programming features.
Java 9 (2017):
o Introduced the module system (Jigsaw).
o Added JShell for REPL (Read-Eval-Print Loop).
Java 10 (2018):
o Introduced var for local variable type inference.
Java 11 (2018):
o Long-Term Support (LTS) version.
o Removed JavaFX from core distribution.
Java 12–16 (2019–2021):
o Added incremental improvements like switch expressions, records, and pattern
matching.
Java 17 (2021):
o Another LTS version, introducing sealed classes and pattern matching
enhancements.
Java 18–20 (2022–2023):
o Incremental improvements and performance enhancements.
Java 21 (2023):
o Next LTS version, with updates to virtual threads, pattern matching, and more.
5. Acquisition by Oracle
2010:
o Oracle Corporation acquired Sun Microsystems.
o Oracle continued the development of Java and introduced a new licensing
model.
Faster release cycles: Since Java 9, a new feature release occurs every 6 months.
Focus on performance, security, and modularity.
Growing adoption of GraalVM and native images for performance optimization.
1. Features of Java
Java code is compiled into bytecode that runs on any platform using the JVM (Java
Virtual Machine).
“Write Once, Run Anywhere (WORA)” principle.
1.2 Object-Oriented
Syntax is similar to C++ but eliminates complexities such as pointers and multiple
inheritance.
1.4 Secure
Provides runtime security with features like bytecode verification and security APIs.
Avoids explicit pointer manipulation.
1.5 Robust
1.6 Multithreaded
Supports concurrent execution with multiple threads using APIs like Thread and
Runnable.
1.7 Distributed
Supports dynamic class loading and integrates easily with other technologies.
1.10 Portable
2.1 Keywords
2.2 Identifiers
Rules:
2.3 Literals
2.5 Separators
Common Separators:
Symbol Purpose
{} Block of code
() Method parameter list
[] Array declaration
; End of a statement
, Separate multiple values
. Access class or object
Examples:
public class MyClass {
int[] arr = {1, 2, 3};
public void display() {
System.out.println("Hello");
}
}
2.6 Comments
Comments are used to describe code and are ignored by the compiler.
Types of Comments:
1. Single-Line Comment: //
2. Multi-Line Comment: /* */
3. Documentation Comment: /** */
Examples:
A character set is a collection of valid characters that can be used in a Java program.
Java uses the Unicode Standard to represent characters, which allows Java to support
multiple languages and platforms.
✅Unicode Basics:
Unicode: A 16-bit character encoding system that supports over 65,000 characters.
ASCII (American Standard Code for Information Interchange):
o Subset of Unicode.
o Represents characters using 7 bits (128 characters).
1. Java Keywords
Keywords are reserved words in Java that have a predefined meaning and cannot be
used for naming variables, methods, classes, or other identifiers.
Java Identifiers
Identifiers are the names assigned by the programmer to variables, classes, methods,
and objects.
They uniquely identify entities in a Java program.
Characteristics of Identifiers
Can include letters, digits, underscore (_), and dollar sign ($).
Must not start with a digit.
Cannot be a Java keyword.
Java identifiers are case-sensitive.
1. Start with a letter: Can start with A-Z, a-z, _, or $, but not with a digit.
2. Subsequent characters: Can be letters, digits, _, or $.
3. No spaces allowed: Identifiers cannot contain spaces.
4. Case-sensitive: age and Age are different identifiers.
5. Cannot be a keyword: class, int, or public cannot be used as an identifier.
Data types define the type of data that a variable can hold.
Java is a statically typed language, meaning variables must be declared before use.
Java data types are classified into:
o ✅Primitive Data Types (basic data types)
o ✅Non-Primitive Data Types (reference types)
Definition:
Primitive data types are predefined by Java and directly store simple values.
Java has 8 primitive data types, divided into four categories.
Definition:
Non-primitive data types (reference types) do not store values directly but hold
references to memory locations where data is stored.
They can be user-defined and provide more complex data structures.
Java Operators
Java operators are special symbols that perform operations on variables or values. They can be
classified into several categories based on their functionality. These operators play a crucial role in
performing arithmetic, logical, relational, and bitwise operations etc.
Example:
public class Geeks
{
public static void main(String[] args)
{
}
}
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations
on primitive and non-primitive data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
Example:
import java.io.*;
class Geeks
{
public static void main (String[] args)
{
int a = 10;
int b = 3;
String n1 = "15";
String n2 = "25";
int a1 = Integer.parseInt(n1);
int b1 = Integer.parseInt(n2);
}
}
2. Unary Operators
Unary Operators need only one operand. They are used to increment,
decrement, or negate a value.
- , Negates the value.
+ , Indicates a positive value (automatically converts byte, char,
or short to int).
++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
-- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
! , Inverts a boolean value.
Example:
import java.io.*;
class test {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;
Example:
import java.io.*;
class Test
{
public static void main(String[] args)
{
int d = 0b1010;
int e = 0b1100;
System.out.println("d & e : " + (d & e));
System.out.println("d | e : " + (d | e));
System.out.println("d ^ e : " + (d ^ e));
System.out.println("~d : " + (~d));
System.out.println("d << 2 : " + (d << 2));
System.out.println("e >> 1 : " + (e >> 1));
System.out.println("e >>> 1 : " + (e >>> 1));
}
}
8. Shift Operators
Shift Operators are used to shift the bits of a number left or right,
thereby multiplying or dividing the number by two, respectively. They
can be used when we have to multiply or divide a number by two. The
general format ,
number shift_op number_of_places_to_shift;
<< (Left shift) – Shifts bits left, filling 0s (multiplies by a power of
two).
>> (Signed right shift) – Shifts bits right, filling 0s (divides by a
power of two), with the leftmost bit depending on the sign.
>>> (Unsigned right shift) – Shifts bits right, filling 0s, with the
leftmost bit always 0.
Example:
import java.io.*;
class Geeks
{
public static void main(String[] args)
{
int a = 10;
System.out.println("a<<1 : " + (a << 1));
System.out.println("a>>1 : " + (a >> 1));
}
}
instanceof operator
The instance of operator is used for type checking. It can be used to
test if an object is an instance of a class, a subclass, or an interface.
The general format ,
object instance of class/subclass/interface
Example:
public class Geeks
{
public static void main(String[] args)
{
Example:
float num_float = 10.5;
int num_int = (int)num_float;
int_num = 5
float_num = int_num # Implicitly converts int to float
1. Java if Statement
The if statement is the most simple decision-making statement. It is
used to decide whether a certain statement or block of statements will
be executed or not i.e. if a certain condition is true then a block of
statements is executed otherwise not.
Syntax:
if(condition) {
// Statements to execute if
// condition is true
}
Here, the condition after evaluation will be either true or false. if
statement accepts boolean values – if the value is true then it will
execute the block of statements under it. If we don’t use curly braces( {}
), only the next line after the if is considered as part of the if block For
example,
if (condition) // Assume condition is true
statement1; // Belongs to the if block
statement2; // Does NOT belong to the if block
Here’s what happens:
If the condition is True statement1 executes.
statement2 runs no matter what because it’s not a part of the if block
if Statement Execution Flow
The below diagram demonstrates the flow chart of an “if Statement
execution flow” in programming.
import java.util.*;
class Geeks {
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("Inside If block");
System.out.println("10 is less than 15");
System.out.println("I am Not in if");
}
}
2. Java if-else Statement
The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But what if we
want to do something else if the condition is false? Here, comes the
“else” statement. We can use the else statement with the if statement
to execute a block of code when the condition is false.
Syntax:
if(condition){
// Executes this block if
// condition is true
}else{
// Executes this block if
// condition is false
}
if-else Statement Execution flow
The below diagram demonstrates the flow chart of an “if-else Statement
execution flow” in programmin
import java.util.*;
class Geeks {
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
class Geeks {
public static void main(String args[])
{
int i = 10;
if (i == 10 || i < 15) {
if (i < 15)
System.out.println("i is smaller than 15");
if (i < 12)
System.out.println(
"i is smaller than 12 too");
}
else {
System.out.println("i is greater than 15");
}
}
}
4. Java if-else-if ladder
Here, a user can decide among multiple options.The if statements are
executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that ‘if’ is
executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed. There
can be as many as ‘else if’ blocks associated with one ‘if’ block but only
one ‘else’ block is allowed with one ‘if’ block.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
if-else-if ladder Execution Flow
The below diagram demonstrates the flow chart of an “if-else-if ladder
execution flow” in programming
import java.util.*;
class Geeks {
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Java Switch Case
The switch statement is a multiway branch statement. It provides an
easy way to dispatch execution to different parts of code based on the
value of the expression.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// more cases…
default:
// code to be executed if no cases match
}
switch Statements Execution Flow
The below diagram demonstrates the flow chart of a “switch Statements
execution flow” in programming.
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int num = 20;
switch (num) {
case 5:
System.out.println("It is 5");
break;
case 10:
System.out.println("It is 10");
break;
case 15:
System.out.println("It is 15");
break;
case 20:
System.out.println("It is 20");
break;
default:
System.out.println("Not present");
}
}
}
6. jump Statements
Java supports three jump statements: break, continue and return.
These three statements transfer control to another part of the program.
Break: In Java, a break is majorly used for:
class Geeks {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
import java.util.*;
public class Geeks {
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if (t)
return;
System.out.println("This won't execute.");
}
}
for loop
while loop
do...while loop
In the previous tutorial, we learned about for loop. In this tutorial, we will learn about while and
do..while loop.
while loop
The syntax of the while loop is:
while (testExpression) {
// the body of the loop
}
Java Class
A Class is a user-defined blueprint or prototype from which objects
are created. It represents the set of properties or methods that are
common to all objects of one type. Using classes, you can create
multiple objects with the same behavior instead of writing their code
multiple times. This includes classes for objects occurring more than
once in your code. In general, class declarations can include these
components in order:
Modifiers: A class can be public or have default access (Refer
to this for details).
Class name: The class name should begin with the initial letter
capitalized by convention.
Body: The class body is surrounded by braces, { }.
Java Object
An Object is a basic unit of Object-Oriented Programming that
represents real-life entities. A typical Java program creates many
objects, which as you know, interact by invoking methods. The objects
are what perform your code, they are the part of your code visible to the
viewer/user. An object mainly consists of:
State: It is represented by the attributes of an object. It also reflects
the properties of an object.
Behavior: It is represented by the methods of an object. It also
reflects the response of an object to other objects.
Identity: It is a unique name given to an object that enables it to
interact with other objects.
Method: A method is a collection of statements that perform some
specific task and return the result to the caller. A method can
perform some specific task without returning anything. Methods
allow us to reuse the code without retyping it, which is why they are
considered time savers. In Java, every method must be part of
some class, which is different from languages like C, C++,
and Python.
Example:
// Getter methods
public int getId() { return id; }
public String getName() { return name; }
}
class Main {
public static void main(String[] args) {
// Proper initialization
Student obj = new Student(28, "Geek");
// Method with parameter
obj.printStudent("Student Details:");
}
}
1. Abstraction
Data Abstraction is the property by virtue of which only the essential
details are displayed to the user. The trivial or non-essential units are
not displayed to the user. Data Abstraction may also be defined as the
process of identifying only the required characteristics of an object,
ignoring the irrelevant details. The properties and behaviors of an
object differentiate it from other objects of similar type and also help in
classifying/grouping the object.
Real-life Example: Consider a real-life example of a man driving a car.
The man only knows that pressing the accelerators will increase the car
speed or applying brakes will stop the car, but he does not know how
on pressing the accelerator, the speed is actually increasing. He does
not know about the inner mechanism of the car or the implementation
of the accelerators, brakes etc. in the car. This is what abstraction is.
Note: In Java, abstraction is achieved by interfaces and abstract
classes. We can achieve 100% abstraction using interfaces.
Example:
void brake() {
System.out.println("Car: Applying brakes...")
}
}
class Employee {
// Private fields (encapsulated data)
private int id;
private String name;
// Setter methods
public void setId(int id) {
this.id = id;
}
// Getter methods
public int getId() {
return id;
}
emp.setId(101);
emp.setName("Geek");
System.out.println("Employee ID: " + emp.getId());
System.out.println("Employee Name: " + emp.getName());
}
}
Inheritance
Inheritance is an important pillar of OOP (Object Oriented
Programming). It is the mechanism in Java by which one class is
allowed to inherit the features (fields and methods) of another class.
We are achieving inheritance by using extends keyword. Inheritance is
also known as “is-a” relationship.
Let us discuss some frequently used important terminologies:
Superclass: The class whose features are inherited is known as
superclass (also known as base or parent class).
Subclass: The class that inherits the other class is known as
subclass (also known as derived or extended or child class). The
subclass can add its own fields and methods in addition to the
superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e.
when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new
class from the existing class. By doing this, we are reusing the fields
and methods of the existing class.
// Superclass (Parent)
class Animal {
void eat() {
System.out.println("Animal is eating...");
}
void sleep() {
System.out.println("Animal is sleeping...");
}
}
// Parent Class
class Parent {
// Overloaded method (compile-time polymorphism)
public void func() {
System.out.println("Parent.func()");
}
// Child Class
class Child extends Parent {
// Overrides Parent.func(int) (runtime polymorphism)
@Override
public void func(int a) {
System.out.println("Child.func(int): " + a);
}
}
// Polymorphism in action
polymorphicObj.func(30);
}
}
Advantage of OOPs over Procedure-Oriented Programming
Language
Object-oriented programming (OOP) offers several key advantages
over procedural programming:
OOP promotes code reusability: By using objects and classes,
you can create reusable components, leading to less duplication and
more efficient development.
OOP enhances code organization: It provides a clear and logical
structure, making the code easier to understand, maintain, and
debug.
OOP supports the DRY (Don’t Repeat Yourself) principle: This
principle encourages minimizing code repetition, leading to cleaner,
more maintainable code. Common functionalities are placed in a
single location and reused, reducing redundancy.
OOP enables faster development: By reusing existing code and
creating modular components, OOP allows for quicker and more
efficient application development
What is HTML?
HTML stands for Hyper Text Markup Language
HTML is the standard markup language for creating Web pages
HTML describes the structure of a Web page
HTML consists of a series of elements
HTML elements tell the browser how to display the content
HTML elements label pieces of content such as "this is a heading", "this
is a paragraph", "this is a link", etc.
HTML Document
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>
When you move the mouse over a link, the mouse arrow will turn into a little
hand.
HTML Links - Syntax
The HTML <a> tag defines a hyperlink. It has the following syntax:
The most important attribute of the <a> element is the href attribute, which
indicates the link's destination.
The link text is the part that will be visible to the reader.
Clicking on the link text, will send the reader to the specified URL address.
Example
<a href="https://www.w3schools.com/">Visit W3Schools.com!</a>
Try it Yourself »