Notes Java
Notes Java
1. Origins (mid-1990s):
Java was developed by James Gosling and his team at Sun Microsystems (later acquired by Oracle Corporation) in the early 1990s.
It was originally designed for interactive television, but Sun Microsystems recognized its potential in the emerging internet era.
2. Introduction (1995):
Java was officially released to the public in 1995. Its slogan was "Write Once, Run Anywhere" (WORA), emphasizing its platform
independence.
Java's ability to run on any device with the Java Virtual Machine (JVM) made it particularly attractive for web development and other cross-
platform applications.
3. Evolution of the Java Platform:
a. J2SE (Java 2 Platform, Standard Edition): Introduced in December 1998, it brought significant enhancements and new
features, including Swing GUI toolkit, JDBC (Java Database Connectivity), and more.
b. J2EE (Java 2 Platform, Enterprise Edition): Aimed at enterprise applications, it provided tools and APIs for building
large-scale, distributed applications.
c. J2ME (Java 2 Platform, Micro Edition): Tailored for mobile and embedded devices, it enabled developers to create
applications for devices with limited resources.
4. Major Releases:
a. Java 5 (2004): Introduced generics, metadata annotations, enumerated types, and the enhanced for loop.
b. Java 6 (2006): Focus on performance improvements, including faster startup time and lower memory consumption.
c. Java 7 (2011): Introduces features like the try-with-resources statement, diamond operator, and improvements to the
concurrency API.
d. Java 8 (2014): A major release introducing lambda expressions, the Stream API, and the java.time package for
date/time manipulation.
e. Java 9 (2017): Introduces the module system (Project Jigsaw), enhancing scalability, maintainability, and
performance.
f. Java 10 (2018): Introduced local variable type inference (var), enhancing developer productivity.
g. Java 11 (2018): Long-term support (LTS) release with updates including HTTP client API and improvements to the
garbage collector.
h. Java 12-17 (2019-2021): Continued incremental updates with new features and improvements, including switch
expressions, text blocks, and records.
7. Future Directions:
Oracle and the Java community continue to work on evolving the Java platform, with ongoing efforts to improve performance, security, and
developer productivity.
JVM:
Installing Java Development Kit (JDK):
Installing the Java Development Kit (JDK) typically involves a few straightforward steps. Here's a general guide:
For example, on Windows, you may need to set the JAVA_HOME environment variable to point to the directory where the JDK is
installed, and add the JDK's bin directory to the system's PATH variable.
These commands should display the version numbers of the Java runtime and compiler, respectively, indicating that the JDK is installed and
configured correctly.
2. Method Names:
Start with a lowercase letter.
Use verbs or verb phrases, and capitalize the first letter of each word thereafter.
Follow camelCase convention.
Example: calculateSalary(), printDetails(), getUserInput().
3. Variable Names:
Start with a lowercase letter.
Use meaningful names that describe the variable's purpose.
Follow camelCase convention.
Example: firstName, totalAmount, numberOfStudents.
4. Constant Names:
Use uppercase letters.
Separate words with underscores.
Example: MAX_VALUE, PI, DEFAULT_TIMEOUT.
5. Package Names:
Use lowercase letters.
Use a reversed domain name to prevent naming conflicts.
Example: com.example.myproject, org.openai.gpt.
6. Enum Names:
Follow the same conventions as class names.
Use singular nouns or noun phrases.
Example: DayOfWeek, Color.
7. Parameter Names:
Follow the same conventions as variable names.
Use meaningful names that describe the parameter's purpose.
Example: radius, numItems, username.
Data Types:
Primitive Data Types:
Primitive data types are basic data types provided by Java. They are used to store simple values.
In Java, data types are crucial for declaring variables, defining methods, and creating classes. Understanding the differences between
primitive and reference data types is fundamental for writing efficient and correct Java programs.
Local Variables: Declared within a method or a block of code. They have a limited scope and are accessible only within the block where
they are declared.
Class Variables (Static Fields): Shared among all instances of a class. There is only one copy of a class variable, regardless of how many
objects are created from the class.
Floating-Point Literals: Numbers with fractional parts. Can be specified using decimal notation.
double d = 10.5;
float f = 3.14f; // Floating-point literals are treated as double by default, so need 'f' suffix for float
` Arithmetic Operators:
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;
Relational Operators:
Greater than (>): Checks if the first operand is greater than the second.
Less than (<): Checks if the first operand is less than the second.
Greater than or equal to (>=): Checks if the first operand is greater than or equal to the second.
Less than or equal to (<=): Checks if the first operand is less than or equal to the second.
Logical Operators:
Assignment Operators:
int x = 10;
Addition assignment (+=): Adds right operand to the left operand and assigns the result to the left operand.
x += 5; // Equivalent to x = x + 5;
Subtraction assignment (-=): Subtracts right operand from the left operand and assigns the result to the left operand.
x -= 5; // Equivalent to x = x - 5;
Multiplication assignment (*=): Multiplies right operand with the left operand and assigns the result to the left operand.
x *= 5; // Equivalent to x = x * 5;
Division assignment (/=): Divides left operand with the right operand and assigns the result to the left operand.
x /= 5; // Equivalent to x = x / 5;
x++; // Equivalent to x = x + 1;
x--; // Equivalent to x = x - 1;
if-else if-else:
if (condition1) {
// code block executed if condition1 is true
} else if (condition2) {
// code block executed if condition2 is true
} else {
// code block executed if neither condition1 nor condition2 is true
}
Switch Statement:
switch (expression) {
case value1:
// code block executed if expression equals value1
break;
case value2:
// code block executed if expression equals value2
break;
// add more cases as needed
default:
// code block executed if expression doesn't match any case
}
Loops:
for Loop:
while Loop:
while (condition) {
// code block to be executed
}
do-while Loop:
do {
// code block to be executed
} while (condition);
Branching Statements:
break:
Terminates the loop or switch statement it's in.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
// code block to be executed
}
continue:
Skips the current iteration of a loop and continues with the next iteration.
return:
Exits from the current method and optionally returns a value.
public int someMethod() {
// code block
if (condition) {
return value;
}
// code block
}
Java Keywords:
Keyword Usage
boolean A data type that can hold True and False values only
char A data type that can hold unsigned 16-bit Unicode characters
import java.util.Arrays;
import java.util.Arrays;
STRING
String:
Declared in java.lang package: The String class is part of the java.lang package,
which is automatically imported into every Java program. This means you can
use String without explicitly importing it.
ENCAPSULATION:
Encapsulation is one of the four fundamental principles of object-oriented
programming (OOP), along with inheritance, polymorphism, and abstraction. It
refers to the bundling of data (attributes) and methods (behaviors) that
operate on the data into a single unit, known as a class. Encapsulation hides
the internal state of an object from the outside world and only exposes the
necessary functionality through well-defined interfaces.
Key Concepts of Encapsulation:
Data Hiding: Encapsulation allows data to be hidden from outside
access, preventing direct manipulation of an object's internal state. This
is achieved by declaring the fields of a class as private and providing
public methods (getters and setters) to access and modify the data.
Benefits of Encapsulation:
Modularity: Encapsulation promotes modularity by organizing code into
self-contained units (classes) that can be developed, tested, and
maintained independently.
EXAMPLE:
public class Person {
// Private fields (attributes)
private String name;
private int age;
private String gender;
// Constructor
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// Getter methods
public String getName() {
return name;
}
// Setter methods
public void setName(String name) {
this.name = name;
}
The method signature (name and parameters) in the subclass must match the
method signature in the superclass.
The return type of the overriding method can be the same as, or a subtype of,
the return type in the superclass.
The access level of the overriding method in the subclass can't be more
restrictive than the access level in the superclass.
Keyword super: The super keyword is used to access members (fields,
methods, and constructors) of the superclass from within the subclass. It's also
used to call the superclass constructor explicitly.
Final Classes and Methods: The final keyword can be used to prevent a class
from being subclassed or a method from being overridden.
Object Class: All classes in Java implicitly inherit from the Object class, which is
the root of the class hierarchy in Java.
Abstract Classes and Interfaces: Abstract classes and interfaces are used to
define contracts for subclasses, promoting polymorphism and abstraction in
Java. Subclasses must implement all abstract methods defined in abstract
classes or interfaces.
Access Modifiers:
Inherited members (fields and methods) of the superclass can have different
access modifiers:
public: accessible from anywhere
protected: accessible within the same package and subclasses
default (no modifier): accessible within the same package
private: not accessible in subclasses
Single Inheritance:
Java supports single inheritance, meaning a subclass can inherit from only one
superclass. However, a superclass can have multiple subclasses.
Super Keyword:
The super keyword is used to access members of the superclass from
within the subclass.
It can be used to call the superclass constructor, access superclass
methods, and access superclass fields if they are not overridden.
Method Overriding:
Subclasses can provide a specific implementation for methods inherited
from the superclass. This is known as method overriding.
The method signature (name, parameters, return type) must be the
same in both the superclass and subclass for overriding.
Methods marked with the final or private modifier cannot be
overridden.
Constructor Chaining:
Subclass constructors implicitly call a superclass constructor.
If no explicit call to a superclass constructor is made using super(), the
compiler inserts a call to the superclass's default constructor (super()).
Benefits of Inheritance:
Code Reusability: Inheritance allows subclasses to inherit fields and
methods from the superclass, promoting code reuse and reducing
redundancy.
// Methods
public void publicMethod() { }
protected void protectedMethod() { }
void defaultMethod() { }
private void privateMethod() { }
}
import mypackage.Superclass;
EXAMPLE:
// Superclass Vehicle
class Vehicle {
private String brand;
private String model;
// Subclass Car
class Car extends Vehicle {
private int numberOfSeats;
// Subclass Bicycle
class Bicycle extends Vehicle {
private int numberOfGears;
// Main class
public class Main {
public static void main(String[] args) {
Car car = new Car("Toyota", "Camry", 5);
car.drive(); // Output: The Toyota Camry is driving.
car.park(); // Output: The Toyota Camry is parking.
POLYMORPHISEM:
Polymorphism is a fundamental concept in object-oriented programming
(OOP) that allows objects to be treated as instances of their parent class, even
if they are instances of a subclass of that parent class. It enables a single
interface (method or function) to be used to represent different types of
objects. Polymorphism allows for flexibility and extensibility in code, facilitating
code reuse and simplifying the design of complex systems.
Types of Polymorphism:
1. Compile-Time Polymorphism (Static Binding or Method Overloading):
Method overloading allows multiple methods in the same class to have the
same name but different parameters.
The decision of which method to execute is made at compile time based on the
number and types of arguments.
class MyClass {
void display(int a) {
System.out.println("Value of a: " + a);
}
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
EXAMPLE:
class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}