0% found this document useful (0 votes)
3 views17 pages

Java Notes Complete Handwritten

Uploaded by

ramyargowda1113
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views17 pages

Java Notes Complete Handwritten

Uploaded by

ramyargowda1113
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA PROGRAMMING

UNIT 1
Introduction to Java:
Developed by James Gosling at Sun Microsystems. Java is a high-level, object-oriented programming language. It fol
Class
A class is a blueprint or template used to create objects.
It defines variables and methods.
Object
An object is an instance of a class.
It represents a real-world entity and uses the properties of a class.
Example
For example, Car is a class and BMW, Audi are objects.
Example program to demonstrate class and object:
class Student {
int id;
String name;

void display() {
[Link](id + " " + name);
}

public static void main(String[] args) {


Student s1 = new Student(); // object creation

[Link] = 1;
[Link] = "Bhavana";

[Link](); // method call


}
}
Object-Oriented Programming (OOP) Paradigms
Object-Oriented Programming (OOP) is a programming approach where programs are designed using objects and cla
• OOP is based on classes and objects
• Improves code reusability
• Makes program easy to manage and secure
• Follows real-world approach
Pillars of OOPs:
1. Encapsulation
Encapsulation means wrapping data and methods into a single unit (class).
Data + Functions = One unit
2. Abstraction
Abstraction means hiding internal details and showing only necessary information.
It only show what is needed, hide the rest
Example:
Using ATM → you don’t know internal working.
3. Inheritance
Inheritance means one class can use properties of another class.
Like Child gets features from parent
Example:
Dog inherits from Animal
4. Polymorphism
Polymorphism means one thing can have many forms.
Same method, but different behavior
Example:
Method overloading / overriding
C■JAVA
Procedural programming language■Object-oriented programming language
Follows top-down approach■Follows bottom-up approach
Platform dependent■Platform independent
Less secure■More secure
Uses pointers■Does not use pointers
No support for inheritance■Supports inheritance
No data hiding■Supports encapsulation (data hiding)
Memory managed manually■Automatic memory management (Garbage Collection)
Difference between C and Java

Features of JAVA
■■Object Oriented
Java is an object-oriented programming language based on classes and objects. It supports concepts like encapsulat
■■Platform Independent
Java is platform-independent because of Java Virtual Machine (JVM).
When we write Java code, it is first compiled by the compiler and then converted into bytecode (which is platform-inde
This byte code can run on any platform which has JVM installed.
■■Interpreted
Java code is not directly executed by the computer. It is first compiled into bytecode. This byte code is then understan
■■Scalable
Java can handle both small and large-scale applications. Java provides features like multithreading and distributed co
■■Portable
When we write a Java program, the code first get converted into bytecode and this bytecode does not depend on any

■■Secured and Robust


Java is a reliable programming language because it can catch mistakes early while writing the code and also keeps ch
■■Memory Management
Memory management in Java is automatically handled by the Java Virtual Machine (JVM).
Java garbage collector reclaim memory from objects that are no longer needed.
Memory for objects are allocated in the heap
Method calls and local variables are stored in the stack.
■■Multithreading
Multithreading in Java allows multiple threads to run at the same time.
It improves CPU utilization and enhancing performance in applications that require concurrent task execution.
■■Rich Standard Library
Java provides various pre-built tools and libraries which is known as Java API. Java API is used to cover tasks like file
■■Support for Mobile and Web Application
Java offers support for both web and mobile applications.

Structure of a Java Program:

package mypackage; // (optional)


import [Link].*; // (optional)
class Demo // Class definition
{
int x = 10; // Instance variable
void display() // Method
■■{
[Link]("Hello");
■■}
■public static void main(String[] args) // Main method
{
[Link]("Program starts here");
■}
}

Components of Java Program:


Package Declaration
•■Defines the namespace of the class
•■Written at the top of the program
•■Example: package mypackage;
Import Statement
•■Used to include predefined classes and packages
•■Example: import [Link].*;
Class Definition
•■Java program must contain at least one class
•■Syntax: class ClassName { }
Variables
•■Used to store data
•■Can be instance, static, or local variables
Methods
•■Block of code used to perform a task
•■Improves code reusability
Main Method (Entry Point)
•■Execution of program starts from main()
•■Syntax:
Execution Flow
1.■Source code (.java) is written
2.■Compiled using compiler → bytecode (.class)
3.■JVM executes the bytecode
Data Types:
A data type specifies the type of data that a variable can store, such as numbers, characters, or boolean values.
Java data types are broadly classified into two categories:
■■Primitive Data Types
■■Non-Primitive Data Types (Reference Types)

Primitive data types:


Primitive data types are the basic built-in data types in Java that are used to store simple values.
byte
•■Used to store small integer values
•■Saves memory when large arrays are used
•■Example: byte b = 10;
short
•■Used for storing slightly larger integers than byte
•■Not commonly used in daily programs
•■Example: short s = 200;
int
•■Most commonly used data type for integers
•■Suitable for general numeric calculations
•■Example: int a = 1000;
long
•■Used to store very large integer values
•■Requires L at the end of the value
•■Example: long l = 100000L;
float
•■Used to store decimal (fractional) values
•■Less precision compared to double
•■Requires f at the end
•■Example: float f = 5.5f;
double
•■Used for large decimal values with higher precision
•■Default choice for decimal numbers
•■Example: double d = 99.99;
char
•■Used to store a single character
•■Written inside single quotes
•■Example: char c = 'A';
boolean
•■Used to store true or false values
•■Mainly used in decision-making conditions
•■Example: boolean a = true;
Non-Primitive Data Types: Non-primitive data types (also called reference types) are data types that do not store actu
String
•■Used to store a sequence of characters (text)
•■Strings are objects in Java
String name = "Bangalore";
Array
•■Used to store multiple values of the same type
•■All elements are stored in a single variable
int arr[] = {1, 2, 3, 4};
Class
•■A class is a blueprint used to create objects
•■It contains variables and methods
class Student {
int id;
}
Object
•■An object is an instance of a class
•■Used to access properties and methods
Student s = new Student();

Variables:
A variable is a named memory location used to store data that can be changed during program execution.
Variables are used to store data temporarily so that it can be processed in a program. Each variable must be declared
Types of Variables:
Local Variables
A local variable is a variable that is declared inside a method, constructor, or block, and it is accessible only within tha
• Declared inside a method or block
• Scope is limited to that method/block only
• Created when the method is called
• Destroyed when the method ends
Example:
class Demo {
void show() {
int x = 10; // local variable
[Link](x);
}

public static void main(String[] args) {


Demo d = new Demo();
[Link]();
}
}
Instance Variable:
An instance variable is a variable that is declared inside a class but outside any method, and each object gets its own
• Declared inside class, outside methods
• Created when an object is created
• Each object has different values
• Accessed using object
Example:
class Student {
int marks; // instance variable
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();

[Link] = 80;
[Link] = 90;

[Link]([Link]); // 80
[Link]([Link]); // 90
}
}

