Unit 1 Java Notes
Unit 1 Java Notes
UNIT – I
Foundations of Java: History of Java, Java Features, Variables, Data Types, Operators, Expressions,
Control Statements. Elements of Java - Class, Object, Methods, Constructors and Access Modifiers,
Generics, Inner classes, String class and Annotations.
OOP Principles: Encapsulation – concept, setter and getter method usage, this keyword. Inheritance -
concept, Inheritance Types, super keyword. Polymorphism – concept, Method Overriding usage and
Type Casting. Abstraction – concept, abstract keyword and Interface.
History of Java:
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995.
Applications
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as [Link], [Link], etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
Java Features
Data Types
Java programming language has a rich set of data types. The data type is a category of data
stored in variables. In java, data types are classified into two types and they are as follows.
Primitive Data Types
Non-primitive Data Types
Primitive Data Types
Primitive data types are the basic building blocks of data manipulation in Java. They are
predefined and store simple values directly in memory. There are eight primitive types:
Data Type Size
byte 1 byte
short 2 bytes
int 4 bytes
long 8 bytes
float 4 bytes
double 8 bytes
boolean JVM-dependent
char 2 bytes
Java operators
Java operators are special symbols used to perform operations on variables and values, such
as mathematical calculations, comparisons, and logical evaluations. They are categorized into
several groups, each serving a specific purpose.
The main types of operators in Java are:
Arithmetic Operators: Used for performing basic mathematical operations.
o + (Addition), - (Subtraction), * (Multiplication), / (Division),
% (Modulus/Remainder)
Example 1: Arithmetic Operators
class Main {
public static void main(String[] args) {
// declare variables
int a = 12, b = 5;
// addition operator
[Link]("a + b = " + (a + b));
// subtraction operator
[Link]("a - b = " + (a - b));
// multiplication operator
[Link]("a * b = " + (a * b));
// division operator
[Link]("a / b = " + (a / b));
// modulo operator
[Link]("a % b = " + (a % b));
}
}
Increment and Decrement Operators
o ++ (Increment, increases value by 1)
o -- (Decrement, decreases value by 1)
class Main {
public static void main(String[] args) {
// declare variables
int a = 12, b = 12;
int result1, result2;
// original value
[Link]("Value of a: " + a);
// increment operator
result1 = ++a;
[Link]("After increment: " + result1);
// decrement operator
result2 = --b;
[Link]("After decrement: " + result2);
}
}
Assignment Operators: Used to assign values to variables. The simple assignment
operator is =, but compound operators provide a shorthand for combining an
arithmetic operation with assignment (e.g., += is equivalent to a = a + 3).
// create variables
int a = 7, b = 11;
// value of a and b
[Link]("a is " + a + " and b is " + b);
// == operator
[Link](a == b); // false
// != operator
[Link](a != b); // true
// > operator
[Link](a > b); // false
// < operator
[Link](a < b); // true
// >= operator
[Link](a >= b); // false
// <= operator
[Link](a <= b); // true
}
}
// && operator
[Link]((5 > 3) && (8 > 5)); // true
[Link]((5 > 3) && (8 < 5)); // false
// || operator
[Link]((5 < 3) || (8 > 5)); // true
[Link]((5 > 3) || (8 < 5)); // true
[Link]((5 < 3) || (8 < 5)); // false
// ! operator
[Link](!(5 == 3)); // true
[Link](!(5 > 3)); // false
}
}
Control Statements
Control statements in Java allow you to control the flow of your program, make
decisions, and repeat tasks.
Simple if Statement:
The 'if' statement is used to execute a block of code only if a specified condition
is 'true'. It's one of the most fundamental control structures in Java.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
Example:
int age = 18;
if (age >= 18)
{
[Link]("You are an adult.");
}
In this example, the code inside the 'if' block is executed because the condition 'age
>= 18' is 'true'.
if-else Statement:
The 'if-else' statement is used to execute one block of code if a condition is 'true' and
another block if the condition is 'false'.
Syntax:
if (condition)
{
// Code to execute if the condition is true
}
else
{
// Code to execute if the condition is false
}
Example:
int age = 15;
if (age >= 18) {
[Link]("You are an adult.");
}
else {
[Link]("You are not yet an adult.");
}
Nested if else:
Syntax
if (condition1) {
// Code to be executed if condition1 is true
if (condition2) {
// Code to be executed if both condition1 and condition2 are true
} else {
// Code to be executed if condition1 is true, but condition2 is false
}
} else {
// Code to be executed if condition1 is false
}
Example:
else if statement:
Syntax
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition1 is false and condition2 is true
} else if (condition3) {
// Code to execute if condition1 and condition2 are false, and condition3 is true
} else {
// Code to execute if none of the conditions are true (optional)
}
Example:
public class Example4
{
public static void main(String[]args)
{
int marks;
marks=80;
if (marks>=90)
{
[Link]("grade is O");
}
else if(marks>=80&&marks<90)
{
[Link]("grade is A");
}
else if(marks>=70&&marks<80)
{
[Link]("grade is B");
}
else if(marks>=60&&marks<70)
{
[Link]("grade is C");
}
else
{
[Link]("grade is D");
}
}
}
'switch' Statement:
The 'switch' statement is used for multiple branches of execution based on the value
of an expression. It's an alternative to using multiple 'if-else' statements.
Syntax:
switch (expression)
{
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
// ...
default:
// Code to execute if expression doesn't match any case
}
Example:
int dayofWeek = 3;
switch (dayofWeek)
{
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
// ...
default:
[Link]("Invalid day");
}
Loops:
Loops in Java allow you to execute a block of code repeatedly. Java provides several
types of loops:
1. for Loop:
for loop is used when you know in advance how many times you want to execute a
block of code.
Syntax:
for (initialization; condition; iteration)
{
// Code to execute repeatedly
}
Example:
for (int i = 1; i <= 5; i++) {
[Link]("Iteration " + i);
}
This 'for' loop will execute the code block five times, printing "Iteration 1" through
"Iteration 5."
2. while Loop:
while loop is used when you want to execute a block of code as long as a certain
condition is 'true'.
Syntax:
while (condition)
{
// Code to execute repeatedly
}
Example:
int count = 0;
while (count < 3) {
[Link]("Count: " + count);
count++;
}
This 'while' loop will execute the code block three times, printing "Count: 0," "Count:
1," and "Count: 2."
3. do-while Loop:
do-while' loop is similar to the 'while' loop, but it always executes the code block at
least once, even if the condition is initially false.
Syntax:
do {
// Code to execute repeatedly
} while (condition);
Example:
int i = 1;
do {
[Link]("Iteration " + i);
i++;
} while (i <= 3);
This 'do-while' loop will execute the code block three times, printing "Iteration 1,"
"Iteration 2," and "Iteration 3."
// Constructors
public ClassName()
{
// Constructor code
}
// Methods (functions)
returnType methodName1(parameterType1 param1, parameterType2 param2, ...)
{
// Method code
}
// ...
}
// Constructor
public Person(String n, int a) {
name = n;
age = a;
}
2. Object:
An object is an instance of a class. It represents a real-world entity and has its own
state and behavior. To create an object, you use the 'new' keyword followed by a
constructor of the class.
Syntax:
ClassName objectName = new ClassName();
Copy to Clipboard
In this example, we created two 'Person' objects, 'person1' and 'person2', and called
the 'displayInfo' method on each object to display their information.
3. Constructors:
Constructors are special methods used to initialize objects when they are created.
They have the same name as the class and do not have a return type.
Example:
public class Student {
String name;
int age;
// Constructor
public Student(String n, int a) {
name = n;
age = a;
}
In this example, the 'Student' class has a constructor that takes two
parameters, 'name'and 'age', to initialize the object's state when it's created.
4. Methods:
Methods define the behavior of objects created from a class. They are functions that
can perform actions and return values.
Example:
public class Circle {
double radius;
// Constructor
public Circle(double r) {
radius = r;
}
Access Modifiers
In Java, access modifiers are keywords used to set the accessibility (scope) of classes,
interfaces, variables, methods, and constructors. They control which other parts of the
code can access a particular member, enforcing encapsulation and security.
public: This provides the widest scope. Anything declared public can be accessed
from any other class, in any package.
protected: This level is more restrictive than public but less than default. It is
typically used with inheritance to allow subclasses to access specific members of a
parent class.
default (package-private): When no access modifier is specified, the member or
class has default access. It is only visible to classes within the same package.
private: This is the most restrictive level. Members declared private are only visible
within the class where they are declared.
Inner Class:
An inner class is a class declared inside the body of another class. The inner class has
access to all members (including private) of the outer class, but the outer class can
access the inner class members only through an object of the inner class.
Syntax:
class OuterClass {
// Outer class members
class InnerClass {
// Inner class members
}
Example:
class InnerClass {
void display() {
[Link]("Hello from Inner Class!");
}
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
InnerClass inner = [Link] InnerClass();
[Link]();
}
}
class GFG {
public static void main (String[] args) {
String str = "hello geeks";
[Link]("Length of String-> "+[Link]());
[Link]("Changed String ->"+[Link]());
}
}
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must:
declare class variables/attributes as private
provide public get and set methods to access and update the value of
a private variable
Get and Set methods
You learned from the previous chapter that private variables can only be accessed within the
same class (an outside class has no access to it). However, it is possible to access them if we
provide public get and set methods.
The get method returns the variable value, and the set method sets the value.
Syntax for both is that they start with either get or set, followed by the name of the variable,
with the first letter in upper case:
Example
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
[Link] = newName;
}
}
The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the name variable.
this keyword is used to refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside this
class:
this Keyword
this keyword in Java refers to the current object in a method or constructor.
this keyword is often used to avoid confusion when class attributes have the same name as
method or constructor parameters.
class Vehicle
{
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
[Link]("Tuut, tuut!");
}
}
// Call the honk() method (from the Vehicle class) on the myCar object
[Link]();
// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
[Link]([Link] + " " + [Link]);
}
}
Types of Inheritance in Java
Below are the different types of inheritance which are supported by Java.
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance.
Single Inheritance
//Super class
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}
// Subclass
class Car extends Vehicle {
Car() {
[Link]("This Vehicle is Car");
}
}
Output
This is a Vehicle
This Vehicle is Car
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also acts as the base class for other classes.
Multilevel Inheritance
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}
class FourWheeler extends Vehicle {
FourWheeler() {
[Link]("4 Wheeler Vehicles");
}
}
class Car extends FourWheeler {
Car() {
[Link]("This 4 Wheeler Vehicle is a Car");
}
}
public class Geeks {
public static void main(String[] args) {
Car obj = new Car(); // Triggers all constructors in order
}
}
Output
This is a Vehicle
4 Wheeler Vehicles
This 4 Wheeler Vehicle is a Car
3. Hierarchical Inheritance
In hierarchical inheritance, more than one subclass is inherited from a single base class. i.e.
more than one derived class is created from a single base class. For example, cars and buses
both are vehicle
Hierarchical Inheritance
class Vehicle {
Vehicle() {
[Link]("This is a Vehicle");
}
}
Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus
Output
This is an AmphibiousVehicle
This is a WaterVehicle
This is a LandVehicle
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. In Java, we can achieve hybrid
inheritance only through Interfaces if we want to involve multiple inheritance to implement
Hybrid inheritance.
Hybrid Inheritance
Explanation:
class Car extends Vehicle->Single Inheritance
class Bus extends Vehicle and class Bus implements Interface Fare->Hybrid
Inheritance (since Bus inherits from two sources, forming a combination of single +
multiple inheritance).
class SolarSystem {
}
class Earth extends SolarSystem {
}
class Mars extends SolarSystem {
}
public class Moon extends Earth {
public static void main(String args[])
{
SolarSystem s = new SolarSystem();
Earth e = new Earth();
Mars m = new Mars();
super Keyword
In Java, the super keyword is used to refer to the parent class of a subclass.
The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
It can be used in two main ways:
To access attributes and methods from the parent class
To call the parent class constructor
Polymorphism:
Polymorphism in Java is one of the core concepts in object-oriented programming
(OOP) that allows objects to behave differently based on their specific class type. The
word polymorphism means having many forms, and it comes from the Greek words poly
(many) and morph (forms), this means one entity can take many forms. In Java,
polymorphism allows the same method or object to behave differently based on the context,
specially on the project's actual runtime class.
Features of polymorphism:
Multiple Behaviors: The same method can behave differently depending on the
object that calls this method.
Method Overriding: A child class can redefine a method of its parent class.
Method Overloading: We can define multiple methods with the same name but
different parameters.
Runtime Decision: At runtime, Java determines which method to call depending on
the object's actual class.
Types of Polymorphism in Java
In Java Polymorphism is mainly divided into two types:
Types of Polymorphism in Java
1. Compile-Time Polymorphism
Compile-Time Polymorphism in Java is also known as static polymorphism and also known
as method overloading. This happens when multiple methods in the same class have the
same name but different parameters.
Note: But Java doesn't support the Operator Overloading.
Method Overloading
As we discussed above. Method overloading in Java means when there are multiple
functions with the same name but different parameters then these functions are said to be
overloaded. Functions can be overloaded by changes in the number of arguments or/and a
change in the type of arguments.
Example: Method overloading by changing the number of arguments
// Class 1
// Helper class
class Helper {
// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{
// Returns product of double numbers
return a * b;
}
}
// Class 2
// Main class
class Geeks
{
// Main driver method
public static void main(String[] args) {
Output
8
34.65
Explanation: The Multiply method is overloaded with different parameter types. The
compiler picks the correct method during compile time based on the arguments.
2. Runtime Polymorphism
Runtime Polymorphism in Java known as Dynamic Method Dispatch. It is a process in
which a function call to the overridden method is resolved at Runtime. This type of
polymorphism is achieved by Method Overriding. Method overriding, on the other hand,
occurs when a derived class has a definition for one of the member functions of the base
class. That base function is said to be overridden.
Method Overriding
Method overriding in Java means when a subclass provides a specific implementation of a
method that is already defined in its superclass. The method in the subclass must have the
same name, return type, and parameters as the method in the superclass. Method overriding
allows a subclass to modify or extend the behavior of an existing method in the parent
class. This enables dynamic method dispatch, where the method that gets executed is
determined at runtime based on the object's actual type.
Example: This program demonstrates method overriding in Java, where the Print() method
is redefined in the subclasses (subclass1 and subclass2) to provide specific
implementations.
// Class 1
// Helper class
class Parent {
// Class 2
// Helper class
class subclass1 extends Parent {
// Method
void Print() {
[Link]("subclass1");
}
}
// Class 3
// Helper class
class subclass2 extends Parent {
// Method
void Print() {
[Link]("subclass2");
}
}
// Class 4
// Main class
class Geeks {
a = new subclass2();
[Link]();
}
}
Output
subclass1
subclass2
abstract keyword:
Java Abstract Class
The abstract class in Java cannot be instantiated (we cannot create objects of abstract classes).
We use the abstract keyword to declare an abstract class. For example,
// create an abstract class
abstract class Language {
// fields and methods
}
...
// abstract method
abstract void method1();
// regular method
void method2() {
[Link]("This is regular method");
}
}
To know about the non-abstract methods, visit Java methods. Here, we will learn about
abstract methods.
// abstract method
abstract void method1();
}
Interfaces
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with
empty bodies:
Example
// interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void run(); // interface method (does not have a body)
}
To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class:
Example
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
[Link]();
[Link]();
}
}
*********