Java Notes
Java Notes
INDEX
A. Evolution of Java 🔊
B. Object Oriented Concepts of Java 🔊
C. Encapsulation, Polymorphism, Inheritance 🔊
D. Java and its uses 🔊
D.1. Lab work 🔊
E. Introduction to Java, Dynamic Initialization of
Variables, Scope and Lifetime of Variables,
Operators 🔊
F. Difference between Scope and Visibility 🔊
F.1. Lab work 🔊
G. Initialization of Arrays, Control Statements,
Iterative Statements (Loops), Jump Statements,
Class Fundamentals, Methods 🔊
G.1. Lab work 🔊
H. Important Questions 🔊
A. Evolution of Java
1. Inception (1991-1995):
James Gosling and Sun Microsystems: Java was created by James Gosling and his team at
Sun Microsystems in the early 1990s.
Key Features: Introduced key features such as the Java Virtual Machine (JVM), applets, and
Swing for GUI development.
3. Java 2 (J2SE 1.2, 1998):
Swing API: The Swing API was introduced, providing a more advanced set of GUI components.
Collections Framework: The Collections Framework was added for better data structure support.
Enumeration and Autoboxing: Enhanced with features like enumeration and autoboxing.
5. Java 6 (2006)
Scripting API: Introduced the Java Compiler API and Scripting API.
6. Java 7 (2011)
Fork/Join Framework: Added support for parallel programming with the Fork/Join framework.
7. Java 8 (2014)
Streams API: Added the Streams API for working with sequences of data.
Date and Time API: Improved date and time handling with the java.time package.
8. Java 9 (2017)
Module System: Introduced the Java Platform Module System (Project Jigsaw).
Local-Variable Type Inference: Java 10 introduced var for local variable type inference.
Versatility: Java's "Write Once, Run Anywhere" philosophy has led to widespread adoption in
enterprise and web development.
Android Platform: Java is the primary language for Android app development.
Java 17 and Beyond: Continuing the tradition of regular releases, Java evolves with new features
and improvements.
Long-Term Support (LTS): Certain releases are designated as Long-Term Support for stability in
enterprise environments.
Conclusion: Java's evolution has been marked by a commitment to platform independence, continuous
enhancements, and community involvement. Its adaptability and versatility make it a cornerstone in
various domains, ensuring its relevance in the dynamic landscape of software development.
Class: A class is a blueprint or template for creating objects. It defines the properties (attributes)
and behaviors (methods) that objects of the class will have.
Object: An object is an instance of a class. It represents a real-world entity and encapsulates both
data (attributes) and functionality (methods).
2. Encapsulation:
Definition: Encapsulation is the bundling of data and methods that operate on the data within a
single unit, i.e., a class.
Access Modifiers: Java provides access modifiers (public, private, protected) to control the
visibility of class members, supporting the principle of information hiding.
3. Inheritance:
Definition: Inheritance is a mechanism by which a class can inherit properties and behaviors from
another class, promoting code reusability.
Superclass and Subclass: The existing class is called the superclass, and the new class is the
subclass. Subclasses can extend the functionality of the superclass.
4. Polymorphism:
5. Abstraction:
Definition: Abstraction is the process of simplifying complex systems by modeling classes based
on essential properties and behaviors.
Abstract Classes and Interfaces: Java provides abstract classes and interfaces for abstraction.
Abstract classes may have abstract methods, and interfaces define a contract for implementing
classes.
6. Association:
Definition: Association represents a relationship between two or more classes. It can be one-to-
one, one-to-many, or many-to-many.
Example: In a university system, a Student class might be associated with a Course class.
7. Aggregation:
Definition: Aggregation is a special form of association where one class contains another class
as a part, but the contained class can exist independently.
Example: A Department class may aggregate Faculty and Students classes.
8. Composition:
Definition: Composition is a stronger form of aggregation where the parts are wholly owned by
the composite class. If the composite class is destroyed, its parts are also destroyed.
Example: A Car class composed of Engine and Wheels classes.
9. Interfaces:
Definition: An interface in Java is a collection of abstract methods. A class can implement one or
more interfaces, ensuring that the implementing class provides concrete implementations for all
interface methods.
10. Packages:
Definition: Packages in Java help in organizing classes into a hierarchical structure. They provide
a namespace, preventing naming conflicts.
Access Control: Packages also contribute to access control by allowing the use of the public,
protected, default, and private access modifiers.
Constructors: Constructors are special methods used for initializing objects when they are
created. They have the same name as the class.
Destructors: Java doesn't have explicit destructors. The garbage collector automatically
deallocates memory when an object is no longer referenced.
Definition: Java supports polymorphic algorithms through interfaces and abstract classes,
allowing different classes to be used interchangeably in algorithms.
Conclusion: Understanding these object-oriented concepts is fundamental to effective Java
programming. They provide a modular and structured approach to software development, facilitating
code organization, reusability, and maintenance. By leveraging these concepts, developers can design
robust and scalable systems in Java.
2. Polymorphism:
Definition: Polymorphism is the ability of a single function, class, or operator to work in different
ways based on the context. In Java, polymorphism is primarily achieved through method
overloading and method overriding.
Method Overloading: This occurs when multiple methods in the same class have the same name
but different parameter lists. The compiler determines which method to call based on the number
and types of arguments.
Method Overriding: This happens when a subclass provides a specific implementation for a
method that is already defined in its superclass. It allows a subclass to provide a specialized
version of a method.
Compile-time and Runtime Polymorphism: Method overloading is an example of compile-time
polymorphism (or static polymorphism), as the decision is made by the compiler. Method
overriding is an example of runtime polymorphism (or dynamic polymorphism), as the decision is
made at runtime.
3. Inheritance:
Definition: Inheritance is a fundamental OOP concept that allows a class (subclass or derived
class) to inherit the properties and behaviors of another class (superclass or base class).
Superclass and Subclass: The superclass is the existing class, and the subclass is the new
class that inherits from the superclass. The subclass can reuse the code of the superclass and
extend its functionality.
Keyword 'extends': In Java, the extends keyword is used to establish an inheritance relationship.
For example, class Subclass extends Superclass { ... }.
Types of Inheritance: Java supports single inheritance, where a class can inherit from only one
superclass, and multiple inheritance through interfaces, where a class can implement multiple
interfaces.
Super Keyword: The super keyword is used to refer to the immediate parent class. It is often
used to call the superclass's methods, access its fields, or invoke its constructor.
Java is a versatile, object-oriented, high-level programming language known for its platform
independence, readability, and robustness. It was developed by James Gosling and his team at Sun
Microsystems in the mid-1990s. Over the years, Java has evolved into a widely-used language in
various domains, including web development, enterprise applications, mobile app development, and
more.
📄 Copy
// Sample Java code goes here
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Platform Independence: Java applications can run on any device with a Java Virtual Machine
(JVM), making it platform-independent. The "Write Once, Run Anywhere" (WORA) principle is
achieved by compiling Java code into bytecode, which is then executed by the JVM.
Object-Oriented Programming: Java is built on object-oriented principles, promoting concepts
like encapsulation, inheritance, and polymorphism. This approach fosters modularity, code reuse,
and maintainability.
Rich Standard Library: Java comes with a comprehensive standard library (Java API) that
provides pre-built classes and methods, offering solutions for various programming tasks. This
library covers everything from basic data structures to networking and GUI development.
Memory Management: Java handles memory management automatically through a garbage
collector, which deallocates memory occupied by objects that are no longer in use. This helps
prevent memory leaks and simplifies memory management for developers.
Security: Java's design emphasizes security, particularly in the context of networked
environments. The JVM includes a Security Manager that helps protect systems from potentially
harmful actions in Java applications.
Multithreading: Java supports multithreading, allowing developers to create concurrent
applications that can execute multiple tasks simultaneously. This is crucial for performance
optimization and responsiveness in various applications.
Portability: Java's platform independence and the availability of the JVM on a wide range of
devices contribute to the portability of Java applications. Code written on one system can be
easily transported and executed on another system with a compatible JVM.
Uses of Java:
Web Development: Java is widely used for developing server-side applications, web services,
and dynamic web content. Popular frameworks like Spring and JavaServer Faces (JSF) are
employed in Java web development.
Enterprise Applications: Java is a dominant language for building large-scale enterprise
applications. Enterprise JavaBeans (EJB), Java Persistence API (JPA), and the Spring Framework
are commonly used in this context.
Mobile App Development: Java is used for developing Android applications. Android Studio, the
official IDE for Android development, supports Java as one of the primary languages for creating
Android apps.
Desktop Applications: Java's Swing and JavaFX libraries enable the development of cross-
platform desktop applications with rich graphical user interfaces (GUIs).
Cloud Computing: Java is extensively used in cloud computing services and platforms. It
provides the scalability and reliability required for cloud-based applications.
Big Data Technologies: Java is utilized in various big data technologies and frameworks,
including Apache Hadoop, Apache Spark, and Apache Flink, due to its performance and
scalability.
IoT (Internet of Things): Java's portability and adaptability make it suitable for developing
applications in the IoT space, connecting devices and enabling communication between them.
Scientific and Research Applications: Java is employed in scientific computing and research
applications due to its reliability, extensive libraries, and support for numerical computing.
Java's versatility and strong community support have contributed to its enduring popularity across a
wide range of domains, making it a language of choice for many developers and organizations.
Assessment 1:
Write a simple Java program that prints "Hello, World!" to the console.
Save the file with a ".java" extension.
Open a command prompt or terminal and navigate to the directory containing the Java file.
Compile the program using the javac command.
Execute the compiled program using the java command.
Assessment 2:
Create a Java program that takes two integers as input and prints their sum.
Compile and execute the program using command-line tools.
Test the program with different sets of integer inputs.
2. Beginner-Friendly Questions:
Question 1:
Question 2:
Question 3:
Question 4:
Question 5:
Question 6:
Question 7:
Question 8:
These questions cover a range of basic Java programming concepts, including output, arithmetic
operations, conditional statements, loops, and operators. They are designed to help students practice
and reinforce their understanding of fundamental programming principles in Java.
In Java, variables can be dynamically initialized, meaning their values can be set during runtime
rather than at compile-time. This is often done through user input or by computing the initial value
based on certain conditions. Here's an example in Java:
📄 Copy
import java.util.Scanner;
In this example, the value of dynamicVariable is determined based on user input at runtime.
1. Scope: The scope of a variable defines where in the code it can be accessed. In Java, there
are different levels of scope, including block scope, method scope, class scope, and global
scope.
2. Lifetime: The lifetime of a variable is the duration during which the variable exists in the
program's memory. Local variables have a shorter lifetime compared to instance and class
variables.
📄 Copy
public class ScopeExample {
// Class-level variable (global scope)
static int globalVariable = 10;
{
// Block-level variable (block scope)
int blockVariable = 3;
System.out.println("Block Variable: " + blockVariab
}
4. Introduction to Operators:
Java provides a variety of operators for performing operations on variables and values. These
operators can be categorized into:
📄 Copy
int a = 10;
int b = 5;
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;
📄 Copy
int x = 10;
int y = 20;
boolean isEqual = (x == y);
boolean isNotEqual = (x != y);
boolean isGreaterThan = (x > y);
boolean isLessThan = (x < y);
📄 Copy
boolean p = true;
boolean q = false;
boolean andResult = (p && q);
boolean orResult = (p || q);
boolean notResult = !p;
📄 Copy
int c = 5;
c += 3; // Equivalent to c = c + 3;
📄 Copy
int count = 10;
count++; // Increment by 1
count--; // Decrement by 1
These are just a few examples of the operators available in Java. Operators play a crucial role in
performing various computations and comparisons within Java programs.
1. Scope:
Definition: Scope refers to the region of the program in which a variable is defined and can be
accessed. It defines the portion of the code where a variable is valid and can be used.
Levels of Scope:
Block Scope: Variables declared within a block of code (e.g., inside a set of curly braces {})
have block scope. They are only accessible within that specific block.
Method/Function Scope: Variables declared within a method or function have method
scope. They are accessible only within that method or function.
Class Scope (Instance and Static Variables): Instance variables have class scope and are
accessible throughout the class. Static variables, which belong to the class rather than
instances, also have class scope.
Global/Program Scope: Variables declared at the class level but outside of any method or
block have global or program scope. They can be accessed throughout the entire class.
Example:
📄 Copy
public class ScopeExample {
// Class-level variable (class scope)
int globalVariable = 10;
{
// Block-level variable (block scope)
int blockVariable = 3;
// Accessible: methodVariable, blockVariable
}
// Accessible: methodVariable
}
// Accessible: globalVariable
}
2. Visibility:
Definition: Visibility, in the context of Java, refers to the access level of a variable or method from
outside its class. Java provides access modifiers (public, private, protected, and default) to control
the visibility of members within a class.
Access Modifiers:
1. Public: Members with public access modifier are visible to all classes, regardless of their
package or location.
2. Private: Members with private access modifier are visible only within the same class. They
are not accessible from outside the class.
3. Protected:Members with protected access modifier are visible within the same class,
package, and subclasses.
4. Default (Package-Private): Members with no explicit access modifier have default visibility,
meaning they are accessible within the same package but not outside it.
Example:
📄 Copy
// File: MyClass.java
public class MyClass {
// Public variable
public int publicVariable = 10;
// Private variable
private int privateVariable = 20;
// Protected variable
protected int protectedVariable = 30;
📄 Copy
// File: AnotherClass.java
public class AnotherClass {
public static void main(String[] args) {
MyClass myObject = new MyClass();
// Accessible: publicVariable
System.out.println(myObject.publicVariable);
In summary, scope deals with where a variable is valid and can be used within the program, while
visibility deals with who can access the variable or method from outside its class. Understanding both
concepts is crucial for designing well-organized and secure Java programs.
Assessment 1:
Objective: Test students' understanding of operators within different scopes.
Task:
Assessment 2:
Objective:
Assess students' ability to work with arithmetic and comparison operators in different scopes.
Task:
Assessment 3:
Objective:Test students' understanding of logical operators in various scopes.
Task:
Assessment 4:
Task:
1. Introduction:
Definition: An array in Java is a data structure that allows you to store multiple values of the
same type under a single variable name. Initializing an array involves allocating memory and
assigning initial values to its elements.
Declaration: Arrays are declared using square brackets []. For example, int[] numbers;
declares an integer array.
Basic Initialization: Arrays can be initialized using the new keyword, specifying the
data type and size of the array. For example, int[] numbers = new int[5]; creates an
integer array with a size of 5.
3. Inline Initialization:
Inline Initialization: Arrays can be initialized at the time of declaration, specifying the values
within curly braces {}. For example, int[] numbers = {1, 2, 3, 4, 5}; initializes an array with
specific values.
4. Multidimensional Arrays:
Multidimensional Arrays: Arrays can have more than one dimension. For example, int[][]
matrix = new int[3][4]; declares a 3x4 matrix.
Indexing: Array elements are accessed using indices. The first element is at index 0, the
second at index 1, and so on. For example, int value = numbers[2]; retrieves the third
element in the array.
6. Array Length:
Length Property: The length property is used to determine the number of elements in an
array. For example, int size = numbers.length; gives the size of the numbers array.
7. Dynamic Initialization:
Dynamic Initialization: : Arrays can be dynamically initialized with user input or calculated
values during runtime. For example
📄 Copy
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] dynamicArray = new int[size];
8. Understanding Types of Arrays:
📄 Copy
int[] numbers = {1, 2, 3, 4, 5};
b. Jagged Array:A jagged array is an array of arrays where each sub-array can have a
different size.
Example:
📄 Copy
int[][] jaggedArray = {
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
📄 Copy
int[][][] threeDArray = new int[3][4][2];
Conclusion:
Understanding the initialization of arrays in Java is fundamental for working with collections
of data. Whether it's a one-dimensional array, a two-dimensional matrix, or a more complex
jagged array, Java's array capabilities provide flexibility in representing and processing data
efficiently.
II. Control Statements:
1. Introduction:
Definition: Control statements in Java are used to alter the flow of program execution. They
enable decision-making, looping, and branching within the code.
2. Conditional Statements:
if Statement:
📄 Copy
if (condition) {
// code block executed if condition is true
}
if-else Statement:
📄 Copy
if (condition) {
// code block executed if condition is true
} else {
// code block executed if condition is false
}
📄 Copy
if (condition) {
// code block executed if condition is true
} else if (condition2) {
// code block executed if condition2 is true
} else {
// code block executed if no conditions are true
}
3. Switch Statement:
📄 Copy
switch (expression) {
case value1:
// code block executed if expression equals value1
break;
case value2:
// code block executed if expression equals value2
break;
// ...
default:
// code block executed if no cases match
}
More on it later...
H. Important Questions
Coming Soon
Contact the associated faculty in case of additional guidance.