Static Variable:
A static variable is a variable that is declared using the static keyword, and it is shared among all objects of the class.
• Declared with static keyword
• Only one copy exists
• Shared by all objects
• Accessed using class name

Example:

class Student {
static String college = "ABC College"; // static variable
}

public class Main {


public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();

[Link]([Link]);
}
}

Operators:
Operators are symbols used to perform operations on variables and values.
Type of Operator■Operators■Description■Example
Arithmetic■+, -, *, /, %■Perform mathematical operations■a + b
Relational■==, !=, >, <, >=, <=■Compare two values and return boolean■a > b
Logical■&&, ||, !■Combine conditions■a > 5 && b < 10
Assignment■=, +=, -=, *=, /=■Assign values to variables■a += 5
Unary■++, --, !■Operate on single operand■a++
Bitwise■&, |, ^, ~, <<, >>■Perform operations on bits■a & b
Types of Operators:
Control structures :
Control structures in Java are used to control the flow of execution of a program, deciding which statements are execu
Types of Control Structures
Java control structures are mainly classified into Branching (Decision-making) and Looping (Iteration) statements.
1. Branching Statements (Decision Making)
These statements are used to execute code based on conditions.
■ if statement
Executes a block of code only if the condition is true.
int age = 18;
if(age >= 18) {
[Link]("Eligible");
}
________________________________________
■ if-else statement
Executes one block if the condition is true and another if it is false.
if(age >= 18) {
[Link]("Adult");
} else {
[Link]("Minor");
}
________________________________________
■ else-if ladder
Used when there are multiple conditions to check.
int marks = 85;

if(marks >= 90) {


[Link]("A");
} else if(marks >= 75) {
[Link]("B");
} else {
[Link]("C");
}
________________________________________
■ switch statement
Used to select one block from multiple options.
int day = 2;

switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
default: [Link]("Invalid");
}
________________________________________
2. Looping Statements (Iteration)
These statements are used to execute a block of code repeatedly.
________________________________________
■ for loop
Used when the number of iterations is known.
for(int i = 1; i <= 5; i++) {
[Link](i);
}
________________________________________
■ while loop
Executes as long as the condition is true.
int i = 1;
while(i <= 5) {
[Link](i);
i++;
}
________________________________________
■ do-while loop
Executes at least once, even if the condition is false.
int i = 1;
do {
[Link](i);
i++;
} while(i <= 5);
________________________________________
Jump Statements in Java
✍■ Definition
Jump statements in Java are used to transfer the control of execution from one part of the program to another, either
________________________________________
■ Types of Jump Statements
Java provides three main jump statements:
________________________________________
1. break Statement
The break statement is used to immediately terminate a loop or switch statement and transfer control to the next state
________________________________________
Example
for(int i = 1; i <= 5; i++) {
if(i == 3) {
break;
}
[Link](i);
}
■ Output:
1
2

•■Stops execution completely

2. continue Statement
The continue statement is used to skip the current iteration and continue with the next iteration of the loop.

Example
for(int i = 1; i <= 5; i++) {
if(i == 3) {
continue;
}
[Link](i);
}
Output:
1
2
4
5
[Link] Statement:
The return statement is used to exit from a method and optionally return a value.
Example

int add(int a, int b) {


return a + b;
}

Methods in Java
Definition
A method is a block of code that is used to perform a specific task and can be executed whenever it is called.
________________________________________
Purpose of Methods
To reduce code repetition
To improve readability
To make programs modular and reusable
________________________________________
Syntax
returnType methodName(parameters) {
// method body
}
________________________________________
Example
class Demo {
int add(int a, int b) {
return a + b;
}

public static void main(String[] args) {


Demo d = new Demo();
int result = [Link](5, 3);
[Link](result);
}
}
________________________________________
Types of Methods in Java
Methods are mainly classified based on parameters and return type.
________________________________________
Method with Parameters and Return Value
Takes input values
Returns a result
int add(int a, int b) {
return a + b;
}
Used when both input and output are required
________________________________________
Method with Parameters but No Return Value
Takes input values
Does not return anything
void printSum(int a, int b) {
[Link](a + b);
}
Used when only action or output is needed
________________________________________
Method without Parameters but with Return Value
Does not take input
Returns a value
int getValue() {
return 10;
}
Used when value is generated inside the method
________________________________________
Method without Parameters and without Return Value
No input
No return value
void display() {
[Link]("Hello");
}
Constructors in Java
Definition
A constructor is a special member of a class that is used to initialize objects when they are created.
________________________________________
Purpose of Constructors
To assign initial values to instance variables
To ensure objects are properly initialized at the time of creation
________________________________________
Characteristics of Constructors
Constructor name must be the same as the class name
Constructor does not have any return type
Constructor is called automatically when an object is created
Constructor is used with the new keyword
________________________________________
Syntax
class ClassName {
ClassName() {
// constructor body
}
}
________________________________________
Default Constructor
A default constructor is a constructor that does not take any parameters.
If no constructor is written in a class, Java automatically provides a default constructor that initializes variables with de
________________________________________
Example of Default Constructor
class Student {
int id;

Student() {
id = 100;
}

public static void main(String[] args) {


Student s = new Student();
[Link]([Link]);
}
}
________________________________________
Parameterized Constructor
A parameterized constructor is a constructor that takes parameters to initialize variables with specific values.
________________________________________
Example of Parameterized Constructor
class Student {
int id;

Student(int x) {
id = x;
}

public static void main(String[] args) {


Student s = new Student(50);
[Link]([Link]);
}
}
________________________________________
Constructor Overloading
Constructor overloading means having more than one constructor in the same class with different parameters.
class Student {
int id;

Student() {
id = 0;
}

Student(int x) {
id = x;
}
}
Java Development Kit (JDK)
Java Development Kit is a software package used to develop, compile, and run Java programs.
It includes Java Runtime Environment, Java Virtual Machine, and development tools required for programming.
JDK is mainly used by programmers to write and compile Java programs.
________________________________________
Components of JDK
Java Runtime Environment is used to run Java programs
Java Virtual Machine executes bytecode and converts it into machine code
Java Compiler converts source code into bytecode using javac
Development tools include javac, java, javadoc, and jar
________________________________________
Workflow of Java Program
1.■Write program in a file with .java extension
2.■Compile the program using javac
Source code is converted into bytecode
3.■Bytecode file is generated with .class extension
4.■JVM executes the bytecode
5.■Output is displayed
Built-in Classes in Java
Definition
Built-in classes are predefined classes provided by Java that help perform common tasks like mathematical operation
________________________________________
Math Class
The Math class provides methods to perform mathematical operations.
Common methods include finding square root, power, maximum, minimum, and random values.
double result = [Link](25);
double power = [Link](2, 3);
int max = [Link](10, 20);
________________________________________
Character Class
The Character class is used to work with single characters.
It provides methods to check character properties.
[Link]('5');
[Link]('A');
[Link]('A');
________________________________________
String Class
String class is used to store and manipulate text.
Strings are immutable, meaning their values cannot be changed after creation.
String name = "Java";
[Link]([Link]());
[Link]([Link]());
________________________________________
StringBuffer Class
StringBuffer is used to modify strings.
It is mutable, meaning values can be changed.
StringBuffer sb = new StringBuffer("Hello");
[Link](" World");
[Link](sb);
________________________________________
Scanner Class
Scanner class is used to take input from the user.
It is part of [Link] package.
import [Link];

Scanner sc = new Scanner([Link]);


int x = [Link]();
String name = [Link]();
Abstract Class in Java
Definition
An abstract class is a class that cannot be instantiated and is used as a base class for other classes.
It may contain both abstract methods and concrete methods.
________________________________________
Abstract Method
An abstract method is a method without a body, and it must be implemented by subclasses.
________________________________________
Key Points
An abstract class is declared using the abstract keyword
It cannot be used to create objects
It can contain both abstract and non-abstract methods
Subclasses must implement all abstract methods
________________________________________
Example
abstract class Animal {
abstract void sound();

void eat() {
[Link]("Animal eats food");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}

public static void main(String[] args) {


Dog d = new Dog();
[Link]();
[Link]();
}
}
________________________________________
Explanation
Animal is an abstract class
sound method is abstract and must be implemented
Dog class provides implementation for sound
________________________________________
________________________________________
Static Class in Java
Definition
A static class is a class that contains static members and does not require object creation to access them.
In Java, only nested classes can be declared static.
________________________________________
Key Points
Static members belong to the class, not objects
They can be accessed using class name
No need to create an object to use static members
________________________________________
Example
class Outer {
static class Inner {
void display() {
[Link]("Static nested class");
}
}

public static void main(String[] args) {


[Link] obj = new [Link]();
[Link]();
}
}
________________________________________
Explanation
Inner is a static nested class
It is accessed using [Link]
________________________________________
________________________________________
Final Class in Java
Definition
A final class is a class that cannot be inherited.
________________________________________
Key Points
Declared using final keyword
Cannot be extended by other classes
Used for security and to prevent modification
________________________________________
Example
final class Vehicle {
void display() {
[Link]("Vehicle class");
}
}

// This will cause error


class Car extends Vehicle {
}
________________________________________
Explanation
Vehicle is a final class
It cannot be extended, so Car class will give an error
Casting Objects in Java
Definition
Object casting is the process of converting one object type into another type within the same inheritance hierarchy.
________________________________________
Types of Casting
Upcasting
Upcasting means converting a subclass object into a superclass reference.
It is done automatically.
class Animal {
void sound() {
[Link]("Animal sound");
}
}

class Dog extends Animal {


void bark() {
[Link]("Dog barks");
}
}

class Main {
public static void main(String[] args) {
Animal a = new Dog(); // upcasting
[Link]();
}
}
________________________________________
Downcasting
Downcasting means converting a superclass reference into a subclass type.
It must be done explicitly.
class Main {
public static void main(String[] args) {
Animal a = new Dog();
Dog d = (Dog) a; // downcasting
[Link]();
}
}
________________________________________
Key Points
Casting works only when there is inheritance
Upcasting is safe and automatic
Downcasting must be done carefully
________________________________________
________________________________________
instanceof Operator in Java
Definition
The instanceof operator is used to check whether an object belongs to a particular class or not.
________________________________________
Syntax
object instanceof ClassName
________________________________________
Example
class Main {
public static void main(String[] args) {
Animal a = new Dog();

if(a instanceof Dog) {


[Link]("a is an object of Dog");
}
}
}
________________________________________
Key Points
Returns true or false
Used before downcasting to avoid errors
Improves program safety
this Keyword in Java
Definition
The this keyword is used to refer to the current object of a class.
________________________________________
Purpose
Used to distinguish between instance variables and local variables
Helps to access current object data
________________________________________
Example
class Student {
int id;

Student(int id) {
[Link] = id;
}

void display() {
[Link](id);
}

public static void main(String[] args) {


Student s1 = new Student(10);
[Link]();
}
}
________________________________________
Explanation
The class has an instance variable id
The constructor has a parameter also named id
[Link] refers to the instance variable of the object
id refers to the local variable passed to the constructor
[Link] = id assigns the value 10 to the object variable
________________________________________
Output
10

this refers to the current object


Used when instance and local variables have same name
Helps avoid confusion in programs

You might also like